1 // ignore-tidy-filelength
3 use crate::ast::{AngleBracketedArgs, AsyncArgument, ParenthesizedArgs, AttrStyle, BareFnTy};
4 use crate::ast::{GenericBound, TraitBoundModifier};
5 use crate::ast::Unsafety;
6 use crate::ast::{Mod, AnonConst, Arg, ArgSource, Arm, Guard, Attribute, BindingMode, TraitItemKind};
8 use crate::ast::{BlockCheckMode, CaptureBy, Movability};
9 use crate::ast::{Constness, Crate};
10 use crate::ast::Defaultness;
11 use crate::ast::EnumDef;
12 use crate::ast::{Expr, ExprKind, RangeLimits};
13 use crate::ast::{Field, FnDecl, FnHeader};
14 use crate::ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
15 use crate::ast::{GenericParam, GenericParamKind};
16 use crate::ast::GenericArg;
17 use crate::ast::{Ident, ImplItem, IsAsync, IsAuto, Item, ItemKind};
18 use crate::ast::{Label, Lifetime, Lit, LitKind};
19 use crate::ast::{Local, LocalSource};
20 use crate::ast::MacStmtStyle;
21 use crate::ast::{Mac, Mac_, MacDelimiter};
22 use crate::ast::{MutTy, Mutability};
23 use crate::ast::{Pat, PatKind, PathSegment};
24 use crate::ast::{PolyTraitRef, QSelf};
25 use crate::ast::{Stmt, StmtKind};
26 use crate::ast::{VariantData, StructField};
27 use crate::ast::StrStyle;
28 use crate::ast::SelfKind;
29 use crate::ast::{TraitItem, TraitRef, TraitObjectSyntax};
30 use crate::ast::{Ty, TyKind, TypeBinding, GenericBounds};
31 use crate::ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
32 use crate::ast::{UseTree, UseTreeKind};
33 use crate::ast::{BinOpKind, UnOp};
34 use crate::ast::{RangeEnd, RangeSyntax};
35 use crate::{ast, attr};
36 use crate::ext::base::DummyResult;
37 use crate::source_map::{self, SourceMap, Spanned, respan};
38 use crate::parse::{self, SeqSep, classify, token};
39 use crate::parse::lexer::{TokenAndSpan, UnmatchedBrace};
40 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
41 use crate::parse::token::DelimToken;
42 use crate::parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
43 use crate::util::parser::{AssocOp, Fixity};
44 use crate::print::pprust;
46 use crate::parse::PResult;
48 use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
49 use crate::symbol::{Symbol, keywords};
51 use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError};
52 use rustc_target::spec::abi::{self, Abi};
53 use syntax_pos::{Span, MultiSpan, BytePos, FileName};
54 use log::{debug, trace};
59 use std::path::{self, Path, PathBuf};
63 /// Whether the type alias or associated type is a concrete type or an existential type
65 /// Just a new name for the same type
67 /// Only trait impls of the type will be usable, not the actual type itself
68 Existential(GenericBounds),
72 struct Restrictions: u8 {
73 const STMT_EXPR = 1 << 0;
74 const NO_STRUCT_LITERAL = 1 << 1;
78 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
80 /// Specifies how to parse a path.
81 #[derive(Copy, Clone, PartialEq)]
83 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
84 /// with something else. For example, in expressions `segment < ....` can be interpreted
85 /// as a comparison and `segment ( ....` can be interpreted as a function call.
86 /// In all such contexts the non-path interpretation is preferred by default for practical
87 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
88 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
90 /// In other contexts, notably in types, no ambiguity exists and paths can be written
91 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
92 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
94 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
95 /// visibilities or attributes.
96 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
97 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
98 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
99 /// tokens when something goes wrong.
103 #[derive(Clone, Copy, PartialEq, Debug)]
110 #[derive(Clone, Copy, PartialEq, Debug)]
116 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
117 /// dropped into the token stream, which happens while parsing the result of
118 /// macro expansion). Placement of these is not as complex as I feared it would
119 /// be. The important thing is to make sure that lookahead doesn't balk at
120 /// `token::Interpolated` tokens.
121 macro_rules! maybe_whole_expr {
123 if let token::Interpolated(nt) = &$p.token {
125 token::NtExpr(e) | token::NtLiteral(e) => {
130 token::NtPath(path) => {
131 let path = path.clone();
133 return Ok($p.mk_expr($p.span, ExprKind::Path(None, path), ThinVec::new()));
135 token::NtBlock(block) => {
136 let block = block.clone();
138 return Ok($p.mk_expr($p.span, ExprKind::Block(block, None), ThinVec::new()));
146 /// As maybe_whole_expr, but for things other than expressions
147 macro_rules! maybe_whole {
148 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
149 if let token::Interpolated(nt) = &$p.token {
150 if let token::$constructor(x) = &**nt {
159 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
160 macro_rules! maybe_recover_from_interpolated_ty_qpath {
161 ($self: expr, $allow_qpath_recovery: expr) => {
162 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
163 if let token::Interpolated(nt) = &$self.token {
164 if let token::NtTy(ty) = &**nt {
167 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
174 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
175 if let Some(ref mut rhs) = rhs {
181 #[derive(Debug, Clone, Copy, PartialEq)]
192 /* ident is handled by common.rs */
195 pub struct Parser<'a> {
196 pub sess: &'a ParseSess,
197 /// the current token:
198 pub token: token::Token,
199 /// the span of the current token:
201 /// the span of the previous token:
202 meta_var_span: Option<Span>,
204 /// the previous token kind
205 prev_token_kind: PrevTokenKind,
206 restrictions: Restrictions,
207 /// Used to determine the path to externally loaded source files
208 crate directory: Directory<'a>,
209 /// Whether to parse sub-modules in other files.
210 pub recurse_into_file_modules: bool,
211 /// Name of the root module this parser originated from. If `None`, then the
212 /// name is not known. This does not change while the parser is descending
213 /// into modules, and sub-parsers have new values for this name.
214 pub root_module_name: Option<String>,
215 crate expected_tokens: Vec<TokenType>,
216 token_cursor: TokenCursor,
217 desugar_doc_comments: bool,
218 /// Whether we should configure out of line modules as we parse.
220 /// This field is used to keep track of how many left angle brackets we have seen. This is
221 /// required in order to detect extra leading left angle brackets (`<` characters) and error
224 /// See the comments in the `parse_path_segment` function for more details.
225 crate unmatched_angle_bracket_count: u32,
226 crate max_angle_bracket_count: u32,
227 /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
228 /// it gets removed from here. Every entry left at the end gets emitted as an independent
230 crate unclosed_delims: Vec<UnmatchedBrace>,
231 last_unexpected_token_span: Option<Span>,
234 impl<'a> Drop for Parser<'a> {
236 let diag = self.diagnostic();
237 emit_unclosed_delims(&mut self.unclosed_delims, diag);
243 frame: TokenCursorFrame,
244 stack: Vec<TokenCursorFrame>,
248 struct TokenCursorFrame {
249 delim: token::DelimToken,
252 tree_cursor: tokenstream::Cursor,
254 last_token: LastToken,
257 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
258 /// by the parser, and then that's transitively used to record the tokens that
259 /// each parse AST item is created with.
261 /// Right now this has two states, either collecting tokens or not collecting
262 /// tokens. If we're collecting tokens we just save everything off into a local
263 /// `Vec`. This should eventually though likely save tokens from the original
264 /// token stream and just use slicing of token streams to avoid creation of a
265 /// whole new vector.
267 /// The second state is where we're passively not recording tokens, but the last
268 /// token is still tracked for when we want to start recording tokens. This
269 /// "last token" means that when we start recording tokens we'll want to ensure
270 /// that this, the first token, is included in the output.
272 /// You can find some more example usage of this in the `collect_tokens` method
276 Collecting(Vec<TreeAndJoint>),
277 Was(Option<TreeAndJoint>),
280 impl TokenCursorFrame {
281 fn new(sp: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
285 open_delim: delim == token::NoDelim,
286 tree_cursor: tts.clone().into_trees(),
287 close_delim: delim == token::NoDelim,
288 last_token: LastToken::Was(None),
294 fn next(&mut self) -> TokenAndSpan {
296 let tree = if !self.frame.open_delim {
297 self.frame.open_delim = true;
298 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
299 } else if let Some(tree) = self.frame.tree_cursor.next() {
301 } else if !self.frame.close_delim {
302 self.frame.close_delim = true;
303 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
304 } else if let Some(frame) = self.stack.pop() {
308 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
311 match self.frame.last_token {
312 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
313 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
317 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
318 TokenTree::Delimited(sp, delim, tts) => {
319 let frame = TokenCursorFrame::new(sp, delim, &tts);
320 self.stack.push(mem::replace(&mut self.frame, frame));
326 fn next_desugared(&mut self) -> TokenAndSpan {
327 let (sp, name) = match self.next() {
328 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
332 let stripped = strip_doc_comment_decoration(&name.as_str());
334 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
335 // required to wrap the text.
336 let mut num_of_hashes = 0;
338 for ch in stripped.chars() {
341 '#' if count > 0 => count + 1,
344 num_of_hashes = cmp::max(num_of_hashes, count);
347 let delim_span = DelimSpan::from_single(sp);
348 let body = TokenTree::Delimited(
351 [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
352 TokenTree::Token(sp, token::Eq),
353 TokenTree::Token(sp, token::Literal(
354 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))
356 .iter().cloned().collect::<TokenStream>().into(),
359 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
362 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
363 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
364 .iter().cloned().collect::<TokenStream>().into()
366 [TokenTree::Token(sp, token::Pound), body]
367 .iter().cloned().collect::<TokenStream>().into()
375 #[derive(Clone, PartialEq)]
376 crate enum TokenType {
378 Keyword(keywords::Keyword),
388 fn to_string(&self) -> String {
390 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
391 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
392 TokenType::Operator => "an operator".to_string(),
393 TokenType::Lifetime => "lifetime".to_string(),
394 TokenType::Ident => "identifier".to_string(),
395 TokenType::Path => "path".to_string(),
396 TokenType::Type => "type".to_string(),
397 TokenType::Const => "const".to_string(),
402 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
403 /// `IDENT<<u8 as Trait>::AssocTy>`.
405 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
406 /// that `IDENT` is not the ident of a fn trait.
407 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
408 t == &token::ModSep || t == &token::Lt ||
409 t == &token::BinOp(token::Shl)
412 /// Information about the path to a module.
413 pub struct ModulePath {
416 pub result: Result<ModulePathSuccess, Error>,
419 pub struct ModulePathSuccess {
421 pub directory_ownership: DirectoryOwnership,
426 FileNotFoundForModule {
428 default_path: String,
429 secondary_path: String,
434 default_path: String,
435 secondary_path: String,
438 InclusiveRangeWithNoEnd,
442 fn span_err<S: Into<MultiSpan>>(self,
444 handler: &errors::Handler) -> DiagnosticBuilder<'_> {
446 Error::FileNotFoundForModule { ref mod_name,
450 let mut err = struct_span_err!(handler, sp, E0583,
451 "file not found for module `{}`", mod_name);
452 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
458 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
459 let mut err = struct_span_err!(handler, sp, E0584,
460 "file for module `{}` found at both {} and {}",
464 err.help("delete or rename one of them to remove the ambiguity");
467 Error::UselessDocComment => {
468 let mut err = struct_span_err!(handler, sp, E0585,
469 "found a documentation comment that doesn't document anything");
470 err.help("doc comments must come before what they document, maybe a comment was \
471 intended with `//`?");
474 Error::InclusiveRangeWithNoEnd => {
475 let mut err = struct_span_err!(handler, sp, E0586,
476 "inclusive range with no end");
477 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
487 AttributesParsed(ThinVec<Attribute>),
488 AlreadyParsed(P<Expr>),
491 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
492 fn from(o: Option<ThinVec<Attribute>>) -> Self {
493 if let Some(attrs) = o {
494 LhsExpr::AttributesParsed(attrs)
496 LhsExpr::NotYetParsed
501 impl From<P<Expr>> for LhsExpr {
502 fn from(expr: P<Expr>) -> Self {
503 LhsExpr::AlreadyParsed(expr)
507 /// Creates a placeholder argument.
508 fn dummy_arg(span: Span) -> Arg {
509 let ident = Ident::new(keywords::Invalid.name(), span);
511 id: ast::DUMMY_NODE_ID,
512 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
518 id: ast::DUMMY_NODE_ID
520 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal }
523 #[derive(Copy, Clone, Debug)]
524 enum TokenExpectType {
529 impl<'a> Parser<'a> {
530 pub fn new(sess: &'a ParseSess,
532 directory: Option<Directory<'a>>,
533 recurse_into_file_modules: bool,
534 desugar_doc_comments: bool)
536 let mut parser = Parser {
538 token: token::Whitespace,
539 span: syntax_pos::DUMMY_SP,
540 prev_span: syntax_pos::DUMMY_SP,
542 prev_token_kind: PrevTokenKind::Other,
543 restrictions: Restrictions::empty(),
544 recurse_into_file_modules,
545 directory: Directory {
546 path: Cow::from(PathBuf::new()),
547 ownership: DirectoryOwnership::Owned { relative: None }
549 root_module_name: None,
550 expected_tokens: Vec::new(),
551 token_cursor: TokenCursor {
552 frame: TokenCursorFrame::new(
559 desugar_doc_comments,
561 unmatched_angle_bracket_count: 0,
562 max_angle_bracket_count: 0,
563 unclosed_delims: Vec::new(),
564 last_unexpected_token_span: None,
567 let tok = parser.next_tok();
568 parser.token = tok.tok;
569 parser.span = tok.sp;
571 if let Some(directory) = directory {
572 parser.directory = directory;
573 } else if !parser.span.is_dummy() {
574 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
576 parser.directory.path = Cow::from(path);
580 parser.process_potential_macro_variable();
584 fn next_tok(&mut self) -> TokenAndSpan {
585 let mut next = if self.desugar_doc_comments {
586 self.token_cursor.next_desugared()
588 self.token_cursor.next()
590 if next.sp.is_dummy() {
591 // Tweak the location for better diagnostics, but keep syntactic context intact.
592 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
597 /// Converts the current token to a string using `self`'s reader.
598 pub fn this_token_to_string(&self) -> String {
599 pprust::token_to_string(&self.token)
602 fn token_descr(&self) -> Option<&'static str> {
603 Some(match &self.token {
604 t if t.is_special_ident() => "reserved identifier",
605 t if t.is_used_keyword() => "keyword",
606 t if t.is_unused_keyword() => "reserved keyword",
607 token::DocComment(..) => "doc comment",
612 fn this_token_descr(&self) -> String {
613 if let Some(prefix) = self.token_descr() {
614 format!("{} `{}`", prefix, self.this_token_to_string())
616 format!("`{}`", self.this_token_to_string())
620 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
621 let token_str = pprust::token_to_string(t);
622 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
625 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
626 match self.expect_one_of(&[], &[]) {
628 Ok(_) => unreachable!(),
632 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
633 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, bool /* recovered */> {
634 if self.expected_tokens.is_empty() {
635 if self.token == *t {
639 let token_str = pprust::token_to_string(t);
640 let this_token_str = self.this_token_descr();
641 let mut err = self.fatal(&format!("expected `{}`, found {}",
645 let sp = if self.token == token::Token::Eof {
646 // EOF, don't want to point at the following char, but rather the last token
649 self.sess.source_map().next_point(self.prev_span)
651 let label_exp = format!("expected `{}`", token_str);
652 match self.recover_closing_delimiter(&[t.clone()], err) {
655 return Ok(recovered);
658 let cm = self.sess.source_map();
659 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
660 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
661 // When the spans are in the same line, it means that the only content
662 // between them is whitespace, point only at the found token.
663 err.span_label(self.span, label_exp);
666 err.span_label(sp, label_exp);
667 err.span_label(self.span, "unexpected token");
673 self.expect_one_of(slice::from_ref(t), &[])
677 fn recover_closing_delimiter(
679 tokens: &[token::Token],
680 mut err: DiagnosticBuilder<'a>,
681 ) -> PResult<'a, bool> {
683 // we want to use the last closing delim that would apply
684 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
685 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
686 && Some(self.span) > unmatched.unclosed_span
693 // Recover and assume that the detected unclosed delimiter was meant for
694 // this location. Emit the diagnostic and act as if the delimiter was
695 // present for the parser's sake.
697 // Don't attempt to recover from this unclosed delimiter more than once.
698 let unmatched = self.unclosed_delims.remove(pos);
699 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
701 // We want to suggest the inclusion of the closing delimiter where it makes
702 // the most sense, which is immediately after the last token:
707 // | help: `)` may belong here (FIXME: #58270)
709 // unclosed delimiter
710 if let Some(sp) = unmatched.unclosed_span {
711 err.span_label(sp, "unclosed delimiter");
713 err.span_suggestion_short(
714 self.sess.source_map().next_point(self.prev_span),
715 &format!("{} may belong here", delim.to_string()),
717 Applicability::MaybeIncorrect,
720 self.expected_tokens.clear(); // reduce errors
727 /// Expect next token to be edible or inedible token. If edible,
728 /// then consume it; if inedible, then return without consuming
729 /// anything. Signal a fatal error if next token is unexpected.
730 pub fn expect_one_of(
732 edible: &[token::Token],
733 inedible: &[token::Token],
734 ) -> PResult<'a, bool /* recovered */> {
735 fn tokens_to_string(tokens: &[TokenType]) -> String {
736 let mut i = tokens.iter();
737 // This might be a sign we need a connect method on Iterator.
739 .map_or(String::new(), |t| t.to_string());
740 i.enumerate().fold(b, |mut b, (i, a)| {
741 if tokens.len() > 2 && i == tokens.len() - 2 {
743 } else if tokens.len() == 2 && i == tokens.len() - 2 {
748 b.push_str(&a.to_string());
752 if edible.contains(&self.token) {
755 } else if inedible.contains(&self.token) {
756 // leave it in the input
758 } else if self.last_unexpected_token_span == Some(self.span) {
761 let mut expected = edible.iter()
762 .map(|x| TokenType::Token(x.clone()))
763 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
764 .chain(self.expected_tokens.iter().cloned())
765 .collect::<Vec<_>>();
766 expected.sort_by_cached_key(|x| x.to_string());
768 let expect = tokens_to_string(&expected[..]);
769 let actual = self.this_token_to_string();
770 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
771 let short_expect = if expected.len() > 6 {
772 format!("{} possible tokens", expected.len())
776 (format!("expected one of {}, found `{}`", expect, actual),
777 (self.sess.source_map().next_point(self.prev_span),
778 format!("expected one of {} here", short_expect)))
779 } else if expected.is_empty() {
780 (format!("unexpected token: `{}`", actual),
781 (self.prev_span, "unexpected token after this".to_string()))
783 (format!("expected {}, found `{}`", expect, actual),
784 (self.sess.source_map().next_point(self.prev_span),
785 format!("expected {} here", expect)))
787 self.last_unexpected_token_span = Some(self.span);
788 let mut err = self.fatal(&msg_exp);
789 if self.token.is_ident_named("and") {
790 err.span_suggestion_short(
792 "use `&&` instead of `and` for the boolean operator",
794 Applicability::MaybeIncorrect,
797 if self.token.is_ident_named("or") {
798 err.span_suggestion_short(
800 "use `||` instead of `or` for the boolean operator",
802 Applicability::MaybeIncorrect,
805 let sp = if self.token == token::Token::Eof {
806 // This is EOF, don't want to point at the following char, but rather the last token
811 match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt {
812 TokenType::Token(t) => Some(t.clone()),
814 }).collect::<Vec<_>>(), err) {
817 return Ok(recovered);
821 let is_semi_suggestable = expected.iter().any(|t| match t {
822 TokenType::Token(token::Semi) => true, // we expect a `;` here
824 }) && ( // a `;` would be expected before the current keyword
825 self.token.is_keyword(keywords::Break) ||
826 self.token.is_keyword(keywords::Continue) ||
827 self.token.is_keyword(keywords::For) ||
828 self.token.is_keyword(keywords::If) ||
829 self.token.is_keyword(keywords::Let) ||
830 self.token.is_keyword(keywords::Loop) ||
831 self.token.is_keyword(keywords::Match) ||
832 self.token.is_keyword(keywords::Return) ||
833 self.token.is_keyword(keywords::While)
835 let cm = self.sess.source_map();
836 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
837 (Ok(ref a), Ok(ref b)) if a.line != b.line && is_semi_suggestable => {
838 // The spans are in different lines, expected `;` and found `let` or `return`.
839 // High likelihood that it is only a missing `;`.
840 err.span_suggestion_short(
842 "a semicolon may be missing here",
844 Applicability::MaybeIncorrect,
849 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
850 // When the spans are in the same line, it means that the only content between
851 // them is whitespace, point at the found token in that case:
853 // X | () => { syntax error };
854 // | ^^^^^ expected one of 8 possible tokens here
856 // instead of having:
858 // X | () => { syntax error };
859 // | -^^^^^ unexpected token
861 // | expected one of 8 possible tokens here
862 err.span_label(self.span, label_exp);
864 _ if self.prev_span == syntax_pos::DUMMY_SP => {
865 // Account for macro context where the previous span might not be
866 // available to avoid incorrect output (#54841).
867 err.span_label(self.span, "unexpected token");
870 err.span_label(sp, label_exp);
871 err.span_label(self.span, "unexpected token");
878 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
879 fn interpolated_or_expr_span(&self,
880 expr: PResult<'a, P<Expr>>)
881 -> PResult<'a, (Span, P<Expr>)> {
883 if self.prev_token_kind == PrevTokenKind::Interpolated {
891 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
892 let mut err = self.struct_span_err(self.span,
893 &format!("expected identifier, found {}",
894 self.this_token_descr()));
895 if let token::Ident(ident, false) = &self.token {
896 if ident.is_raw_guess() {
899 "you can escape reserved keywords to use them as identifiers",
900 format!("r#{}", ident),
901 Applicability::MaybeIncorrect,
905 if let Some(token_descr) = self.token_descr() {
906 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
908 err.span_label(self.span, "expected identifier");
909 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
914 Applicability::MachineApplicable,
921 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
922 self.parse_ident_common(true)
925 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
927 token::Ident(ident, _) => {
928 if self.token.is_reserved_ident() {
929 let mut err = self.expected_ident_found();
936 let span = self.span;
938 Ok(Ident::new(ident.name, span))
941 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
942 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
944 self.expected_ident_found()
950 /// Checks if the next token is `tok`, and returns `true` if so.
952 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
954 crate fn check(&mut self, tok: &token::Token) -> bool {
955 let is_present = self.token == *tok;
956 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
960 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
961 pub fn eat(&mut self, tok: &token::Token) -> bool {
962 let is_present = self.check(tok);
963 if is_present { self.bump() }
967 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
968 self.expected_tokens.push(TokenType::Keyword(kw));
969 self.token.is_keyword(kw)
972 /// If the next token is the given keyword, eats it and returns
973 /// `true`. Otherwise, returns `false`.
974 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
975 if self.check_keyword(kw) {
983 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
984 if self.token.is_keyword(kw) {
992 /// If the given word is not a keyword, signals an error.
993 /// If the next token is not the given word, signals an error.
994 /// Otherwise, eats it.
995 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
996 if !self.eat_keyword(kw) {
1003 fn check_ident(&mut self) -> bool {
1004 if self.token.is_ident() {
1007 self.expected_tokens.push(TokenType::Ident);
1012 fn check_path(&mut self) -> bool {
1013 if self.token.is_path_start() {
1016 self.expected_tokens.push(TokenType::Path);
1021 fn check_type(&mut self) -> bool {
1022 if self.token.can_begin_type() {
1025 self.expected_tokens.push(TokenType::Type);
1030 fn check_const_arg(&mut self) -> bool {
1031 if self.token.can_begin_const_arg() {
1034 self.expected_tokens.push(TokenType::Const);
1039 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
1040 /// and continues. If a `+` is not seen, returns `false`.
1042 /// This is used when token-splitting `+=` into `+`.
1043 /// See issue #47856 for an example of when this may occur.
1044 fn eat_plus(&mut self) -> bool {
1045 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1047 token::BinOp(token::Plus) => {
1051 token::BinOpEq(token::Plus) => {
1052 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1053 self.bump_with(token::Eq, span);
1061 /// Checks to see if the next token is either `+` or `+=`.
1062 /// Otherwise returns `false`.
1063 fn check_plus(&mut self) -> bool {
1064 if self.token.is_like_plus() {
1068 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1073 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
1074 /// `&` and continues. If an `&` is not seen, signals an error.
1075 fn expect_and(&mut self) -> PResult<'a, ()> {
1076 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
1078 token::BinOp(token::And) => {
1083 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1084 Ok(self.bump_with(token::BinOp(token::And), span))
1086 _ => self.unexpected()
1090 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
1091 /// `|` and continues. If an `|` is not seen, signals an error.
1092 fn expect_or(&mut self) -> PResult<'a, ()> {
1093 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
1095 token::BinOp(token::Or) => {
1100 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1101 Ok(self.bump_with(token::BinOp(token::Or), span))
1103 _ => self.unexpected()
1107 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
1109 None => {/* everything ok */}
1111 let text = suf.as_str();
1112 if text.is_empty() {
1113 self.span_bug(sp, "found empty literal suffix in Some")
1115 let mut err = if kind == "a tuple index" &&
1116 ["i32", "u32", "isize", "usize"].contains(&text.to_string().as_str())
1118 // #59553: warn instead of reject out of hand to allow the fix to percolate
1119 // through the ecosystem when people fix their macros
1120 let mut err = self.struct_span_warn(
1122 &format!("suffixes on {} are invalid", kind),
1125 "`{}` is *temporarily* accepted on tuple index fields as it was \
1126 incorrectly accepted on stable for a few releases",
1130 "on proc macros, you'll want to use `syn::Index::from` or \
1131 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1132 to tuple field access",
1135 "for more context, see https://github.com/rust-lang/rust/issues/60210",
1139 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1141 err.span_label(sp, format!("invalid suffix `{}`", text));
1147 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
1148 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
1149 /// and continue. If a `<` is not seen, returns false.
1151 /// This is meant to be used when parsing generics on a path to get the
1153 fn eat_lt(&mut self) -> bool {
1154 self.expected_tokens.push(TokenType::Token(token::Lt));
1155 let ate = match self.token {
1160 token::BinOp(token::Shl) => {
1161 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1162 self.bump_with(token::Lt, span);
1166 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1167 self.bump_with(token::BinOp(token::Minus), span);
1174 // See doc comment for `unmatched_angle_bracket_count`.
1175 self.unmatched_angle_bracket_count += 1;
1176 self.max_angle_bracket_count += 1;
1177 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
1183 fn expect_lt(&mut self) -> PResult<'a, ()> {
1191 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
1192 /// with a single `>` and continues. If a `>` is not seen, signals an error.
1193 fn expect_gt(&mut self) -> PResult<'a, ()> {
1194 self.expected_tokens.push(TokenType::Token(token::Gt));
1195 let ate = match self.token {
1200 token::BinOp(token::Shr) => {
1201 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1202 Some(self.bump_with(token::Gt, span))
1204 token::BinOpEq(token::Shr) => {
1205 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1206 Some(self.bump_with(token::Ge, span))
1209 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1210 Some(self.bump_with(token::Eq, span))
1217 // See doc comment for `unmatched_angle_bracket_count`.
1218 if self.unmatched_angle_bracket_count > 0 {
1219 self.unmatched_angle_bracket_count -= 1;
1220 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1225 None => self.unexpected(),
1229 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
1230 /// passes through any errors encountered. Used for error recovery.
1231 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1232 let handler = self.diagnostic();
1234 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1236 TokenExpectType::Expect,
1237 |p| Ok(p.parse_token_tree())) {
1238 handler.cancel(err);
1242 /// Parses a sequence, 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_end<T, F>(&mut self,
1249 -> PResult<'a, Vec<T>> where
1250 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1252 let (val, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1259 /// Parses a sequence, not including the closing delimiter. The function
1260 /// `f` must consume tokens until reaching the next separator or
1261 /// closing bracket.
1262 pub fn parse_seq_to_before_end<T, F>(
1267 ) -> PResult<'a, (Vec<T>, bool)>
1268 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1270 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1273 fn parse_seq_to_before_tokens<T, F>(
1275 kets: &[&token::Token],
1277 expect: TokenExpectType,
1279 ) -> PResult<'a, (Vec<T>, bool /* recovered */)>
1280 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1282 let mut first = true;
1283 let mut recovered = false;
1285 while !kets.iter().any(|k| {
1287 TokenExpectType::Expect => self.check(k),
1288 TokenExpectType::NoExpect => self.token == **k,
1292 token::CloseDelim(..) | token::Eof => break,
1295 if let Some(ref t) = sep.sep {
1299 match self.expect(t) {
1306 // Attempt to keep parsing if it was a similar separator
1307 if let Some(ref tokens) = t.similar_tokens() {
1308 if tokens.contains(&self.token) {
1313 // Attempt to keep parsing if it was an omitted separator
1328 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1330 TokenExpectType::Expect => self.check(k),
1331 TokenExpectType::NoExpect => self.token == **k,
1344 /// Parses a sequence, including the closing delimiter. The function
1345 /// `f` must consume tokens until reaching the next separator or
1346 /// closing bracket.
1347 fn parse_unspanned_seq<T, F>(
1353 ) -> PResult<'a, Vec<T>> where
1354 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1357 let (result, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1364 /// Advance the parser by one token
1365 pub fn bump(&mut self) {
1366 if self.prev_token_kind == PrevTokenKind::Eof {
1367 // Bumping after EOF is a bad sign, usually an infinite loop.
1368 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1371 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1373 // Record last token kind for possible error recovery.
1374 self.prev_token_kind = match self.token {
1375 token::DocComment(..) => PrevTokenKind::DocComment,
1376 token::Comma => PrevTokenKind::Comma,
1377 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1378 token::Interpolated(..) => PrevTokenKind::Interpolated,
1379 token::Eof => PrevTokenKind::Eof,
1380 token::Ident(..) => PrevTokenKind::Ident,
1381 _ => PrevTokenKind::Other,
1384 let next = self.next_tok();
1385 self.span = next.sp;
1386 self.token = next.tok;
1387 self.expected_tokens.clear();
1388 // check after each token
1389 self.process_potential_macro_variable();
1392 /// Advance the parser using provided token as a next one. Use this when
1393 /// consuming a part of a token. For example a single `<` from `<<`.
1394 fn bump_with(&mut self, next: token::Token, span: Span) {
1395 self.prev_span = self.span.with_hi(span.lo());
1396 // It would be incorrect to record the kind of the current token, but
1397 // fortunately for tokens currently using `bump_with`, the
1398 // prev_token_kind will be of no use anyway.
1399 self.prev_token_kind = PrevTokenKind::Other;
1402 self.expected_tokens.clear();
1405 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1406 F: FnOnce(&token::Token) -> R,
1409 return f(&self.token)
1412 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1413 Some(tree) => match tree {
1414 TokenTree::Token(_, tok) => tok,
1415 TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim),
1417 None => token::CloseDelim(self.token_cursor.frame.delim),
1421 fn look_ahead_span(&self, dist: usize) -> Span {
1426 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1427 Some(TokenTree::Token(span, _)) => span,
1428 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1429 None => self.look_ahead_span(dist - 1),
1432 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1433 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1435 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1436 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1438 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1439 err.span_err(sp, self.diagnostic())
1441 fn bug(&self, m: &str) -> ! {
1442 self.sess.span_diagnostic.span_bug(self.span, m)
1444 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1445 self.sess.span_diagnostic.span_err(sp, m)
1447 crate fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1448 self.sess.span_diagnostic.struct_span_err(sp, m)
1450 fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1451 self.sess.span_diagnostic.struct_span_warn(sp, m)
1453 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1454 self.sess.span_diagnostic.span_bug(sp, m)
1457 fn cancel(&self, err: &mut DiagnosticBuilder<'_>) {
1458 self.sess.span_diagnostic.cancel(err)
1461 crate fn diagnostic(&self) -> &'a errors::Handler {
1462 &self.sess.span_diagnostic
1465 /// Is the current token one of the keywords that signals a bare function type?
1466 fn token_is_bare_fn_keyword(&mut self) -> bool {
1467 self.check_keyword(keywords::Fn) ||
1468 self.check_keyword(keywords::Unsafe) ||
1469 self.check_keyword(keywords::Extern)
1472 /// Parses a `TyKind::BareFn` type.
1473 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1476 [unsafe] [extern "ABI"] fn (S) -> T
1486 let unsafety = self.parse_unsafety();
1487 let abi = if self.eat_keyword(keywords::Extern) {
1488 self.parse_opt_abi()?.unwrap_or(Abi::C)
1493 self.expect_keyword(keywords::Fn)?;
1494 let (inputs, c_variadic) = self.parse_fn_args(false, true)?;
1495 let ret_ty = self.parse_ret_ty(false)?;
1496 let decl = P(FnDecl {
1501 Ok(TyKind::BareFn(P(BareFnTy {
1509 /// Parses asyncness: `async` or nothing.
1510 fn parse_asyncness(&mut self) -> IsAsync {
1511 if self.eat_keyword(keywords::Async) {
1513 closure_id: ast::DUMMY_NODE_ID,
1514 return_impl_trait_id: ast::DUMMY_NODE_ID,
1515 arguments: Vec::new(),
1522 /// Parses unsafety: `unsafe` or nothing.
1523 fn parse_unsafety(&mut self) -> Unsafety {
1524 if self.eat_keyword(keywords::Unsafe) {
1531 /// Parses the items in a trait declaration.
1532 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1533 maybe_whole!(self, NtTraitItem, |x| x);
1534 let attrs = self.parse_outer_attributes()?;
1535 let mut unclosed_delims = vec![];
1536 let (mut item, tokens) = self.collect_tokens(|this| {
1537 let item = this.parse_trait_item_(at_end, attrs);
1538 unclosed_delims.append(&mut this.unclosed_delims);
1541 self.unclosed_delims.append(&mut unclosed_delims);
1542 // See `parse_item` for why this clause is here.
1543 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1544 item.tokens = Some(tokens);
1549 fn parse_trait_item_(&mut self,
1551 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1554 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1555 self.parse_trait_item_assoc_ty()?
1556 } else if self.is_const_item() {
1557 self.expect_keyword(keywords::Const)?;
1558 let ident = self.parse_ident()?;
1559 self.expect(&token::Colon)?;
1560 let ty = self.parse_ty()?;
1561 let default = if self.eat(&token::Eq) {
1562 let expr = self.parse_expr()?;
1563 self.expect(&token::Semi)?;
1566 self.expect(&token::Semi)?;
1569 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1570 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1571 // trait item macro.
1572 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1574 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
1576 let ident = self.parse_ident()?;
1577 let mut generics = self.parse_generics()?;
1579 let mut decl = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1580 // This is somewhat dubious; We don't want to allow
1581 // argument names to be left off if there is a
1584 // We don't allow argument names to be left off in edition 2018.
1585 p.parse_arg_general(p.span.rust_2018(), true, false)
1587 generics.where_clause = self.parse_where_clause()?;
1588 self.construct_async_arguments(&mut asyncness, &mut decl);
1590 let sig = ast::MethodSig {
1600 let body = match self.token {
1604 debug!("parse_trait_methods(): parsing required method");
1607 token::OpenDelim(token::Brace) => {
1608 debug!("parse_trait_methods(): parsing provided method");
1610 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1611 attrs.extend(inner_attrs.iter().cloned());
1614 token::Interpolated(ref nt) => {
1616 token::NtBlock(..) => {
1618 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1619 attrs.extend(inner_attrs.iter().cloned());
1623 let token_str = self.this_token_descr();
1624 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1626 err.span_label(self.span, "expected `;` or `{`");
1632 let token_str = self.this_token_descr();
1633 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1635 err.span_label(self.span, "expected `;` or `{`");
1639 (ident, ast::TraitItemKind::Method(sig, body), generics)
1643 id: ast::DUMMY_NODE_ID,
1648 span: lo.to(self.prev_span),
1653 /// Parses an optional return type `[ -> TY ]` in a function declaration.
1654 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1655 if self.eat(&token::RArrow) {
1656 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?))
1658 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1663 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1664 self.parse_ty_common(true, true, false)
1667 /// Parses a type in restricted contexts where `+` is not permitted.
1669 /// Example 1: `&'a TYPE`
1670 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1671 /// Example 2: `value1 as TYPE + value2`
1672 /// `+` is prohibited to avoid interactions with expression grammar.
1673 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1674 self.parse_ty_common(false, true, false)
1677 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool,
1678 allow_c_variadic: bool) -> PResult<'a, P<Ty>> {
1679 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
1680 maybe_whole!(self, NtTy, |x| x);
1683 let mut impl_dyn_multi = false;
1684 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1685 // `(TYPE)` is a parenthesized type.
1686 // `(TYPE,)` is a tuple with a single field of type TYPE.
1687 let mut ts = vec![];
1688 let mut last_comma = false;
1689 while self.token != token::CloseDelim(token::Paren) {
1690 ts.push(self.parse_ty()?);
1691 if self.eat(&token::Comma) {
1698 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1699 self.expect(&token::CloseDelim(token::Paren))?;
1701 if ts.len() == 1 && !last_comma {
1702 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1703 let maybe_bounds = allow_plus && self.token.is_like_plus();
1705 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1706 TyKind::Path(None, ref path) if maybe_bounds => {
1707 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1709 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1710 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1711 let path = match bounds[0] {
1712 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1713 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1715 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1718 _ => TyKind::Paren(P(ty))
1723 } else if self.eat(&token::Not) {
1726 } else if self.eat(&token::BinOp(token::Star)) {
1728 TyKind::Ptr(self.parse_ptr()?)
1729 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1731 let t = self.parse_ty()?;
1732 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1733 let t = match self.maybe_parse_fixed_length_of_vec()? {
1734 None => TyKind::Slice(t),
1735 Some(length) => TyKind::Array(t, AnonConst {
1736 id: ast::DUMMY_NODE_ID,
1740 self.expect(&token::CloseDelim(token::Bracket))?;
1742 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1745 self.parse_borrowed_pointee()?
1746 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1748 // In order to not be ambiguous, the type must be surrounded by parens.
1749 self.expect(&token::OpenDelim(token::Paren))?;
1751 id: ast::DUMMY_NODE_ID,
1752 value: self.parse_expr()?,
1754 self.expect(&token::CloseDelim(token::Paren))?;
1756 } else if self.eat_keyword(keywords::Underscore) {
1757 // A type to be inferred `_`
1759 } else if self.token_is_bare_fn_keyword() {
1760 // Function pointer type
1761 self.parse_ty_bare_fn(Vec::new())?
1762 } else if self.check_keyword(keywords::For) {
1763 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1764 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1765 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1767 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1768 if self.token_is_bare_fn_keyword() {
1769 self.parse_ty_bare_fn(lifetime_defs)?
1771 let path = self.parse_path(PathStyle::Type)?;
1772 let parse_plus = allow_plus && self.check_plus();
1773 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1775 } else if self.eat_keyword(keywords::Impl) {
1776 // Always parse bounds greedily for better error recovery.
1777 let bounds = self.parse_generic_bounds(None)?;
1778 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1779 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1780 } else if self.check_keyword(keywords::Dyn) &&
1781 (self.span.rust_2018() ||
1782 self.look_ahead(1, |t| t.can_begin_bound() &&
1783 !can_continue_type_after_non_fn_ident(t))) {
1784 self.bump(); // `dyn`
1785 // Always parse bounds greedily for better error recovery.
1786 let bounds = self.parse_generic_bounds(None)?;
1787 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1788 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1789 } else if self.check(&token::Question) ||
1790 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1791 // Bound list (trait object type)
1792 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
1793 TraitObjectSyntax::None)
1794 } else if self.eat_lt() {
1796 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1797 TyKind::Path(Some(qself), path)
1798 } else if self.token.is_path_start() {
1800 let path = self.parse_path(PathStyle::Type)?;
1801 if self.eat(&token::Not) {
1802 // Macro invocation in type position
1803 let (delim, tts) = self.expect_delimited_token_tree()?;
1804 let node = Mac_ { path, tts, delim };
1805 TyKind::Mac(respan(lo.to(self.prev_span), node))
1807 // Just a type path or bound list (trait object type) starting with a trait.
1809 // `Trait1 + Trait2 + 'a`
1810 if allow_plus && self.check_plus() {
1811 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1813 TyKind::Path(None, path)
1816 } else if self.check(&token::DotDotDot) {
1817 if allow_c_variadic {
1818 self.eat(&token::DotDotDot);
1821 return Err(self.fatal(
1822 "only foreign functions are allowed to be C-variadic"
1826 let msg = format!("expected type, found {}", self.this_token_descr());
1827 return Err(self.fatal(&msg));
1830 let span = lo.to(self.prev_span);
1831 let ty = P(Ty { node, span, id: ast::DUMMY_NODE_ID });
1833 // Try to recover from use of `+` with incorrect priority.
1834 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1835 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1836 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
1839 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1840 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1841 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1842 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1844 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1845 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
1847 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1850 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1851 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1852 let mutbl = self.parse_mutability();
1853 let ty = self.parse_ty_no_plus()?;
1854 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1857 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1858 let mutbl = if self.eat_keyword(keywords::Mut) {
1860 } else if self.eat_keyword(keywords::Const) {
1861 Mutability::Immutable
1863 let span = self.prev_span;
1864 let msg = "expected mut or const in raw pointer type";
1865 self.struct_span_err(span, msg)
1866 .span_label(span, msg)
1867 .help("use `*mut T` or `*const T` as appropriate")
1869 Mutability::Immutable
1871 let t = self.parse_ty_no_plus()?;
1872 Ok(MutTy { ty: t, mutbl: mutbl })
1875 fn is_named_argument(&mut self) -> bool {
1876 let offset = match self.token {
1877 token::Interpolated(ref nt) => match **nt {
1878 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1881 token::BinOp(token::And) | token::AndAnd => 1,
1882 _ if self.token.is_keyword(keywords::Mut) => 1,
1886 self.look_ahead(offset, |t| t.is_ident()) &&
1887 self.look_ahead(offset + 1, |t| t == &token::Colon)
1890 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1892 fn eat_incorrect_doc_comment(&mut self, applied_to: &str) {
1893 if let token::DocComment(_) = self.token {
1894 let mut err = self.diagnostic().struct_span_err(
1896 &format!("documentation comments cannot be applied to {}", applied_to),
1898 err.span_label(self.span, "doc comments are not allowed here");
1901 } else if self.token == token::Pound && self.look_ahead(1, |t| {
1902 *t == token::OpenDelim(token::Bracket)
1905 // Skip every token until next possible arg.
1906 while self.token != token::CloseDelim(token::Bracket) {
1909 let sp = lo.to(self.span);
1911 let mut err = self.diagnostic().struct_span_err(
1913 &format!("attributes cannot be applied to {}", applied_to),
1915 err.span_label(sp, "attributes are not allowed here");
1920 /// This version of parse arg doesn't necessarily require identifier names.
1921 fn parse_arg_general(&mut self, require_name: bool, is_trait_item: bool,
1922 allow_c_variadic: bool) -> PResult<'a, Arg> {
1923 maybe_whole!(self, NtArg, |x| x);
1925 if let Ok(Some(_)) = self.parse_self_arg() {
1926 let mut err = self.struct_span_err(self.prev_span,
1927 "unexpected `self` argument in function");
1928 err.span_label(self.prev_span,
1929 "`self` is only valid as the first argument of an associated function");
1933 let (pat, ty) = if require_name || self.is_named_argument() {
1934 debug!("parse_arg_general parse_pat (require_name:{})",
1936 self.eat_incorrect_doc_comment("method arguments");
1937 let pat = self.parse_pat(Some("argument name"))?;
1939 if let Err(mut err) = self.expect(&token::Colon) {
1940 // If we find a pattern followed by an identifier, it could be an (incorrect)
1941 // C-style parameter declaration.
1942 if self.check_ident() && self.look_ahead(1, |t| {
1943 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1945 let ident = self.parse_ident().unwrap();
1946 let span = pat.span.with_hi(ident.span.hi());
1948 err.span_suggestion(
1950 "declare the type after the parameter binding",
1951 String::from("<identifier>: <type>"),
1952 Applicability::HasPlaceholders,
1954 } else if require_name && is_trait_item {
1955 if let PatKind::Ident(_, ident, _) = pat.node {
1956 err.span_suggestion(
1958 "explicitly ignore parameter",
1959 format!("_: {}", ident),
1960 Applicability::MachineApplicable,
1964 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1970 self.eat_incorrect_doc_comment("a method argument's type");
1971 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
1973 debug!("parse_arg_general ident_to_pat");
1974 let parser_snapshot_before_ty = self.clone();
1975 self.eat_incorrect_doc_comment("a method argument's type");
1976 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
1977 if ty.is_ok() && self.token != token::Comma &&
1978 self.token != token::CloseDelim(token::Paren) {
1979 // This wasn't actually a type, but a pattern looking like a type,
1980 // so we are going to rollback and re-parse for recovery.
1981 ty = self.unexpected();
1985 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1987 id: ast::DUMMY_NODE_ID,
1988 node: PatKind::Ident(
1989 BindingMode::ByValue(Mutability::Immutable), ident, None),
1995 // If this is a C-variadic argument and we hit an error, return the
1997 if self.token == token::DotDotDot {
2000 // Recover from attempting to parse the argument as a type without pattern.
2002 mem::replace(self, parser_snapshot_before_ty);
2003 let pat = self.parse_pat(Some("argument name"))?;
2004 self.expect(&token::Colon)?;
2005 let ty = self.parse_ty()?;
2007 let mut err = self.diagnostic().struct_span_err_with_code(
2009 "patterns aren't allowed in methods without bodies",
2010 DiagnosticId::Error("E0642".into()),
2012 err.span_suggestion_short(
2014 "give this argument a name or use an underscore to ignore it",
2016 Applicability::MachineApplicable,
2020 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2022 node: PatKind::Wild,
2024 id: ast::DUMMY_NODE_ID
2031 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal })
2034 /// Parses a single function argument.
2035 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
2036 self.parse_arg_general(true, false, false)
2039 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
2040 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
2041 let pat = self.parse_pat(Some("argument name"))?;
2042 let t = if self.eat(&token::Colon) {
2046 id: ast::DUMMY_NODE_ID,
2047 node: TyKind::Infer,
2048 span: self.prev_span,
2054 id: ast::DUMMY_NODE_ID,
2055 source: ast::ArgSource::Normal,
2059 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
2060 if self.eat(&token::Semi) {
2061 Ok(Some(self.parse_expr()?))
2067 /// Matches `token_lit = LIT_INTEGER | ...`.
2068 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
2069 let out = match self.token {
2070 token::Interpolated(ref nt) => match **nt {
2071 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
2072 ExprKind::Lit(ref lit) => { lit.node.clone() }
2073 _ => { return self.unexpected_last(&self.token); }
2075 _ => { return self.unexpected_last(&self.token); }
2077 token::Literal(lit, suf) => {
2078 let diag = Some((self.span, &self.sess.span_diagnostic));
2079 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
2083 self.expect_no_suffix(sp, &format!("a {}", lit.literal_name()), suf)
2088 token::Dot if self.look_ahead(1, |t| match t {
2089 token::Literal(parse::token::Lit::Integer(_) , _) => true,
2091 }) => { // recover from `let x = .4;`
2094 if let token::Literal(
2095 parse::token::Lit::Integer(val),
2098 let suffix = suffix.and_then(|s| {
2102 } else if s == "f64" {
2109 let sp = lo.to(self.prev_span);
2110 let mut err = self.diagnostic()
2111 .struct_span_err(sp, "float literals must have an integer part");
2112 err.span_suggestion(
2114 "must have an integer part",
2115 format!("0.{}{}", val, suffix),
2116 Applicability::MachineApplicable,
2119 return Ok(match suffix {
2120 "f32" => ast::LitKind::Float(val, ast::FloatTy::F32),
2121 "f64" => ast::LitKind::Float(val, ast::FloatTy::F64),
2122 _ => ast::LitKind::FloatUnsuffixed(val),
2128 _ => { return self.unexpected_last(&self.token); }
2135 /// Matches `lit = true | false | token_lit`.
2136 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
2138 let lit = if self.eat_keyword(keywords::True) {
2140 } else if self.eat_keyword(keywords::False) {
2141 LitKind::Bool(false)
2143 let lit = self.parse_lit_token()?;
2146 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
2149 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
2150 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
2151 maybe_whole_expr!(self);
2153 let minus_lo = self.span;
2154 let minus_present = self.eat(&token::BinOp(token::Minus));
2156 let literal = self.parse_lit()?;
2157 let hi = self.prev_span;
2158 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
2161 let minus_hi = self.prev_span;
2162 let unary = self.mk_unary(UnOp::Neg, expr);
2163 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
2169 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2171 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2172 let span = self.span;
2174 Ok(Ident::new(ident.name, span))
2176 _ => self.parse_ident(),
2180 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
2182 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
2183 let span = self.span;
2185 Ok(Ident::new(ident.name, span))
2187 _ => self.parse_ident(),
2191 /// Parses a qualified path.
2192 /// Assumes that the leading `<` has been parsed already.
2194 /// `qualified_path = <type [as trait_ref]>::path`
2199 /// `<T as U>::F::a<S>` (without disambiguator)
2200 /// `<T as U>::F::a::<S>` (with disambiguator)
2201 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2202 let lo = self.prev_span;
2203 let ty = self.parse_ty()?;
2205 // `path` will contain the prefix of the path up to the `>`,
2206 // if any (e.g., `U` in the `<T as U>::*` examples
2207 // above). `path_span` has the span of that path, or an empty
2208 // span in the case of something like `<T>::Bar`.
2209 let (mut path, path_span);
2210 if self.eat_keyword(keywords::As) {
2211 let path_lo = self.span;
2212 path = self.parse_path(PathStyle::Type)?;
2213 path_span = path_lo.to(self.prev_span);
2215 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2216 path_span = self.span.to(self.span);
2219 // See doc comment for `unmatched_angle_bracket_count`.
2220 self.expect(&token::Gt)?;
2221 if self.unmatched_angle_bracket_count > 0 {
2222 self.unmatched_angle_bracket_count -= 1;
2223 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
2226 self.expect(&token::ModSep)?;
2228 let qself = QSelf { ty, path_span, position: path.segments.len() };
2229 self.parse_path_segments(&mut path.segments, style)?;
2231 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2234 /// Parses simple paths.
2236 /// `path = [::] segment+`
2237 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2240 /// `a::b::C<D>` (without disambiguator)
2241 /// `a::b::C::<D>` (with disambiguator)
2242 /// `Fn(Args)` (without disambiguator)
2243 /// `Fn::(Args)` (with disambiguator)
2244 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2245 maybe_whole!(self, NtPath, |path| {
2246 if style == PathStyle::Mod &&
2247 path.segments.iter().any(|segment| segment.args.is_some()) {
2248 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2253 let lo = self.meta_var_span.unwrap_or(self.span);
2254 let mut segments = Vec::new();
2255 let mod_sep_ctxt = self.span.ctxt();
2256 if self.eat(&token::ModSep) {
2257 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2259 self.parse_path_segments(&mut segments, style)?;
2261 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2264 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
2265 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
2267 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2268 let meta_ident = match self.token {
2269 token::Interpolated(ref nt) => match **nt {
2270 token::NtMeta(ref meta) => match meta.node {
2271 ast::MetaItemKind::Word => Some(meta.path.clone()),
2278 if let Some(path) = meta_ident {
2282 self.parse_path(style)
2285 crate fn parse_path_segments(&mut self,
2286 segments: &mut Vec<PathSegment>,
2288 -> PResult<'a, ()> {
2290 let segment = self.parse_path_segment(style)?;
2291 if style == PathStyle::Expr {
2292 // In order to check for trailing angle brackets, we must have finished
2293 // recursing (`parse_path_segment` can indirectly call this function),
2294 // that is, the next token must be the highlighted part of the below example:
2296 // `Foo::<Bar as Baz<T>>::Qux`
2299 // As opposed to the below highlight (if we had only finished the first
2302 // `Foo::<Bar as Baz<T>>::Qux`
2305 // `PathStyle::Expr` is only provided at the root invocation and never in
2306 // `parse_path_segment` to recurse and therefore can be checked to maintain
2308 self.check_trailing_angle_brackets(&segment, token::ModSep);
2310 segments.push(segment);
2312 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2318 fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
2319 let ident = self.parse_path_segment_ident()?;
2321 let is_args_start = |token: &token::Token| match *token {
2322 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren)
2323 | token::LArrow => true,
2326 let check_args_start = |this: &mut Self| {
2327 this.expected_tokens.extend_from_slice(
2328 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2330 is_args_start(&this.token)
2333 Ok(if style == PathStyle::Type && check_args_start(self) ||
2334 style != PathStyle::Mod && self.check(&token::ModSep)
2335 && self.look_ahead(1, |t| is_args_start(t)) {
2336 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
2337 // it isn't, then we reset the unmatched angle bracket count as we're about to start
2338 // parsing a new path.
2339 if style == PathStyle::Expr {
2340 self.unmatched_angle_bracket_count = 0;
2341 self.max_angle_bracket_count = 0;
2344 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2345 self.eat(&token::ModSep);
2347 let args = if self.eat_lt() {
2349 let (args, bindings) =
2350 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
2352 let span = lo.to(self.prev_span);
2353 AngleBracketedArgs { args, bindings, span }.into()
2357 let (inputs, recovered) = self.parse_seq_to_before_tokens(
2358 &[&token::CloseDelim(token::Paren)],
2359 SeqSep::trailing_allowed(token::Comma),
2360 TokenExpectType::Expect,
2365 let span = lo.to(self.prev_span);
2366 let output = if self.eat(&token::RArrow) {
2367 Some(self.parse_ty_common(false, false, false)?)
2371 ParenthesizedArgs { inputs, output, span }.into()
2374 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2376 // Generic arguments are not found.
2377 PathSegment::from_ident(ident)
2381 crate fn check_lifetime(&mut self) -> bool {
2382 self.expected_tokens.push(TokenType::Lifetime);
2383 self.token.is_lifetime()
2386 /// Parses a single lifetime `'a` or panics.
2387 crate fn expect_lifetime(&mut self) -> Lifetime {
2388 if let Some(ident) = self.token.lifetime() {
2389 let span = self.span;
2391 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2393 self.span_bug(self.span, "not a lifetime")
2397 fn eat_label(&mut self) -> Option<Label> {
2398 if let Some(ident) = self.token.lifetime() {
2399 let span = self.span;
2401 Some(Label { ident: Ident::new(ident.name, span) })
2407 /// Parses mutability (`mut` or nothing).
2408 fn parse_mutability(&mut self) -> Mutability {
2409 if self.eat_keyword(keywords::Mut) {
2412 Mutability::Immutable
2416 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2417 if let token::Literal(token::Integer(name), suffix) = self.token {
2418 self.expect_no_suffix(self.span, "a tuple index", suffix);
2420 Ok(Ident::new(name, self.prev_span))
2422 self.parse_ident_common(false)
2426 /// Parse ident (COLON expr)?
2427 fn parse_field(&mut self) -> PResult<'a, Field> {
2428 let attrs = self.parse_outer_attributes()?;
2431 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2432 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
2433 t == &token::Colon || t == &token::Eq
2435 let fieldname = self.parse_field_name()?;
2437 // Check for an equals token. This means the source incorrectly attempts to
2438 // initialize a field with an eq rather than a colon.
2439 if self.token == token::Eq {
2441 .struct_span_err(self.span, "expected `:`, found `=`")
2443 fieldname.span.shrink_to_hi().to(self.span),
2444 "replace equals symbol with a colon",
2446 Applicability::MachineApplicable,
2451 (fieldname, self.parse_expr()?, false)
2453 let fieldname = self.parse_ident_common(false)?;
2455 // Mimic `x: x` for the `x` field shorthand.
2456 let path = ast::Path::from_ident(fieldname);
2457 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2458 (fieldname, expr, true)
2462 span: lo.to(expr.span),
2465 attrs: attrs.into(),
2469 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2470 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2473 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2474 ExprKind::Unary(unop, expr)
2477 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2478 ExprKind::Binary(binop, lhs, rhs)
2481 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2482 ExprKind::Call(f, args)
2485 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2486 ExprKind::Index(expr, idx)
2489 fn mk_range(&mut self,
2490 start: Option<P<Expr>>,
2491 end: Option<P<Expr>>,
2492 limits: RangeLimits)
2493 -> PResult<'a, ast::ExprKind> {
2494 if end.is_none() && limits == RangeLimits::Closed {
2495 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2497 Ok(ExprKind::Range(start, end, limits))
2501 fn mk_assign_op(&mut self, binop: ast::BinOp,
2502 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2503 ExprKind::AssignOp(binop, lhs, rhs)
2506 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
2507 let delim = match self.token {
2508 token::OpenDelim(delim) => delim,
2510 let msg = "expected open delimiter";
2511 let mut err = self.fatal(msg);
2512 err.span_label(self.span, msg);
2516 let tts = match self.parse_token_tree() {
2517 TokenTree::Delimited(_, _, tts) => tts,
2518 _ => unreachable!(),
2520 let delim = match delim {
2521 token::Paren => MacDelimiter::Parenthesis,
2522 token::Bracket => MacDelimiter::Bracket,
2523 token::Brace => MacDelimiter::Brace,
2524 token::NoDelim => self.bug("unexpected no delimiter"),
2526 Ok((delim, tts.into()))
2529 /// At the bottom (top?) of the precedence hierarchy,
2530 /// Parses things like parenthesized exprs, macros, `return`, etc.
2532 /// N.B., this does not parse outer attributes, and is private because it only works
2533 /// correctly if called from `parse_dot_or_call_expr()`.
2534 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2535 maybe_recover_from_interpolated_ty_qpath!(self, true);
2536 maybe_whole_expr!(self);
2538 // Outer attributes are already parsed and will be
2539 // added to the return value after the fact.
2541 // Therefore, prevent sub-parser from parsing
2542 // attributes by giving them a empty "already parsed" list.
2543 let mut attrs = ThinVec::new();
2546 let mut hi = self.span;
2550 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2552 token::OpenDelim(token::Paren) => {
2555 attrs.extend(self.parse_inner_attributes()?);
2557 // (e) is parenthesized e
2558 // (e,) is a tuple with only one field, e
2559 let mut es = vec![];
2560 let mut trailing_comma = false;
2561 let mut recovered = false;
2562 while self.token != token::CloseDelim(token::Paren) {
2563 es.push(match self.parse_expr() {
2566 // recover from parse error in tuple list
2567 return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2570 recovered = self.expect_one_of(
2572 &[token::Comma, token::CloseDelim(token::Paren)],
2574 if self.eat(&token::Comma) {
2575 trailing_comma = true;
2577 trailing_comma = false;
2585 hi = self.prev_span;
2586 ex = if es.len() == 1 && !trailing_comma {
2587 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2592 token::OpenDelim(token::Brace) => {
2593 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2595 token::BinOp(token::Or) | token::OrOr => {
2596 return self.parse_lambda_expr(attrs);
2598 token::OpenDelim(token::Bracket) => {
2601 attrs.extend(self.parse_inner_attributes()?);
2603 if self.eat(&token::CloseDelim(token::Bracket)) {
2605 ex = ExprKind::Array(Vec::new());
2608 let first_expr = self.parse_expr()?;
2609 if self.eat(&token::Semi) {
2610 // Repeating array syntax: [ 0; 512 ]
2611 let count = AnonConst {
2612 id: ast::DUMMY_NODE_ID,
2613 value: self.parse_expr()?,
2615 self.expect(&token::CloseDelim(token::Bracket))?;
2616 ex = ExprKind::Repeat(first_expr, count);
2617 } else if self.eat(&token::Comma) {
2618 // Vector with two or more elements.
2619 let remaining_exprs = self.parse_seq_to_end(
2620 &token::CloseDelim(token::Bracket),
2621 SeqSep::trailing_allowed(token::Comma),
2622 |p| Ok(p.parse_expr()?)
2624 let mut exprs = vec![first_expr];
2625 exprs.extend(remaining_exprs);
2626 ex = ExprKind::Array(exprs);
2628 // Vector with one element.
2629 self.expect(&token::CloseDelim(token::Bracket))?;
2630 ex = ExprKind::Array(vec![first_expr]);
2633 hi = self.prev_span;
2637 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2639 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2641 if self.span.rust_2018() && self.check_keyword(keywords::Async)
2643 if self.is_async_block() { // check for `async {` and `async move {`
2644 return self.parse_async_block(attrs);
2646 return self.parse_lambda_expr(attrs);
2649 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2650 return self.parse_lambda_expr(attrs);
2652 if self.eat_keyword(keywords::If) {
2653 return self.parse_if_expr(attrs);
2655 if self.eat_keyword(keywords::For) {
2656 let lo = self.prev_span;
2657 return self.parse_for_expr(None, lo, attrs);
2659 if self.eat_keyword(keywords::While) {
2660 let lo = self.prev_span;
2661 return self.parse_while_expr(None, lo, attrs);
2663 if let Some(label) = self.eat_label() {
2664 let lo = label.ident.span;
2665 self.expect(&token::Colon)?;
2666 if self.eat_keyword(keywords::While) {
2667 return self.parse_while_expr(Some(label), lo, attrs)
2669 if self.eat_keyword(keywords::For) {
2670 return self.parse_for_expr(Some(label), lo, attrs)
2672 if self.eat_keyword(keywords::Loop) {
2673 return self.parse_loop_expr(Some(label), lo, attrs)
2675 if self.token == token::OpenDelim(token::Brace) {
2676 return self.parse_block_expr(Some(label),
2678 BlockCheckMode::Default,
2681 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2682 let mut err = self.fatal(msg);
2683 err.span_label(self.span, msg);
2686 if self.eat_keyword(keywords::Loop) {
2687 let lo = self.prev_span;
2688 return self.parse_loop_expr(None, lo, attrs);
2690 if self.eat_keyword(keywords::Continue) {
2691 let label = self.eat_label();
2692 let ex = ExprKind::Continue(label);
2693 let hi = self.prev_span;
2694 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2696 if self.eat_keyword(keywords::Match) {
2697 let match_sp = self.prev_span;
2698 return self.parse_match_expr(attrs).map_err(|mut err| {
2699 err.span_label(match_sp, "while parsing this match expression");
2703 if self.eat_keyword(keywords::Unsafe) {
2704 return self.parse_block_expr(
2707 BlockCheckMode::Unsafe(ast::UserProvided),
2710 if self.is_do_catch_block() {
2711 let mut db = self.fatal("found removed `do catch` syntax");
2712 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2715 if self.is_try_block() {
2717 assert!(self.eat_keyword(keywords::Try));
2718 return self.parse_try_block(lo, attrs);
2720 if self.eat_keyword(keywords::Return) {
2721 if self.token.can_begin_expr() {
2722 let e = self.parse_expr()?;
2724 ex = ExprKind::Ret(Some(e));
2726 ex = ExprKind::Ret(None);
2728 } else if self.eat_keyword(keywords::Break) {
2729 let label = self.eat_label();
2730 let e = if self.token.can_begin_expr()
2731 && !(self.token == token::OpenDelim(token::Brace)
2732 && self.restrictions.contains(
2733 Restrictions::NO_STRUCT_LITERAL)) {
2734 Some(self.parse_expr()?)
2738 ex = ExprKind::Break(label, e);
2739 hi = self.prev_span;
2740 } else if self.eat_keyword(keywords::Yield) {
2741 if self.token.can_begin_expr() {
2742 let e = self.parse_expr()?;
2744 ex = ExprKind::Yield(Some(e));
2746 ex = ExprKind::Yield(None);
2748 } else if self.token.is_keyword(keywords::Let) {
2749 // Catch this syntax error here, instead of in `parse_ident`, so
2750 // that we can explicitly mention that let is not to be used as an expression
2751 let mut db = self.fatal("expected expression, found statement (`let`)");
2752 db.span_label(self.span, "expected expression");
2753 db.note("variable declaration using `let` is a statement");
2755 } else if self.token.is_path_start() {
2756 let path = self.parse_path(PathStyle::Expr)?;
2758 // `!`, as an operator, is prefix, so we know this isn't that
2759 if self.eat(&token::Not) {
2760 // MACRO INVOCATION expression
2761 let (delim, tts) = self.expect_delimited_token_tree()?;
2762 hi = self.prev_span;
2763 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2764 } else if self.check(&token::OpenDelim(token::Brace)) {
2765 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2769 ex = ExprKind::Path(None, path);
2773 ex = ExprKind::Path(None, path);
2776 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2777 // Don't complain about bare semicolons after unclosed braces
2778 // recovery in order to keep the error count down. Fixing the
2779 // delimiters will possibly also fix the bare semicolon found in
2780 // expression context. For example, silence the following error:
2782 // error: expected expression, found `;`
2786 // | ^ expected expression
2789 return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
2791 match self.parse_literal_maybe_minus() {
2794 ex = expr.node.clone();
2797 self.cancel(&mut err);
2798 let msg = format!("expected expression, found {}",
2799 self.this_token_descr());
2800 let mut err = self.fatal(&msg);
2801 err.span_label(self.span, "expected expression");
2809 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2810 self.maybe_recover_from_bad_qpath(expr, true)
2813 fn maybe_parse_struct_expr(
2817 attrs: &ThinVec<Attribute>,
2818 ) -> Option<PResult<'a, P<Expr>>> {
2819 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2820 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2821 // `{ ident, ` cannot start a block
2822 self.look_ahead(2, |t| t == &token::Comma) ||
2823 self.look_ahead(2, |t| t == &token::Colon) && (
2824 // `{ ident: token, ` cannot start a block
2825 self.look_ahead(4, |t| t == &token::Comma) ||
2826 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2827 self.look_ahead(3, |t| !t.can_begin_type())
2831 if struct_allowed || certainly_not_a_block() {
2832 // This is a struct literal, but we don't can't accept them here
2833 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2834 if let (Ok(expr), false) = (&expr, struct_allowed) {
2835 let mut err = self.diagnostic().struct_span_err(
2837 "struct literals are not allowed here",
2839 err.multipart_suggestion(
2840 "surround the struct literal with parenthesis",
2842 (lo.shrink_to_lo(), "(".to_string()),
2843 (expr.span.shrink_to_hi(), ")".to_string()),
2845 Applicability::MachineApplicable,
2854 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2855 -> PResult<'a, P<Expr>> {
2856 let struct_sp = lo.to(self.prev_span);
2858 let mut fields = Vec::new();
2859 let mut base = None;
2861 attrs.extend(self.parse_inner_attributes()?);
2863 while self.token != token::CloseDelim(token::Brace) {
2864 if self.eat(&token::DotDot) {
2865 let exp_span = self.prev_span;
2866 match self.parse_expr() {
2872 self.recover_stmt();
2875 if self.token == token::Comma {
2876 let mut err = self.sess.span_diagnostic.mut_span_err(
2877 exp_span.to(self.prev_span),
2878 "cannot use a comma after the base struct",
2880 err.span_suggestion_short(
2882 "remove this comma",
2884 Applicability::MachineApplicable
2886 err.note("the base struct must always be the last field");
2888 self.recover_stmt();
2893 let mut recovery_field = None;
2894 if let token::Ident(ident, _) = self.token {
2895 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2896 // Use in case of error after field-looking code: `S { foo: () with a }`
2897 let mut ident = ident.clone();
2898 ident.span = self.span;
2899 recovery_field = Some(ast::Field {
2902 expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
2903 is_shorthand: false,
2904 attrs: ThinVec::new(),
2908 let mut parsed_field = None;
2909 match self.parse_field() {
2910 Ok(f) => parsed_field = Some(f),
2912 e.span_label(struct_sp, "while parsing this struct");
2915 // If the next token is a comma, then try to parse
2916 // what comes next as additional fields, rather than
2917 // bailing out until next `}`.
2918 if self.token != token::Comma {
2919 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2920 if self.token != token::Comma {
2927 match self.expect_one_of(&[token::Comma],
2928 &[token::CloseDelim(token::Brace)]) {
2929 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2930 // only include the field if there's no parse error for the field name
2934 if let Some(f) = recovery_field {
2937 e.span_label(struct_sp, "while parsing this struct");
2939 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2940 self.eat(&token::Comma);
2945 let span = lo.to(self.span);
2946 self.expect(&token::CloseDelim(token::Brace))?;
2947 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2950 fn parse_or_use_outer_attributes(&mut self,
2951 already_parsed_attrs: Option<ThinVec<Attribute>>)
2952 -> PResult<'a, ThinVec<Attribute>> {
2953 if let Some(attrs) = already_parsed_attrs {
2956 self.parse_outer_attributes().map(|a| a.into())
2960 /// Parses a block or unsafe block.
2961 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2962 lo: Span, blk_mode: BlockCheckMode,
2963 outer_attrs: ThinVec<Attribute>)
2964 -> PResult<'a, P<Expr>> {
2965 self.expect(&token::OpenDelim(token::Brace))?;
2967 let mut attrs = outer_attrs;
2968 attrs.extend(self.parse_inner_attributes()?);
2970 let blk = self.parse_block_tail(lo, blk_mode)?;
2971 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2974 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2975 fn parse_dot_or_call_expr(&mut self,
2976 already_parsed_attrs: Option<ThinVec<Attribute>>)
2977 -> PResult<'a, P<Expr>> {
2978 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2980 let b = self.parse_bottom_expr();
2981 let (span, b) = self.interpolated_or_expr_span(b)?;
2982 self.parse_dot_or_call_expr_with(b, span, attrs)
2985 fn parse_dot_or_call_expr_with(&mut self,
2988 mut attrs: ThinVec<Attribute>)
2989 -> PResult<'a, P<Expr>> {
2990 // Stitch the list of outer attributes onto the return value.
2991 // A little bit ugly, but the best way given the current code
2993 self.parse_dot_or_call_expr_with_(e0, lo)
2995 expr.map(|mut expr| {
2996 attrs.extend::<Vec<_>>(expr.attrs.into());
2999 ExprKind::If(..) | ExprKind::IfLet(..) => {
3000 if !expr.attrs.is_empty() {
3001 // Just point to the first attribute in there...
3002 let span = expr.attrs[0].span;
3005 "attributes are not yet allowed on `if` \
3016 // Assuming we have just parsed `.`, continue parsing into an expression.
3017 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3018 let segment = self.parse_path_segment(PathStyle::Expr)?;
3019 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
3021 Ok(match self.token {
3022 token::OpenDelim(token::Paren) => {
3023 // Method call `expr.f()`
3024 let mut args = self.parse_unspanned_seq(
3025 &token::OpenDelim(token::Paren),
3026 &token::CloseDelim(token::Paren),
3027 SeqSep::trailing_allowed(token::Comma),
3028 |p| Ok(p.parse_expr()?)
3030 args.insert(0, self_arg);
3032 let span = lo.to(self.prev_span);
3033 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
3036 // Field access `expr.f`
3037 if let Some(args) = segment.args {
3038 self.span_err(args.span(),
3039 "field expressions may not have generic arguments");
3042 let span = lo.to(self.prev_span);
3043 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
3048 /// This function checks if there are trailing angle brackets and produces
3049 /// a diagnostic to suggest removing them.
3051 /// ```ignore (diagnostic)
3052 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
3053 /// ^^ help: remove extra angle brackets
3055 fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) {
3056 // This function is intended to be invoked after parsing a path segment where there are two
3059 // 1. A specific token is expected after the path segment.
3060 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
3061 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
3062 // 2. No specific token is expected after the path segment.
3063 // eg. `x.foo` (field access)
3065 // This function is called after parsing `.foo` and before parsing the token `end` (if
3066 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
3069 // We only care about trailing angle brackets if we previously parsed angle bracket
3070 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
3071 // removed in this case:
3073 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
3075 // This case is particularly tricky as we won't notice it just looking at the tokens -
3076 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
3077 // have already been parsed):
3079 // `x.foo::<u32>>>(3)`
3080 let parsed_angle_bracket_args = segment.args
3082 .map(|args| args.is_angle_bracketed())
3086 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
3087 parsed_angle_bracket_args,
3089 if !parsed_angle_bracket_args {
3093 // Keep the span at the start so we can highlight the sequence of `>` characters to be
3097 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
3098 // (since we might have the field access case and the characters we're eating are
3099 // actual operators and not trailing characters - ie `x.foo >> 3`).
3100 let mut position = 0;
3102 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
3103 // many of each (so we can correctly pluralize our error messages) and continue to
3105 let mut number_of_shr = 0;
3106 let mut number_of_gt = 0;
3107 while self.look_ahead(position, |t| {
3108 trace!("check_trailing_angle_brackets: t={:?}", t);
3109 if *t == token::BinOp(token::BinOpToken::Shr) {
3112 } else if *t == token::Gt {
3122 // If we didn't find any trailing `>` characters, then we have nothing to error about.
3124 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
3125 number_of_gt, number_of_shr,
3127 if number_of_gt < 1 && number_of_shr < 1 {
3131 // Finally, double check that we have our end token as otherwise this is the
3133 if self.look_ahead(position, |t| {
3134 trace!("check_trailing_angle_brackets: t={:?}", t);
3137 // Eat from where we started until the end token so that parsing can continue
3138 // as if we didn't have those extra angle brackets.
3139 self.eat_to_tokens(&[&end]);
3140 let span = lo.until(self.span);
3142 let plural = number_of_gt > 1 || number_of_shr >= 1;
3146 &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
3150 &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
3152 Applicability::MachineApplicable,
3158 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3163 while self.eat(&token::Question) {
3164 let hi = self.prev_span;
3165 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
3169 if self.eat(&token::Dot) {
3171 token::Ident(..) => {
3172 e = self.parse_dot_suffix(e, lo)?;
3174 token::Literal(token::Integer(name), suffix) => {
3175 let span = self.span;
3177 let field = ExprKind::Field(e, Ident::new(name, span));
3178 e = self.mk_expr(lo.to(span), field, ThinVec::new());
3180 self.expect_no_suffix(span, "a tuple index", suffix);
3182 token::Literal(token::Float(n), _suf) => {
3184 let fstr = n.as_str();
3185 let mut err = self.diagnostic()
3186 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
3187 err.span_label(self.prev_span, "unexpected token");
3188 if fstr.chars().all(|x| "0123456789.".contains(x)) {
3189 let float = match fstr.parse::<f64>().ok() {
3193 let sugg = pprust::to_string(|s| {
3194 use crate::print::pprust::PrintState;
3198 s.print_usize(float.trunc() as usize)?;
3201 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
3203 err.span_suggestion(
3204 lo.to(self.prev_span),
3205 "try parenthesizing the first index",
3207 Applicability::MachineApplicable
3214 // FIXME Could factor this out into non_fatal_unexpected or something.
3215 let actual = self.this_token_to_string();
3216 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
3221 if self.expr_is_complete(&e) { break; }
3224 token::OpenDelim(token::Paren) => {
3225 let seq = self.parse_unspanned_seq(
3226 &token::OpenDelim(token::Paren),
3227 &token::CloseDelim(token::Paren),
3228 SeqSep::trailing_allowed(token::Comma),
3229 |p| Ok(p.parse_expr()?)
3231 let nd = self.mk_call(e, es);
3232 let hi = self.prev_span;
3233 self.mk_expr(lo.to(hi), nd, ThinVec::new())
3235 e = self.recover_seq_parse_error(token::Paren, lo, seq);
3239 // Could be either an index expression or a slicing expression.
3240 token::OpenDelim(token::Bracket) => {
3242 let ix = self.parse_expr()?;
3244 self.expect(&token::CloseDelim(token::Bracket))?;
3245 let index = self.mk_index(e, ix);
3246 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
3254 fn recover_seq_parse_error(
3256 delim: token::DelimToken,
3258 result: PResult<'a, P<Expr>>,
3264 // recover from parse error
3265 self.consume_block(delim);
3266 self.mk_expr(lo.to(self.prev_span), ExprKind::Err, ThinVec::new())
3271 crate fn process_potential_macro_variable(&mut self) {
3272 let (token, span) = match self.token {
3273 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
3274 self.look_ahead(1, |t| t.is_ident()) => {
3276 let name = match self.token {
3277 token::Ident(ident, _) => ident,
3280 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
3281 err.span_label(self.span, "unknown macro variable");
3286 token::Interpolated(ref nt) => {
3287 self.meta_var_span = Some(self.span);
3288 // Interpolated identifier and lifetime tokens are replaced with usual identifier
3289 // and lifetime tokens, so the former are never encountered during normal parsing.
3291 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
3292 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
3302 /// Parses a single token tree from the input.
3303 crate fn parse_token_tree(&mut self) -> TokenTree {
3305 token::OpenDelim(..) => {
3306 let frame = mem::replace(&mut self.token_cursor.frame,
3307 self.token_cursor.stack.pop().unwrap());
3308 self.span = frame.span.entire();
3310 TokenTree::Delimited(
3313 frame.tree_cursor.stream.into(),
3316 token::CloseDelim(_) | token::Eof => unreachable!(),
3318 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
3320 TokenTree::Token(span, token)
3325 // parse a stream of tokens into a list of TokenTree's,
3327 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
3328 let mut tts = Vec::new();
3329 while self.token != token::Eof {
3330 tts.push(self.parse_token_tree());
3335 pub fn parse_tokens(&mut self) -> TokenStream {
3336 let mut result = Vec::new();
3339 token::Eof | token::CloseDelim(..) => break,
3340 _ => result.push(self.parse_token_tree().into()),
3343 TokenStream::new(result)
3346 /// Parse a prefix-unary-operator expr
3347 fn parse_prefix_expr(&mut self,
3348 already_parsed_attrs: Option<ThinVec<Attribute>>)
3349 -> PResult<'a, P<Expr>> {
3350 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3352 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
3353 let (hi, ex) = match self.token {
3356 let e = self.parse_prefix_expr(None);
3357 let (span, e) = self.interpolated_or_expr_span(e)?;
3358 (lo.to(span), self.mk_unary(UnOp::Not, e))
3360 // Suggest `!` for bitwise negation when encountering a `~`
3363 let e = self.parse_prefix_expr(None);
3364 let (span, e) = self.interpolated_or_expr_span(e)?;
3365 let span_of_tilde = lo;
3366 let mut err = self.diagnostic()
3367 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
3368 err.span_suggestion_short(
3370 "use `!` to perform bitwise negation",
3372 Applicability::MachineApplicable
3375 (lo.to(span), self.mk_unary(UnOp::Not, e))
3377 token::BinOp(token::Minus) => {
3379 let e = self.parse_prefix_expr(None);
3380 let (span, e) = self.interpolated_or_expr_span(e)?;
3381 (lo.to(span), self.mk_unary(UnOp::Neg, e))
3383 token::BinOp(token::Star) => {
3385 let e = self.parse_prefix_expr(None);
3386 let (span, e) = self.interpolated_or_expr_span(e)?;
3387 (lo.to(span), self.mk_unary(UnOp::Deref, e))
3389 token::BinOp(token::And) | token::AndAnd => {
3391 let m = self.parse_mutability();
3392 let e = self.parse_prefix_expr(None);
3393 let (span, e) = self.interpolated_or_expr_span(e)?;
3394 (lo.to(span), ExprKind::AddrOf(m, e))
3396 token::Ident(..) if self.token.is_keyword(keywords::In) => {
3398 let place = self.parse_expr_res(
3399 Restrictions::NO_STRUCT_LITERAL,
3402 let blk = self.parse_block()?;
3403 let span = blk.span;
3404 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
3405 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
3407 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
3409 let e = self.parse_prefix_expr(None);
3410 let (span, e) = self.interpolated_or_expr_span(e)?;
3411 (lo.to(span), ExprKind::Box(e))
3413 token::Ident(..) if self.token.is_ident_named("not") => {
3414 // `not` is just an ordinary identifier in Rust-the-language,
3415 // but as `rustc`-the-compiler, we can issue clever diagnostics
3416 // for confused users who really want to say `!`
3417 let token_cannot_continue_expr = |t: &token::Token| match *t {
3418 // These tokens can start an expression after `!`, but
3419 // can't continue an expression after an ident
3420 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3421 token::Literal(..) | token::Pound => true,
3422 token::Interpolated(ref nt) => match **nt {
3423 token::NtIdent(..) | token::NtExpr(..) |
3424 token::NtBlock(..) | token::NtPath(..) => true,
3429 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3430 if cannot_continue_expr {
3432 // Emit the error ...
3433 let mut err = self.diagnostic()
3434 .struct_span_err(self.span,
3435 &format!("unexpected {} after identifier",
3436 self.this_token_descr()));
3437 // span the `not` plus trailing whitespace to avoid
3438 // trailing whitespace after the `!` in our suggestion
3439 let to_replace = self.sess.source_map()
3440 .span_until_non_whitespace(lo.to(self.span));
3441 err.span_suggestion_short(
3443 "use `!` to perform logical negation",
3445 Applicability::MachineApplicable
3448 // —and recover! (just as if we were in the block
3449 // for the `token::Not` arm)
3450 let e = self.parse_prefix_expr(None);
3451 let (span, e) = self.interpolated_or_expr_span(e)?;
3452 (lo.to(span), self.mk_unary(UnOp::Not, e))
3454 return self.parse_dot_or_call_expr(Some(attrs));
3457 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3459 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3462 /// Parses an associative expression.
3464 /// This parses an expression accounting for associativity and precedence of the operators in
3467 fn parse_assoc_expr(&mut self,
3468 already_parsed_attrs: Option<ThinVec<Attribute>>)
3469 -> PResult<'a, P<Expr>> {
3470 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3473 /// Parses an associative expression with operators of at least `min_prec` precedence.
3474 fn parse_assoc_expr_with(&mut self,
3477 -> PResult<'a, P<Expr>> {
3478 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3481 let attrs = match lhs {
3482 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3485 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3486 return self.parse_prefix_range_expr(attrs);
3488 self.parse_prefix_expr(attrs)?
3492 if self.expr_is_complete(&lhs) {
3493 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3496 self.expected_tokens.push(TokenType::Operator);
3497 while let Some(op) = AssocOp::from_token(&self.token) {
3499 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3500 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3501 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3502 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3503 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3504 (PrevTokenKind::Interpolated, _) => self.prev_span,
3505 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3506 if path.segments.len() == 1 => self.prev_span,
3510 let cur_op_span = self.span;
3511 let restrictions = if op.is_assign_like() {
3512 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3516 if op.precedence() < min_prec {
3519 // Check for deprecated `...` syntax
3520 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3521 self.err_dotdotdot_syntax(self.span);
3525 if op.is_comparison() {
3526 self.check_no_chained_comparison(&lhs, &op);
3529 if op == AssocOp::As {
3530 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3532 } else if op == AssocOp::Colon {
3533 let maybe_path = self.could_ascription_be_path(&lhs.node);
3534 let next_sp = self.span;
3536 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3539 self.bad_type_ascription(
3550 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3551 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3552 // generalise it to the Fixity::None code.
3554 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3555 // two variants are handled with `parse_prefix_range_expr` call above.
3556 let rhs = if self.is_at_start_of_range_notation_rhs() {
3557 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3558 LhsExpr::NotYetParsed)?)
3562 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3567 let limits = if op == AssocOp::DotDot {
3568 RangeLimits::HalfOpen
3573 let r = self.mk_range(Some(lhs), rhs, limits)?;
3574 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3578 let rhs = match op.fixity() {
3579 Fixity::Right => self.with_res(
3580 restrictions - Restrictions::STMT_EXPR,
3582 this.parse_assoc_expr_with(op.precedence(),
3583 LhsExpr::NotYetParsed)
3585 Fixity::Left => self.with_res(
3586 restrictions - Restrictions::STMT_EXPR,
3588 this.parse_assoc_expr_with(op.precedence() + 1,
3589 LhsExpr::NotYetParsed)
3591 // We currently have no non-associative operators that are not handled above by
3592 // the special cases. The code is here only for future convenience.
3593 Fixity::None => self.with_res(
3594 restrictions - Restrictions::STMT_EXPR,
3596 this.parse_assoc_expr_with(op.precedence() + 1,
3597 LhsExpr::NotYetParsed)
3601 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
3602 // including the attributes.
3606 .filter(|a| a.style == AttrStyle::Outer)
3608 .map_or(lhs_span, |a| a.span);
3609 let span = lhs_span.to(rhs.span);
3611 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3612 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3613 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3614 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3615 AssocOp::Greater | AssocOp::GreaterEqual => {
3616 let ast_op = op.to_ast_binop().unwrap();
3617 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3618 self.mk_expr(span, binary, ThinVec::new())
3621 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3622 AssocOp::ObsoleteInPlace =>
3623 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3624 AssocOp::AssignOp(k) => {
3626 token::Plus => BinOpKind::Add,
3627 token::Minus => BinOpKind::Sub,
3628 token::Star => BinOpKind::Mul,
3629 token::Slash => BinOpKind::Div,
3630 token::Percent => BinOpKind::Rem,
3631 token::Caret => BinOpKind::BitXor,
3632 token::And => BinOpKind::BitAnd,
3633 token::Or => BinOpKind::BitOr,
3634 token::Shl => BinOpKind::Shl,
3635 token::Shr => BinOpKind::Shr,
3637 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3638 self.mk_expr(span, aopexpr, ThinVec::new())
3640 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3641 self.bug("AssocOp should have been handled by special case")
3645 if op.fixity() == Fixity::None { break }
3650 fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
3651 self.token.is_ident() &&
3652 if let ast::ExprKind::Path(..) = node { true } else { false } &&
3653 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
3654 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren)) ||
3655 self.look_ahead(1, |t| t == &token::Lt) && // `foo:bar<baz`
3656 self.look_ahead(2, |t| t.is_ident()) ||
3657 self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
3658 self.look_ahead(2, |t| t.is_ident()) ||
3659 self.look_ahead(1, |t| t == &token::ModSep) && // `foo:bar::baz`
3660 self.look_ahead(2, |t| t.is_ident())
3663 fn bad_type_ascription(
3665 err: &mut DiagnosticBuilder<'a>,
3671 err.span_label(self.span, "expecting a type here because of type ascription");
3672 let cm = self.sess.source_map();
3673 let next_pos = cm.lookup_char_pos(next_sp.lo());
3674 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3675 if op_pos.line != next_pos.line {
3676 err.span_suggestion(
3678 "try using a semicolon",
3680 Applicability::MaybeIncorrect,
3684 err.span_suggestion(
3686 "maybe you meant to write a path separator here",
3688 Applicability::MaybeIncorrect,
3691 err.note("type ascription is a nightly-only feature that lets \
3692 you annotate an expression with a type: `<expr>: <type>`");
3695 "this expression expects an ascribed type after the colon",
3697 err.help("this might be indicative of a syntax error elsewhere");
3702 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3703 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3704 -> PResult<'a, P<Expr>> {
3705 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3706 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3709 // Save the state of the parser before parsing type normally, in case there is a
3710 // LessThan comparison after this cast.
3711 let parser_snapshot_before_type = self.clone();
3712 match self.parse_ty_no_plus() {
3714 Ok(mk_expr(self, rhs))
3716 Err(mut type_err) => {
3717 // Rewind to before attempting to parse the type with generics, to recover
3718 // from situations like `x as usize < y` in which we first tried to parse
3719 // `usize < y` as a type with generic arguments.
3720 let parser_snapshot_after_type = self.clone();
3721 mem::replace(self, parser_snapshot_before_type);
3723 match self.parse_path(PathStyle::Expr) {
3725 let (op_noun, op_verb) = match self.token {
3726 token::Lt => ("comparison", "comparing"),
3727 token::BinOp(token::Shl) => ("shift", "shifting"),
3729 // We can end up here even without `<` being the next token, for
3730 // example because `parse_ty_no_plus` returns `Err` on keywords,
3731 // but `parse_path` returns `Ok` on them due to error recovery.
3732 // Return original error and parser state.
3733 mem::replace(self, parser_snapshot_after_type);
3734 return Err(type_err);
3738 // Successfully parsed the type path leaving a `<` yet to parse.
3741 // Report non-fatal diagnostics, keep `x as usize` as an expression
3742 // in AST and continue parsing.
3743 let msg = format!("`<` is interpreted as a start of generic \
3744 arguments for `{}`, not a {}", path, op_noun);
3745 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3746 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3747 "interpreted as generic arguments");
3748 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3750 let expr = mk_expr(self, P(Ty {
3752 node: TyKind::Path(None, path),
3753 id: ast::DUMMY_NODE_ID
3756 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3757 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3758 err.span_suggestion(
3760 &format!("try {} the cast value", op_verb),
3761 format!("({})", expr_str),
3762 Applicability::MachineApplicable
3768 Err(mut path_err) => {
3769 // Couldn't parse as a path, return original error and parser state.
3771 mem::replace(self, parser_snapshot_after_type);
3779 /// Produce an error if comparison operators are chained (RFC #558).
3780 /// We only need to check lhs, not rhs, because all comparison ops
3781 /// have same precedence and are left-associative
3782 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3783 debug_assert!(outer_op.is_comparison(),
3784 "check_no_chained_comparison: {:?} is not comparison",
3787 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3788 // respan to include both operators
3789 let op_span = op.span.to(self.span);
3790 let mut err = self.diagnostic().struct_span_err(op_span,
3791 "chained comparison operators require parentheses");
3792 if op.node == BinOpKind::Lt &&
3793 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3794 *outer_op == AssocOp::Greater // even in a case like the following:
3795 { // Foo<Bar<Baz<Qux, ()>>>
3797 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3798 err.help("or use `(...)` if you meant to specify fn arguments");
3806 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3807 fn parse_prefix_range_expr(&mut self,
3808 already_parsed_attrs: Option<ThinVec<Attribute>>)
3809 -> PResult<'a, P<Expr>> {
3810 // Check for deprecated `...` syntax
3811 if self.token == token::DotDotDot {
3812 self.err_dotdotdot_syntax(self.span);
3815 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3816 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3818 let tok = self.token.clone();
3819 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3821 let mut hi = self.span;
3823 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3824 // RHS must be parsed with more associativity than the dots.
3825 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3826 Some(self.parse_assoc_expr_with(next_prec,
3827 LhsExpr::NotYetParsed)
3835 let limits = if tok == token::DotDot {
3836 RangeLimits::HalfOpen
3841 let r = self.mk_range(None, opt_end, limits)?;
3842 Ok(self.mk_expr(lo.to(hi), r, attrs))
3845 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3846 if self.token.can_begin_expr() {
3847 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3848 if self.token == token::OpenDelim(token::Brace) {
3849 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3857 /// Parses an `if` or `if let` expression (`if` token already eaten).
3858 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3859 if self.check_keyword(keywords::Let) {
3860 return self.parse_if_let_expr(attrs);
3862 let lo = self.prev_span;
3863 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3865 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3866 // verify that the last statement is either an implicit return (no `;`) or an explicit
3867 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3868 // the dead code lint.
3869 if self.eat_keyword(keywords::Else) || !cond.returns() {
3870 let sp = self.sess.source_map().next_point(lo);
3871 let mut err = self.diagnostic()
3872 .struct_span_err(sp, "missing condition for `if` statemement");
3873 err.span_label(sp, "expected if condition here");
3876 let not_block = self.token != token::OpenDelim(token::Brace);
3877 let thn = self.parse_block().map_err(|mut err| {
3879 err.span_label(lo, "this `if` statement has a condition, but no block");
3883 let mut els: Option<P<Expr>> = None;
3884 let mut hi = thn.span;
3885 if self.eat_keyword(keywords::Else) {
3886 let elexpr = self.parse_else_expr()?;
3890 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3893 /// Parses an `if let` expression (`if` token already eaten).
3894 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3895 -> PResult<'a, P<Expr>> {
3896 let lo = self.prev_span;
3897 self.expect_keyword(keywords::Let)?;
3898 let pats = self.parse_pats()?;
3899 self.expect(&token::Eq)?;
3900 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3901 let thn = self.parse_block()?;
3902 let (hi, els) = if self.eat_keyword(keywords::Else) {
3903 let expr = self.parse_else_expr()?;
3904 (expr.span, Some(expr))
3908 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3911 /// Parses `move |args| expr`.
3912 fn parse_lambda_expr(&mut self,
3913 attrs: ThinVec<Attribute>)
3914 -> PResult<'a, P<Expr>>
3917 let movability = if self.eat_keyword(keywords::Static) {
3922 let asyncness = if self.span.rust_2018() {
3923 self.parse_asyncness()
3927 let capture_clause = if self.eat_keyword(keywords::Move) {
3932 let decl = self.parse_fn_block_decl()?;
3933 let decl_hi = self.prev_span;
3934 let body = match decl.output {
3935 FunctionRetTy::Default(_) => {
3936 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3937 self.parse_expr_res(restrictions, None)?
3940 // If an explicit return type is given, require a
3941 // block to appear (RFC 968).
3942 let body_lo = self.span;
3943 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3949 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3953 // `else` token already eaten
3954 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3955 if self.eat_keyword(keywords::If) {
3956 return self.parse_if_expr(ThinVec::new());
3958 let blk = self.parse_block()?;
3959 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3963 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3964 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3966 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3967 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3969 let pat = self.parse_top_level_pat()?;
3970 if !self.eat_keyword(keywords::In) {
3971 let in_span = self.prev_span.between(self.span);
3972 let mut err = self.sess.span_diagnostic
3973 .struct_span_err(in_span, "missing `in` in `for` loop");
3974 err.span_suggestion_short(
3975 in_span, "try adding `in` here", " in ".into(),
3976 // has been misleading, at least in the past (closed Issue #48492)
3977 Applicability::MaybeIncorrect
3981 let in_span = self.prev_span;
3982 if self.eat_keyword(keywords::In) {
3983 // a common typo: `for _ in in bar {}`
3984 let mut err = self.sess.span_diagnostic.struct_span_err(
3986 "expected iterable, found keyword `in`",
3988 err.span_suggestion_short(
3989 in_span.until(self.prev_span),
3990 "remove the duplicated `in`",
3992 Applicability::MachineApplicable,
3994 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
3995 err.note("for more information on the status of emplacement syntax, see <\
3996 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
3999 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4000 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
4001 attrs.extend(iattrs);
4003 let hi = self.prev_span;
4004 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
4007 /// Parses a `while` or `while let` expression (`while` token already eaten).
4008 fn parse_while_expr(&mut self, opt_label: Option<Label>,
4010 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4011 if self.token.is_keyword(keywords::Let) {
4012 return self.parse_while_let_expr(opt_label, span_lo, attrs);
4014 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4015 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4016 attrs.extend(iattrs);
4017 let span = span_lo.to(body.span);
4018 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
4021 /// Parses a `while let` expression (`while` token already eaten).
4022 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
4024 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4025 self.expect_keyword(keywords::Let)?;
4026 let pats = self.parse_pats()?;
4027 self.expect(&token::Eq)?;
4028 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4029 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4030 attrs.extend(iattrs);
4031 let span = span_lo.to(body.span);
4032 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
4035 // parse `loop {...}`, `loop` token already eaten
4036 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
4038 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4039 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4040 attrs.extend(iattrs);
4041 let span = span_lo.to(body.span);
4042 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
4045 /// Parses an `async move {...}` expression.
4046 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
4047 -> PResult<'a, P<Expr>>
4049 let span_lo = self.span;
4050 self.expect_keyword(keywords::Async)?;
4051 let capture_clause = if self.eat_keyword(keywords::Move) {
4056 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4057 attrs.extend(iattrs);
4059 span_lo.to(body.span),
4060 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
4063 /// Parses a `try {...}` expression (`try` token already eaten).
4064 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
4065 -> PResult<'a, P<Expr>>
4067 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4068 attrs.extend(iattrs);
4069 if self.eat_keyword(keywords::Catch) {
4070 let mut error = self.struct_span_err(self.prev_span,
4071 "keyword `catch` cannot follow a `try` block");
4072 error.help("try using `match` on the result of the `try` block instead");
4076 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
4080 // `match` token already eaten
4081 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4082 let match_span = self.prev_span;
4083 let lo = self.prev_span;
4084 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
4086 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
4087 if self.token == token::Token::Semi {
4088 e.span_suggestion_short(
4090 "try removing this `match`",
4092 Applicability::MaybeIncorrect // speculative
4097 attrs.extend(self.parse_inner_attributes()?);
4099 let mut arms: Vec<Arm> = Vec::new();
4100 while self.token != token::CloseDelim(token::Brace) {
4101 match self.parse_arm() {
4102 Ok(arm) => arms.push(arm),
4104 // Recover by skipping to the end of the block.
4106 self.recover_stmt();
4107 let span = lo.to(self.span);
4108 if self.token == token::CloseDelim(token::Brace) {
4111 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
4117 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
4120 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
4121 maybe_whole!(self, NtArm, |x| x);
4123 let attrs = self.parse_outer_attributes()?;
4124 let pats = self.parse_pats()?;
4125 let guard = if self.eat_keyword(keywords::If) {
4126 Some(Guard::If(self.parse_expr()?))
4130 let arrow_span = self.span;
4131 self.expect(&token::FatArrow)?;
4132 let arm_start_span = self.span;
4134 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
4135 .map_err(|mut err| {
4136 err.span_label(arrow_span, "while parsing the `match` arm starting here");
4140 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
4141 && self.token != token::CloseDelim(token::Brace);
4144 let cm = self.sess.source_map();
4145 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
4146 .map_err(|mut err| {
4147 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
4148 (Ok(ref expr_lines), Ok(ref arm_start_lines))
4149 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
4150 && expr_lines.lines.len() == 2
4151 && self.token == token::FatArrow => {
4152 // We check whether there's any trailing code in the parse span,
4153 // if there isn't, we very likely have the following:
4156 // | -- - missing comma
4162 // | parsed until here as `"y" & X`
4163 err.span_suggestion_short(
4164 cm.next_point(arm_start_span),
4165 "missing a comma here to end this `match` arm",
4167 Applicability::MachineApplicable
4171 err.span_label(arrow_span,
4172 "while parsing the `match` arm starting here");
4178 self.eat(&token::Comma);
4189 /// Parses an expression.
4191 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
4192 self.parse_expr_res(Restrictions::empty(), None)
4195 /// Evaluates the closure with restrictions in place.
4197 /// Afters the closure is evaluated, restrictions are reset.
4198 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
4199 where F: FnOnce(&mut Self) -> T
4201 let old = self.restrictions;
4202 self.restrictions = r;
4204 self.restrictions = old;
4209 /// Parses an expression, subject to the given restrictions.
4211 fn parse_expr_res(&mut self, r: Restrictions,
4212 already_parsed_attrs: Option<ThinVec<Attribute>>)
4213 -> PResult<'a, P<Expr>> {
4214 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
4217 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
4218 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
4219 if self.eat(&token::Eq) {
4220 Ok(Some(self.parse_expr()?))
4222 Ok(Some(self.parse_expr()?))
4228 /// Parses patterns, separated by '|' s.
4229 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
4230 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
4231 self.eat(&token::BinOp(token::Or));
4233 let mut pats = Vec::new();
4235 pats.push(self.parse_top_level_pat()?);
4237 if self.token == token::OrOr {
4238 let mut err = self.struct_span_err(self.span,
4239 "unexpected token `||` after pattern");
4240 err.span_suggestion(
4242 "use a single `|` to specify multiple patterns",
4244 Applicability::MachineApplicable
4248 } else if self.eat(&token::BinOp(token::Or)) {
4249 // This is a No-op. Continue the loop to parse the next
4257 // Parses a parenthesized list of patterns like
4258 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
4259 // - a vector of the patterns that were parsed
4260 // - an option indicating the index of the `..` element
4261 // - a boolean indicating whether a trailing comma was present.
4262 // Trailing commas are significant because (p) and (p,) are different patterns.
4263 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4264 self.expect(&token::OpenDelim(token::Paren))?;
4265 let result = match self.parse_pat_list() {
4266 Ok(result) => result,
4267 Err(mut err) => { // recover from parse error in tuple pattern list
4269 self.consume_block(token::Paren);
4270 return Ok((vec![], Some(0), false));
4273 self.expect(&token::CloseDelim(token::Paren))?;
4277 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4278 let mut fields = Vec::new();
4279 let mut ddpos = None;
4280 let mut prev_dd_sp = None;
4281 let mut trailing_comma = false;
4283 if self.eat(&token::DotDot) {
4284 if ddpos.is_none() {
4285 ddpos = Some(fields.len());
4286 prev_dd_sp = Some(self.prev_span);
4288 // Emit a friendly error, ignore `..` and continue parsing
4289 let mut err = self.struct_span_err(
4291 "`..` can only be used once per tuple or tuple struct pattern",
4293 err.span_label(self.prev_span, "can only be used once per pattern");
4294 if let Some(sp) = prev_dd_sp {
4295 err.span_label(sp, "previously present here");
4299 } else if !self.check(&token::CloseDelim(token::Paren)) {
4300 fields.push(self.parse_pat(None)?);
4305 trailing_comma = self.eat(&token::Comma);
4306 if !trailing_comma {
4311 if ddpos == Some(fields.len()) && trailing_comma {
4312 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
4313 let msg = "trailing comma is not permitted after `..`";
4314 self.struct_span_err(self.prev_span, msg)
4315 .span_label(self.prev_span, msg)
4319 Ok((fields, ddpos, trailing_comma))
4322 fn parse_pat_vec_elements(
4324 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
4325 let mut before = Vec::new();
4326 let mut slice = None;
4327 let mut after = Vec::new();
4328 let mut first = true;
4329 let mut before_slice = true;
4331 while self.token != token::CloseDelim(token::Bracket) {
4335 self.expect(&token::Comma)?;
4337 if self.token == token::CloseDelim(token::Bracket)
4338 && (before_slice || !after.is_empty()) {
4344 if self.eat(&token::DotDot) {
4346 if self.check(&token::Comma) ||
4347 self.check(&token::CloseDelim(token::Bracket)) {
4348 slice = Some(P(Pat {
4349 id: ast::DUMMY_NODE_ID,
4350 node: PatKind::Wild,
4351 span: self.prev_span,
4353 before_slice = false;
4359 let subpat = self.parse_pat(None)?;
4360 if before_slice && self.eat(&token::DotDot) {
4361 slice = Some(subpat);
4362 before_slice = false;
4363 } else if before_slice {
4364 before.push(subpat);
4370 Ok((before, slice, after))
4376 attrs: Vec<Attribute>
4377 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
4378 // Check if a colon exists one ahead. This means we're parsing a fieldname.
4380 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
4381 // Parsing a pattern of the form "fieldname: pat"
4382 let fieldname = self.parse_field_name()?;
4384 let pat = self.parse_pat(None)?;
4386 (pat, fieldname, false)
4388 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
4389 let is_box = self.eat_keyword(keywords::Box);
4390 let boxed_span = self.span;
4391 let is_ref = self.eat_keyword(keywords::Ref);
4392 let is_mut = self.eat_keyword(keywords::Mut);
4393 let fieldname = self.parse_ident()?;
4394 hi = self.prev_span;
4396 let bind_type = match (is_ref, is_mut) {
4397 (true, true) => BindingMode::ByRef(Mutability::Mutable),
4398 (true, false) => BindingMode::ByRef(Mutability::Immutable),
4399 (false, true) => BindingMode::ByValue(Mutability::Mutable),
4400 (false, false) => BindingMode::ByValue(Mutability::Immutable),
4402 let fieldpat = P(Pat {
4403 id: ast::DUMMY_NODE_ID,
4404 node: PatKind::Ident(bind_type, fieldname, None),
4405 span: boxed_span.to(hi),
4408 let subpat = if is_box {
4410 id: ast::DUMMY_NODE_ID,
4411 node: PatKind::Box(fieldpat),
4417 (subpat, fieldname, true)
4420 Ok(source_map::Spanned {
4422 node: ast::FieldPat {
4426 attrs: attrs.into(),
4431 /// Parses the fields of a struct-like pattern.
4432 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
4433 let mut fields = Vec::new();
4434 let mut etc = false;
4435 let mut ate_comma = true;
4436 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
4437 let mut etc_span = None;
4439 while self.token != token::CloseDelim(token::Brace) {
4440 let attrs = self.parse_outer_attributes()?;
4443 // check that a comma comes after every field
4445 let err = self.struct_span_err(self.prev_span, "expected `,`");
4446 if let Some(mut delayed) = delayed_err {
4453 if self.check(&token::DotDot) || self.token == token::DotDotDot {
4455 let mut etc_sp = self.span;
4457 if self.token == token::DotDotDot { // Issue #46718
4458 // Accept `...` as if it were `..` to avoid further errors
4459 let mut err = self.struct_span_err(self.span,
4460 "expected field pattern, found `...`");
4461 err.span_suggestion(
4463 "to omit remaining fields, use one fewer `.`",
4465 Applicability::MachineApplicable
4469 self.bump(); // `..` || `...`
4471 if self.token == token::CloseDelim(token::Brace) {
4472 etc_span = Some(etc_sp);
4475 let token_str = self.this_token_descr();
4476 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
4478 err.span_label(self.span, "expected `}`");
4479 let mut comma_sp = None;
4480 if self.token == token::Comma { // Issue #49257
4481 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
4482 err.span_label(etc_sp,
4483 "`..` must be at the end and cannot have a trailing comma");
4484 comma_sp = Some(self.span);
4489 etc_span = Some(etc_sp.until(self.span));
4490 if self.token == token::CloseDelim(token::Brace) {
4491 // If the struct looks otherwise well formed, recover and continue.
4492 if let Some(sp) = comma_sp {
4493 err.span_suggestion_short(
4495 "remove this comma",
4497 Applicability::MachineApplicable,
4502 } else if self.token.is_ident() && ate_comma {
4503 // Accept fields coming after `..,`.
4504 // This way we avoid "pattern missing fields" errors afterwards.
4505 // We delay this error until the end in order to have a span for a
4507 if let Some(mut delayed_err) = delayed_err {
4511 delayed_err = Some(err);
4514 if let Some(mut err) = delayed_err {
4521 fields.push(match self.parse_pat_field(lo, attrs) {
4524 if let Some(mut delayed_err) = delayed_err {
4530 ate_comma = self.eat(&token::Comma);
4533 if let Some(mut err) = delayed_err {
4534 if let Some(etc_span) = etc_span {
4535 err.multipart_suggestion(
4536 "move the `..` to the end of the field list",
4538 (etc_span, String::new()),
4539 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4541 Applicability::MachineApplicable,
4546 return Ok((fields, etc));
4549 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4550 if self.token.is_path_start() {
4552 let (qself, path) = if self.eat_lt() {
4553 // Parse a qualified path
4554 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4557 // Parse an unqualified path
4558 (None, self.parse_path(PathStyle::Expr)?)
4560 let hi = self.prev_span;
4561 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4563 self.parse_literal_maybe_minus()
4567 // helper function to decide whether to parse as ident binding or to try to do
4568 // something more complex like range patterns
4569 fn parse_as_ident(&mut self) -> bool {
4570 self.look_ahead(1, |t| match *t {
4571 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4572 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4573 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4574 // range pattern branch
4575 token::DotDot => None,
4577 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4578 token::Comma | token::CloseDelim(token::Bracket) => true,
4583 /// A wrapper around `parse_pat` with some special error handling for the
4584 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4585 /// to subpatterns within such).
4586 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4587 let pat = self.parse_pat(None)?;
4588 if self.token == token::Comma {
4589 // An unexpected comma after a top-level pattern is a clue that the
4590 // user (perhaps more accustomed to some other language) forgot the
4591 // parentheses in what should have been a tuple pattern; return a
4592 // suggestion-enhanced error here rather than choking on the comma
4594 let comma_span = self.span;
4596 if let Err(mut err) = self.parse_pat_list() {
4597 // We didn't expect this to work anyway; we just wanted
4598 // to advance to the end of the comma-sequence so we know
4599 // the span to suggest parenthesizing
4602 let seq_span = pat.span.to(self.prev_span);
4603 let mut err = self.struct_span_err(comma_span,
4604 "unexpected `,` in pattern");
4605 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4606 err.span_suggestion(
4608 "try adding parentheses to match on a tuple..",
4609 format!("({})", seq_snippet),
4610 Applicability::MachineApplicable
4613 "..or a vertical bar to match on multiple alternatives",
4614 format!("{}", seq_snippet.replace(",", " |")),
4615 Applicability::MachineApplicable
4623 /// Parses a pattern.
4624 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4625 self.parse_pat_with_range_pat(true, expected)
4628 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
4630 fn parse_pat_with_range_pat(
4632 allow_range_pat: bool,
4633 expected: Option<&'static str>,
4634 ) -> PResult<'a, P<Pat>> {
4635 maybe_recover_from_interpolated_ty_qpath!(self, true);
4636 maybe_whole!(self, NtPat, |x| x);
4641 token::BinOp(token::And) | token::AndAnd => {
4642 // Parse &pat / &mut pat
4644 let mutbl = self.parse_mutability();
4645 if let token::Lifetime(ident) = self.token {
4646 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4648 err.span_label(self.span, "unexpected lifetime");
4651 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4652 pat = PatKind::Ref(subpat, mutbl);
4654 token::OpenDelim(token::Paren) => {
4655 // Parse (pat,pat,pat,...) as tuple pattern
4656 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4657 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4658 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4660 PatKind::Tuple(fields, ddpos)
4663 token::OpenDelim(token::Bracket) => {
4664 // Parse [pat,pat,...] as slice pattern
4666 let (before, slice, after) = self.parse_pat_vec_elements()?;
4667 self.expect(&token::CloseDelim(token::Bracket))?;
4668 pat = PatKind::Slice(before, slice, after);
4670 // At this point, token != &, &&, (, [
4671 _ => if self.eat_keyword(keywords::Underscore) {
4673 pat = PatKind::Wild;
4674 } else if self.eat_keyword(keywords::Mut) {
4675 // Parse mut ident @ pat / mut ref ident @ pat
4676 let mutref_span = self.prev_span.to(self.span);
4677 let binding_mode = if self.eat_keyword(keywords::Ref) {
4679 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4682 "try switching the order",
4684 Applicability::MachineApplicable
4686 BindingMode::ByRef(Mutability::Mutable)
4688 BindingMode::ByValue(Mutability::Mutable)
4690 pat = self.parse_pat_ident(binding_mode)?;
4691 } else if self.eat_keyword(keywords::Ref) {
4692 // Parse ref ident @ pat / ref mut ident @ pat
4693 let mutbl = self.parse_mutability();
4694 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4695 } else if self.eat_keyword(keywords::Box) {
4697 let subpat = self.parse_pat_with_range_pat(false, None)?;
4698 pat = PatKind::Box(subpat);
4699 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4700 self.parse_as_ident() {
4701 // Parse ident @ pat
4702 // This can give false positives and parse nullary enums,
4703 // they are dealt with later in resolve
4704 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4705 pat = self.parse_pat_ident(binding_mode)?;
4706 } else if self.token.is_path_start() {
4707 // Parse pattern starting with a path
4708 let (qself, path) = if self.eat_lt() {
4709 // Parse a qualified path
4710 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4713 // Parse an unqualified path
4714 (None, self.parse_path(PathStyle::Expr)?)
4717 token::Not if qself.is_none() => {
4718 // Parse macro invocation
4720 let (delim, tts) = self.expect_delimited_token_tree()?;
4721 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4722 pat = PatKind::Mac(mac);
4724 token::DotDotDot | token::DotDotEq | token::DotDot => {
4725 let end_kind = match self.token {
4726 token::DotDot => RangeEnd::Excluded,
4727 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4728 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4729 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4732 let op_span = self.span;
4734 let span = lo.to(self.prev_span);
4735 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4737 let end = self.parse_pat_range_end()?;
4738 let op = Spanned { span: op_span, node: end_kind };
4739 pat = PatKind::Range(begin, end, op);
4741 token::OpenDelim(token::Brace) => {
4742 if qself.is_some() {
4743 let msg = "unexpected `{` after qualified path";
4744 let mut err = self.fatal(msg);
4745 err.span_label(self.span, msg);
4748 // Parse struct pattern
4750 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4752 self.recover_stmt();
4756 pat = PatKind::Struct(path, fields, etc);
4758 token::OpenDelim(token::Paren) => {
4759 if qself.is_some() {
4760 let msg = "unexpected `(` after qualified path";
4761 let mut err = self.fatal(msg);
4762 err.span_label(self.span, msg);
4765 // Parse tuple struct or enum pattern
4766 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4767 pat = PatKind::TupleStruct(path, fields, ddpos)
4769 _ => pat = PatKind::Path(qself, path),
4772 // Try to parse everything else as literal with optional minus
4773 match self.parse_literal_maybe_minus() {
4775 let op_span = self.span;
4776 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4777 self.check(&token::DotDotDot) {
4778 let end_kind = if self.eat(&token::DotDotDot) {
4779 RangeEnd::Included(RangeSyntax::DotDotDot)
4780 } else if self.eat(&token::DotDotEq) {
4781 RangeEnd::Included(RangeSyntax::DotDotEq)
4782 } else if self.eat(&token::DotDot) {
4785 panic!("impossible case: we already matched \
4786 on a range-operator token")
4788 let end = self.parse_pat_range_end()?;
4789 let op = Spanned { span: op_span, node: end_kind };
4790 pat = PatKind::Range(begin, end, op);
4792 pat = PatKind::Lit(begin);
4796 self.cancel(&mut err);
4797 let expected = expected.unwrap_or("pattern");
4799 "expected {}, found {}",
4801 self.this_token_descr(),
4803 let mut err = self.fatal(&msg);
4804 err.span_label(self.span, format!("expected {}", expected));
4811 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4812 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4814 if !allow_range_pat {
4817 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4819 PatKind::Range(..) => {
4820 let mut err = self.struct_span_err(
4822 "the range pattern here has ambiguous interpretation",
4824 err.span_suggestion(
4826 "add parentheses to clarify the precedence",
4827 format!("({})", pprust::pat_to_string(&pat)),
4828 // "ambiguous interpretation" implies that we have to be guessing
4829 Applicability::MaybeIncorrect
4840 /// Parses `ident` or `ident @ pat`.
4841 /// used by the copy foo and ref foo patterns to give a good
4842 /// error message when parsing mistakes like `ref foo(a, b)`.
4843 fn parse_pat_ident(&mut self,
4844 binding_mode: ast::BindingMode)
4845 -> PResult<'a, PatKind> {
4846 let ident = self.parse_ident()?;
4847 let sub = if self.eat(&token::At) {
4848 Some(self.parse_pat(Some("binding pattern"))?)
4853 // just to be friendly, if they write something like
4855 // we end up here with ( as the current token. This shortly
4856 // leads to a parse error. Note that if there is no explicit
4857 // binding mode then we do not end up here, because the lookahead
4858 // will direct us over to parse_enum_variant()
4859 if self.token == token::OpenDelim(token::Paren) {
4860 return Err(self.span_fatal(
4862 "expected identifier, found enum pattern"))
4865 Ok(PatKind::Ident(binding_mode, ident, sub))
4868 /// Parses a local variable declaration.
4869 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4870 let lo = self.prev_span;
4871 let pat = self.parse_top_level_pat()?;
4873 let (err, ty) = if self.eat(&token::Colon) {
4874 // Save the state of the parser before parsing type normally, in case there is a `:`
4875 // instead of an `=` typo.
4876 let parser_snapshot_before_type = self.clone();
4877 let colon_sp = self.prev_span;
4878 match self.parse_ty() {
4879 Ok(ty) => (None, Some(ty)),
4881 // Rewind to before attempting to parse the type and continue parsing
4882 let parser_snapshot_after_type = self.clone();
4883 mem::replace(self, parser_snapshot_before_type);
4885 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4886 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4887 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4893 let init = match (self.parse_initializer(err.is_some()), err) {
4894 (Ok(init), None) => { // init parsed, ty parsed
4897 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4898 // Could parse the type as if it were the initializer, it is likely there was a
4899 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4900 err.span_suggestion_short(
4902 "use `=` if you meant to assign",
4904 Applicability::MachineApplicable
4907 // As this was parsed successfully, continue as if the code has been fixed for the
4908 // rest of the file. It will still fail due to the emitted error, but we avoid
4912 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4914 // Couldn't parse the type nor the initializer, only raise the type error and
4915 // return to the parser state before parsing the type as the initializer.
4916 // let x: <parse_error>;
4917 mem::replace(self, snapshot);
4920 (Err(err), None) => { // init error, ty parsed
4921 // Couldn't parse the initializer and we're not attempting to recover a failed
4922 // parse of the type, return the error.
4926 let hi = if self.token == token::Semi {
4935 id: ast::DUMMY_NODE_ID,
4938 source: LocalSource::Normal,
4942 /// Parses a structure field.
4943 fn parse_name_and_ty(&mut self,
4946 attrs: Vec<Attribute>)
4947 -> PResult<'a, StructField> {
4948 let name = self.parse_ident()?;
4949 self.expect(&token::Colon)?;
4950 let ty = self.parse_ty()?;
4952 span: lo.to(self.prev_span),
4955 id: ast::DUMMY_NODE_ID,
4961 /// Emits an expected-item-after-attributes error.
4962 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
4963 let message = match attrs.last() {
4964 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4965 _ => "expected item after attributes",
4968 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
4969 if attrs.last().unwrap().is_sugared_doc {
4970 err.span_label(self.prev_span, "this doc comment doesn't document anything");
4975 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4976 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4977 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4978 Ok(self.parse_stmt_(true))
4981 // Eat tokens until we can be relatively sure we reached the end of the
4982 // statement. This is something of a best-effort heuristic.
4984 // We terminate when we find an unmatched `}` (without consuming it).
4985 fn recover_stmt(&mut self) {
4986 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4989 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4990 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4991 // approximate - it can mean we break too early due to macros, but that
4992 // should only lead to sub-optimal recovery, not inaccurate parsing).
4994 // If `break_on_block` is `Break`, then we will stop consuming tokens
4995 // after finding (and consuming) a brace-delimited block.
4996 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4997 let mut brace_depth = 0;
4998 let mut bracket_depth = 0;
4999 let mut in_block = false;
5000 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
5001 break_on_semi, break_on_block);
5003 debug!("recover_stmt_ loop {:?}", self.token);
5005 token::OpenDelim(token::DelimToken::Brace) => {
5008 if break_on_block == BlockMode::Break &&
5010 bracket_depth == 0 {
5014 token::OpenDelim(token::DelimToken::Bracket) => {
5018 token::CloseDelim(token::DelimToken::Brace) => {
5019 if brace_depth == 0 {
5020 debug!("recover_stmt_ return - close delim {:?}", self.token);
5025 if in_block && bracket_depth == 0 && brace_depth == 0 {
5026 debug!("recover_stmt_ return - block end {:?}", self.token);
5030 token::CloseDelim(token::DelimToken::Bracket) => {
5032 if bracket_depth < 0 {
5038 debug!("recover_stmt_ return - Eof");
5043 if break_on_semi == SemiColonMode::Break &&
5045 bracket_depth == 0 {
5046 debug!("recover_stmt_ return - Semi");
5051 if break_on_semi == SemiColonMode::Comma &&
5053 bracket_depth == 0 {
5054 debug!("recover_stmt_ return - Semi");
5067 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
5068 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
5070 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5075 fn is_async_block(&mut self) -> bool {
5076 self.token.is_keyword(keywords::Async) &&
5079 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
5080 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
5082 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
5087 fn is_async_fn(&mut self) -> bool {
5088 self.token.is_keyword(keywords::Async) &&
5089 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
5092 fn is_do_catch_block(&mut self) -> bool {
5093 self.token.is_keyword(keywords::Do) &&
5094 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
5095 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
5096 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5099 fn is_try_block(&mut self) -> bool {
5100 self.token.is_keyword(keywords::Try) &&
5101 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
5102 self.span.rust_2018() &&
5103 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
5104 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5107 fn is_union_item(&self) -> bool {
5108 self.token.is_keyword(keywords::Union) &&
5109 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
5112 fn is_crate_vis(&self) -> bool {
5113 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
5116 fn is_existential_type_decl(&self) -> bool {
5117 self.token.is_keyword(keywords::Existential) &&
5118 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
5121 fn is_auto_trait_item(&mut self) -> bool {
5123 (self.token.is_keyword(keywords::Auto)
5124 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
5125 || // unsafe auto trait
5126 (self.token.is_keyword(keywords::Unsafe) &&
5127 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
5128 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
5131 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
5132 -> PResult<'a, Option<P<Item>>> {
5133 let token_lo = self.span;
5134 let (ident, def) = match self.token {
5135 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
5137 let ident = self.parse_ident()?;
5138 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
5139 match self.parse_token_tree() {
5140 TokenTree::Delimited(_, _, tts) => tts,
5141 _ => unreachable!(),
5143 } else if self.check(&token::OpenDelim(token::Paren)) {
5144 let args = self.parse_token_tree();
5145 let body = if self.check(&token::OpenDelim(token::Brace)) {
5146 self.parse_token_tree()
5151 TokenStream::new(vec![
5153 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
5161 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
5163 token::Ident(ident, _) if ident.name == "macro_rules" &&
5164 self.look_ahead(1, |t| *t == token::Not) => {
5165 let prev_span = self.prev_span;
5166 self.complain_if_pub_macro(&vis.node, prev_span);
5170 let ident = self.parse_ident()?;
5171 let (delim, tokens) = self.expect_delimited_token_tree()?;
5172 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
5173 self.report_invalid_macro_expansion_item();
5176 (ident, ast::MacroDef { tokens: tokens, legacy: true })
5178 _ => return Ok(None),
5181 let span = lo.to(self.prev_span);
5182 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
5185 fn parse_stmt_without_recovery(&mut self,
5186 macro_legacy_warnings: bool)
5187 -> PResult<'a, Option<Stmt>> {
5188 maybe_whole!(self, NtStmt, |x| Some(x));
5190 let attrs = self.parse_outer_attributes()?;
5193 Ok(Some(if self.eat_keyword(keywords::Let) {
5195 id: ast::DUMMY_NODE_ID,
5196 node: StmtKind::Local(self.parse_local(attrs.into())?),
5197 span: lo.to(self.prev_span),
5199 } else if let Some(macro_def) = self.eat_macro_def(
5201 &source_map::respan(lo, VisibilityKind::Inherited),
5205 id: ast::DUMMY_NODE_ID,
5206 node: StmtKind::Item(macro_def),
5207 span: lo.to(self.prev_span),
5209 // Starts like a simple path, being careful to avoid contextual keywords
5210 // such as a union items, item with `crate` visibility or auto trait items.
5211 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
5212 // like a path (1 token), but it fact not a path.
5213 // `union::b::c` - path, `union U { ... }` - not a path.
5214 // `crate::b::c` - path, `crate struct S;` - not a path.
5215 } else if self.token.is_path_start() &&
5216 !self.token.is_qpath_start() &&
5217 !self.is_union_item() &&
5218 !self.is_crate_vis() &&
5219 !self.is_existential_type_decl() &&
5220 !self.is_auto_trait_item() &&
5221 !self.is_async_fn() {
5222 let pth = self.parse_path(PathStyle::Expr)?;
5224 if !self.eat(&token::Not) {
5225 let expr = if self.check(&token::OpenDelim(token::Brace)) {
5226 self.parse_struct_expr(lo, pth, ThinVec::new())?
5228 let hi = self.prev_span;
5229 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
5232 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
5233 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
5234 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
5237 return Ok(Some(Stmt {
5238 id: ast::DUMMY_NODE_ID,
5239 node: StmtKind::Expr(expr),
5240 span: lo.to(self.prev_span),
5244 // it's a macro invocation
5245 let id = match self.token {
5246 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
5247 _ => self.parse_ident()?,
5250 // check that we're pointing at delimiters (need to check
5251 // again after the `if`, because of `parse_ident`
5252 // consuming more tokens).
5254 token::OpenDelim(_) => {}
5256 // we only expect an ident if we didn't parse one
5258 let ident_str = if id.name == keywords::Invalid.name() {
5263 let tok_str = self.this_token_descr();
5264 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
5267 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
5272 let (delim, tts) = self.expect_delimited_token_tree()?;
5273 let hi = self.prev_span;
5275 let style = if delim == MacDelimiter::Brace {
5276 MacStmtStyle::Braces
5278 MacStmtStyle::NoBraces
5281 if id.name == keywords::Invalid.name() {
5282 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
5283 let node = if delim == MacDelimiter::Brace ||
5284 self.token == token::Semi || self.token == token::Eof {
5285 StmtKind::Mac(P((mac, style, attrs.into())))
5287 // We used to incorrectly stop parsing macro-expanded statements here.
5288 // If the next token will be an error anyway but could have parsed with the
5289 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
5290 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
5291 // These can continue an expression, so we can't stop parsing and warn.
5292 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
5293 token::BinOp(token::Minus) | token::BinOp(token::Star) |
5294 token::BinOp(token::And) | token::BinOp(token::Or) |
5295 token::AndAnd | token::OrOr |
5296 token::DotDot | token::DotDotDot | token::DotDotEq => false,
5299 self.warn_missing_semicolon();
5300 StmtKind::Mac(P((mac, style, attrs.into())))
5302 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
5303 let e = self.maybe_recover_from_bad_qpath(e, true)?;
5304 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
5305 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
5309 id: ast::DUMMY_NODE_ID,
5314 // if it has a special ident, it's definitely an item
5316 // Require a semicolon or braces.
5317 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
5318 self.report_invalid_macro_expansion_item();
5320 let span = lo.to(hi);
5322 id: ast::DUMMY_NODE_ID,
5324 node: StmtKind::Item({
5326 span, id /*id is good here*/,
5327 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
5328 respan(lo, VisibilityKind::Inherited),
5334 // FIXME: Bad copy of attrs
5335 let old_directory_ownership =
5336 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
5337 let item = self.parse_item_(attrs.clone(), false, true)?;
5338 self.directory.ownership = old_directory_ownership;
5342 id: ast::DUMMY_NODE_ID,
5343 span: lo.to(i.span),
5344 node: StmtKind::Item(i),
5347 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
5348 if !attrs.is_empty() {
5349 if s.prev_token_kind == PrevTokenKind::DocComment {
5350 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
5351 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
5352 s.span_err(s.span, "expected statement after outer attribute");
5357 // Do not attempt to parse an expression if we're done here.
5358 if self.token == token::Semi {
5359 unused_attrs(&attrs, self);
5364 if self.token == token::CloseDelim(token::Brace) {
5365 unused_attrs(&attrs, self);
5369 // Remainder are line-expr stmts.
5370 let e = self.parse_expr_res(
5371 Restrictions::STMT_EXPR, Some(attrs.into()))?;
5373 id: ast::DUMMY_NODE_ID,
5374 span: lo.to(e.span),
5375 node: StmtKind::Expr(e),
5382 /// Checks if this expression is a successfully parsed statement.
5383 fn expr_is_complete(&mut self, e: &Expr) -> bool {
5384 self.restrictions.contains(Restrictions::STMT_EXPR) &&
5385 !classify::expr_requires_semi_to_be_stmt(e)
5388 /// Parses a block. No inner attributes are allowed.
5389 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
5390 maybe_whole!(self, NtBlock, |x| x);
5394 if !self.eat(&token::OpenDelim(token::Brace)) {
5396 let tok = self.this_token_descr();
5397 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
5398 let do_not_suggest_help =
5399 self.token.is_keyword(keywords::In) || self.token == token::Colon;
5401 if self.token.is_ident_named("and") {
5402 e.span_suggestion_short(
5404 "use `&&` instead of `and` for the boolean operator",
5406 Applicability::MaybeIncorrect,
5409 if self.token.is_ident_named("or") {
5410 e.span_suggestion_short(
5412 "use `||` instead of `or` for the boolean operator",
5414 Applicability::MaybeIncorrect,
5418 // Check to see if the user has written something like
5423 // Which is valid in other languages, but not Rust.
5424 match self.parse_stmt_without_recovery(false) {
5426 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
5427 || do_not_suggest_help {
5428 // if the next token is an open brace (e.g., `if a b {`), the place-
5429 // inside-a-block suggestion would be more likely wrong than right
5430 e.span_label(sp, "expected `{`");
5433 let mut stmt_span = stmt.span;
5434 // expand the span to include the semicolon, if it exists
5435 if self.eat(&token::Semi) {
5436 stmt_span = stmt_span.with_hi(self.prev_span.hi());
5438 let sugg = pprust::to_string(|s| {
5439 use crate::print::pprust::{PrintState, INDENT_UNIT};
5440 s.ibox(INDENT_UNIT)?;
5442 s.print_stmt(&stmt)?;
5443 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
5447 "try placing this code inside a block",
5449 // speculative, has been misleading in the past (closed Issue #46836)
5450 Applicability::MaybeIncorrect
5454 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5455 self.cancel(&mut e);
5459 e.span_label(sp, "expected `{`");
5463 self.parse_block_tail(lo, BlockCheckMode::Default)
5466 /// Parses a block. Inner attributes are allowed.
5467 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
5468 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
5471 self.expect(&token::OpenDelim(token::Brace))?;
5472 Ok((self.parse_inner_attributes()?,
5473 self.parse_block_tail(lo, BlockCheckMode::Default)?))
5476 /// Parses the rest of a block expression or function body.
5477 /// Precondition: already parsed the '{'.
5478 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
5479 let mut stmts = vec![];
5480 while !self.eat(&token::CloseDelim(token::Brace)) {
5481 let stmt = match self.parse_full_stmt(false) {
5484 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
5486 id: ast::DUMMY_NODE_ID,
5487 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
5493 if let Some(stmt) = stmt {
5495 } else if self.token == token::Eof {
5498 // Found only `;` or `}`.
5504 id: ast::DUMMY_NODE_ID,
5506 span: lo.to(self.prev_span),
5510 /// Parses a statement, including the trailing semicolon.
5511 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5512 // skip looking for a trailing semicolon when we have an interpolated statement
5513 maybe_whole!(self, NtStmt, |x| Some(x));
5515 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5517 None => return Ok(None),
5521 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5522 // expression without semicolon
5523 if classify::expr_requires_semi_to_be_stmt(expr) {
5524 // Just check for errors and recover; do not eat semicolon yet.
5526 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5529 self.recover_stmt();
5533 StmtKind::Local(..) => {
5534 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5535 if macro_legacy_warnings && self.token != token::Semi {
5536 self.warn_missing_semicolon();
5538 self.expect_one_of(&[], &[token::Semi])?;
5544 if self.eat(&token::Semi) {
5545 stmt = stmt.add_trailing_semicolon();
5548 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5552 fn warn_missing_semicolon(&self) {
5553 self.diagnostic().struct_span_warn(self.span, {
5554 &format!("expected `;`, found {}", self.this_token_descr())
5556 "This was erroneously allowed and will become a hard error in a future release"
5560 fn err_dotdotdot_syntax(&self, span: Span) {
5561 self.diagnostic().struct_span_err(span, {
5562 "unexpected token: `...`"
5564 span, "use `..` for an exclusive range", "..".to_owned(),
5565 Applicability::MaybeIncorrect
5567 span, "or `..=` for an inclusive range", "..=".to_owned(),
5568 Applicability::MaybeIncorrect
5572 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
5575 /// BOUND = TY_BOUND | LT_BOUND
5576 /// LT_BOUND = LIFETIME (e.g., `'a`)
5577 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5578 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5580 fn parse_generic_bounds_common(&mut self,
5582 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5583 let mut bounds = Vec::new();
5584 let mut negative_bounds = Vec::new();
5585 let mut last_plus_span = None;
5586 let mut was_negative = false;
5588 // This needs to be synchronized with `Token::can_begin_bound`.
5589 let is_bound_start = self.check_path() || self.check_lifetime() ||
5590 self.check(&token::Not) || // used for error reporting only
5591 self.check(&token::Question) ||
5592 self.check_keyword(keywords::For) ||
5593 self.check(&token::OpenDelim(token::Paren));
5596 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5597 let inner_lo = self.span;
5598 let is_negative = self.eat(&token::Not);
5599 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5600 if self.token.is_lifetime() {
5601 if let Some(question_span) = question {
5602 self.span_err(question_span,
5603 "`?` may only modify trait bounds, not lifetime bounds");
5605 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5607 let inner_span = inner_lo.to(self.prev_span);
5608 self.expect(&token::CloseDelim(token::Paren))?;
5609 let mut err = self.struct_span_err(
5610 lo.to(self.prev_span),
5611 "parenthesized lifetime bounds are not supported"
5613 if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
5614 err.span_suggestion_short(
5615 lo.to(self.prev_span),
5616 "remove the parentheses",
5618 Applicability::MachineApplicable
5624 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5625 let path = self.parse_path(PathStyle::Type)?;
5627 self.expect(&token::CloseDelim(token::Paren))?;
5629 let poly_span = lo.to(self.prev_span);
5631 was_negative = true;
5632 if let Some(sp) = last_plus_span.or(colon_span) {
5633 negative_bounds.push(sp.to(poly_span));
5636 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
5637 let modifier = if question.is_some() {
5638 TraitBoundModifier::Maybe
5640 TraitBoundModifier::None
5642 bounds.push(GenericBound::Trait(poly_trait, modifier));
5649 if !allow_plus || !self.eat_plus() {
5652 last_plus_span = Some(self.prev_span);
5656 if !negative_bounds.is_empty() || was_negative {
5657 let plural = negative_bounds.len() > 1;
5658 let last_span = negative_bounds.last().map(|sp| *sp);
5659 let mut err = self.struct_span_err(
5661 "negative trait bounds are not supported",
5663 if let Some(sp) = last_span {
5664 err.span_label(sp, "negative trait bounds are not supported");
5666 if let Some(bound_list) = colon_span {
5667 let bound_list = bound_list.to(self.prev_span);
5668 let mut new_bound_list = String::new();
5669 if !bounds.is_empty() {
5670 let mut snippets = bounds.iter().map(|bound| bound.span())
5671 .map(|span| self.sess.source_map().span_to_snippet(span));
5672 while let Some(Ok(snippet)) = snippets.next() {
5673 new_bound_list.push_str(" + ");
5674 new_bound_list.push_str(&snippet);
5676 new_bound_list = new_bound_list.replacen(" +", ":", 1);
5678 err.span_suggestion_hidden(
5680 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
5682 Applicability::MachineApplicable,
5691 crate fn parse_generic_bounds(&mut self,
5692 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5693 self.parse_generic_bounds_common(true, colon_span)
5696 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5699 /// BOUND = LT_BOUND (e.g., `'a`)
5701 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5702 let mut lifetimes = Vec::new();
5703 while self.check_lifetime() {
5704 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5706 if !self.eat_plus() {
5713 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
5714 fn parse_ty_param(&mut self,
5715 preceding_attrs: Vec<Attribute>)
5716 -> PResult<'a, GenericParam> {
5717 let ident = self.parse_ident()?;
5719 // Parse optional colon and param bounds.
5720 let bounds = if self.eat(&token::Colon) {
5721 self.parse_generic_bounds(Some(self.prev_span))?
5726 let default = if self.eat(&token::Eq) {
5727 Some(self.parse_ty()?)
5734 id: ast::DUMMY_NODE_ID,
5735 attrs: preceding_attrs.into(),
5737 kind: GenericParamKind::Type {
5743 /// Parses the following grammar:
5745 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5746 fn parse_trait_item_assoc_ty(&mut self)
5747 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5748 let ident = self.parse_ident()?;
5749 let mut generics = self.parse_generics()?;
5751 // Parse optional colon and param bounds.
5752 let bounds = if self.eat(&token::Colon) {
5753 self.parse_generic_bounds(None)?
5757 generics.where_clause = self.parse_where_clause()?;
5759 let default = if self.eat(&token::Eq) {
5760 Some(self.parse_ty()?)
5764 self.expect(&token::Semi)?;
5766 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5769 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
5770 self.expect_keyword(keywords::Const)?;
5771 let ident = self.parse_ident()?;
5772 self.expect(&token::Colon)?;
5773 let ty = self.parse_ty()?;
5777 id: ast::DUMMY_NODE_ID,
5778 attrs: preceding_attrs.into(),
5780 kind: GenericParamKind::Const {
5786 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
5787 /// a trailing comma and erroneous trailing attributes.
5788 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5789 let mut params = Vec::new();
5791 let attrs = self.parse_outer_attributes()?;
5792 if self.check_lifetime() {
5793 let lifetime = self.expect_lifetime();
5794 // Parse lifetime parameter.
5795 let bounds = if self.eat(&token::Colon) {
5796 self.parse_lt_param_bounds()
5800 params.push(ast::GenericParam {
5801 ident: lifetime.ident,
5803 attrs: attrs.into(),
5805 kind: ast::GenericParamKind::Lifetime,
5807 } else if self.check_keyword(keywords::Const) {
5808 // Parse const parameter.
5809 params.push(self.parse_const_param(attrs)?);
5810 } else if self.check_ident() {
5811 // Parse type parameter.
5812 params.push(self.parse_ty_param(attrs)?);
5814 // Check for trailing attributes and stop parsing.
5815 if !attrs.is_empty() {
5816 if !params.is_empty() {
5817 self.struct_span_err(
5819 &format!("trailing attribute after generic parameter"),
5821 .span_label(attrs[0].span, "attributes must go before parameters")
5824 self.struct_span_err(
5826 &format!("attribute without generic parameters"),
5830 "attributes are only permitted when preceding parameters",
5838 if !self.eat(&token::Comma) {
5845 /// Parses a set of optional generic type parameter declarations. Where
5846 /// clauses are not parsed here, and must be added later via
5847 /// `parse_where_clause()`.
5849 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5850 /// | ( < lifetimes , typaramseq ( , )? > )
5851 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5852 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5853 maybe_whole!(self, NtGenerics, |x| x);
5855 let span_lo = self.span;
5857 let params = self.parse_generic_params()?;
5861 where_clause: WhereClause {
5862 id: ast::DUMMY_NODE_ID,
5863 predicates: Vec::new(),
5864 span: syntax_pos::DUMMY_SP,
5866 span: span_lo.to(self.prev_span),
5869 Ok(ast::Generics::default())
5873 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5874 /// For the purposes of understanding the parsing logic of generic arguments, this function
5875 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5876 /// had the correct amount of leading angle brackets.
5878 /// ```ignore (diagnostics)
5879 /// bar::<<<<T as Foo>::Output>();
5880 /// ^^ help: remove extra angle brackets
5882 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5886 ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5887 // We need to detect whether there are extra leading left angle brackets and produce an
5888 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5889 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5890 // then there won't be matching `>` tokens to find.
5892 // To explain how this detection works, consider the following example:
5894 // ```ignore (diagnostics)
5895 // bar::<<<<T as Foo>::Output>();
5896 // ^^ help: remove extra angle brackets
5899 // Parsing of the left angle brackets starts in this function. We start by parsing the
5900 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5903 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5904 // *Unmatched count:* 1
5905 // *`parse_path_segment` calls deep:* 0
5907 // This has the effect of recursing as this function is called if a `<` character
5908 // is found within the expected generic arguments:
5910 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5911 // *Unmatched count:* 2
5912 // *`parse_path_segment` calls deep:* 1
5914 // Eventually we will have recursed until having consumed all of the `<` tokens and
5915 // this will be reflected in the count:
5917 // *Upcoming tokens:* `T as Foo>::Output>;`
5918 // *Unmatched count:* 4
5919 // `parse_path_segment` calls deep:* 3
5921 // The parser will continue until reaching the first `>` - this will decrement the
5922 // unmatched angle bracket count and return to the parent invocation of this function
5923 // having succeeded in parsing:
5925 // *Upcoming tokens:* `::Output>;`
5926 // *Unmatched count:* 3
5927 // *`parse_path_segment` calls deep:* 2
5929 // This will continue until the next `>` character which will also return successfully
5930 // to the parent invocation of this function and decrement the count:
5932 // *Upcoming tokens:* `;`
5933 // *Unmatched count:* 2
5934 // *`parse_path_segment` calls deep:* 1
5936 // At this point, this function will expect to find another matching `>` character but
5937 // won't be able to and will return an error. This will continue all the way up the
5938 // call stack until the first invocation:
5940 // *Upcoming tokens:* `;`
5941 // *Unmatched count:* 2
5942 // *`parse_path_segment` calls deep:* 0
5944 // In doing this, we have managed to work out how many unmatched leading left angle
5945 // brackets there are, but we cannot recover as the unmatched angle brackets have
5946 // already been consumed. To remedy this, we keep a snapshot of the parser state
5947 // before we do the above. We can then inspect whether we ended up with a parsing error
5948 // and unmatched left angle brackets and if so, restore the parser state before we
5949 // consumed any `<` characters to emit an error and consume the erroneous tokens to
5950 // recover by attempting to parse again.
5952 // In practice, the recursion of this function is indirect and there will be other
5953 // locations that consume some `<` characters - as long as we update the count when
5954 // this happens, it isn't an issue.
5956 let is_first_invocation = style == PathStyle::Expr;
5957 // Take a snapshot before attempting to parse - we can restore this later.
5958 let snapshot = if is_first_invocation {
5964 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
5965 match self.parse_generic_args() {
5966 Ok(value) => Ok(value),
5967 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
5968 // Cancel error from being unable to find `>`. We know the error
5969 // must have been this due to a non-zero unmatched angle bracket
5973 // Swap `self` with our backup of the parser state before attempting to parse
5974 // generic arguments.
5975 let snapshot = mem::replace(self, snapshot.unwrap());
5978 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
5979 snapshot.count={:?}",
5980 snapshot.unmatched_angle_bracket_count,
5983 // Eat the unmatched angle brackets.
5984 for _ in 0..snapshot.unmatched_angle_bracket_count {
5988 // Make a span over ${unmatched angle bracket count} characters.
5989 let span = lo.with_hi(
5990 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
5992 let plural = snapshot.unmatched_angle_bracket_count > 1;
5997 "unmatched angle bracket{}",
5998 if plural { "s" } else { "" }
6004 "remove extra angle bracket{}",
6005 if plural { "s" } else { "" }
6008 Applicability::MachineApplicable,
6012 // Try again without unmatched angle bracket characters.
6013 self.parse_generic_args()
6019 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
6020 /// possibly including trailing comma.
6021 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
6022 let mut args = Vec::new();
6023 let mut bindings = Vec::new();
6024 let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new();
6025 let mut assoc_ty_bindings: Vec<Span> = Vec::new();
6027 let args_lo = self.span;
6030 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6031 // Parse lifetime argument.
6032 args.push(GenericArg::Lifetime(self.expect_lifetime()));
6033 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6034 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
6035 // Parse associated type binding.
6037 let ident = self.parse_ident()?;
6039 let ty = self.parse_ty()?;
6040 let span = lo.to(self.prev_span);
6041 bindings.push(TypeBinding {
6042 id: ast::DUMMY_NODE_ID,
6047 assoc_ty_bindings.push(span);
6048 } else if self.check_const_arg() {
6049 // Parse const argument.
6050 let expr = if let token::OpenDelim(token::Brace) = self.token {
6051 self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
6052 } else if self.token.is_ident() {
6053 // FIXME(const_generics): to distinguish between idents for types and consts,
6054 // we should introduce a GenericArg::Ident in the AST and distinguish when
6055 // lowering to the HIR. For now, idents for const args are not permitted.
6057 self.fatal("identifiers may currently not be used for const generics")
6060 self.parse_literal_maybe_minus()?
6062 let value = AnonConst {
6063 id: ast::DUMMY_NODE_ID,
6066 args.push(GenericArg::Const(value));
6067 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6068 } else if self.check_type() {
6069 // Parse type argument.
6070 args.push(GenericArg::Type(self.parse_ty()?));
6071 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6076 if !self.eat(&token::Comma) {
6081 // FIXME: we would like to report this in ast_validation instead, but we currently do not
6082 // preserve ordering of generic parameters with respect to associated type binding, so we
6083 // lose that information after parsing.
6084 if misplaced_assoc_ty_bindings.len() > 0 {
6085 let mut err = self.struct_span_err(
6086 args_lo.to(self.prev_span),
6087 "associated type bindings must be declared after generic parameters",
6089 for span in misplaced_assoc_ty_bindings {
6092 "this associated type binding should be moved after the generic parameters",
6098 Ok((args, bindings))
6101 /// Parses an optional where-clause and places it in `generics`.
6103 /// ```ignore (only-for-syntax-highlight)
6104 /// where T : Trait<U, V> + 'b, 'a : 'b
6106 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
6107 maybe_whole!(self, NtWhereClause, |x| x);
6109 let mut where_clause = WhereClause {
6110 id: ast::DUMMY_NODE_ID,
6111 predicates: Vec::new(),
6112 span: syntax_pos::DUMMY_SP,
6115 if !self.eat_keyword(keywords::Where) {
6116 return Ok(where_clause);
6118 let lo = self.prev_span;
6120 // We are considering adding generics to the `where` keyword as an alternative higher-rank
6121 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
6122 // change we parse those generics now, but report an error.
6123 if self.choose_generics_over_qpath() {
6124 let generics = self.parse_generics()?;
6125 self.struct_span_err(
6127 "generic parameters on `where` clauses are reserved for future use",
6129 .span_label(generics.span, "currently unsupported")
6135 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6136 let lifetime = self.expect_lifetime();
6137 // Bounds starting with a colon are mandatory, but possibly empty.
6138 self.expect(&token::Colon)?;
6139 let bounds = self.parse_lt_param_bounds();
6140 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
6141 ast::WhereRegionPredicate {
6142 span: lo.to(self.prev_span),
6147 } else if self.check_type() {
6148 // Parse optional `for<'a, 'b>`.
6149 // This `for` is parsed greedily and applies to the whole predicate,
6150 // the bounded type can have its own `for` applying only to it.
6151 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
6152 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
6153 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
6154 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
6156 // Parse type with mandatory colon and (possibly empty) bounds,
6157 // or with mandatory equality sign and the second type.
6158 let ty = self.parse_ty()?;
6159 if self.eat(&token::Colon) {
6160 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6161 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
6162 ast::WhereBoundPredicate {
6163 span: lo.to(self.prev_span),
6164 bound_generic_params: lifetime_defs,
6169 // FIXME: Decide what should be used here, `=` or `==`.
6170 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
6171 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
6172 let rhs_ty = self.parse_ty()?;
6173 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
6174 ast::WhereEqPredicate {
6175 span: lo.to(self.prev_span),
6178 id: ast::DUMMY_NODE_ID,
6182 return self.unexpected();
6188 if !self.eat(&token::Comma) {
6193 where_clause.span = lo.to(self.prev_span);
6197 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
6198 -> PResult<'a, (Vec<Arg> , bool)> {
6199 self.expect(&token::OpenDelim(token::Paren))?;
6202 let mut c_variadic = false;
6203 let (args, recovered): (Vec<Option<Arg>>, bool) =
6204 self.parse_seq_to_before_end(
6205 &token::CloseDelim(token::Paren),
6206 SeqSep::trailing_allowed(token::Comma),
6208 // If the argument is a C-variadic argument we should not
6209 // enforce named arguments.
6210 let enforce_named_args = if p.token == token::DotDotDot {
6215 match p.parse_arg_general(enforce_named_args, false,
6218 if let TyKind::CVarArgs = arg.ty.node {
6220 if p.token != token::CloseDelim(token::Paren) {
6223 "`...` must be the last argument of a C-variadic function");
6234 let lo = p.prev_span;
6235 // Skip every token until next possible arg or end.
6236 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
6237 // Create a placeholder argument for proper arg count (issue #34264).
6238 let span = lo.to(p.prev_span);
6239 Ok(Some(dummy_arg(span)))
6246 self.eat(&token::CloseDelim(token::Paren));
6249 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
6251 if c_variadic && args.is_empty() {
6253 "C-variadic function must be declared with at least one named argument");
6256 Ok((args, c_variadic))
6259 /// Parses the argument list and result type of a function declaration.
6260 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
6262 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
6263 let ret_ty = self.parse_ret_ty(true)?;
6272 /// Returns the parsed optional self argument and whether a self shortcut was used.
6273 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
6274 let expect_ident = |this: &mut Self| match this.token {
6275 // Preserve hygienic context.
6276 token::Ident(ident, _) =>
6277 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
6280 let isolated_self = |this: &mut Self, n| {
6281 this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) &&
6282 this.look_ahead(n + 1, |t| t != &token::ModSep)
6285 // Parse optional self parameter of a method.
6286 // Only a limited set of initial token sequences is considered self parameters, anything
6287 // else is parsed as a normal function parameter list, so some lookahead is required.
6288 let eself_lo = self.span;
6289 let (eself, eself_ident, eself_hi) = match self.token {
6290 token::BinOp(token::And) => {
6296 (if isolated_self(self, 1) {
6298 SelfKind::Region(None, Mutability::Immutable)
6299 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
6300 isolated_self(self, 2) {
6303 SelfKind::Region(None, Mutability::Mutable)
6304 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6305 isolated_self(self, 2) {
6307 let lt = self.expect_lifetime();
6308 SelfKind::Region(Some(lt), Mutability::Immutable)
6309 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6310 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
6311 isolated_self(self, 3) {
6313 let lt = self.expect_lifetime();
6315 SelfKind::Region(Some(lt), Mutability::Mutable)
6318 }, expect_ident(self), self.prev_span)
6320 token::BinOp(token::Star) => {
6325 // Emit special error for `self` cases.
6326 let msg = "cannot pass `self` by raw pointer";
6327 (if isolated_self(self, 1) {
6329 self.struct_span_err(self.span, msg)
6330 .span_label(self.span, msg)
6332 SelfKind::Value(Mutability::Immutable)
6333 } else if self.look_ahead(1, |t| t.is_mutability()) &&
6334 isolated_self(self, 2) {
6337 self.struct_span_err(self.span, msg)
6338 .span_label(self.span, msg)
6340 SelfKind::Value(Mutability::Immutable)
6343 }, expect_ident(self), self.prev_span)
6345 token::Ident(..) => {
6346 if isolated_self(self, 0) {
6349 let eself_ident = expect_ident(self);
6350 let eself_hi = self.prev_span;
6351 (if self.eat(&token::Colon) {
6352 let ty = self.parse_ty()?;
6353 SelfKind::Explicit(ty, Mutability::Immutable)
6355 SelfKind::Value(Mutability::Immutable)
6356 }, eself_ident, eself_hi)
6357 } else if self.token.is_keyword(keywords::Mut) &&
6358 isolated_self(self, 1) {
6362 let eself_ident = expect_ident(self);
6363 let eself_hi = self.prev_span;
6364 (if self.eat(&token::Colon) {
6365 let ty = self.parse_ty()?;
6366 SelfKind::Explicit(ty, Mutability::Mutable)
6368 SelfKind::Value(Mutability::Mutable)
6369 }, eself_ident, eself_hi)
6374 _ => return Ok(None),
6377 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
6378 Ok(Some(Arg::from_self(eself, eself_ident)))
6381 /// Parses the parameter list and result type of a function that may have a `self` parameter.
6382 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
6383 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
6385 self.expect(&token::OpenDelim(token::Paren))?;
6387 // Parse optional self argument
6388 let self_arg = self.parse_self_arg()?;
6390 // Parse the rest of the function parameter list.
6391 let sep = SeqSep::trailing_allowed(token::Comma);
6392 let (fn_inputs, recovered) = if let Some(self_arg) = self_arg {
6393 if self.check(&token::CloseDelim(token::Paren)) {
6394 (vec![self_arg], false)
6395 } else if self.eat(&token::Comma) {
6396 let mut fn_inputs = vec![self_arg];
6397 let (mut input, recovered) = self.parse_seq_to_before_end(
6398 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
6399 fn_inputs.append(&mut input);
6400 (fn_inputs, recovered)
6402 match self.expect_one_of(&[], &[]) {
6403 Err(err) => return Err(err),
6404 Ok(recovered) => (vec![self_arg], recovered),
6408 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
6412 // Parse closing paren and return type.
6413 self.expect(&token::CloseDelim(token::Paren))?;
6417 output: self.parse_ret_ty(true)?,
6422 /// Parses the `|arg, arg|` header of a closure.
6423 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
6424 let inputs_captures = {
6425 if self.eat(&token::OrOr) {
6428 self.expect(&token::BinOp(token::Or))?;
6429 let args = self.parse_seq_to_before_tokens(
6430 &[&token::BinOp(token::Or), &token::OrOr],
6431 SeqSep::trailing_allowed(token::Comma),
6432 TokenExpectType::NoExpect,
6433 |p| p.parse_fn_block_arg()
6439 let output = self.parse_ret_ty(true)?;
6442 inputs: inputs_captures,
6448 /// Parses the name and optional generic types of a function header.
6449 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
6450 let id = self.parse_ident()?;
6451 let generics = self.parse_generics()?;
6455 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
6456 attrs: Vec<Attribute>) -> P<Item> {
6460 id: ast::DUMMY_NODE_ID,
6468 /// Parses an item-position function declaration.
6469 fn parse_item_fn(&mut self,
6471 mut asyncness: Spanned<IsAsync>,
6472 constness: Spanned<Constness>,
6474 -> PResult<'a, ItemInfo> {
6475 let (ident, mut generics) = self.parse_fn_header()?;
6476 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
6477 let mut decl = self.parse_fn_decl(allow_c_variadic)?;
6478 generics.where_clause = self.parse_where_clause()?;
6479 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6480 self.construct_async_arguments(&mut asyncness, &mut decl);
6481 let header = FnHeader { unsafety, asyncness, constness, abi };
6482 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
6485 /// Returns `true` if we are looking at `const ID`
6486 /// (returns `false` for things like `const fn`, etc.).
6487 fn is_const_item(&mut self) -> bool {
6488 self.token.is_keyword(keywords::Const) &&
6489 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
6490 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
6493 /// Parses all the "front matter" for a `fn` declaration, up to
6494 /// and including the `fn` keyword:
6498 /// - `const unsafe fn`
6501 fn parse_fn_front_matter(&mut self)
6509 let is_const_fn = self.eat_keyword(keywords::Const);
6510 let const_span = self.prev_span;
6511 let unsafety = self.parse_unsafety();
6512 let asyncness = self.parse_asyncness();
6513 let asyncness = respan(self.prev_span, asyncness);
6514 let (constness, unsafety, abi) = if is_const_fn {
6515 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
6517 let abi = if self.eat_keyword(keywords::Extern) {
6518 self.parse_opt_abi()?.unwrap_or(Abi::C)
6522 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
6524 if !self.eat_keyword(keywords::Fn) {
6525 // It is possible for `expect_one_of` to recover given the contents of
6526 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
6527 // account for this.
6528 if !self.expect_one_of(&[], &[])? { unreachable!() }
6530 Ok((constness, unsafety, asyncness, abi))
6533 /// Parses an impl item.
6534 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
6535 maybe_whole!(self, NtImplItem, |x| x);
6536 let attrs = self.parse_outer_attributes()?;
6537 let mut unclosed_delims = vec![];
6538 let (mut item, tokens) = self.collect_tokens(|this| {
6539 let item = this.parse_impl_item_(at_end, attrs);
6540 unclosed_delims.append(&mut this.unclosed_delims);
6543 self.unclosed_delims.append(&mut unclosed_delims);
6545 // See `parse_item` for why this clause is here.
6546 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6547 item.tokens = Some(tokens);
6552 fn parse_impl_item_(&mut self,
6554 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
6556 let vis = self.parse_visibility(false)?;
6557 let defaultness = self.parse_defaultness();
6558 let (name, node, generics) = if let Some(type_) = self.eat_type() {
6559 let (name, alias, generics) = type_?;
6560 let kind = match alias {
6561 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
6562 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
6564 (name, kind, generics)
6565 } else if self.is_const_item() {
6566 // This parses the grammar:
6567 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
6568 self.expect_keyword(keywords::Const)?;
6569 let name = self.parse_ident()?;
6570 self.expect(&token::Colon)?;
6571 let typ = self.parse_ty()?;
6572 self.expect(&token::Eq)?;
6573 let expr = self.parse_expr()?;
6574 self.expect(&token::Semi)?;
6575 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
6577 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
6578 attrs.extend(inner_attrs);
6579 (name, node, generics)
6583 id: ast::DUMMY_NODE_ID,
6584 span: lo.to(self.prev_span),
6595 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
6597 VisibilityKind::Inherited => {}
6599 let is_macro_rules: bool = match self.token {
6600 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
6603 let mut err = if is_macro_rules {
6604 let mut err = self.diagnostic()
6605 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
6606 err.span_suggestion(
6608 "try exporting the macro",
6609 "#[macro_export]".to_owned(),
6610 Applicability::MaybeIncorrect // speculative
6614 let mut err = self.diagnostic()
6615 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
6616 err.help("try adjusting the macro to put `pub` inside the invocation");
6624 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
6625 -> DiagnosticBuilder<'a>
6627 let expected_kinds = if item_type == "extern" {
6628 "missing `fn`, `type`, or `static`"
6630 "missing `fn`, `type`, or `const`"
6633 // Given this code `path(`, it seems like this is not
6634 // setting the visibility of a macro invocation, but rather
6635 // a mistyped method declaration.
6636 // Create a diagnostic pointing out that `fn` is missing.
6638 // x | pub path(&self) {
6639 // | ^ missing `fn`, `type`, or `const`
6641 // ^^ `sp` below will point to this
6642 let sp = prev_span.between(self.prev_span);
6643 let mut err = self.diagnostic().struct_span_err(
6645 &format!("{} for {}-item declaration",
6646 expected_kinds, item_type));
6647 err.span_label(sp, expected_kinds);
6651 /// Parse a method or a macro invocation in a trait impl.
6652 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
6653 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
6654 ast::ImplItemKind)> {
6655 // code copied from parse_macro_use_or_failure... abstraction!
6656 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
6658 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
6659 ast::ImplItemKind::Macro(mac)))
6661 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
6662 let ident = self.parse_ident()?;
6663 let mut generics = self.parse_generics()?;
6664 let mut decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
6665 generics.where_clause = self.parse_where_clause()?;
6666 self.construct_async_arguments(&mut asyncness, &mut decl);
6668 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6669 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
6670 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
6671 ast::MethodSig { header, decl },
6677 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
6678 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
6679 let ident = self.parse_ident()?;
6680 let mut tps = self.parse_generics()?;
6682 // Parse optional colon and supertrait bounds.
6683 let bounds = if self.eat(&token::Colon) {
6684 self.parse_generic_bounds(Some(self.prev_span))?
6689 if self.eat(&token::Eq) {
6690 // it's a trait alias
6691 let bounds = self.parse_generic_bounds(None)?;
6692 tps.where_clause = self.parse_where_clause()?;
6693 self.expect(&token::Semi)?;
6694 if is_auto == IsAuto::Yes {
6695 let msg = "trait aliases cannot be `auto`";
6696 self.struct_span_err(self.prev_span, msg)
6697 .span_label(self.prev_span, msg)
6700 if unsafety != Unsafety::Normal {
6701 let msg = "trait aliases cannot be `unsafe`";
6702 self.struct_span_err(self.prev_span, msg)
6703 .span_label(self.prev_span, msg)
6706 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
6708 // it's a normal trait
6709 tps.where_clause = self.parse_where_clause()?;
6710 self.expect(&token::OpenDelim(token::Brace))?;
6711 let mut trait_items = vec![];
6712 while !self.eat(&token::CloseDelim(token::Brace)) {
6713 if let token::DocComment(_) = self.token {
6714 if self.look_ahead(1,
6715 |tok| tok == &token::Token::CloseDelim(token::Brace)) {
6716 let mut err = self.diagnostic().struct_span_err_with_code(
6718 "found a documentation comment that doesn't document anything",
6719 DiagnosticId::Error("E0584".into()),
6721 err.help("doc comments must come before what they document, maybe a \
6722 comment was intended with `//`?",
6729 let mut at_end = false;
6730 match self.parse_trait_item(&mut at_end) {
6731 Ok(item) => trait_items.push(item),
6735 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6740 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
6744 fn choose_generics_over_qpath(&self) -> bool {
6745 // There's an ambiguity between generic parameters and qualified paths in impls.
6746 // If we see `<` it may start both, so we have to inspect some following tokens.
6747 // The following combinations can only start generics,
6748 // but not qualified paths (with one exception):
6749 // `<` `>` - empty generic parameters
6750 // `<` `#` - generic parameters with attributes
6751 // `<` (LIFETIME|IDENT) `>` - single generic parameter
6752 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
6753 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
6754 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
6755 // `<` const - generic const parameter
6756 // The only truly ambiguous case is
6757 // `<` IDENT `>` `::` IDENT ...
6758 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
6759 // because this is what almost always expected in practice, qualified paths in impls
6760 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
6761 self.token == token::Lt &&
6762 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
6763 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
6764 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
6765 t == &token::Colon || t == &token::Eq) ||
6766 self.look_ahead(1, |t| t.is_keyword(keywords::Const)))
6769 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6770 self.expect(&token::OpenDelim(token::Brace))?;
6771 let attrs = self.parse_inner_attributes()?;
6773 let mut impl_items = Vec::new();
6774 while !self.eat(&token::CloseDelim(token::Brace)) {
6775 let mut at_end = false;
6776 match self.parse_impl_item(&mut at_end) {
6777 Ok(impl_item) => impl_items.push(impl_item),
6781 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6786 Ok((impl_items, attrs))
6789 /// Parses an implementation item, `impl` keyword is already parsed.
6791 /// impl<'a, T> TYPE { /* impl items */ }
6792 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6793 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6795 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6796 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6797 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6798 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6799 -> PResult<'a, ItemInfo> {
6800 // First, parse generic parameters if necessary.
6801 let mut generics = if self.choose_generics_over_qpath() {
6802 self.parse_generics()?
6804 ast::Generics::default()
6807 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6808 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6810 ast::ImplPolarity::Negative
6812 ast::ImplPolarity::Positive
6815 // Parse both types and traits as a type, then reinterpret if necessary.
6816 let err_path = |span| ast::Path::from_ident(Ident::new(keywords::Invalid.name(), span));
6817 let ty_first = if self.token.is_keyword(keywords::For) &&
6818 self.look_ahead(1, |t| t != &token::Lt) {
6819 let span = self.prev_span.between(self.span);
6820 self.struct_span_err(span, "missing trait in a trait impl").emit();
6821 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6826 // If `for` is missing we try to recover.
6827 let has_for = self.eat_keyword(keywords::For);
6828 let missing_for_span = self.prev_span.between(self.span);
6830 let ty_second = if self.token == token::DotDot {
6831 // We need to report this error after `cfg` expansion for compatibility reasons
6832 self.bump(); // `..`, do not add it to expected tokens
6833 Some(DummyResult::raw_ty(self.prev_span, true))
6834 } else if has_for || self.token.can_begin_type() {
6835 Some(self.parse_ty()?)
6840 generics.where_clause = self.parse_where_clause()?;
6842 let (impl_items, attrs) = self.parse_impl_body()?;
6844 let item_kind = match ty_second {
6845 Some(ty_second) => {
6846 // impl Trait for Type
6848 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6849 .span_suggestion_short(
6852 " for ".to_string(),
6853 Applicability::MachineApplicable,
6857 let ty_first = ty_first.into_inner();
6858 let path = match ty_first.node {
6859 // This notably includes paths passed through `ty` macro fragments (#46438).
6860 TyKind::Path(None, path) => path,
6862 self.span_err(ty_first.span, "expected a trait, found type");
6863 err_path(ty_first.span)
6866 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6868 ItemKind::Impl(unsafety, polarity, defaultness,
6869 generics, Some(trait_ref), ty_second, impl_items)
6873 ItemKind::Impl(unsafety, polarity, defaultness,
6874 generics, None, ty_first, impl_items)
6878 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
6881 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6882 if self.eat_keyword(keywords::For) {
6884 let params = self.parse_generic_params()?;
6886 // We rely on AST validation to rule out invalid cases: There must not be type
6887 // parameters, and the lifetime parameters must not have bounds.
6894 /// Parses `struct Foo { ... }`.
6895 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6896 let class_name = self.parse_ident()?;
6898 let mut generics = self.parse_generics()?;
6900 // There is a special case worth noting here, as reported in issue #17904.
6901 // If we are parsing a tuple struct it is the case that the where clause
6902 // should follow the field list. Like so:
6904 // struct Foo<T>(T) where T: Copy;
6906 // If we are parsing a normal record-style struct it is the case
6907 // that the where clause comes before the body, and after the generics.
6908 // So if we look ahead and see a brace or a where-clause we begin
6909 // parsing a record style struct.
6911 // Otherwise if we look ahead and see a paren we parse a tuple-style
6914 let vdata = if self.token.is_keyword(keywords::Where) {
6915 generics.where_clause = self.parse_where_clause()?;
6916 if self.eat(&token::Semi) {
6917 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6918 VariantData::Unit(ast::DUMMY_NODE_ID)
6920 // If we see: `struct Foo<T> where T: Copy { ... }`
6921 let (fields, recovered) = self.parse_record_struct_body()?;
6922 VariantData::Struct(fields, recovered)
6924 // No `where` so: `struct Foo<T>;`
6925 } else if self.eat(&token::Semi) {
6926 VariantData::Unit(ast::DUMMY_NODE_ID)
6927 // Record-style struct definition
6928 } else if self.token == token::OpenDelim(token::Brace) {
6929 let (fields, recovered) = self.parse_record_struct_body()?;
6930 VariantData::Struct(fields, recovered)
6931 // Tuple-style struct definition with optional where-clause.
6932 } else if self.token == token::OpenDelim(token::Paren) {
6933 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6934 generics.where_clause = self.parse_where_clause()?;
6935 self.expect(&token::Semi)?;
6938 let token_str = self.this_token_descr();
6939 let mut err = self.fatal(&format!(
6940 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6943 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6947 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6950 /// Parses `union Foo { ... }`.
6951 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6952 let class_name = self.parse_ident()?;
6954 let mut generics = self.parse_generics()?;
6956 let vdata = if self.token.is_keyword(keywords::Where) {
6957 generics.where_clause = self.parse_where_clause()?;
6958 let (fields, recovered) = self.parse_record_struct_body()?;
6959 VariantData::Struct(fields, recovered)
6960 } else if self.token == token::OpenDelim(token::Brace) {
6961 let (fields, recovered) = self.parse_record_struct_body()?;
6962 VariantData::Struct(fields, recovered)
6964 let token_str = self.this_token_descr();
6965 let mut err = self.fatal(&format!(
6966 "expected `where` or `{{` after union name, found {}", token_str));
6967 err.span_label(self.span, "expected `where` or `{` after union name");
6971 Ok((class_name, ItemKind::Union(vdata, generics), None))
6974 fn consume_block(&mut self, delim: token::DelimToken) {
6975 let mut brace_depth = 0;
6977 if self.eat(&token::OpenDelim(delim)) {
6979 } else if self.eat(&token::CloseDelim(delim)) {
6980 if brace_depth == 0 {
6986 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
6994 fn parse_record_struct_body(
6996 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
6997 let mut fields = Vec::new();
6998 let mut recovered = false;
6999 if self.eat(&token::OpenDelim(token::Brace)) {
7000 while self.token != token::CloseDelim(token::Brace) {
7001 let field = self.parse_struct_decl_field().map_err(|e| {
7002 self.recover_stmt();
7007 Ok(field) => fields.push(field),
7013 self.eat(&token::CloseDelim(token::Brace));
7015 let token_str = self.this_token_descr();
7016 let mut err = self.fatal(&format!(
7017 "expected `where`, or `{{` after struct name, found {}", token_str));
7018 err.span_label(self.span, "expected `where`, or `{` after struct name");
7022 Ok((fields, recovered))
7025 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
7026 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
7027 // Unit like structs are handled in parse_item_struct function
7028 let fields = self.parse_unspanned_seq(
7029 &token::OpenDelim(token::Paren),
7030 &token::CloseDelim(token::Paren),
7031 SeqSep::trailing_allowed(token::Comma),
7033 let attrs = p.parse_outer_attributes()?;
7035 let vis = p.parse_visibility(true)?;
7036 let ty = p.parse_ty()?;
7038 span: lo.to(ty.span),
7041 id: ast::DUMMY_NODE_ID,
7050 /// Parses a structure field declaration.
7051 fn parse_single_struct_field(&mut self,
7054 attrs: Vec<Attribute> )
7055 -> PResult<'a, StructField> {
7056 let mut seen_comma: bool = false;
7057 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
7058 if self.token == token::Comma {
7065 token::CloseDelim(token::Brace) => {}
7066 token::DocComment(_) => {
7067 let previous_span = self.prev_span;
7068 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
7069 self.bump(); // consume the doc comment
7070 let comma_after_doc_seen = self.eat(&token::Comma);
7071 // `seen_comma` is always false, because we are inside doc block
7072 // condition is here to make code more readable
7073 if seen_comma == false && comma_after_doc_seen == true {
7076 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
7079 if seen_comma == false {
7080 let sp = self.sess.source_map().next_point(previous_span);
7081 err.span_suggestion(
7083 "missing comma here",
7085 Applicability::MachineApplicable
7092 let sp = self.sess.source_map().next_point(self.prev_span);
7093 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
7094 self.this_token_descr()));
7095 if self.token.is_ident() {
7096 // This is likely another field; emit the diagnostic and keep going
7097 err.span_suggestion(
7099 "try adding a comma",
7101 Applicability::MachineApplicable,
7112 /// Parses an element of a struct declaration.
7113 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
7114 let attrs = self.parse_outer_attributes()?;
7116 let vis = self.parse_visibility(false)?;
7117 self.parse_single_struct_field(lo, vis, attrs)
7120 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
7121 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
7122 /// If the following element can't be a tuple (i.e., it's a function definition), then
7123 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
7124 /// so emit a proper diagnostic.
7125 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
7126 maybe_whole!(self, NtVis, |x| x);
7128 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
7129 if self.is_crate_vis() {
7130 self.bump(); // `crate`
7131 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
7134 if !self.eat_keyword(keywords::Pub) {
7135 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
7136 // keyword to grab a span from for inherited visibility; an empty span at the
7137 // beginning of the current token would seem to be the "Schelling span".
7138 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
7140 let lo = self.prev_span;
7142 if self.check(&token::OpenDelim(token::Paren)) {
7143 // We don't `self.bump()` the `(` yet because this might be a struct definition where
7144 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
7145 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
7146 // by the following tokens.
7147 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) &&
7148 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
7152 self.bump(); // `crate`
7153 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7155 lo.to(self.prev_span),
7156 VisibilityKind::Crate(CrateSugar::PubCrate),
7159 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
7162 self.bump(); // `in`
7163 let path = self.parse_path(PathStyle::Mod)?; // `path`
7164 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7165 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7167 id: ast::DUMMY_NODE_ID,
7170 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
7171 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
7172 t.is_keyword(keywords::SelfLower))
7174 // `pub(self)` or `pub(super)`
7176 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
7177 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7178 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7180 id: ast::DUMMY_NODE_ID,
7183 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
7184 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
7186 let msg = "incorrect visibility restriction";
7187 let suggestion = r##"some possible visibility restrictions are:
7188 `pub(crate)`: visible only on the current crate
7189 `pub(super)`: visible only in the current module's parent
7190 `pub(in path::to::module)`: visible only on the specified path"##;
7191 let path = self.parse_path(PathStyle::Mod)?;
7193 let help_msg = format!("make this visible only to module `{}` with `in`", path);
7194 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7195 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
7196 err.help(suggestion);
7197 err.span_suggestion(
7198 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
7200 err.emit(); // emit diagnostic, but continue with public visibility
7204 Ok(respan(lo, VisibilityKind::Public))
7207 /// Parses defaultness (i.e., `default` or nothing).
7208 fn parse_defaultness(&mut self) -> Defaultness {
7209 // `pub` is included for better error messages
7210 if self.check_keyword(keywords::Default) &&
7211 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
7212 t.is_keyword(keywords::Const) ||
7213 t.is_keyword(keywords::Fn) ||
7214 t.is_keyword(keywords::Unsafe) ||
7215 t.is_keyword(keywords::Extern) ||
7216 t.is_keyword(keywords::Type) ||
7217 t.is_keyword(keywords::Pub)) {
7218 self.bump(); // `default`
7219 Defaultness::Default
7225 /// Given a termination token, parses all of the items in a module.
7226 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
7227 let mut items = vec![];
7228 while let Some(item) = self.parse_item()? {
7230 self.maybe_consume_incorrect_semicolon(&items);
7233 if !self.eat(term) {
7234 let token_str = self.this_token_descr();
7235 if !self.maybe_consume_incorrect_semicolon(&items) {
7236 let mut err = self.fatal(&format!("expected item, found {}", token_str));
7237 err.span_label(self.span, "expected item");
7242 let hi = if self.span.is_dummy() {
7249 inner: inner_lo.to(hi),
7255 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
7256 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
7257 self.expect(&token::Colon)?;
7258 let ty = self.parse_ty()?;
7259 self.expect(&token::Eq)?;
7260 let e = self.parse_expr()?;
7261 self.expect(&token::Semi)?;
7262 let item = match m {
7263 Some(m) => ItemKind::Static(ty, m, e),
7264 None => ItemKind::Const(ty, e),
7266 Ok((id, item, None))
7269 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
7270 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
7271 let (in_cfg, outer_attrs) = {
7272 let mut strip_unconfigured = crate::config::StripUnconfigured {
7274 features: None, // don't perform gated feature checking
7276 let mut outer_attrs = outer_attrs.to_owned();
7277 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
7278 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
7281 let id_span = self.span;
7282 let id = self.parse_ident()?;
7283 if self.eat(&token::Semi) {
7284 if in_cfg && self.recurse_into_file_modules {
7285 // This mod is in an external file. Let's go get it!
7286 let ModulePathSuccess { path, directory_ownership, warn } =
7287 self.submod_path(id, &outer_attrs, id_span)?;
7288 let (module, mut attrs) =
7289 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
7290 // Record that we fetched the mod from an external file
7292 let attr = Attribute {
7293 id: attr::mk_attr_id(),
7294 style: ast::AttrStyle::Outer,
7295 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
7296 tokens: TokenStream::empty(),
7297 is_sugared_doc: false,
7298 span: syntax_pos::DUMMY_SP,
7300 attr::mark_known(&attr);
7303 Ok((id, ItemKind::Mod(module), Some(attrs)))
7305 let placeholder = ast::Mod {
7306 inner: syntax_pos::DUMMY_SP,
7310 Ok((id, ItemKind::Mod(placeholder), None))
7313 let old_directory = self.directory.clone();
7314 self.push_directory(id, &outer_attrs);
7316 self.expect(&token::OpenDelim(token::Brace))?;
7317 let mod_inner_lo = self.span;
7318 let attrs = self.parse_inner_attributes()?;
7319 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
7321 self.directory = old_directory;
7322 Ok((id, ItemKind::Mod(module), Some(attrs)))
7326 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
7327 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
7328 self.directory.path.to_mut().push(&path.as_str());
7329 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
7331 // We have to push on the current module name in the case of relative
7332 // paths in order to ensure that any additional module paths from inline
7333 // `mod x { ... }` come after the relative extension.
7335 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
7336 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
7337 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
7338 if let Some(ident) = relative.take() { // remove the relative offset
7339 self.directory.path.to_mut().push(ident.as_str());
7342 self.directory.path.to_mut().push(&id.as_str());
7346 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
7347 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
7350 // On windows, the base path might have the form
7351 // `\\?\foo\bar` in which case it does not tolerate
7352 // mixed `/` and `\` separators, so canonicalize
7355 let s = s.replace("/", "\\");
7356 Some(dir_path.join(s))
7362 /// Returns a path to a module.
7363 pub fn default_submod_path(
7365 relative: Option<ast::Ident>,
7367 source_map: &SourceMap) -> ModulePath
7369 // If we're in a foo.rs file instead of a mod.rs file,
7370 // we need to look for submodules in
7371 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
7372 // `./<id>.rs` and `./<id>/mod.rs`.
7373 let relative_prefix_string;
7374 let relative_prefix = if let Some(ident) = relative {
7375 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
7376 &relative_prefix_string
7381 let mod_name = id.to_string();
7382 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
7383 let secondary_path_str = format!("{}{}{}mod.rs",
7384 relative_prefix, mod_name, path::MAIN_SEPARATOR);
7385 let default_path = dir_path.join(&default_path_str);
7386 let secondary_path = dir_path.join(&secondary_path_str);
7387 let default_exists = source_map.file_exists(&default_path);
7388 let secondary_exists = source_map.file_exists(&secondary_path);
7390 let result = match (default_exists, secondary_exists) {
7391 (true, false) => Ok(ModulePathSuccess {
7393 directory_ownership: DirectoryOwnership::Owned {
7398 (false, true) => Ok(ModulePathSuccess {
7399 path: secondary_path,
7400 directory_ownership: DirectoryOwnership::Owned {
7405 (false, false) => Err(Error::FileNotFoundForModule {
7406 mod_name: mod_name.clone(),
7407 default_path: default_path_str,
7408 secondary_path: secondary_path_str,
7409 dir_path: dir_path.display().to_string(),
7411 (true, true) => Err(Error::DuplicatePaths {
7412 mod_name: mod_name.clone(),
7413 default_path: default_path_str,
7414 secondary_path: secondary_path_str,
7420 path_exists: default_exists || secondary_exists,
7425 fn submod_path(&mut self,
7427 outer_attrs: &[Attribute],
7429 -> PResult<'a, ModulePathSuccess> {
7430 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
7431 return Ok(ModulePathSuccess {
7432 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
7433 // All `#[path]` files are treated as though they are a `mod.rs` file.
7434 // This means that `mod foo;` declarations inside `#[path]`-included
7435 // files are siblings,
7437 // Note that this will produce weirdness when a file named `foo.rs` is
7438 // `#[path]` included and contains a `mod foo;` declaration.
7439 // If you encounter this, it's your own darn fault :P
7440 Some(_) => DirectoryOwnership::Owned { relative: None },
7441 _ => DirectoryOwnership::UnownedViaMod(true),
7448 let relative = match self.directory.ownership {
7449 DirectoryOwnership::Owned { relative } => relative,
7450 DirectoryOwnership::UnownedViaBlock |
7451 DirectoryOwnership::UnownedViaMod(_) => None,
7453 let paths = Parser::default_submod_path(
7454 id, relative, &self.directory.path, self.sess.source_map());
7456 match self.directory.ownership {
7457 DirectoryOwnership::Owned { .. } => {
7458 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
7460 DirectoryOwnership::UnownedViaBlock => {
7462 "Cannot declare a non-inline module inside a block \
7463 unless it has a path attribute";
7464 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
7465 if paths.path_exists {
7466 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
7468 err.span_note(id_sp, &msg);
7472 DirectoryOwnership::UnownedViaMod(warn) => {
7474 if let Ok(result) = paths.result {
7475 return Ok(ModulePathSuccess { warn: true, ..result });
7478 let mut err = self.diagnostic().struct_span_err(id_sp,
7479 "cannot declare a new module at this location");
7480 if !id_sp.is_dummy() {
7481 let src_path = self.sess.source_map().span_to_filename(id_sp);
7482 if let FileName::Real(src_path) = src_path {
7483 if let Some(stem) = src_path.file_stem() {
7484 let mut dest_path = src_path.clone();
7485 dest_path.set_file_name(stem);
7486 dest_path.push("mod.rs");
7487 err.span_note(id_sp,
7488 &format!("maybe move this module `{}` to its own \
7489 directory via `{}`", src_path.display(),
7490 dest_path.display()));
7494 if paths.path_exists {
7495 err.span_note(id_sp,
7496 &format!("... or maybe `use` the module `{}` instead \
7497 of possibly redeclaring it",
7505 /// Reads a module from a source file.
7506 fn eval_src_mod(&mut self,
7508 directory_ownership: DirectoryOwnership,
7511 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
7512 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
7513 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
7514 let mut err = String::from("circular modules: ");
7515 let len = included_mod_stack.len();
7516 for p in &included_mod_stack[i.. len] {
7517 err.push_str(&p.to_string_lossy());
7518 err.push_str(" -> ");
7520 err.push_str(&path.to_string_lossy());
7521 return Err(self.span_fatal(id_sp, &err[..]));
7523 included_mod_stack.push(path.clone());
7524 drop(included_mod_stack);
7527 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
7528 p0.cfg_mods = self.cfg_mods;
7529 let mod_inner_lo = p0.span;
7530 let mod_attrs = p0.parse_inner_attributes()?;
7531 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
7533 self.sess.included_mod_stack.borrow_mut().pop();
7537 /// Parses a function declaration from a foreign module.
7538 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7539 -> PResult<'a, ForeignItem> {
7540 self.expect_keyword(keywords::Fn)?;
7542 let (ident, mut generics) = self.parse_fn_header()?;
7543 let decl = self.parse_fn_decl(true)?;
7544 generics.where_clause = self.parse_where_clause()?;
7546 self.expect(&token::Semi)?;
7547 Ok(ast::ForeignItem {
7550 node: ForeignItemKind::Fn(decl, generics),
7551 id: ast::DUMMY_NODE_ID,
7557 /// Parses a static item from a foreign module.
7558 /// Assumes that the `static` keyword is already parsed.
7559 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7560 -> PResult<'a, ForeignItem> {
7561 let mutbl = self.parse_mutability();
7562 let ident = self.parse_ident()?;
7563 self.expect(&token::Colon)?;
7564 let ty = self.parse_ty()?;
7566 self.expect(&token::Semi)?;
7570 node: ForeignItemKind::Static(ty, mutbl),
7571 id: ast::DUMMY_NODE_ID,
7577 /// Parses a type from a foreign module.
7578 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7579 -> PResult<'a, ForeignItem> {
7580 self.expect_keyword(keywords::Type)?;
7582 let ident = self.parse_ident()?;
7584 self.expect(&token::Semi)?;
7585 Ok(ast::ForeignItem {
7588 node: ForeignItemKind::Ty,
7589 id: ast::DUMMY_NODE_ID,
7595 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
7596 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
7597 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
7599 let mut ident = if self.token.is_keyword(keywords::SelfLower) {
7600 self.parse_path_segment_ident()
7604 let mut idents = vec![];
7605 let mut replacement = vec![];
7606 let mut fixed_crate_name = false;
7607 // Accept `extern crate name-like-this` for better diagnostics
7608 let dash = token::Token::BinOp(token::BinOpToken::Minus);
7609 if self.token == dash { // Do not include `-` as part of the expected tokens list
7610 while self.eat(&dash) {
7611 fixed_crate_name = true;
7612 replacement.push((self.prev_span, "_".to_string()));
7613 idents.push(self.parse_ident()?);
7616 if fixed_crate_name {
7617 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
7618 let mut fixed_name = format!("{}", ident.name);
7619 for part in idents {
7620 fixed_name.push_str(&format!("_{}", part.name));
7622 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
7624 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
7625 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
7626 err.multipart_suggestion(
7629 Applicability::MachineApplicable,
7636 /// Parses `extern crate` links.
7641 /// extern crate foo;
7642 /// extern crate bar as foo;
7644 fn parse_item_extern_crate(&mut self,
7646 visibility: Visibility,
7647 attrs: Vec<Attribute>)
7648 -> PResult<'a, P<Item>> {
7649 // Accept `extern crate name-like-this` for better diagnostics
7650 let orig_name = self.parse_crate_name_with_dashes()?;
7651 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
7652 (rename, Some(orig_name.name))
7656 self.expect(&token::Semi)?;
7658 let span = lo.to(self.prev_span);
7659 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
7662 /// Parses `extern` for foreign ABIs modules.
7664 /// `extern` is expected to have been
7665 /// consumed before calling this method.
7669 /// ```ignore (only-for-syntax-highlight)
7673 fn parse_item_foreign_mod(&mut self,
7675 opt_abi: Option<Abi>,
7676 visibility: Visibility,
7677 mut attrs: Vec<Attribute>)
7678 -> PResult<'a, P<Item>> {
7679 self.expect(&token::OpenDelim(token::Brace))?;
7681 let abi = opt_abi.unwrap_or(Abi::C);
7683 attrs.extend(self.parse_inner_attributes()?);
7685 let mut foreign_items = vec![];
7686 while !self.eat(&token::CloseDelim(token::Brace)) {
7687 foreign_items.push(self.parse_foreign_item()?);
7690 let prev_span = self.prev_span;
7691 let m = ast::ForeignMod {
7693 items: foreign_items
7695 let invalid = keywords::Invalid.ident();
7696 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
7699 /// Parses `type Foo = Bar;`
7701 /// `existential type Foo: Bar;`
7704 /// without modifying the parser state.
7705 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
7706 // This parses the grammar:
7707 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
7708 if self.check_keyword(keywords::Type) ||
7709 self.check_keyword(keywords::Existential) &&
7710 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
7711 let existential = self.eat_keyword(keywords::Existential);
7712 assert!(self.eat_keyword(keywords::Type));
7713 Some(self.parse_existential_or_alias(existential))
7719 /// Parses a type alias or existential type.
7720 fn parse_existential_or_alias(
7723 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
7724 let ident = self.parse_ident()?;
7725 let mut tps = self.parse_generics()?;
7726 tps.where_clause = self.parse_where_clause()?;
7727 let alias = if existential {
7728 self.expect(&token::Colon)?;
7729 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
7730 AliasKind::Existential(bounds)
7732 self.expect(&token::Eq)?;
7733 let ty = self.parse_ty()?;
7736 self.expect(&token::Semi)?;
7737 Ok((ident, alias, tps))
7740 /// Parses the part of an enum declaration following the `{`.
7741 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
7742 let mut variants = Vec::new();
7743 let mut all_nullary = true;
7744 let mut any_disr = vec![];
7745 while self.token != token::CloseDelim(token::Brace) {
7746 let variant_attrs = self.parse_outer_attributes()?;
7747 let vlo = self.span;
7750 let mut disr_expr = None;
7752 let ident = self.parse_ident()?;
7753 if self.check(&token::OpenDelim(token::Brace)) {
7754 // Parse a struct variant.
7755 all_nullary = false;
7756 let (fields, recovered) = self.parse_record_struct_body()?;
7757 struct_def = VariantData::Struct(fields, recovered);
7758 } else if self.check(&token::OpenDelim(token::Paren)) {
7759 all_nullary = false;
7760 struct_def = VariantData::Tuple(
7761 self.parse_tuple_struct_body()?,
7764 } else if self.eat(&token::Eq) {
7765 disr_expr = Some(AnonConst {
7766 id: ast::DUMMY_NODE_ID,
7767 value: self.parse_expr()?,
7769 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
7772 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7774 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7777 let vr = ast::Variant_ {
7779 id: ast::DUMMY_NODE_ID,
7780 attrs: variant_attrs,
7784 variants.push(respan(vlo.to(self.prev_span), vr));
7786 if !self.eat(&token::Comma) {
7787 if self.token.is_ident() && !self.token.is_reserved_ident() {
7788 let sp = self.sess.source_map().next_point(self.prev_span);
7789 let mut err = self.struct_span_err(sp, "missing comma");
7790 err.span_suggestion_short(
7794 Applicability::MaybeIncorrect,
7802 self.expect(&token::CloseDelim(token::Brace))?;
7803 if !any_disr.is_empty() && !all_nullary {
7804 let mut err = self.struct_span_err(
7806 "discriminator values can only be used with a field-less enum",
7808 for sp in any_disr {
7809 err.span_label(sp, "only valid in field-less enums");
7814 Ok(ast::EnumDef { variants })
7817 /// Parses an enum declaration.
7818 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7819 let id = self.parse_ident()?;
7820 let mut generics = self.parse_generics()?;
7821 generics.where_clause = self.parse_where_clause()?;
7822 self.expect(&token::OpenDelim(token::Brace))?;
7824 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7825 self.recover_stmt();
7826 self.eat(&token::CloseDelim(token::Brace));
7829 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7832 /// Parses a string as an ABI spec on an extern type or module. Consumes
7833 /// the `extern` keyword, if one is found.
7834 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7836 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
7838 self.expect_no_suffix(sp, "an ABI spec", suf);
7840 match abi::lookup(&s.as_str()) {
7841 Some(abi) => Ok(Some(abi)),
7843 let prev_span = self.prev_span;
7844 let mut err = struct_span_err!(
7845 self.sess.span_diagnostic,
7848 "invalid ABI: found `{}`",
7850 err.span_label(prev_span, "invalid ABI");
7851 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7862 fn is_static_global(&mut self) -> bool {
7863 if self.check_keyword(keywords::Static) {
7864 // Check if this could be a closure
7865 !self.look_ahead(1, |token| {
7866 if token.is_keyword(keywords::Move) {
7870 token::BinOp(token::Or) | token::OrOr => true,
7881 attrs: Vec<Attribute>,
7882 macros_allowed: bool,
7883 attributes_allowed: bool,
7884 ) -> PResult<'a, Option<P<Item>>> {
7885 let mut unclosed_delims = vec![];
7886 let (ret, tokens) = self.collect_tokens(|this| {
7887 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7888 unclosed_delims.append(&mut this.unclosed_delims);
7891 self.unclosed_delims.append(&mut unclosed_delims);
7893 // Once we've parsed an item and recorded the tokens we got while
7894 // parsing we may want to store `tokens` into the item we're about to
7895 // return. Note, though, that we specifically didn't capture tokens
7896 // related to outer attributes. The `tokens` field here may later be
7897 // used with procedural macros to convert this item back into a token
7898 // stream, but during expansion we may be removing attributes as we go
7901 // If we've got inner attributes then the `tokens` we've got above holds
7902 // these inner attributes. If an inner attribute is expanded we won't
7903 // actually remove it from the token stream, so we'll just keep yielding
7904 // it (bad!). To work around this case for now we just avoid recording
7905 // `tokens` if we detect any inner attributes. This should help keep
7906 // expansion correct, but we should fix this bug one day!
7909 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7910 i.tokens = Some(tokens);
7917 /// Parses one of the items allowed by the flags.
7918 fn parse_item_implementation(
7920 attrs: Vec<Attribute>,
7921 macros_allowed: bool,
7922 attributes_allowed: bool,
7923 ) -> PResult<'a, Option<P<Item>>> {
7924 maybe_whole!(self, NtItem, |item| {
7925 let mut item = item.into_inner();
7926 let mut attrs = attrs;
7927 mem::swap(&mut item.attrs, &mut attrs);
7928 item.attrs.extend(attrs);
7934 let visibility = self.parse_visibility(false)?;
7936 if self.eat_keyword(keywords::Use) {
7938 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7939 self.expect(&token::Semi)?;
7941 let span = lo.to(self.prev_span);
7942 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
7943 return Ok(Some(item));
7946 if self.eat_keyword(keywords::Extern) {
7947 if self.eat_keyword(keywords::Crate) {
7948 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7951 let opt_abi = self.parse_opt_abi()?;
7953 if self.eat_keyword(keywords::Fn) {
7954 // EXTERN FUNCTION ITEM
7955 let fn_span = self.prev_span;
7956 let abi = opt_abi.unwrap_or(Abi::C);
7957 let (ident, item_, extra_attrs) =
7958 self.parse_item_fn(Unsafety::Normal,
7959 respan(fn_span, IsAsync::NotAsync),
7960 respan(fn_span, Constness::NotConst),
7962 let prev_span = self.prev_span;
7963 let item = self.mk_item(lo.to(prev_span),
7967 maybe_append(attrs, extra_attrs));
7968 return Ok(Some(item));
7969 } else if self.check(&token::OpenDelim(token::Brace)) {
7970 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7976 if self.is_static_global() {
7979 let m = if self.eat_keyword(keywords::Mut) {
7982 Mutability::Immutable
7984 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7985 let prev_span = self.prev_span;
7986 let item = self.mk_item(lo.to(prev_span),
7990 maybe_append(attrs, extra_attrs));
7991 return Ok(Some(item));
7993 if self.eat_keyword(keywords::Const) {
7994 let const_span = self.prev_span;
7995 if self.check_keyword(keywords::Fn)
7996 || (self.check_keyword(keywords::Unsafe)
7997 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
7998 // CONST FUNCTION ITEM
7999 let unsafety = self.parse_unsafety();
8001 let (ident, item_, extra_attrs) =
8002 self.parse_item_fn(unsafety,
8003 respan(const_span, IsAsync::NotAsync),
8004 respan(const_span, Constness::Const),
8006 let prev_span = self.prev_span;
8007 let item = self.mk_item(lo.to(prev_span),
8011 maybe_append(attrs, extra_attrs));
8012 return Ok(Some(item));
8016 if self.eat_keyword(keywords::Mut) {
8017 let prev_span = self.prev_span;
8018 let mut err = self.diagnostic()
8019 .struct_span_err(prev_span, "const globals cannot be mutable");
8020 err.span_label(prev_span, "cannot be mutable");
8021 err.span_suggestion(
8023 "you might want to declare a static instead",
8024 "static".to_owned(),
8025 Applicability::MaybeIncorrect,
8029 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
8030 let prev_span = self.prev_span;
8031 let item = self.mk_item(lo.to(prev_span),
8035 maybe_append(attrs, extra_attrs));
8036 return Ok(Some(item));
8039 // `unsafe async fn` or `async fn`
8041 self.check_keyword(keywords::Unsafe) &&
8042 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
8044 self.check_keyword(keywords::Async) &&
8045 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
8048 // ASYNC FUNCTION ITEM
8049 let unsafety = self.parse_unsafety();
8050 self.expect_keyword(keywords::Async)?;
8051 let async_span = self.prev_span;
8052 self.expect_keyword(keywords::Fn)?;
8053 let fn_span = self.prev_span;
8054 let (ident, item_, extra_attrs) =
8055 self.parse_item_fn(unsafety,
8056 respan(async_span, IsAsync::Async {
8057 closure_id: ast::DUMMY_NODE_ID,
8058 return_impl_trait_id: ast::DUMMY_NODE_ID,
8059 arguments: Vec::new(),
8061 respan(fn_span, Constness::NotConst),
8063 let prev_span = self.prev_span;
8064 let item = self.mk_item(lo.to(prev_span),
8068 maybe_append(attrs, extra_attrs));
8069 if self.span.rust_2015() {
8070 self.diagnostic().struct_span_err_with_code(
8072 "`async fn` is not permitted in the 2015 edition",
8073 DiagnosticId::Error("E0670".into())
8076 return Ok(Some(item));
8078 if self.check_keyword(keywords::Unsafe) &&
8079 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
8080 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
8082 // UNSAFE TRAIT ITEM
8083 self.bump(); // `unsafe`
8084 let is_auto = if self.eat_keyword(keywords::Trait) {
8087 self.expect_keyword(keywords::Auto)?;
8088 self.expect_keyword(keywords::Trait)?;
8091 let (ident, item_, extra_attrs) =
8092 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
8093 let prev_span = self.prev_span;
8094 let item = self.mk_item(lo.to(prev_span),
8098 maybe_append(attrs, extra_attrs));
8099 return Ok(Some(item));
8101 if self.check_keyword(keywords::Impl) ||
8102 self.check_keyword(keywords::Unsafe) &&
8103 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8104 self.check_keyword(keywords::Default) &&
8105 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8106 self.check_keyword(keywords::Default) &&
8107 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
8109 let defaultness = self.parse_defaultness();
8110 let unsafety = self.parse_unsafety();
8111 self.expect_keyword(keywords::Impl)?;
8112 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
8113 let span = lo.to(self.prev_span);
8114 return Ok(Some(self.mk_item(span, ident, item, visibility,
8115 maybe_append(attrs, extra_attrs))));
8117 if self.check_keyword(keywords::Fn) {
8120 let fn_span = self.prev_span;
8121 let (ident, item_, extra_attrs) =
8122 self.parse_item_fn(Unsafety::Normal,
8123 respan(fn_span, IsAsync::NotAsync),
8124 respan(fn_span, Constness::NotConst),
8126 let prev_span = self.prev_span;
8127 let item = self.mk_item(lo.to(prev_span),
8131 maybe_append(attrs, extra_attrs));
8132 return Ok(Some(item));
8134 if self.check_keyword(keywords::Unsafe)
8135 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
8136 // UNSAFE FUNCTION ITEM
8137 self.bump(); // `unsafe`
8138 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
8139 self.check(&token::OpenDelim(token::Brace));
8140 let abi = if self.eat_keyword(keywords::Extern) {
8141 self.parse_opt_abi()?.unwrap_or(Abi::C)
8145 self.expect_keyword(keywords::Fn)?;
8146 let fn_span = self.prev_span;
8147 let (ident, item_, extra_attrs) =
8148 self.parse_item_fn(Unsafety::Unsafe,
8149 respan(fn_span, IsAsync::NotAsync),
8150 respan(fn_span, Constness::NotConst),
8152 let prev_span = self.prev_span;
8153 let item = self.mk_item(lo.to(prev_span),
8157 maybe_append(attrs, extra_attrs));
8158 return Ok(Some(item));
8160 if self.eat_keyword(keywords::Mod) {
8162 let (ident, item_, extra_attrs) =
8163 self.parse_item_mod(&attrs[..])?;
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 let Some(type_) = self.eat_type() {
8173 let (ident, alias, generics) = type_?;
8175 let item_ = match alias {
8176 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
8177 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
8179 let prev_span = self.prev_span;
8180 let item = self.mk_item(lo.to(prev_span),
8185 return Ok(Some(item));
8187 if self.eat_keyword(keywords::Enum) {
8189 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
8190 let prev_span = self.prev_span;
8191 let item = self.mk_item(lo.to(prev_span),
8195 maybe_append(attrs, extra_attrs));
8196 return Ok(Some(item));
8198 if self.check_keyword(keywords::Trait)
8199 || (self.check_keyword(keywords::Auto)
8200 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
8202 let is_auto = if self.eat_keyword(keywords::Trait) {
8205 self.expect_keyword(keywords::Auto)?;
8206 self.expect_keyword(keywords::Trait)?;
8210 let (ident, item_, extra_attrs) =
8211 self.parse_item_trait(is_auto, Unsafety::Normal)?;
8212 let prev_span = self.prev_span;
8213 let item = self.mk_item(lo.to(prev_span),
8217 maybe_append(attrs, extra_attrs));
8218 return Ok(Some(item));
8220 if self.eat_keyword(keywords::Struct) {
8222 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
8223 let prev_span = self.prev_span;
8224 let item = self.mk_item(lo.to(prev_span),
8228 maybe_append(attrs, extra_attrs));
8229 return Ok(Some(item));
8231 if self.is_union_item() {
8234 let (ident, item_, extra_attrs) = self.parse_item_union()?;
8235 let prev_span = self.prev_span;
8236 let item = self.mk_item(lo.to(prev_span),
8240 maybe_append(attrs, extra_attrs));
8241 return Ok(Some(item));
8243 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
8244 return Ok(Some(macro_def));
8247 // Verify whether we have encountered a struct or method definition where the user forgot to
8248 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
8249 if visibility.node.is_pub() &&
8250 self.check_ident() &&
8251 self.look_ahead(1, |t| *t != token::Not)
8253 // Space between `pub` keyword and the identifier
8256 // ^^^ `sp` points here
8257 let sp = self.prev_span.between(self.span);
8258 let full_sp = self.prev_span.to(self.span);
8259 let ident_sp = self.span;
8260 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
8261 // possible public struct definition where `struct` was forgotten
8262 let ident = self.parse_ident().unwrap();
8263 let msg = format!("add `struct` here to parse `{}` as a public struct",
8265 let mut err = self.diagnostic()
8266 .struct_span_err(sp, "missing `struct` for struct definition");
8267 err.span_suggestion_short(
8268 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
8271 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
8272 let ident = self.parse_ident().unwrap();
8274 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
8279 self.consume_block(token::Paren);
8280 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
8281 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
8283 ("fn", kw_name, false)
8284 } else if self.check(&token::OpenDelim(token::Brace)) {
8286 ("fn", kw_name, false)
8287 } else if self.check(&token::Colon) {
8291 ("fn` or `struct", "function or struct", true)
8294 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8295 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8297 self.consume_block(token::Brace);
8298 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
8302 err.span_suggestion_short(
8303 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
8306 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
8307 err.span_suggestion(
8309 "if you meant to call a macro, try",
8310 format!("{}!", snippet),
8311 // this is the `ambiguous` conditional branch
8312 Applicability::MaybeIncorrect
8315 err.help("if you meant to call a macro, remove the `pub` \
8316 and add a trailing `!` after the identifier");
8320 } else if self.look_ahead(1, |t| *t == token::Lt) {
8321 let ident = self.parse_ident().unwrap();
8322 self.eat_to_tokens(&[&token::Gt]);
8324 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
8325 if let Ok(Some(_)) = self.parse_self_arg() {
8326 ("fn", "method", false)
8328 ("fn", "function", false)
8330 } else if self.check(&token::OpenDelim(token::Brace)) {
8331 ("struct", "struct", false)
8333 ("fn` or `struct", "function or struct", true)
8335 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8336 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8338 err.span_suggestion_short(
8340 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
8341 format!(" {} ", kw),
8342 Applicability::MachineApplicable,
8348 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
8351 /// Parses a foreign item.
8352 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
8353 maybe_whole!(self, NtForeignItem, |ni| ni);
8355 let attrs = self.parse_outer_attributes()?;
8357 let visibility = self.parse_visibility(false)?;
8359 // FOREIGN STATIC ITEM
8360 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
8361 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
8362 if self.token.is_keyword(keywords::Const) {
8364 .struct_span_err(self.span, "extern items cannot be `const`")
8367 "try using a static value",
8368 "static".to_owned(),
8369 Applicability::MachineApplicable
8372 self.bump(); // `static` or `const`
8373 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
8375 // FOREIGN FUNCTION ITEM
8376 if self.check_keyword(keywords::Fn) {
8377 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
8379 // FOREIGN TYPE ITEM
8380 if self.check_keyword(keywords::Type) {
8381 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
8384 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
8388 ident: keywords::Invalid.ident(),
8389 span: lo.to(self.prev_span),
8390 id: ast::DUMMY_NODE_ID,
8393 node: ForeignItemKind::Macro(mac),
8398 if !attrs.is_empty() {
8399 self.expected_item_err(&attrs)?;
8407 /// This is the fall-through for parsing items.
8408 fn parse_macro_use_or_failure(
8410 attrs: Vec<Attribute> ,
8411 macros_allowed: bool,
8412 attributes_allowed: bool,
8414 visibility: Visibility
8415 ) -> PResult<'a, Option<P<Item>>> {
8416 if macros_allowed && self.token.is_path_start() &&
8417 !(self.is_async_fn() && self.span.rust_2015()) {
8418 // MACRO INVOCATION ITEM
8420 let prev_span = self.prev_span;
8421 self.complain_if_pub_macro(&visibility.node, prev_span);
8423 let mac_lo = self.span;
8426 let pth = self.parse_path(PathStyle::Mod)?;
8427 self.expect(&token::Not)?;
8429 // a 'special' identifier (like what `macro_rules!` uses)
8430 // is optional. We should eventually unify invoc syntax
8432 let id = if self.token.is_ident() {
8435 keywords::Invalid.ident() // no special identifier
8437 // eat a matched-delimiter token tree:
8438 let (delim, tts) = self.expect_delimited_token_tree()?;
8439 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
8440 self.report_invalid_macro_expansion_item();
8443 let hi = self.prev_span;
8444 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
8445 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
8446 return Ok(Some(item));
8449 // FAILURE TO PARSE ITEM
8450 match visibility.node {
8451 VisibilityKind::Inherited => {}
8453 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
8457 if !attributes_allowed && !attrs.is_empty() {
8458 self.expected_item_err(&attrs)?;
8463 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
8464 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
8465 at_end: &mut bool) -> PResult<'a, Option<Mac>>
8467 if self.token.is_path_start() &&
8468 !(self.is_async_fn() && self.span.rust_2015()) {
8469 let prev_span = self.prev_span;
8471 let pth = self.parse_path(PathStyle::Mod)?;
8473 if pth.segments.len() == 1 {
8474 if !self.eat(&token::Not) {
8475 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
8478 self.expect(&token::Not)?;
8481 if let Some(vis) = vis {
8482 self.complain_if_pub_macro(&vis.node, prev_span);
8487 // eat a matched-delimiter token tree:
8488 let (delim, tts) = self.expect_delimited_token_tree()?;
8489 if delim != MacDelimiter::Brace {
8490 self.expect(&token::Semi)?;
8493 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
8499 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
8500 where F: FnOnce(&mut Self) -> PResult<'a, R>
8502 // Record all tokens we parse when parsing this item.
8503 let mut tokens = Vec::new();
8504 let prev_collecting = match self.token_cursor.frame.last_token {
8505 LastToken::Collecting(ref mut list) => {
8506 Some(mem::replace(list, Vec::new()))
8508 LastToken::Was(ref mut last) => {
8509 tokens.extend(last.take());
8513 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
8514 let prev = self.token_cursor.stack.len();
8516 let last_token = if self.token_cursor.stack.len() == prev {
8517 &mut self.token_cursor.frame.last_token
8519 &mut self.token_cursor.stack[prev].last_token
8522 // Pull out the tokens that we've collected from the call to `f` above.
8523 let mut collected_tokens = match *last_token {
8524 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
8525 LastToken::Was(_) => panic!("our vector went away?"),
8528 // If we're not at EOF our current token wasn't actually consumed by
8529 // `f`, but it'll still be in our list that we pulled out. In that case
8531 let extra_token = if self.token != token::Eof {
8532 collected_tokens.pop()
8537 // If we were previously collecting tokens, then this was a recursive
8538 // call. In that case we need to record all the tokens we collected in
8539 // our parent list as well. To do that we push a clone of our stream
8540 // onto the previous list.
8541 match prev_collecting {
8543 list.extend(collected_tokens.iter().cloned());
8544 list.extend(extra_token);
8545 *last_token = LastToken::Collecting(list);
8548 *last_token = LastToken::Was(extra_token);
8552 Ok((ret?, TokenStream::new(collected_tokens)))
8555 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
8556 let attrs = self.parse_outer_attributes()?;
8557 self.parse_item_(attrs, true, false)
8561 fn is_import_coupler(&mut self) -> bool {
8562 self.check(&token::ModSep) &&
8563 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
8564 *t == token::BinOp(token::Star))
8567 /// Parses a `UseTree`.
8570 /// USE_TREE = [`::`] `*` |
8571 /// [`::`] `{` USE_TREE_LIST `}` |
8573 /// PATH `::` `{` USE_TREE_LIST `}` |
8574 /// PATH [`as` IDENT]
8576 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
8579 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
8580 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
8581 self.check(&token::BinOp(token::Star)) ||
8582 self.is_import_coupler() {
8583 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
8584 let mod_sep_ctxt = self.span.ctxt();
8585 if self.eat(&token::ModSep) {
8586 prefix.segments.push(
8587 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
8591 if self.eat(&token::BinOp(token::Star)) {
8594 UseTreeKind::Nested(self.parse_use_tree_list()?)
8597 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
8598 prefix = self.parse_path(PathStyle::Mod)?;
8600 if self.eat(&token::ModSep) {
8601 if self.eat(&token::BinOp(token::Star)) {
8604 UseTreeKind::Nested(self.parse_use_tree_list()?)
8607 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
8611 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
8614 /// Parses a `UseTreeKind::Nested(list)`.
8617 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
8619 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
8620 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
8621 &token::CloseDelim(token::Brace),
8622 SeqSep::trailing_allowed(token::Comma), |this| {
8623 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
8627 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
8628 if self.eat_keyword(keywords::As) {
8629 self.parse_ident_or_underscore().map(Some)
8635 /// Parses a source module as a crate. This is the main entry point for the parser.
8636 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
8638 let krate = Ok(ast::Crate {
8639 attrs: self.parse_inner_attributes()?,
8640 module: self.parse_mod_items(&token::Eof, lo)?,
8641 span: lo.to(self.span),
8646 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
8647 let ret = match self.token {
8648 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
8649 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
8656 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
8657 match self.parse_optional_str() {
8658 Some((s, style, suf)) => {
8659 let sp = self.prev_span;
8660 self.expect_no_suffix(sp, "a string literal", suf);
8664 let msg = "expected string literal";
8665 let mut err = self.fatal(msg);
8666 err.span_label(self.span, msg);
8672 fn report_invalid_macro_expansion_item(&self) {
8673 self.struct_span_err(
8675 "macros that expand to items must be delimited with braces or followed by a semicolon",
8676 ).multipart_suggestion(
8677 "change the delimiters to curly braces",
8679 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
8680 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
8682 Applicability::MaybeIncorrect,
8684 self.sess.source_map.next_point(self.prev_span),
8687 Applicability::MaybeIncorrect,
8691 /// Recover from `pub` keyword in places where it seems _reasonable_ but isn't valid.
8692 fn eat_bad_pub(&mut self) {
8693 if self.token.is_keyword(keywords::Pub) {
8694 match self.parse_visibility(false) {
8696 let mut err = self.diagnostic()
8697 .struct_span_err(vis.span, "unnecessary visibility qualifier");
8698 err.span_label(vis.span, "`pub` not permitted here");
8701 Err(mut err) => err.emit(),
8706 /// When lowering a `async fn` to the HIR, we need to move all of the arguments of the function
8707 /// into the generated closure so that they are dropped when the future is polled and not when
8710 /// The arguments of the function are replaced in HIR lowering with the arguments created by
8711 /// this function and the statements created here are inserted at the top of the closure body.
8712 fn construct_async_arguments(&mut self, asyncness: &mut Spanned<IsAsync>, decl: &mut FnDecl) {
8713 if let IsAsync::Async { ref mut arguments, .. } = asyncness.node {
8714 for (index, input) in decl.inputs.iter_mut().enumerate() {
8715 let id = ast::DUMMY_NODE_ID;
8716 let span = input.pat.span;
8718 // Construct a name for our temporary argument.
8719 let name = format!("__arg{}", index);
8720 let ident = Ident::from_str(&name).gensym();
8722 // Check if this is a ident pattern, if so, we can optimize and avoid adding a
8723 // `let <pat> = __argN;` statement, instead just adding a `let <pat> = <pat>;`
8725 let (binding_mode, ident, is_simple_pattern) = match input.pat.node {
8726 PatKind::Ident(binding_mode @ BindingMode::ByValue(_), ident, _) => {
8727 (binding_mode, ident, true)
8729 _ => (BindingMode::ByValue(Mutability::Mutable), ident, false),
8732 // Construct an argument representing `__argN: <ty>` to replace the argument of the
8733 // async function if it isn't a simple pattern.
8734 let arg = if is_simple_pattern {
8738 ty: input.ty.clone(),
8742 node: PatKind::Ident(
8743 BindingMode::ByValue(Mutability::Immutable), ident, None,
8747 source: ArgSource::AsyncFn(input.pat.clone()),
8751 // Construct a `let __argN = __argN;` statement to insert at the top of the
8752 // async closure. This makes sure that the argument is captured by the closure and
8753 // that the drop order is correct.
8754 let move_local = Local {
8757 node: PatKind::Ident(binding_mode, ident, None),
8760 // We explicitly do not specify the type for this statement. When the user's
8761 // argument type is `impl Trait` then this would require the
8762 // `impl_trait_in_bindings` feature to also be present for that same type to
8763 // be valid in this binding. At the time of writing (13 Mar 19),
8764 // `impl_trait_in_bindings` is not stable.
8768 node: ExprKind::Path(None, ast::Path {
8770 segments: vec![PathSegment { ident, id, args: None }],
8773 attrs: ThinVec::new(),
8777 attrs: ThinVec::new(),
8778 source: LocalSource::AsyncFn,
8781 // Construct a `let <pat> = __argN;` statement to insert at the top of the
8782 // async closure if this isn't a simple pattern.
8783 let pat_stmt = if is_simple_pattern {
8788 node: StmtKind::Local(P(Local {
8789 pat: input.pat.clone(),
8790 ..move_local.clone()
8796 // Remove mutability from arguments. If this is not a simple pattern,
8797 // those arguments are replaced by `__argN`, so there is no need to do this.
8798 if let PatKind::Ident(BindingMode::ByValue(mutability @ Mutability::Mutable), ..) =
8801 assert!(is_simple_pattern);
8802 *mutability = Mutability::Immutable;
8805 let move_stmt = Stmt { id, node: StmtKind::Local(P(move_local)), span };
8806 arguments.push(AsyncArgument { ident, arg, pat_stmt, move_stmt });
8812 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
8813 for unmatched in unclosed_delims.iter() {
8814 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
8815 "incorrect close delimiter: `{}`",
8816 pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
8818 err.span_label(unmatched.found_span, "incorrect close delimiter");
8819 if let Some(sp) = unmatched.candidate_span {
8820 err.span_label(sp, "close delimiter possibly meant for this");
8822 if let Some(sp) = unmatched.unclosed_span {
8823 err.span_label(sp, "un-closed delimiter");
8827 unclosed_delims.clear();