1 use crate::ast::{AngleBracketedArgs, ParenthesizedArgs, AttrStyle, BareFnTy};
2 use crate::ast::{GenericBound, TraitBoundModifier};
3 use crate::ast::Unsafety;
4 use crate::ast::{Mod, AnonConst, Arg, Arm, Guard, Attribute, BindingMode, TraitItemKind};
6 use crate::ast::{BlockCheckMode, CaptureBy, Movability};
7 use crate::ast::{Constness, Crate};
8 use crate::ast::Defaultness;
9 use crate::ast::EnumDef;
10 use crate::ast::{Expr, ExprKind, RangeLimits};
11 use crate::ast::{Field, FnDecl, FnHeader};
12 use crate::ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
13 use crate::ast::{GenericParam, GenericParamKind};
14 use crate::ast::GenericArg;
15 use crate::ast::{Ident, ImplItem, IsAsync, IsAuto, Item, ItemKind};
16 use crate::ast::{Label, Lifetime, Lit, LitKind};
17 use crate::ast::Local;
18 use crate::ast::MacStmtStyle;
19 use crate::ast::{Mac, Mac_, MacDelimiter};
20 use crate::ast::{MutTy, Mutability};
21 use crate::ast::{Pat, PatKind, PathSegment};
22 use crate::ast::{PolyTraitRef, QSelf};
23 use crate::ast::{Stmt, StmtKind};
24 use crate::ast::{VariantData, StructField};
25 use crate::ast::StrStyle;
26 use crate::ast::SelfKind;
27 use crate::ast::{TraitItem, TraitRef, TraitObjectSyntax};
28 use crate::ast::{Ty, TyKind, TypeBinding, GenericBounds};
29 use crate::ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
30 use crate::ast::{UseTree, UseTreeKind};
31 use crate::ast::{BinOpKind, UnOp};
32 use crate::ast::{RangeEnd, RangeSyntax};
33 use crate::{ast, attr};
34 use crate::ext::base::DummyResult;
35 use crate::source_map::{self, SourceMap, Spanned, respan};
36 use crate::parse::{self, SeqSep, classify, token};
37 use crate::parse::lexer::{TokenAndSpan, UnmatchedBrace};
38 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
39 use crate::parse::token::DelimToken;
40 use crate::parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
41 use crate::util::parser::{AssocOp, Fixity};
42 use crate::print::pprust;
44 use crate::parse::PResult;
46 use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
47 use crate::symbol::{Symbol, keywords};
49 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
50 use rustc_target::spec::abi::{self, Abi};
51 use syntax_pos::{Span, MultiSpan, BytePos, FileName};
52 use log::{debug, trace};
57 use std::path::{self, Path, PathBuf};
61 /// Whether the type alias or associated type is a concrete type or an existential type
63 /// Just a new name for the same type
65 /// Only trait impls of the type will be usable, not the actual type itself
66 Existential(GenericBounds),
70 struct Restrictions: u8 {
71 const STMT_EXPR = 1 << 0;
72 const NO_STRUCT_LITERAL = 1 << 1;
76 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
78 /// Specifies how to parse a path.
79 #[derive(Copy, Clone, PartialEq)]
81 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
82 /// with something else. For example, in expressions `segment < ....` can be interpreted
83 /// as a comparison and `segment ( ....` can be interpreted as a function call.
84 /// In all such contexts the non-path interpretation is preferred by default for practical
85 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
86 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
88 /// In other contexts, notably in types, no ambiguity exists and paths can be written
89 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
90 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
92 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
93 /// visibilities or attributes.
94 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
95 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
96 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
97 /// tokens when something goes wrong.
101 #[derive(Clone, Copy, PartialEq, Debug)]
108 #[derive(Clone, Copy, PartialEq, Debug)]
114 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
115 /// dropped into the token stream, which happens while parsing the result of
116 /// macro expansion). Placement of these is not as complex as I feared it would
117 /// be. The important thing is to make sure that lookahead doesn't balk at
118 /// `token::Interpolated` tokens.
119 macro_rules! maybe_whole_expr {
121 if let token::Interpolated(nt) = $p.token.clone() {
123 token::NtExpr(ref e) | token::NtLiteral(ref e) => {
125 return Ok((*e).clone());
127 token::NtPath(ref path) => {
130 let kind = ExprKind::Path(None, (*path).clone());
131 return Ok($p.mk_expr(span, kind, ThinVec::new()));
133 token::NtBlock(ref block) => {
136 let kind = ExprKind::Block((*block).clone(), None);
137 return Ok($p.mk_expr(span, kind, ThinVec::new()));
145 /// As maybe_whole_expr, but for things other than expressions
146 macro_rules! maybe_whole {
147 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
148 if let token::Interpolated(nt) = $p.token.clone() {
149 if let token::$constructor($x) = (*nt).clone() {
157 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
158 if let Some(ref mut rhs) = rhs {
164 #[derive(Debug, Clone, Copy, PartialEq)]
175 trait RecoverQPath: Sized {
176 const PATH_STYLE: PathStyle = PathStyle::Expr;
177 fn to_ty(&self) -> Option<P<Ty>>;
178 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self;
179 fn to_string(&self) -> String;
182 impl RecoverQPath for Ty {
183 const PATH_STYLE: PathStyle = PathStyle::Type;
184 fn to_ty(&self) -> Option<P<Ty>> {
185 Some(P(self.clone()))
187 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
188 Self { span: path.span, node: TyKind::Path(qself, path), id: self.id }
190 fn to_string(&self) -> String {
191 pprust::ty_to_string(self)
195 impl RecoverQPath for Pat {
196 fn to_ty(&self) -> Option<P<Ty>> {
199 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
200 Self { span: path.span, node: PatKind::Path(qself, path), id: self.id }
202 fn to_string(&self) -> String {
203 pprust::pat_to_string(self)
207 impl RecoverQPath for Expr {
208 fn to_ty(&self) -> Option<P<Ty>> {
211 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
212 Self { span: path.span, node: ExprKind::Path(qself, path),
213 id: self.id, attrs: self.attrs.clone() }
215 fn to_string(&self) -> String {
216 pprust::expr_to_string(self)
220 /* ident is handled by common.rs */
223 pub struct Parser<'a> {
224 pub sess: &'a ParseSess,
225 /// the current token:
226 pub token: token::Token,
227 /// the span of the current token:
229 /// the span of the previous token:
230 meta_var_span: Option<Span>,
232 /// the previous token kind
233 prev_token_kind: PrevTokenKind,
234 restrictions: Restrictions,
235 /// Used to determine the path to externally loaded source files
236 crate directory: Directory<'a>,
237 /// Whether to parse sub-modules in other files.
238 pub recurse_into_file_modules: bool,
239 /// Name of the root module this parser originated from. If `None`, then the
240 /// name is not known. This does not change while the parser is descending
241 /// into modules, and sub-parsers have new values for this name.
242 pub root_module_name: Option<String>,
243 crate expected_tokens: Vec<TokenType>,
244 token_cursor: TokenCursor,
245 desugar_doc_comments: bool,
246 /// Whether we should configure out of line modules as we parse.
248 /// This field is used to keep track of how many left angle brackets we have seen. This is
249 /// required in order to detect extra leading left angle brackets (`<` characters) and error
252 /// See the comments in the `parse_path_segment` function for more details.
253 crate unmatched_angle_bracket_count: u32,
254 crate max_angle_bracket_count: u32,
255 /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
256 /// it gets removed from here. Every entry left at the end gets emitted as an independent
258 crate unclosed_delims: Vec<UnmatchedBrace>,
264 frame: TokenCursorFrame,
265 stack: Vec<TokenCursorFrame>,
269 struct TokenCursorFrame {
270 delim: token::DelimToken,
273 tree_cursor: tokenstream::Cursor,
275 last_token: LastToken,
278 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
279 /// by the parser, and then that's transitively used to record the tokens that
280 /// each parse AST item is created with.
282 /// Right now this has two states, either collecting tokens or not collecting
283 /// tokens. If we're collecting tokens we just save everything off into a local
284 /// `Vec`. This should eventually though likely save tokens from the original
285 /// token stream and just use slicing of token streams to avoid creation of a
286 /// whole new vector.
288 /// The second state is where we're passively not recording tokens, but the last
289 /// token is still tracked for when we want to start recording tokens. This
290 /// "last token" means that when we start recording tokens we'll want to ensure
291 /// that this, the first token, is included in the output.
293 /// You can find some more example usage of this in the `collect_tokens` method
297 Collecting(Vec<TreeAndJoint>),
298 Was(Option<TreeAndJoint>),
301 impl TokenCursorFrame {
302 fn new(sp: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
306 open_delim: delim == token::NoDelim,
307 tree_cursor: tts.clone().into_trees(),
308 close_delim: delim == token::NoDelim,
309 last_token: LastToken::Was(None),
315 fn next(&mut self) -> TokenAndSpan {
317 let tree = if !self.frame.open_delim {
318 self.frame.open_delim = true;
319 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
320 } else if let Some(tree) = self.frame.tree_cursor.next() {
322 } else if !self.frame.close_delim {
323 self.frame.close_delim = true;
324 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
325 } else if let Some(frame) = self.stack.pop() {
329 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
332 match self.frame.last_token {
333 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
334 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
338 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
339 TokenTree::Delimited(sp, delim, tts) => {
340 let frame = TokenCursorFrame::new(sp, delim, &tts);
341 self.stack.push(mem::replace(&mut self.frame, frame));
347 fn next_desugared(&mut self) -> TokenAndSpan {
348 let (sp, name) = match self.next() {
349 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
353 let stripped = strip_doc_comment_decoration(&name.as_str());
355 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
356 // required to wrap the text.
357 let mut num_of_hashes = 0;
359 for ch in stripped.chars() {
362 '#' if count > 0 => count + 1,
365 num_of_hashes = cmp::max(num_of_hashes, count);
368 let delim_span = DelimSpan::from_single(sp);
369 let body = TokenTree::Delimited(
372 [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
373 TokenTree::Token(sp, token::Eq),
374 TokenTree::Token(sp, token::Literal(
375 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))
377 .iter().cloned().collect::<TokenStream>().into(),
380 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
383 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
384 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
385 .iter().cloned().collect::<TokenStream>().into()
387 [TokenTree::Token(sp, token::Pound), body]
388 .iter().cloned().collect::<TokenStream>().into()
396 #[derive(Clone, PartialEq)]
397 crate enum TokenType {
399 Keyword(keywords::Keyword),
409 fn to_string(&self) -> String {
411 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
412 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
413 TokenType::Operator => "an operator".to_string(),
414 TokenType::Lifetime => "lifetime".to_string(),
415 TokenType::Ident => "identifier".to_string(),
416 TokenType::Path => "path".to_string(),
417 TokenType::Type => "type".to_string(),
418 TokenType::Const => "const".to_string(),
423 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
424 /// `IDENT<<u8 as Trait>::AssocTy>`.
426 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
427 /// that `IDENT` is not the ident of a fn trait.
428 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
429 t == &token::ModSep || t == &token::Lt ||
430 t == &token::BinOp(token::Shl)
433 /// Information about the path to a module.
434 pub struct ModulePath {
437 pub result: Result<ModulePathSuccess, Error>,
440 pub struct ModulePathSuccess {
442 pub directory_ownership: DirectoryOwnership,
447 FileNotFoundForModule {
449 default_path: String,
450 secondary_path: String,
455 default_path: String,
456 secondary_path: String,
459 InclusiveRangeWithNoEnd,
463 fn span_err<S: Into<MultiSpan>>(self,
465 handler: &errors::Handler) -> DiagnosticBuilder<'_> {
467 Error::FileNotFoundForModule { ref mod_name,
471 let mut err = struct_span_err!(handler, sp, E0583,
472 "file not found for module `{}`", mod_name);
473 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
479 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
480 let mut err = struct_span_err!(handler, sp, E0584,
481 "file for module `{}` found at both {} and {}",
485 err.help("delete or rename one of them to remove the ambiguity");
488 Error::UselessDocComment => {
489 let mut err = struct_span_err!(handler, sp, E0585,
490 "found a documentation comment that doesn't document anything");
491 err.help("doc comments must come before what they document, maybe a comment was \
492 intended with `//`?");
495 Error::InclusiveRangeWithNoEnd => {
496 let mut err = struct_span_err!(handler, sp, E0586,
497 "inclusive range with no end");
498 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
508 AttributesParsed(ThinVec<Attribute>),
509 AlreadyParsed(P<Expr>),
512 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
513 fn from(o: Option<ThinVec<Attribute>>) -> Self {
514 if let Some(attrs) = o {
515 LhsExpr::AttributesParsed(attrs)
517 LhsExpr::NotYetParsed
522 impl From<P<Expr>> for LhsExpr {
523 fn from(expr: P<Expr>) -> Self {
524 LhsExpr::AlreadyParsed(expr)
528 /// Creates a placeholder argument.
529 fn dummy_arg(span: Span) -> Arg {
530 let ident = Ident::new(keywords::Invalid.name(), span);
532 id: ast::DUMMY_NODE_ID,
533 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
539 id: ast::DUMMY_NODE_ID
541 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
544 #[derive(Copy, Clone, Debug)]
545 enum TokenExpectType {
550 impl<'a> Parser<'a> {
551 pub fn new(sess: &'a ParseSess,
553 directory: Option<Directory<'a>>,
554 recurse_into_file_modules: bool,
555 desugar_doc_comments: bool)
557 let mut parser = Parser {
559 token: token::Whitespace,
560 span: syntax_pos::DUMMY_SP,
561 prev_span: syntax_pos::DUMMY_SP,
563 prev_token_kind: PrevTokenKind::Other,
564 restrictions: Restrictions::empty(),
565 recurse_into_file_modules,
566 directory: Directory {
567 path: Cow::from(PathBuf::new()),
568 ownership: DirectoryOwnership::Owned { relative: None }
570 root_module_name: None,
571 expected_tokens: Vec::new(),
572 token_cursor: TokenCursor {
573 frame: TokenCursorFrame::new(
580 desugar_doc_comments,
582 unmatched_angle_bracket_count: 0,
583 max_angle_bracket_count: 0,
584 unclosed_delims: Vec::new(),
587 let tok = parser.next_tok();
588 parser.token = tok.tok;
589 parser.span = tok.sp;
591 if let Some(directory) = directory {
592 parser.directory = directory;
593 } else if !parser.span.is_dummy() {
594 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
596 parser.directory.path = Cow::from(path);
600 parser.process_potential_macro_variable();
604 fn next_tok(&mut self) -> TokenAndSpan {
605 let mut next = if self.desugar_doc_comments {
606 self.token_cursor.next_desugared()
608 self.token_cursor.next()
610 if next.sp.is_dummy() {
611 // Tweak the location for better diagnostics, but keep syntactic context intact.
612 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
617 /// Converts the current token to a string using `self`'s reader.
618 pub fn this_token_to_string(&self) -> String {
619 pprust::token_to_string(&self.token)
622 fn token_descr(&self) -> Option<&'static str> {
623 Some(match &self.token {
624 t if t.is_special_ident() => "reserved identifier",
625 t if t.is_used_keyword() => "keyword",
626 t if t.is_unused_keyword() => "reserved keyword",
627 token::DocComment(..) => "doc comment",
632 fn this_token_descr(&self) -> String {
633 if let Some(prefix) = self.token_descr() {
634 format!("{} `{}`", prefix, self.this_token_to_string())
636 format!("`{}`", self.this_token_to_string())
640 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
641 let token_str = pprust::token_to_string(t);
642 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
645 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
646 match self.expect_one_of(&[], &[]) {
648 Ok(_) => unreachable!(),
652 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
653 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, bool /* recovered */> {
654 if self.expected_tokens.is_empty() {
655 if self.token == *t {
659 let token_str = pprust::token_to_string(t);
660 let this_token_str = self.this_token_descr();
661 let mut err = self.fatal(&format!("expected `{}`, found {}",
665 let sp = if self.token == token::Token::Eof {
666 // EOF, don't want to point at the following char, but rather the last token
669 self.sess.source_map().next_point(self.prev_span)
671 let label_exp = format!("expected `{}`", token_str);
672 match self.recover_closing_delimiter(&[t.clone()], err) {
675 return Ok(recovered);
678 let cm = self.sess.source_map();
679 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
680 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
681 // When the spans are in the same line, it means that the only content
682 // between them is whitespace, point only at the found token.
683 err.span_label(self.span, label_exp);
686 err.span_label(sp, label_exp);
687 err.span_label(self.span, "unexpected token");
693 self.expect_one_of(slice::from_ref(t), &[])
697 fn recover_closing_delimiter(
699 tokens: &[token::Token],
700 mut err: DiagnosticBuilder<'a>,
701 ) -> PResult<'a, bool> {
703 // we want to use the last closing delim that would apply
704 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
705 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
706 && Some(self.span) > unmatched.unclosed_span
713 // Recover and assume that the detected unclosed delimiter was meant for
714 // this location. Emit the diagnostic and act as if the delimiter was
715 // present for the parser's sake.
717 // Don't attempt to recover from this unclosed delimiter more than once.
718 let unmatched = self.unclosed_delims.remove(pos);
719 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
721 // We want to suggest the inclusion of the closing delimiter where it makes
722 // the most sense, which is immediately after the last token:
727 // | help: `)` may belong here (FIXME: #58270)
729 // unclosed delimiter
730 if let Some(sp) = unmatched.unclosed_span {
731 err.span_label(sp, "unclosed delimiter");
733 err.span_suggestion_short(
734 self.sess.source_map().next_point(self.prev_span),
735 &format!("{} may belong here", delim.to_string()),
737 Applicability::MaybeIncorrect,
740 self.expected_tokens.clear(); // reduce errors
747 /// Expect next token to be edible or inedible token. If edible,
748 /// then consume it; if inedible, then return without consuming
749 /// anything. Signal a fatal error if next token is unexpected.
750 pub fn expect_one_of(
752 edible: &[token::Token],
753 inedible: &[token::Token],
754 ) -> PResult<'a, bool /* recovered */> {
755 fn tokens_to_string(tokens: &[TokenType]) -> String {
756 let mut i = tokens.iter();
757 // This might be a sign we need a connect method on Iterator.
759 .map_or(String::new(), |t| t.to_string());
760 i.enumerate().fold(b, |mut b, (i, a)| {
761 if tokens.len() > 2 && i == tokens.len() - 2 {
763 } else if tokens.len() == 2 && i == tokens.len() - 2 {
768 b.push_str(&a.to_string());
772 if edible.contains(&self.token) {
775 } else if inedible.contains(&self.token) {
776 // leave it in the input
779 let mut expected = edible.iter()
780 .map(|x| TokenType::Token(x.clone()))
781 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
782 .chain(self.expected_tokens.iter().cloned())
783 .collect::<Vec<_>>();
784 expected.sort_by_cached_key(|x| x.to_string());
786 let expect = tokens_to_string(&expected[..]);
787 let actual = self.this_token_to_string();
788 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
789 let short_expect = if expected.len() > 6 {
790 format!("{} possible tokens", expected.len())
794 (format!("expected one of {}, found `{}`", expect, actual),
795 (self.sess.source_map().next_point(self.prev_span),
796 format!("expected one of {} here", short_expect)))
797 } else if expected.is_empty() {
798 (format!("unexpected token: `{}`", actual),
799 (self.prev_span, "unexpected token after this".to_string()))
801 (format!("expected {}, found `{}`", expect, actual),
802 (self.sess.source_map().next_point(self.prev_span),
803 format!("expected {} here", expect)))
805 let mut err = self.fatal(&msg_exp);
806 if self.token.is_ident_named("and") {
807 err.span_suggestion_short(
809 "use `&&` instead of `and` for the boolean operator",
811 Applicability::MaybeIncorrect,
814 if self.token.is_ident_named("or") {
815 err.span_suggestion_short(
817 "use `||` instead of `or` for the boolean operator",
819 Applicability::MaybeIncorrect,
822 let sp = if self.token == token::Token::Eof {
823 // This is EOF, don't want to point at the following char, but rather the last token
828 match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt {
829 TokenType::Token(t) => Some(t.clone()),
831 }).collect::<Vec<_>>(), err) {
834 return Ok(recovered);
838 let cm = self.sess.source_map();
839 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
840 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
841 // When the spans are in the same line, it means that the only content between
842 // them is whitespace, point at the found token in that case:
844 // X | () => { syntax error };
845 // | ^^^^^ expected one of 8 possible tokens here
847 // instead of having:
849 // X | () => { syntax error };
850 // | -^^^^^ unexpected token
852 // | expected one of 8 possible tokens here
853 err.span_label(self.span, label_exp);
855 _ if self.prev_span == syntax_pos::DUMMY_SP => {
856 // Account for macro context where the previous span might not be
857 // available to avoid incorrect output (#54841).
858 err.span_label(self.span, "unexpected token");
861 err.span_label(sp, label_exp);
862 err.span_label(self.span, "unexpected token");
869 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
870 fn interpolated_or_expr_span(&self,
871 expr: PResult<'a, P<Expr>>)
872 -> PResult<'a, (Span, P<Expr>)> {
874 if self.prev_token_kind == PrevTokenKind::Interpolated {
882 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
883 let mut err = self.struct_span_err(self.span,
884 &format!("expected identifier, found {}",
885 self.this_token_descr()));
886 if let token::Ident(ident, false) = &self.token {
887 if ident.is_reserved() && !ident.is_path_segment_keyword() &&
888 ident.name != keywords::Underscore.name()
892 "you can escape reserved keywords to use them as identifiers",
893 format!("r#{}", ident),
894 Applicability::MaybeIncorrect,
898 if let Some(token_descr) = self.token_descr() {
899 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
901 err.span_label(self.span, "expected identifier");
902 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
907 Applicability::MachineApplicable,
914 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
915 self.parse_ident_common(true)
918 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
920 token::Ident(ident, _) => {
921 if self.token.is_reserved_ident() {
922 let mut err = self.expected_ident_found();
929 let span = self.span;
931 Ok(Ident::new(ident.name, span))
934 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
935 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
937 self.expected_ident_found()
943 /// Checks if the next token is `tok`, and returns `true` if so.
945 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
947 crate fn check(&mut self, tok: &token::Token) -> bool {
948 let is_present = self.token == *tok;
949 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
953 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
954 pub fn eat(&mut self, tok: &token::Token) -> bool {
955 let is_present = self.check(tok);
956 if is_present { self.bump() }
960 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
961 self.expected_tokens.push(TokenType::Keyword(kw));
962 self.token.is_keyword(kw)
965 /// If the next token is the given keyword, eats it and returns
966 /// `true`. Otherwise, returns `false`.
967 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
968 if self.check_keyword(kw) {
976 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
977 if self.token.is_keyword(kw) {
985 /// If the given word is not a keyword, signals an error.
986 /// If the next token is not the given word, signals an error.
987 /// Otherwise, eats it.
988 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
989 if !self.eat_keyword(kw) {
996 fn check_ident(&mut self) -> bool {
997 if self.token.is_ident() {
1000 self.expected_tokens.push(TokenType::Ident);
1005 fn check_path(&mut self) -> bool {
1006 if self.token.is_path_start() {
1009 self.expected_tokens.push(TokenType::Path);
1014 fn check_type(&mut self) -> bool {
1015 if self.token.can_begin_type() {
1018 self.expected_tokens.push(TokenType::Type);
1023 fn check_const_arg(&mut self) -> bool {
1024 if self.token.can_begin_const_arg() {
1027 self.expected_tokens.push(TokenType::Const);
1032 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
1033 /// and continues. If a `+` is not seen, returns `false`.
1035 /// This is used when token-splitting `+=` into `+`.
1036 /// See issue #47856 for an example of when this may occur.
1037 fn eat_plus(&mut self) -> bool {
1038 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1040 token::BinOp(token::Plus) => {
1044 token::BinOpEq(token::Plus) => {
1045 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1046 self.bump_with(token::Eq, span);
1054 /// Checks to see if the next token is either `+` or `+=`.
1055 /// Otherwise returns `false`.
1056 fn check_plus(&mut self) -> bool {
1057 if self.token.is_like_plus() {
1061 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1066 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
1067 /// `&` and continues. If an `&` is not seen, signals an error.
1068 fn expect_and(&mut self) -> PResult<'a, ()> {
1069 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
1071 token::BinOp(token::And) => {
1076 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1077 Ok(self.bump_with(token::BinOp(token::And), span))
1079 _ => self.unexpected()
1083 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
1084 /// `|` and continues. If an `|` is not seen, signals an error.
1085 fn expect_or(&mut self) -> PResult<'a, ()> {
1086 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
1088 token::BinOp(token::Or) => {
1093 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1094 Ok(self.bump_with(token::BinOp(token::Or), span))
1096 _ => self.unexpected()
1100 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
1102 None => {/* everything ok */}
1104 let text = suf.as_str();
1105 if text.is_empty() {
1106 self.span_bug(sp, "found empty literal suffix in Some")
1108 let msg = format!("{} with a suffix is invalid", kind);
1109 self.struct_span_err(sp, &msg)
1110 .span_label(sp, msg)
1116 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
1117 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
1118 /// and continue. If a `<` is not seen, returns false.
1120 /// This is meant to be used when parsing generics on a path to get the
1122 fn eat_lt(&mut self) -> bool {
1123 self.expected_tokens.push(TokenType::Token(token::Lt));
1124 let ate = match self.token {
1129 token::BinOp(token::Shl) => {
1130 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1131 self.bump_with(token::Lt, span);
1135 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1136 self.bump_with(token::BinOp(token::Minus), span);
1143 // See doc comment for `unmatched_angle_bracket_count`.
1144 self.unmatched_angle_bracket_count += 1;
1145 self.max_angle_bracket_count += 1;
1146 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
1152 fn expect_lt(&mut self) -> PResult<'a, ()> {
1160 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
1161 /// with a single `>` and continues. If a `>` is not seen, signals an error.
1162 fn expect_gt(&mut self) -> PResult<'a, ()> {
1163 self.expected_tokens.push(TokenType::Token(token::Gt));
1164 let ate = match self.token {
1169 token::BinOp(token::Shr) => {
1170 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1171 Some(self.bump_with(token::Gt, span))
1173 token::BinOpEq(token::Shr) => {
1174 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1175 Some(self.bump_with(token::Ge, span))
1178 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1179 Some(self.bump_with(token::Eq, span))
1186 // See doc comment for `unmatched_angle_bracket_count`.
1187 if self.unmatched_angle_bracket_count > 0 {
1188 self.unmatched_angle_bracket_count -= 1;
1189 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1194 None => self.unexpected(),
1198 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
1199 /// passes through any errors encountered. Used for error recovery.
1200 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1201 let handler = self.diagnostic();
1203 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1205 TokenExpectType::Expect,
1206 |p| Ok(p.parse_token_tree())) {
1207 handler.cancel(err);
1211 /// Parses a sequence, including the closing delimiter. The function
1212 /// `f` must consume tokens until reaching the next separator or
1213 /// closing bracket.
1214 pub fn parse_seq_to_end<T, F>(&mut self,
1218 -> PResult<'a, Vec<T>> where
1219 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1221 let (val, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1228 /// Parses a sequence, not including the closing delimiter. The function
1229 /// `f` must consume tokens until reaching the next separator or
1230 /// closing bracket.
1231 pub fn parse_seq_to_before_end<T, F>(
1236 ) -> PResult<'a, (Vec<T>, bool)>
1237 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1239 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1242 fn parse_seq_to_before_tokens<T, F>(
1244 kets: &[&token::Token],
1246 expect: TokenExpectType,
1248 ) -> PResult<'a, (Vec<T>, bool /* recovered */)>
1249 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1251 let mut first = true;
1252 let mut recovered = false;
1254 while !kets.iter().any(|k| {
1256 TokenExpectType::Expect => self.check(k),
1257 TokenExpectType::NoExpect => self.token == **k,
1261 token::CloseDelim(..) | token::Eof => break,
1264 if let Some(ref t) = sep.sep {
1268 match self.expect(t) {
1275 // Attempt to keep parsing if it was a similar separator
1276 if let Some(ref tokens) = t.similar_tokens() {
1277 if tokens.contains(&self.token) {
1282 // Attempt to keep parsing if it was an omitted separator
1297 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1299 TokenExpectType::Expect => self.check(k),
1300 TokenExpectType::NoExpect => self.token == **k,
1313 /// Parses a sequence, including the closing delimiter. The function
1314 /// `f` must consume tokens until reaching the next separator or
1315 /// closing bracket.
1316 fn parse_unspanned_seq<T, F>(
1322 ) -> PResult<'a, Vec<T>> where
1323 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1326 let (result, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1333 /// Advance the parser by one token
1334 pub fn bump(&mut self) {
1335 if self.prev_token_kind == PrevTokenKind::Eof {
1336 // Bumping after EOF is a bad sign, usually an infinite loop.
1337 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1340 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1342 // Record last token kind for possible error recovery.
1343 self.prev_token_kind = match self.token {
1344 token::DocComment(..) => PrevTokenKind::DocComment,
1345 token::Comma => PrevTokenKind::Comma,
1346 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1347 token::Interpolated(..) => PrevTokenKind::Interpolated,
1348 token::Eof => PrevTokenKind::Eof,
1349 token::Ident(..) => PrevTokenKind::Ident,
1350 _ => PrevTokenKind::Other,
1353 let next = self.next_tok();
1354 self.span = next.sp;
1355 self.token = next.tok;
1356 self.expected_tokens.clear();
1357 // check after each token
1358 self.process_potential_macro_variable();
1361 /// Advance the parser using provided token as a next one. Use this when
1362 /// consuming a part of a token. For example a single `<` from `<<`.
1363 fn bump_with(&mut self, next: token::Token, span: Span) {
1364 self.prev_span = self.span.with_hi(span.lo());
1365 // It would be incorrect to record the kind of the current token, but
1366 // fortunately for tokens currently using `bump_with`, the
1367 // prev_token_kind will be of no use anyway.
1368 self.prev_token_kind = PrevTokenKind::Other;
1371 self.expected_tokens.clear();
1374 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1375 F: FnOnce(&token::Token) -> R,
1378 return f(&self.token)
1381 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1382 Some(tree) => match tree {
1383 TokenTree::Token(_, tok) => tok,
1384 TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim),
1386 None => token::CloseDelim(self.token_cursor.frame.delim),
1390 fn look_ahead_span(&self, dist: usize) -> Span {
1395 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1396 Some(TokenTree::Token(span, _)) => span,
1397 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1398 None => self.look_ahead_span(dist - 1),
1401 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1402 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1404 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1405 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1407 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1408 err.span_err(sp, self.diagnostic())
1410 fn bug(&self, m: &str) -> ! {
1411 self.sess.span_diagnostic.span_bug(self.span, m)
1413 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1414 self.sess.span_diagnostic.span_err(sp, m)
1416 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1417 self.sess.span_diagnostic.struct_span_err(sp, m)
1419 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1420 self.sess.span_diagnostic.span_bug(sp, m)
1423 fn cancel(&self, err: &mut DiagnosticBuilder<'_>) {
1424 self.sess.span_diagnostic.cancel(err)
1427 crate fn diagnostic(&self) -> &'a errors::Handler {
1428 &self.sess.span_diagnostic
1431 /// Is the current token one of the keywords that signals a bare function type?
1432 fn token_is_bare_fn_keyword(&mut self) -> bool {
1433 self.check_keyword(keywords::Fn) ||
1434 self.check_keyword(keywords::Unsafe) ||
1435 self.check_keyword(keywords::Extern)
1438 /// Parses a `TyKind::BareFn` type.
1439 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1442 [unsafe] [extern "ABI"] fn (S) -> T
1452 let unsafety = self.parse_unsafety();
1453 let abi = if self.eat_keyword(keywords::Extern) {
1454 self.parse_opt_abi()?.unwrap_or(Abi::C)
1459 self.expect_keyword(keywords::Fn)?;
1460 let (inputs, c_variadic) = self.parse_fn_args(false, true)?;
1461 let ret_ty = self.parse_ret_ty(false)?;
1462 let decl = P(FnDecl {
1467 Ok(TyKind::BareFn(P(BareFnTy {
1475 /// Parses asyncness: `async` or nothing.
1476 fn parse_asyncness(&mut self) -> IsAsync {
1477 if self.eat_keyword(keywords::Async) {
1479 closure_id: ast::DUMMY_NODE_ID,
1480 return_impl_trait_id: ast::DUMMY_NODE_ID,
1487 /// Parses unsafety: `unsafe` or nothing.
1488 fn parse_unsafety(&mut self) -> Unsafety {
1489 if self.eat_keyword(keywords::Unsafe) {
1496 /// Parses the items in a trait declaration.
1497 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1498 maybe_whole!(self, NtTraitItem, |x| x);
1499 let attrs = self.parse_outer_attributes()?;
1500 let (mut item, tokens) = self.collect_tokens(|this| {
1501 this.parse_trait_item_(at_end, attrs)
1503 // See `parse_item` for why this clause is here.
1504 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1505 item.tokens = Some(tokens);
1510 fn parse_trait_item_(&mut self,
1512 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1515 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1516 self.parse_trait_item_assoc_ty()?
1517 } else if self.is_const_item() {
1518 self.expect_keyword(keywords::Const)?;
1519 let ident = self.parse_ident()?;
1520 self.expect(&token::Colon)?;
1521 let ty = self.parse_ty()?;
1522 let default = if self.eat(&token::Eq) {
1523 let expr = self.parse_expr()?;
1524 self.expect(&token::Semi)?;
1527 self.expect(&token::Semi)?;
1530 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1531 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1532 // trait item macro.
1533 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1535 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1537 let ident = self.parse_ident()?;
1538 let mut generics = self.parse_generics()?;
1540 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1541 // This is somewhat dubious; We don't want to allow
1542 // argument names to be left off if there is a
1545 // We don't allow argument names to be left off in edition 2018.
1546 p.parse_arg_general(p.span.rust_2018(), true, false)
1548 generics.where_clause = self.parse_where_clause()?;
1550 let sig = ast::MethodSig {
1560 let body = match self.token {
1564 debug!("parse_trait_methods(): parsing required method");
1567 token::OpenDelim(token::Brace) => {
1568 debug!("parse_trait_methods(): parsing provided method");
1570 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1571 attrs.extend(inner_attrs.iter().cloned());
1574 token::Interpolated(ref nt) => {
1576 token::NtBlock(..) => {
1578 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1579 attrs.extend(inner_attrs.iter().cloned());
1583 let token_str = self.this_token_descr();
1584 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1586 err.span_label(self.span, "expected `;` or `{`");
1592 let token_str = self.this_token_descr();
1593 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1595 err.span_label(self.span, "expected `;` or `{`");
1599 (ident, ast::TraitItemKind::Method(sig, body), generics)
1603 id: ast::DUMMY_NODE_ID,
1608 span: lo.to(self.prev_span),
1613 /// Parses an optional return type `[ -> TY ]` in a function declaration.
1614 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1615 if self.eat(&token::RArrow) {
1616 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?))
1618 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1623 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1624 self.parse_ty_common(true, true, false)
1627 /// Parses a type in restricted contexts where `+` is not permitted.
1629 /// Example 1: `&'a TYPE`
1630 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1631 /// Example 2: `value1 as TYPE + value2`
1632 /// `+` is prohibited to avoid interactions with expression grammar.
1633 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1634 self.parse_ty_common(false, true, false)
1637 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool,
1638 allow_c_variadic: bool) -> PResult<'a, P<Ty>> {
1639 maybe_whole!(self, NtTy, |x| x);
1642 let mut impl_dyn_multi = false;
1643 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1644 // `(TYPE)` is a parenthesized type.
1645 // `(TYPE,)` is a tuple with a single field of type TYPE.
1646 let mut ts = vec![];
1647 let mut last_comma = false;
1648 while self.token != token::CloseDelim(token::Paren) {
1649 ts.push(self.parse_ty()?);
1650 if self.eat(&token::Comma) {
1657 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1658 self.expect(&token::CloseDelim(token::Paren))?;
1660 if ts.len() == 1 && !last_comma {
1661 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1662 let maybe_bounds = allow_plus && self.token.is_like_plus();
1664 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1665 TyKind::Path(None, ref path) if maybe_bounds => {
1666 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1668 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1669 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1670 let path = match bounds[0] {
1671 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1672 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1674 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1677 _ => TyKind::Paren(P(ty))
1682 } else if self.eat(&token::Not) {
1685 } else if self.eat(&token::BinOp(token::Star)) {
1687 TyKind::Ptr(self.parse_ptr()?)
1688 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1690 let t = self.parse_ty()?;
1691 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1692 let t = match self.maybe_parse_fixed_length_of_vec()? {
1693 None => TyKind::Slice(t),
1694 Some(length) => TyKind::Array(t, AnonConst {
1695 id: ast::DUMMY_NODE_ID,
1699 self.expect(&token::CloseDelim(token::Bracket))?;
1701 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1704 self.parse_borrowed_pointee()?
1705 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1707 // In order to not be ambiguous, the type must be surrounded by parens.
1708 self.expect(&token::OpenDelim(token::Paren))?;
1710 id: ast::DUMMY_NODE_ID,
1711 value: self.parse_expr()?,
1713 self.expect(&token::CloseDelim(token::Paren))?;
1715 } else if self.eat_keyword(keywords::Underscore) {
1716 // A type to be inferred `_`
1718 } else if self.token_is_bare_fn_keyword() {
1719 // Function pointer type
1720 self.parse_ty_bare_fn(Vec::new())?
1721 } else if self.check_keyword(keywords::For) {
1722 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1723 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1724 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1726 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1727 if self.token_is_bare_fn_keyword() {
1728 self.parse_ty_bare_fn(lifetime_defs)?
1730 let path = self.parse_path(PathStyle::Type)?;
1731 let parse_plus = allow_plus && self.check_plus();
1732 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1734 } else if self.eat_keyword(keywords::Impl) {
1735 // Always parse bounds greedily for better error recovery.
1736 let bounds = self.parse_generic_bounds(None)?;
1737 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1738 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1739 } else if self.check_keyword(keywords::Dyn) &&
1740 (self.span.rust_2018() ||
1741 self.look_ahead(1, |t| t.can_begin_bound() &&
1742 !can_continue_type_after_non_fn_ident(t))) {
1743 self.bump(); // `dyn`
1744 // Always parse bounds greedily for better error recovery.
1745 let bounds = self.parse_generic_bounds(None)?;
1746 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1747 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1748 } else if self.check(&token::Question) ||
1749 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1750 // Bound list (trait object type)
1751 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
1752 TraitObjectSyntax::None)
1753 } else if self.eat_lt() {
1755 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1756 TyKind::Path(Some(qself), path)
1757 } else if self.token.is_path_start() {
1759 let path = self.parse_path(PathStyle::Type)?;
1760 if self.eat(&token::Not) {
1761 // Macro invocation in type position
1762 let (delim, tts) = self.expect_delimited_token_tree()?;
1763 let node = Mac_ { path, tts, delim };
1764 TyKind::Mac(respan(lo.to(self.prev_span), node))
1766 // Just a type path or bound list (trait object type) starting with a trait.
1768 // `Trait1 + Trait2 + 'a`
1769 if allow_plus && self.check_plus() {
1770 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1772 TyKind::Path(None, path)
1775 } else if self.check(&token::DotDotDot) {
1776 if allow_c_variadic {
1777 self.eat(&token::DotDotDot);
1780 return Err(self.fatal(
1781 "only foreign functions are allowed to be C-variadic"
1785 let msg = format!("expected type, found {}", self.this_token_descr());
1786 return Err(self.fatal(&msg));
1789 let span = lo.to(self.prev_span);
1790 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1792 // Try to recover from use of `+` with incorrect priority.
1793 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1794 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1795 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1800 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1801 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1802 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1803 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1805 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1806 bounds.append(&mut self.parse_generic_bounds(None)?);
1808 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1811 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1812 if !allow_plus && impl_dyn_multi {
1813 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1814 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1817 "use parentheses to disambiguate",
1819 Applicability::MachineApplicable
1824 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1825 // Do not add `+` to expected tokens.
1826 if !allow_plus || !self.token.is_like_plus() {
1831 let bounds = self.parse_generic_bounds(None)?;
1832 let sum_span = ty.span.to(self.prev_span);
1834 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1835 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1838 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1839 let sum_with_parens = pprust::to_string(|s| {
1840 use crate::print::pprust::PrintState;
1843 s.print_opt_lifetime(lifetime)?;
1844 s.print_mutability(mut_ty.mutbl)?;
1846 s.print_type(&mut_ty.ty)?;
1847 s.print_type_bounds(" +", &bounds)?;
1850 err.span_suggestion(
1852 "try adding parentheses",
1854 Applicability::MachineApplicable
1857 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1858 err.span_label(sum_span, "perhaps you forgot parentheses?");
1861 err.span_label(sum_span, "expected a path");
1868 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1869 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1871 // Do not add `::` to expected tokens.
1872 if !allow_recovery || self.token != token::ModSep {
1875 let ty = match base.to_ty() {
1877 None => return Ok(base),
1880 self.bump(); // `::`
1881 let mut segments = Vec::new();
1882 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1884 let span = ty.span.to(self.prev_span);
1885 let path_span = span.to(span); // use an empty path since `position` == 0
1886 let recovered = base.to_recovered(
1887 Some(QSelf { ty, path_span, position: 0 }),
1888 ast::Path { segments, span },
1892 .struct_span_err(span, "missing angle brackets in associated item path")
1893 .span_suggestion( // this is a best-effort recovery
1894 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1900 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1901 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1902 let mutbl = self.parse_mutability();
1903 let ty = self.parse_ty_no_plus()?;
1904 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1907 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1908 let mutbl = if self.eat_keyword(keywords::Mut) {
1910 } else if self.eat_keyword(keywords::Const) {
1911 Mutability::Immutable
1913 let span = self.prev_span;
1914 let msg = "expected mut or const in raw pointer type";
1915 self.struct_span_err(span, msg)
1916 .span_label(span, msg)
1917 .help("use `*mut T` or `*const T` as appropriate")
1919 Mutability::Immutable
1921 let t = self.parse_ty_no_plus()?;
1922 Ok(MutTy { ty: t, mutbl: mutbl })
1925 fn is_named_argument(&mut self) -> bool {
1926 let offset = match self.token {
1927 token::Interpolated(ref nt) => match **nt {
1928 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1931 token::BinOp(token::And) | token::AndAnd => 1,
1932 _ if self.token.is_keyword(keywords::Mut) => 1,
1936 self.look_ahead(offset, |t| t.is_ident()) &&
1937 self.look_ahead(offset + 1, |t| t == &token::Colon)
1940 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1942 fn eat_incorrect_doc_comment(&mut self, applied_to: &str) {
1943 if let token::DocComment(_) = self.token {
1944 let mut err = self.diagnostic().struct_span_err(
1946 &format!("documentation comments cannot be applied to {}", applied_to),
1948 err.span_label(self.span, "doc comments are not allowed here");
1951 } else if self.token == token::Pound && self.look_ahead(1, |t| {
1952 *t == token::OpenDelim(token::Bracket)
1955 // Skip every token until next possible arg.
1956 while self.token != token::CloseDelim(token::Bracket) {
1959 let sp = lo.to(self.span);
1961 let mut err = self.diagnostic().struct_span_err(
1963 &format!("attributes cannot be applied to {}", applied_to),
1965 err.span_label(sp, "attributes are not allowed here");
1970 /// This version of parse arg doesn't necessarily require identifier names.
1971 fn parse_arg_general(&mut self, require_name: bool, is_trait_item: bool,
1972 allow_c_variadic: bool) -> PResult<'a, Arg> {
1973 maybe_whole!(self, NtArg, |x| x);
1975 if let Ok(Some(_)) = self.parse_self_arg() {
1976 let mut err = self.struct_span_err(self.prev_span,
1977 "unexpected `self` argument in function");
1978 err.span_label(self.prev_span,
1979 "`self` is only valid as the first argument of an associated function");
1983 let (pat, ty) = if require_name || self.is_named_argument() {
1984 debug!("parse_arg_general parse_pat (require_name:{})",
1986 self.eat_incorrect_doc_comment("method arguments");
1987 let pat = self.parse_pat(Some("argument name"))?;
1989 if let Err(mut err) = self.expect(&token::Colon) {
1990 // If we find a pattern followed by an identifier, it could be an (incorrect)
1991 // C-style parameter declaration.
1992 if self.check_ident() && self.look_ahead(1, |t| {
1993 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1995 let ident = self.parse_ident().unwrap();
1996 let span = pat.span.with_hi(ident.span.hi());
1998 err.span_suggestion(
2000 "declare the type after the parameter binding",
2001 String::from("<identifier>: <type>"),
2002 Applicability::HasPlaceholders,
2004 } else if require_name && is_trait_item {
2005 if let PatKind::Ident(_, ident, _) = pat.node {
2006 err.span_suggestion(
2008 "explicitly ignore parameter",
2009 format!("_: {}", ident),
2010 Applicability::MachineApplicable,
2014 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
2020 self.eat_incorrect_doc_comment("a method argument's type");
2021 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
2023 debug!("parse_arg_general ident_to_pat");
2024 let parser_snapshot_before_ty = self.clone();
2025 self.eat_incorrect_doc_comment("a method argument's type");
2026 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
2027 if ty.is_ok() && self.token != token::Comma &&
2028 self.token != token::CloseDelim(token::Paren) {
2029 // This wasn't actually a type, but a pattern looking like a type,
2030 // so we are going to rollback and re-parse for recovery.
2031 ty = self.unexpected();
2035 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
2037 id: ast::DUMMY_NODE_ID,
2038 node: PatKind::Ident(
2039 BindingMode::ByValue(Mutability::Immutable), ident, None),
2045 // If this is a C-variadic argument and we hit an error, return the
2047 if self.token == token::DotDotDot {
2050 // Recover from attempting to parse the argument as a type without pattern.
2052 mem::replace(self, parser_snapshot_before_ty);
2053 let pat = self.parse_pat(Some("argument name"))?;
2054 self.expect(&token::Colon)?;
2055 let ty = self.parse_ty()?;
2057 let mut err = self.diagnostic().struct_span_err_with_code(
2059 "patterns aren't allowed in methods without bodies",
2060 DiagnosticId::Error("E0642".into()),
2062 err.span_suggestion_short(
2064 "give this argument a name or use an underscore to ignore it",
2066 Applicability::MachineApplicable,
2070 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2072 node: PatKind::Wild,
2074 id: ast::DUMMY_NODE_ID
2081 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
2084 /// Parses a single function argument.
2085 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
2086 self.parse_arg_general(true, false, false)
2089 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
2090 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
2091 let pat = self.parse_pat(Some("argument name"))?;
2092 let t = if self.eat(&token::Colon) {
2096 id: ast::DUMMY_NODE_ID,
2097 node: TyKind::Infer,
2098 span: self.prev_span,
2104 id: ast::DUMMY_NODE_ID
2108 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
2109 if self.eat(&token::Semi) {
2110 Ok(Some(self.parse_expr()?))
2116 /// Matches `token_lit = LIT_INTEGER | ...`.
2117 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
2118 let out = match self.token {
2119 token::Interpolated(ref nt) => match **nt {
2120 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
2121 ExprKind::Lit(ref lit) => { lit.node.clone() }
2122 _ => { return self.unexpected_last(&self.token); }
2124 _ => { return self.unexpected_last(&self.token); }
2126 token::Literal(lit, suf) => {
2127 let diag = Some((self.span, &self.sess.span_diagnostic));
2128 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
2132 self.expect_no_suffix(sp, lit.literal_name(), suf)
2137 token::Dot if self.look_ahead(1, |t| match t {
2138 token::Literal(parse::token::Lit::Integer(_) , _) => true,
2140 }) => { // recover from `let x = .4;`
2143 if let token::Literal(
2144 parse::token::Lit::Integer(val),
2147 let suffix = suffix.and_then(|s| {
2148 let s = s.as_str().get();
2149 if ["f32", "f64"].contains(&s) {
2156 let sp = lo.to(self.prev_span);
2157 let mut err = self.diagnostic()
2158 .struct_span_err(sp, "float literals must have an integer part");
2159 err.span_suggestion(
2161 "must have an integer part",
2162 format!("0.{}{}", val, suffix),
2163 Applicability::MachineApplicable,
2166 return Ok(match suffix {
2167 "f32" => ast::LitKind::Float(val, ast::FloatTy::F32),
2168 "f64" => ast::LitKind::Float(val, ast::FloatTy::F64),
2169 _ => ast::LitKind::FloatUnsuffixed(val),
2175 _ => { return self.unexpected_last(&self.token); }
2182 /// Matches `lit = true | false | token_lit`.
2183 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
2185 let lit = if self.eat_keyword(keywords::True) {
2187 } else if self.eat_keyword(keywords::False) {
2188 LitKind::Bool(false)
2190 let lit = self.parse_lit_token()?;
2193 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
2196 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
2197 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
2198 maybe_whole_expr!(self);
2200 let minus_lo = self.span;
2201 let minus_present = self.eat(&token::BinOp(token::Minus));
2203 let literal = self.parse_lit()?;
2204 let hi = self.prev_span;
2205 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
2208 let minus_hi = self.prev_span;
2209 let unary = self.mk_unary(UnOp::Neg, expr);
2210 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
2216 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2218 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2219 let span = self.span;
2221 Ok(Ident::new(ident.name, span))
2223 _ => self.parse_ident(),
2227 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
2229 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
2230 let span = self.span;
2232 Ok(Ident::new(ident.name, span))
2234 _ => self.parse_ident(),
2238 /// Parses a qualified path.
2239 /// Assumes that the leading `<` has been parsed already.
2241 /// `qualified_path = <type [as trait_ref]>::path`
2246 /// `<T as U>::F::a<S>` (without disambiguator)
2247 /// `<T as U>::F::a::<S>` (with disambiguator)
2248 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2249 let lo = self.prev_span;
2250 let ty = self.parse_ty()?;
2252 // `path` will contain the prefix of the path up to the `>`,
2253 // if any (e.g., `U` in the `<T as U>::*` examples
2254 // above). `path_span` has the span of that path, or an empty
2255 // span in the case of something like `<T>::Bar`.
2256 let (mut path, path_span);
2257 if self.eat_keyword(keywords::As) {
2258 let path_lo = self.span;
2259 path = self.parse_path(PathStyle::Type)?;
2260 path_span = path_lo.to(self.prev_span);
2262 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2263 path_span = self.span.to(self.span);
2266 // See doc comment for `unmatched_angle_bracket_count`.
2267 self.expect(&token::Gt)?;
2268 if self.unmatched_angle_bracket_count > 0 {
2269 self.unmatched_angle_bracket_count -= 1;
2270 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
2273 self.expect(&token::ModSep)?;
2275 let qself = QSelf { ty, path_span, position: path.segments.len() };
2276 self.parse_path_segments(&mut path.segments, style, true)?;
2278 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2281 /// Parses simple paths.
2283 /// `path = [::] segment+`
2284 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2287 /// `a::b::C<D>` (without disambiguator)
2288 /// `a::b::C::<D>` (with disambiguator)
2289 /// `Fn(Args)` (without disambiguator)
2290 /// `Fn::(Args)` (with disambiguator)
2291 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2292 self.parse_path_common(style, true)
2295 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
2296 -> PResult<'a, ast::Path> {
2297 maybe_whole!(self, NtPath, |path| {
2298 if style == PathStyle::Mod &&
2299 path.segments.iter().any(|segment| segment.args.is_some()) {
2300 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2305 let lo = self.meta_var_span.unwrap_or(self.span);
2306 let mut segments = Vec::new();
2307 let mod_sep_ctxt = self.span.ctxt();
2308 if self.eat(&token::ModSep) {
2309 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2311 self.parse_path_segments(&mut segments, style, enable_warning)?;
2313 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2316 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
2317 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
2319 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2320 let meta_ident = match self.token {
2321 token::Interpolated(ref nt) => match **nt {
2322 token::NtMeta(ref meta) => match meta.node {
2323 ast::MetaItemKind::Word => Some(meta.ident.clone()),
2330 if let Some(path) = meta_ident {
2334 self.parse_path(style)
2337 fn parse_path_segments(&mut self,
2338 segments: &mut Vec<PathSegment>,
2340 enable_warning: bool)
2341 -> PResult<'a, ()> {
2343 let segment = self.parse_path_segment(style, enable_warning)?;
2344 if style == PathStyle::Expr {
2345 // In order to check for trailing angle brackets, we must have finished
2346 // recursing (`parse_path_segment` can indirectly call this function),
2347 // that is, the next token must be the highlighted part of the below example:
2349 // `Foo::<Bar as Baz<T>>::Qux`
2352 // As opposed to the below highlight (if we had only finished the first
2355 // `Foo::<Bar as Baz<T>>::Qux`
2358 // `PathStyle::Expr` is only provided at the root invocation and never in
2359 // `parse_path_segment` to recurse and therefore can be checked to maintain
2361 self.check_trailing_angle_brackets(&segment, token::ModSep);
2363 segments.push(segment);
2365 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2371 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2372 -> PResult<'a, PathSegment> {
2373 let ident = self.parse_path_segment_ident()?;
2375 let is_args_start = |token: &token::Token| match *token {
2376 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2379 let check_args_start = |this: &mut Self| {
2380 this.expected_tokens.extend_from_slice(
2381 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2383 is_args_start(&this.token)
2386 Ok(if style == PathStyle::Type && check_args_start(self) ||
2387 style != PathStyle::Mod && self.check(&token::ModSep)
2388 && self.look_ahead(1, |t| is_args_start(t)) {
2389 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2390 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2391 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2392 .span_label(self.prev_span, "try removing `::`").emit();
2396 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
2397 // it isn't, then we reset the unmatched angle bracket count as we're about to start
2398 // parsing a new path.
2399 if style == PathStyle::Expr {
2400 self.unmatched_angle_bracket_count = 0;
2401 self.max_angle_bracket_count = 0;
2404 let args = if self.eat_lt() {
2406 let (args, bindings) =
2407 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
2409 let span = lo.to(self.prev_span);
2410 AngleBracketedArgs { args, bindings, span }.into()
2414 let (inputs, recovered) = self.parse_seq_to_before_tokens(
2415 &[&token::CloseDelim(token::Paren)],
2416 SeqSep::trailing_allowed(token::Comma),
2417 TokenExpectType::Expect,
2422 let span = lo.to(self.prev_span);
2423 let output = if self.eat(&token::RArrow) {
2424 Some(self.parse_ty_common(false, false, false)?)
2428 ParenthesizedArgs { inputs, output, span }.into()
2431 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2433 // Generic arguments are not found.
2434 PathSegment::from_ident(ident)
2438 crate fn check_lifetime(&mut self) -> bool {
2439 self.expected_tokens.push(TokenType::Lifetime);
2440 self.token.is_lifetime()
2443 /// Parses a single lifetime `'a` or panics.
2444 crate fn expect_lifetime(&mut self) -> Lifetime {
2445 if let Some(ident) = self.token.lifetime() {
2446 let span = self.span;
2448 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2450 self.span_bug(self.span, "not a lifetime")
2454 fn eat_label(&mut self) -> Option<Label> {
2455 if let Some(ident) = self.token.lifetime() {
2456 let span = self.span;
2458 Some(Label { ident: Ident::new(ident.name, span) })
2464 /// Parses mutability (`mut` or nothing).
2465 fn parse_mutability(&mut self) -> Mutability {
2466 if self.eat_keyword(keywords::Mut) {
2469 Mutability::Immutable
2473 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2474 if let token::Literal(token::Integer(name), None) = self.token {
2476 Ok(Ident::new(name, self.prev_span))
2478 self.parse_ident_common(false)
2482 /// Parse ident (COLON expr)?
2483 fn parse_field(&mut self) -> PResult<'a, Field> {
2484 let attrs = self.parse_outer_attributes()?;
2487 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2488 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
2489 t == &token::Colon || t == &token::Eq
2491 let fieldname = self.parse_field_name()?;
2493 // Check for an equals token. This means the source incorrectly attempts to
2494 // initialize a field with an eq rather than a colon.
2495 if self.token == token::Eq {
2497 .struct_span_err(self.span, "expected `:`, found `=`")
2499 fieldname.span.shrink_to_hi().to(self.span),
2500 "replace equals symbol with a colon",
2502 Applicability::MachineApplicable,
2507 (fieldname, self.parse_expr()?, false)
2509 let fieldname = self.parse_ident_common(false)?;
2511 // Mimic `x: x` for the `x` field shorthand.
2512 let path = ast::Path::from_ident(fieldname);
2513 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2514 (fieldname, expr, true)
2518 span: lo.to(expr.span),
2521 attrs: attrs.into(),
2525 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2526 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2529 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2530 ExprKind::Unary(unop, expr)
2533 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2534 ExprKind::Binary(binop, lhs, rhs)
2537 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2538 ExprKind::Call(f, args)
2541 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2542 ExprKind::Index(expr, idx)
2545 fn mk_range(&mut self,
2546 start: Option<P<Expr>>,
2547 end: Option<P<Expr>>,
2548 limits: RangeLimits)
2549 -> PResult<'a, ast::ExprKind> {
2550 if end.is_none() && limits == RangeLimits::Closed {
2551 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2553 Ok(ExprKind::Range(start, end, limits))
2557 fn mk_assign_op(&mut self, binop: ast::BinOp,
2558 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2559 ExprKind::AssignOp(binop, lhs, rhs)
2562 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2564 id: ast::DUMMY_NODE_ID,
2565 node: ExprKind::Mac(source_map::Spanned {node: m, span: span}),
2571 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
2572 let delim = match self.token {
2573 token::OpenDelim(delim) => delim,
2575 let msg = "expected open delimiter";
2576 let mut err = self.fatal(msg);
2577 err.span_label(self.span, msg);
2581 let tts = match self.parse_token_tree() {
2582 TokenTree::Delimited(_, _, tts) => tts,
2583 _ => unreachable!(),
2585 let delim = match delim {
2586 token::Paren => MacDelimiter::Parenthesis,
2587 token::Bracket => MacDelimiter::Bracket,
2588 token::Brace => MacDelimiter::Brace,
2589 token::NoDelim => self.bug("unexpected no delimiter"),
2591 Ok((delim, tts.into()))
2594 /// At the bottom (top?) of the precedence hierarchy,
2595 /// Parses things like parenthesized exprs, macros, `return`, etc.
2597 /// N.B., this does not parse outer attributes, and is private because it only works
2598 /// correctly if called from `parse_dot_or_call_expr()`.
2599 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2600 maybe_whole_expr!(self);
2602 // Outer attributes are already parsed and will be
2603 // added to the return value after the fact.
2605 // Therefore, prevent sub-parser from parsing
2606 // attributes by giving them a empty "already parsed" list.
2607 let mut attrs = ThinVec::new();
2610 let mut hi = self.span;
2614 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2616 token::OpenDelim(token::Paren) => {
2619 attrs.extend(self.parse_inner_attributes()?);
2621 // (e) is parenthesized e
2622 // (e,) is a tuple with only one field, e
2623 let mut es = vec![];
2624 let mut trailing_comma = false;
2625 let mut recovered = false;
2626 while self.token != token::CloseDelim(token::Paren) {
2627 es.push(self.parse_expr()?);
2628 recovered = self.expect_one_of(
2630 &[token::Comma, token::CloseDelim(token::Paren)],
2632 if self.eat(&token::Comma) {
2633 trailing_comma = true;
2635 trailing_comma = false;
2643 hi = self.prev_span;
2644 ex = if es.len() == 1 && !trailing_comma {
2645 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2650 token::OpenDelim(token::Brace) => {
2651 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2653 token::BinOp(token::Or) | token::OrOr => {
2654 return self.parse_lambda_expr(attrs);
2656 token::OpenDelim(token::Bracket) => {
2659 attrs.extend(self.parse_inner_attributes()?);
2661 if self.eat(&token::CloseDelim(token::Bracket)) {
2663 ex = ExprKind::Array(Vec::new());
2666 let first_expr = self.parse_expr()?;
2667 if self.eat(&token::Semi) {
2668 // Repeating array syntax: [ 0; 512 ]
2669 let count = AnonConst {
2670 id: ast::DUMMY_NODE_ID,
2671 value: self.parse_expr()?,
2673 self.expect(&token::CloseDelim(token::Bracket))?;
2674 ex = ExprKind::Repeat(first_expr, count);
2675 } else if self.eat(&token::Comma) {
2676 // Vector with two or more elements.
2677 let remaining_exprs = self.parse_seq_to_end(
2678 &token::CloseDelim(token::Bracket),
2679 SeqSep::trailing_allowed(token::Comma),
2680 |p| Ok(p.parse_expr()?)
2682 let mut exprs = vec![first_expr];
2683 exprs.extend(remaining_exprs);
2684 ex = ExprKind::Array(exprs);
2686 // Vector with one element.
2687 self.expect(&token::CloseDelim(token::Bracket))?;
2688 ex = ExprKind::Array(vec![first_expr]);
2691 hi = self.prev_span;
2695 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2697 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2699 if self.span.rust_2018() && self.check_keyword(keywords::Async)
2701 if self.is_async_block() { // check for `async {` and `async move {`
2702 return self.parse_async_block(attrs);
2704 return self.parse_lambda_expr(attrs);
2707 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2708 return self.parse_lambda_expr(attrs);
2710 if self.eat_keyword(keywords::If) {
2711 return self.parse_if_expr(attrs);
2713 if self.eat_keyword(keywords::For) {
2714 let lo = self.prev_span;
2715 return self.parse_for_expr(None, lo, attrs);
2717 if self.eat_keyword(keywords::While) {
2718 let lo = self.prev_span;
2719 return self.parse_while_expr(None, lo, attrs);
2721 if let Some(label) = self.eat_label() {
2722 let lo = label.ident.span;
2723 self.expect(&token::Colon)?;
2724 if self.eat_keyword(keywords::While) {
2725 return self.parse_while_expr(Some(label), lo, attrs)
2727 if self.eat_keyword(keywords::For) {
2728 return self.parse_for_expr(Some(label), lo, attrs)
2730 if self.eat_keyword(keywords::Loop) {
2731 return self.parse_loop_expr(Some(label), lo, attrs)
2733 if self.token == token::OpenDelim(token::Brace) {
2734 return self.parse_block_expr(Some(label),
2736 BlockCheckMode::Default,
2739 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2740 let mut err = self.fatal(msg);
2741 err.span_label(self.span, msg);
2744 if self.eat_keyword(keywords::Loop) {
2745 let lo = self.prev_span;
2746 return self.parse_loop_expr(None, lo, attrs);
2748 if self.eat_keyword(keywords::Continue) {
2749 let label = self.eat_label();
2750 let ex = ExprKind::Continue(label);
2751 let hi = self.prev_span;
2752 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2754 if self.eat_keyword(keywords::Match) {
2755 let match_sp = self.prev_span;
2756 return self.parse_match_expr(attrs).map_err(|mut err| {
2757 err.span_label(match_sp, "while parsing this match expression");
2761 if self.eat_keyword(keywords::Unsafe) {
2762 return self.parse_block_expr(
2765 BlockCheckMode::Unsafe(ast::UserProvided),
2768 if self.is_do_catch_block() {
2769 let mut db = self.fatal("found removed `do catch` syntax");
2770 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2773 if self.is_try_block() {
2775 assert!(self.eat_keyword(keywords::Try));
2776 return self.parse_try_block(lo, attrs);
2778 if self.eat_keyword(keywords::Return) {
2779 if self.token.can_begin_expr() {
2780 let e = self.parse_expr()?;
2782 ex = ExprKind::Ret(Some(e));
2784 ex = ExprKind::Ret(None);
2786 } else if self.eat_keyword(keywords::Break) {
2787 let label = self.eat_label();
2788 let e = if self.token.can_begin_expr()
2789 && !(self.token == token::OpenDelim(token::Brace)
2790 && self.restrictions.contains(
2791 Restrictions::NO_STRUCT_LITERAL)) {
2792 Some(self.parse_expr()?)
2796 ex = ExprKind::Break(label, e);
2797 hi = self.prev_span;
2798 } else if self.eat_keyword(keywords::Yield) {
2799 if self.token.can_begin_expr() {
2800 let e = self.parse_expr()?;
2802 ex = ExprKind::Yield(Some(e));
2804 ex = ExprKind::Yield(None);
2806 } else if self.token.is_keyword(keywords::Let) {
2807 // Catch this syntax error here, instead of in `parse_ident`, so
2808 // that we can explicitly mention that let is not to be used as an expression
2809 let mut db = self.fatal("expected expression, found statement (`let`)");
2810 db.span_label(self.span, "expected expression");
2811 db.note("variable declaration using `let` is a statement");
2813 } else if self.token.is_path_start() {
2814 let pth = self.parse_path(PathStyle::Expr)?;
2816 // `!`, as an operator, is prefix, so we know this isn't that
2817 if self.eat(&token::Not) {
2818 // MACRO INVOCATION expression
2819 let (delim, tts) = self.expect_delimited_token_tree()?;
2820 let hi = self.prev_span;
2821 let node = Mac_ { path: pth, tts, delim };
2822 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2824 if self.check(&token::OpenDelim(token::Brace)) {
2825 // This is a struct literal, unless we're prohibited
2826 // from parsing struct literals here.
2827 let prohibited = self.restrictions.contains(
2828 Restrictions::NO_STRUCT_LITERAL
2831 return self.parse_struct_expr(lo, pth, attrs);
2836 ex = ExprKind::Path(None, pth);
2838 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2839 // Don't complain about bare semicolons after unclosed braces
2840 // recovery in order to keep the error count down. Fixing the
2841 // delimiters will possibly also fix the bare semicolon found in
2842 // expression context. For example, silence the following error:
2844 // error: expected expression, found `;`
2848 // | ^ expected expression
2851 return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
2853 match self.parse_literal_maybe_minus() {
2856 ex = expr.node.clone();
2859 self.cancel(&mut err);
2860 let msg = format!("expected expression, found {}",
2861 self.this_token_descr());
2862 let mut err = self.fatal(&msg);
2863 err.span_label(self.span, "expected expression");
2871 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2872 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2877 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2878 -> PResult<'a, P<Expr>> {
2879 let struct_sp = lo.to(self.prev_span);
2881 let mut fields = Vec::new();
2882 let mut base = None;
2884 attrs.extend(self.parse_inner_attributes()?);
2886 while self.token != token::CloseDelim(token::Brace) {
2887 if self.eat(&token::DotDot) {
2888 let exp_span = self.prev_span;
2889 match self.parse_expr() {
2895 self.recover_stmt();
2898 if self.token == token::Comma {
2899 let mut err = self.sess.span_diagnostic.mut_span_err(
2900 exp_span.to(self.prev_span),
2901 "cannot use a comma after the base struct",
2903 err.span_suggestion_short(
2905 "remove this comma",
2907 Applicability::MachineApplicable
2909 err.note("the base struct must always be the last field");
2911 self.recover_stmt();
2916 let mut recovery_field = None;
2917 if let token::Ident(ident, _) = self.token {
2918 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2919 // Use in case of error after field-looking code: `S { foo: () with a }`
2920 let mut ident = ident.clone();
2921 ident.span = self.span;
2922 recovery_field = Some(ast::Field {
2925 expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
2926 is_shorthand: false,
2927 attrs: ThinVec::new(),
2931 let mut parsed_field = None;
2932 match self.parse_field() {
2933 Ok(f) => parsed_field = Some(f),
2935 e.span_label(struct_sp, "while parsing this struct");
2938 // If the next token is a comma, then try to parse
2939 // what comes next as additional fields, rather than
2940 // bailing out until next `}`.
2941 if self.token != token::Comma {
2942 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2943 if self.token != token::Comma {
2950 match self.expect_one_of(&[token::Comma],
2951 &[token::CloseDelim(token::Brace)]) {
2952 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2953 // only include the field if there's no parse error for the field name
2957 if let Some(f) = recovery_field {
2960 e.span_label(struct_sp, "while parsing this struct");
2962 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2963 self.eat(&token::Comma);
2968 let span = lo.to(self.span);
2969 self.expect(&token::CloseDelim(token::Brace))?;
2970 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2973 fn parse_or_use_outer_attributes(&mut self,
2974 already_parsed_attrs: Option<ThinVec<Attribute>>)
2975 -> PResult<'a, ThinVec<Attribute>> {
2976 if let Some(attrs) = already_parsed_attrs {
2979 self.parse_outer_attributes().map(|a| a.into())
2983 /// Parses a block or unsafe block.
2984 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2985 lo: Span, blk_mode: BlockCheckMode,
2986 outer_attrs: ThinVec<Attribute>)
2987 -> PResult<'a, P<Expr>> {
2988 self.expect(&token::OpenDelim(token::Brace))?;
2990 let mut attrs = outer_attrs;
2991 attrs.extend(self.parse_inner_attributes()?);
2993 let blk = self.parse_block_tail(lo, blk_mode)?;
2994 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2997 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2998 fn parse_dot_or_call_expr(&mut self,
2999 already_parsed_attrs: Option<ThinVec<Attribute>>)
3000 -> PResult<'a, P<Expr>> {
3001 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3003 let b = self.parse_bottom_expr();
3004 let (span, b) = self.interpolated_or_expr_span(b)?;
3005 self.parse_dot_or_call_expr_with(b, span, attrs)
3008 fn parse_dot_or_call_expr_with(&mut self,
3011 mut attrs: ThinVec<Attribute>)
3012 -> PResult<'a, P<Expr>> {
3013 // Stitch the list of outer attributes onto the return value.
3014 // A little bit ugly, but the best way given the current code
3016 self.parse_dot_or_call_expr_with_(e0, lo)
3018 expr.map(|mut expr| {
3019 attrs.extend::<Vec<_>>(expr.attrs.into());
3022 ExprKind::If(..) | ExprKind::IfLet(..) => {
3023 if !expr.attrs.is_empty() {
3024 // Just point to the first attribute in there...
3025 let span = expr.attrs[0].span;
3028 "attributes are not yet allowed on `if` \
3039 // Assuming we have just parsed `.`, continue parsing into an expression.
3040 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3041 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
3042 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
3044 Ok(match self.token {
3045 token::OpenDelim(token::Paren) => {
3046 // Method call `expr.f()`
3047 let mut args = self.parse_unspanned_seq(
3048 &token::OpenDelim(token::Paren),
3049 &token::CloseDelim(token::Paren),
3050 SeqSep::trailing_allowed(token::Comma),
3051 |p| Ok(p.parse_expr()?)
3053 args.insert(0, self_arg);
3055 let span = lo.to(self.prev_span);
3056 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
3059 // Field access `expr.f`
3060 if let Some(args) = segment.args {
3061 self.span_err(args.span(),
3062 "field expressions may not have generic arguments");
3065 let span = lo.to(self.prev_span);
3066 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
3071 /// This function checks if there are trailing angle brackets and produces
3072 /// a diagnostic to suggest removing them.
3074 /// ```ignore (diagnostic)
3075 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
3076 /// ^^ help: remove extra angle brackets
3078 fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) {
3079 // This function is intended to be invoked after parsing a path segment where there are two
3082 // 1. A specific token is expected after the path segment.
3083 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
3084 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
3085 // 2. No specific token is expected after the path segment.
3086 // eg. `x.foo` (field access)
3088 // This function is called after parsing `.foo` and before parsing the token `end` (if
3089 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
3092 // We only care about trailing angle brackets if we previously parsed angle bracket
3093 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
3094 // removed in this case:
3096 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
3098 // This case is particularly tricky as we won't notice it just looking at the tokens -
3099 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
3100 // have already been parsed):
3102 // `x.foo::<u32>>>(3)`
3103 let parsed_angle_bracket_args = segment.args
3105 .map(|args| args.is_angle_bracketed())
3109 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
3110 parsed_angle_bracket_args,
3112 if !parsed_angle_bracket_args {
3116 // Keep the span at the start so we can highlight the sequence of `>` characters to be
3120 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
3121 // (since we might have the field access case and the characters we're eating are
3122 // actual operators and not trailing characters - ie `x.foo >> 3`).
3123 let mut position = 0;
3125 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
3126 // many of each (so we can correctly pluralize our error messages) and continue to
3128 let mut number_of_shr = 0;
3129 let mut number_of_gt = 0;
3130 while self.look_ahead(position, |t| {
3131 trace!("check_trailing_angle_brackets: t={:?}", t);
3132 if *t == token::BinOp(token::BinOpToken::Shr) {
3135 } else if *t == token::Gt {
3145 // If we didn't find any trailing `>` characters, then we have nothing to error about.
3147 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
3148 number_of_gt, number_of_shr,
3150 if number_of_gt < 1 && number_of_shr < 1 {
3154 // Finally, double check that we have our end token as otherwise this is the
3156 if self.look_ahead(position, |t| {
3157 trace!("check_trailing_angle_brackets: t={:?}", t);
3160 // Eat from where we started until the end token so that parsing can continue
3161 // as if we didn't have those extra angle brackets.
3162 self.eat_to_tokens(&[&end]);
3163 let span = lo.until(self.span);
3165 let plural = number_of_gt > 1 || number_of_shr >= 1;
3169 &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
3173 &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
3175 Applicability::MachineApplicable,
3181 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3186 while self.eat(&token::Question) {
3187 let hi = self.prev_span;
3188 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
3192 if self.eat(&token::Dot) {
3194 token::Ident(..) => {
3195 e = self.parse_dot_suffix(e, lo)?;
3197 token::Literal(token::Integer(name), _) => {
3198 let span = self.span;
3200 let field = ExprKind::Field(e, Ident::new(name, span));
3201 e = self.mk_expr(lo.to(span), field, ThinVec::new());
3203 token::Literal(token::Float(n), _suf) => {
3205 let fstr = n.as_str();
3206 let mut err = self.diagnostic()
3207 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
3208 err.span_label(self.prev_span, "unexpected token");
3209 if fstr.chars().all(|x| "0123456789.".contains(x)) {
3210 let float = match fstr.parse::<f64>().ok() {
3214 let sugg = pprust::to_string(|s| {
3215 use crate::print::pprust::PrintState;
3219 s.print_usize(float.trunc() as usize)?;
3222 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
3224 err.span_suggestion(
3225 lo.to(self.prev_span),
3226 "try parenthesizing the first index",
3228 Applicability::MachineApplicable
3235 // FIXME Could factor this out into non_fatal_unexpected or something.
3236 let actual = self.this_token_to_string();
3237 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
3242 if self.expr_is_complete(&e) { break; }
3245 token::OpenDelim(token::Paren) => {
3246 let es = self.parse_unspanned_seq(
3247 &token::OpenDelim(token::Paren),
3248 &token::CloseDelim(token::Paren),
3249 SeqSep::trailing_allowed(token::Comma),
3250 |p| Ok(p.parse_expr()?)
3252 hi = self.prev_span;
3254 let nd = self.mk_call(e, es);
3255 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
3259 // Could be either an index expression or a slicing expression.
3260 token::OpenDelim(token::Bracket) => {
3262 let ix = self.parse_expr()?;
3264 self.expect(&token::CloseDelim(token::Bracket))?;
3265 let index = self.mk_index(e, ix);
3266 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
3274 crate fn process_potential_macro_variable(&mut self) {
3275 let (token, span) = match self.token {
3276 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
3277 self.look_ahead(1, |t| t.is_ident()) => {
3279 let name = match self.token {
3280 token::Ident(ident, _) => ident,
3283 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
3284 err.span_label(self.span, "unknown macro variable");
3289 token::Interpolated(ref nt) => {
3290 self.meta_var_span = Some(self.span);
3291 // Interpolated identifier and lifetime tokens are replaced with usual identifier
3292 // and lifetime tokens, so the former are never encountered during normal parsing.
3294 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
3295 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
3305 /// Parses a single token tree from the input.
3306 crate fn parse_token_tree(&mut self) -> TokenTree {
3308 token::OpenDelim(..) => {
3309 let frame = mem::replace(&mut self.token_cursor.frame,
3310 self.token_cursor.stack.pop().unwrap());
3311 self.span = frame.span.entire();
3313 TokenTree::Delimited(
3316 frame.tree_cursor.stream.into(),
3319 token::CloseDelim(_) | token::Eof => unreachable!(),
3321 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
3323 TokenTree::Token(span, token)
3328 // parse a stream of tokens into a list of TokenTree's,
3330 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
3331 let mut tts = Vec::new();
3332 while self.token != token::Eof {
3333 tts.push(self.parse_token_tree());
3338 pub fn parse_tokens(&mut self) -> TokenStream {
3339 let mut result = Vec::new();
3342 token::Eof | token::CloseDelim(..) => break,
3343 _ => result.push(self.parse_token_tree().into()),
3346 TokenStream::new(result)
3349 /// Parse a prefix-unary-operator expr
3350 fn parse_prefix_expr(&mut self,
3351 already_parsed_attrs: Option<ThinVec<Attribute>>)
3352 -> PResult<'a, P<Expr>> {
3353 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3355 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
3356 let (hi, ex) = match self.token {
3359 let e = self.parse_prefix_expr(None);
3360 let (span, e) = self.interpolated_or_expr_span(e)?;
3361 (lo.to(span), self.mk_unary(UnOp::Not, e))
3363 // Suggest `!` for bitwise negation when encountering a `~`
3366 let e = self.parse_prefix_expr(None);
3367 let (span, e) = self.interpolated_or_expr_span(e)?;
3368 let span_of_tilde = lo;
3369 let mut err = self.diagnostic()
3370 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
3371 err.span_suggestion_short(
3373 "use `!` to perform bitwise negation",
3375 Applicability::MachineApplicable
3378 (lo.to(span), self.mk_unary(UnOp::Not, e))
3380 token::BinOp(token::Minus) => {
3382 let e = self.parse_prefix_expr(None);
3383 let (span, e) = self.interpolated_or_expr_span(e)?;
3384 (lo.to(span), self.mk_unary(UnOp::Neg, e))
3386 token::BinOp(token::Star) => {
3388 let e = self.parse_prefix_expr(None);
3389 let (span, e) = self.interpolated_or_expr_span(e)?;
3390 (lo.to(span), self.mk_unary(UnOp::Deref, e))
3392 token::BinOp(token::And) | token::AndAnd => {
3394 let m = self.parse_mutability();
3395 let e = self.parse_prefix_expr(None);
3396 let (span, e) = self.interpolated_or_expr_span(e)?;
3397 (lo.to(span), ExprKind::AddrOf(m, e))
3399 token::Ident(..) if self.token.is_keyword(keywords::In) => {
3401 let place = self.parse_expr_res(
3402 Restrictions::NO_STRUCT_LITERAL,
3405 let blk = self.parse_block()?;
3406 let span = blk.span;
3407 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
3408 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
3410 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
3412 let e = self.parse_prefix_expr(None);
3413 let (span, e) = self.interpolated_or_expr_span(e)?;
3414 (lo.to(span), ExprKind::Box(e))
3416 token::Ident(..) if self.token.is_ident_named("not") => {
3417 // `not` is just an ordinary identifier in Rust-the-language,
3418 // but as `rustc`-the-compiler, we can issue clever diagnostics
3419 // for confused users who really want to say `!`
3420 let token_cannot_continue_expr = |t: &token::Token| match *t {
3421 // These tokens can start an expression after `!`, but
3422 // can't continue an expression after an ident
3423 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3424 token::Literal(..) | token::Pound => true,
3425 token::Interpolated(ref nt) => match **nt {
3426 token::NtIdent(..) | token::NtExpr(..) |
3427 token::NtBlock(..) | token::NtPath(..) => true,
3432 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3433 if cannot_continue_expr {
3435 // Emit the error ...
3436 let mut err = self.diagnostic()
3437 .struct_span_err(self.span,
3438 &format!("unexpected {} after identifier",
3439 self.this_token_descr()));
3440 // span the `not` plus trailing whitespace to avoid
3441 // trailing whitespace after the `!` in our suggestion
3442 let to_replace = self.sess.source_map()
3443 .span_until_non_whitespace(lo.to(self.span));
3444 err.span_suggestion_short(
3446 "use `!` to perform logical negation",
3448 Applicability::MachineApplicable
3451 // —and recover! (just as if we were in the block
3452 // for the `token::Not` arm)
3453 let e = self.parse_prefix_expr(None);
3454 let (span, e) = self.interpolated_or_expr_span(e)?;
3455 (lo.to(span), self.mk_unary(UnOp::Not, e))
3457 return self.parse_dot_or_call_expr(Some(attrs));
3460 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3462 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3465 /// Parses an associative expression.
3467 /// This parses an expression accounting for associativity and precedence of the operators in
3470 fn parse_assoc_expr(&mut self,
3471 already_parsed_attrs: Option<ThinVec<Attribute>>)
3472 -> PResult<'a, P<Expr>> {
3473 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3476 /// Parses an associative expression with operators of at least `min_prec` precedence.
3477 fn parse_assoc_expr_with(&mut self,
3480 -> PResult<'a, P<Expr>> {
3481 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3484 let attrs = match lhs {
3485 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3488 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3489 return self.parse_prefix_range_expr(attrs);
3491 self.parse_prefix_expr(attrs)?
3495 if self.expr_is_complete(&lhs) {
3496 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3499 self.expected_tokens.push(TokenType::Operator);
3500 while let Some(op) = AssocOp::from_token(&self.token) {
3502 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3503 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3504 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3505 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3506 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3507 (PrevTokenKind::Interpolated, _) => self.prev_span,
3508 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3509 if path.segments.len() == 1 => self.prev_span,
3513 let cur_op_span = self.span;
3514 let restrictions = if op.is_assign_like() {
3515 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3519 if op.precedence() < min_prec {
3522 // Check for deprecated `...` syntax
3523 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3524 self.err_dotdotdot_syntax(self.span);
3528 if op.is_comparison() {
3529 self.check_no_chained_comparison(&lhs, &op);
3532 if op == AssocOp::As {
3533 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3535 } else if op == AssocOp::Colon {
3536 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3539 err.span_label(self.span,
3540 "expecting a type here because of type ascription");
3541 let cm = self.sess.source_map();
3542 let cur_pos = cm.lookup_char_pos(self.span.lo());
3543 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3544 if cur_pos.line != op_pos.line {
3545 err.span_suggestion(
3547 "try using a semicolon",
3549 Applicability::MaybeIncorrect // speculative
3556 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3557 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3558 // generalise it to the Fixity::None code.
3560 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3561 // two variants are handled with `parse_prefix_range_expr` call above.
3562 let rhs = if self.is_at_start_of_range_notation_rhs() {
3563 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3564 LhsExpr::NotYetParsed)?)
3568 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3573 let limits = if op == AssocOp::DotDot {
3574 RangeLimits::HalfOpen
3579 let r = self.mk_range(Some(lhs), rhs, limits)?;
3580 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3584 let rhs = match op.fixity() {
3585 Fixity::Right => self.with_res(
3586 restrictions - Restrictions::STMT_EXPR,
3588 this.parse_assoc_expr_with(op.precedence(),
3589 LhsExpr::NotYetParsed)
3591 Fixity::Left => self.with_res(
3592 restrictions - Restrictions::STMT_EXPR,
3594 this.parse_assoc_expr_with(op.precedence() + 1,
3595 LhsExpr::NotYetParsed)
3597 // We currently have no non-associative operators that are not handled above by
3598 // the special cases. The code is here only for future convenience.
3599 Fixity::None => self.with_res(
3600 restrictions - Restrictions::STMT_EXPR,
3602 this.parse_assoc_expr_with(op.precedence() + 1,
3603 LhsExpr::NotYetParsed)
3607 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
3608 // including the attributes.
3612 .filter(|a| a.style == AttrStyle::Outer)
3614 .map_or(lhs_span, |a| a.span);
3615 let span = lhs_span.to(rhs.span);
3617 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3618 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3619 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3620 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3621 AssocOp::Greater | AssocOp::GreaterEqual => {
3622 let ast_op = op.to_ast_binop().unwrap();
3623 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3624 self.mk_expr(span, binary, ThinVec::new())
3627 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3628 AssocOp::ObsoleteInPlace =>
3629 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3630 AssocOp::AssignOp(k) => {
3632 token::Plus => BinOpKind::Add,
3633 token::Minus => BinOpKind::Sub,
3634 token::Star => BinOpKind::Mul,
3635 token::Slash => BinOpKind::Div,
3636 token::Percent => BinOpKind::Rem,
3637 token::Caret => BinOpKind::BitXor,
3638 token::And => BinOpKind::BitAnd,
3639 token::Or => BinOpKind::BitOr,
3640 token::Shl => BinOpKind::Shl,
3641 token::Shr => BinOpKind::Shr,
3643 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3644 self.mk_expr(span, aopexpr, ThinVec::new())
3646 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3647 self.bug("AssocOp should have been handled by special case")
3651 if op.fixity() == Fixity::None { break }
3656 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3657 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3658 -> PResult<'a, P<Expr>> {
3659 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3660 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3663 // Save the state of the parser before parsing type normally, in case there is a
3664 // LessThan comparison after this cast.
3665 let parser_snapshot_before_type = self.clone();
3666 match self.parse_ty_no_plus() {
3668 Ok(mk_expr(self, rhs))
3670 Err(mut type_err) => {
3671 // Rewind to before attempting to parse the type with generics, to recover
3672 // from situations like `x as usize < y` in which we first tried to parse
3673 // `usize < y` as a type with generic arguments.
3674 let parser_snapshot_after_type = self.clone();
3675 mem::replace(self, parser_snapshot_before_type);
3677 match self.parse_path(PathStyle::Expr) {
3679 let (op_noun, op_verb) = match self.token {
3680 token::Lt => ("comparison", "comparing"),
3681 token::BinOp(token::Shl) => ("shift", "shifting"),
3683 // We can end up here even without `<` being the next token, for
3684 // example because `parse_ty_no_plus` returns `Err` on keywords,
3685 // but `parse_path` returns `Ok` on them due to error recovery.
3686 // Return original error and parser state.
3687 mem::replace(self, parser_snapshot_after_type);
3688 return Err(type_err);
3692 // Successfully parsed the type path leaving a `<` yet to parse.
3695 // Report non-fatal diagnostics, keep `x as usize` as an expression
3696 // in AST and continue parsing.
3697 let msg = format!("`<` is interpreted as a start of generic \
3698 arguments for `{}`, not a {}", path, op_noun);
3699 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3700 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3701 "interpreted as generic arguments");
3702 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3704 let expr = mk_expr(self, P(Ty {
3706 node: TyKind::Path(None, path),
3707 id: ast::DUMMY_NODE_ID
3710 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3711 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3712 err.span_suggestion(
3714 &format!("try {} the cast value", op_verb),
3715 format!("({})", expr_str),
3716 Applicability::MachineApplicable
3722 Err(mut path_err) => {
3723 // Couldn't parse as a path, return original error and parser state.
3725 mem::replace(self, parser_snapshot_after_type);
3733 /// Produce an error if comparison operators are chained (RFC #558).
3734 /// We only need to check lhs, not rhs, because all comparison ops
3735 /// have same precedence and are left-associative
3736 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3737 debug_assert!(outer_op.is_comparison(),
3738 "check_no_chained_comparison: {:?} is not comparison",
3741 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3742 // respan to include both operators
3743 let op_span = op.span.to(self.span);
3744 let mut err = self.diagnostic().struct_span_err(op_span,
3745 "chained comparison operators require parentheses");
3746 if op.node == BinOpKind::Lt &&
3747 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3748 *outer_op == AssocOp::Greater // even in a case like the following:
3749 { // Foo<Bar<Baz<Qux, ()>>>
3751 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3752 err.help("or use `(...)` if you meant to specify fn arguments");
3760 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3761 fn parse_prefix_range_expr(&mut self,
3762 already_parsed_attrs: Option<ThinVec<Attribute>>)
3763 -> PResult<'a, P<Expr>> {
3764 // Check for deprecated `...` syntax
3765 if self.token == token::DotDotDot {
3766 self.err_dotdotdot_syntax(self.span);
3769 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3770 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3772 let tok = self.token.clone();
3773 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3775 let mut hi = self.span;
3777 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3778 // RHS must be parsed with more associativity than the dots.
3779 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3780 Some(self.parse_assoc_expr_with(next_prec,
3781 LhsExpr::NotYetParsed)
3789 let limits = if tok == token::DotDot {
3790 RangeLimits::HalfOpen
3795 let r = self.mk_range(None, opt_end, limits)?;
3796 Ok(self.mk_expr(lo.to(hi), r, attrs))
3799 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3800 if self.token.can_begin_expr() {
3801 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3802 if self.token == token::OpenDelim(token::Brace) {
3803 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3811 /// Parses an `if` or `if let` expression (`if` token already eaten).
3812 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3813 if self.check_keyword(keywords::Let) {
3814 return self.parse_if_let_expr(attrs);
3816 let lo = self.prev_span;
3817 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3819 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3820 // verify that the last statement is either an implicit return (no `;`) or an explicit
3821 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3822 // the dead code lint.
3823 if self.eat_keyword(keywords::Else) || !cond.returns() {
3824 let sp = self.sess.source_map().next_point(lo);
3825 let mut err = self.diagnostic()
3826 .struct_span_err(sp, "missing condition for `if` statemement");
3827 err.span_label(sp, "expected if condition here");
3830 let not_block = self.token != token::OpenDelim(token::Brace);
3831 let thn = self.parse_block().map_err(|mut err| {
3833 err.span_label(lo, "this `if` statement has a condition, but no block");
3837 let mut els: Option<P<Expr>> = None;
3838 let mut hi = thn.span;
3839 if self.eat_keyword(keywords::Else) {
3840 let elexpr = self.parse_else_expr()?;
3844 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3847 /// Parses an `if let` expression (`if` token already eaten).
3848 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3849 -> PResult<'a, P<Expr>> {
3850 let lo = self.prev_span;
3851 self.expect_keyword(keywords::Let)?;
3852 let pats = self.parse_pats()?;
3853 self.expect(&token::Eq)?;
3854 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3855 let thn = self.parse_block()?;
3856 let (hi, els) = if self.eat_keyword(keywords::Else) {
3857 let expr = self.parse_else_expr()?;
3858 (expr.span, Some(expr))
3862 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3865 /// Parses `move |args| expr`.
3866 fn parse_lambda_expr(&mut self,
3867 attrs: ThinVec<Attribute>)
3868 -> PResult<'a, P<Expr>>
3871 let movability = if self.eat_keyword(keywords::Static) {
3876 let asyncness = if self.span.rust_2018() {
3877 self.parse_asyncness()
3881 let capture_clause = if self.eat_keyword(keywords::Move) {
3886 let decl = self.parse_fn_block_decl()?;
3887 let decl_hi = self.prev_span;
3888 let body = match decl.output {
3889 FunctionRetTy::Default(_) => {
3890 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3891 self.parse_expr_res(restrictions, None)?
3894 // If an explicit return type is given, require a
3895 // block to appear (RFC 968).
3896 let body_lo = self.span;
3897 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3903 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3907 // `else` token already eaten
3908 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3909 if self.eat_keyword(keywords::If) {
3910 return self.parse_if_expr(ThinVec::new());
3912 let blk = self.parse_block()?;
3913 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3917 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3918 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3920 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3921 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3923 let pat = self.parse_top_level_pat()?;
3924 if !self.eat_keyword(keywords::In) {
3925 let in_span = self.prev_span.between(self.span);
3926 let mut err = self.sess.span_diagnostic
3927 .struct_span_err(in_span, "missing `in` in `for` loop");
3928 err.span_suggestion_short(
3929 in_span, "try adding `in` here", " in ".into(),
3930 // has been misleading, at least in the past (closed Issue #48492)
3931 Applicability::MaybeIncorrect
3935 let in_span = self.prev_span;
3936 if self.eat_keyword(keywords::In) {
3937 // a common typo: `for _ in in bar {}`
3938 let mut err = self.sess.span_diagnostic.struct_span_err(
3940 "expected iterable, found keyword `in`",
3942 err.span_suggestion_short(
3943 in_span.until(self.prev_span),
3944 "remove the duplicated `in`",
3946 Applicability::MachineApplicable,
3948 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
3949 err.note("for more information on the status of emplacement syntax, see <\
3950 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
3953 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3954 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3955 attrs.extend(iattrs);
3957 let hi = self.prev_span;
3958 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3961 /// Parses a `while` or `while let` expression (`while` token already eaten).
3962 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3964 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3965 if self.token.is_keyword(keywords::Let) {
3966 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3968 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3969 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3970 attrs.extend(iattrs);
3971 let span = span_lo.to(body.span);
3972 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3975 /// Parses a `while let` expression (`while` token already eaten).
3976 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3978 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3979 self.expect_keyword(keywords::Let)?;
3980 let pats = self.parse_pats()?;
3981 self.expect(&token::Eq)?;
3982 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3983 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3984 attrs.extend(iattrs);
3985 let span = span_lo.to(body.span);
3986 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3989 // parse `loop {...}`, `loop` token already eaten
3990 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3992 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3993 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3994 attrs.extend(iattrs);
3995 let span = span_lo.to(body.span);
3996 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3999 /// Parses an `async move {...}` expression.
4000 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
4001 -> PResult<'a, P<Expr>>
4003 let span_lo = self.span;
4004 self.expect_keyword(keywords::Async)?;
4005 let capture_clause = if self.eat_keyword(keywords::Move) {
4010 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4011 attrs.extend(iattrs);
4013 span_lo.to(body.span),
4014 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
4017 /// Parses a `try {...}` expression (`try` token already eaten).
4018 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
4019 -> PResult<'a, P<Expr>>
4021 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4022 attrs.extend(iattrs);
4023 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
4026 // `match` token already eaten
4027 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4028 let match_span = self.prev_span;
4029 let lo = self.prev_span;
4030 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
4032 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
4033 if self.token == token::Token::Semi {
4034 e.span_suggestion_short(
4036 "try removing this `match`",
4038 Applicability::MaybeIncorrect // speculative
4043 attrs.extend(self.parse_inner_attributes()?);
4045 let mut arms: Vec<Arm> = Vec::new();
4046 while self.token != token::CloseDelim(token::Brace) {
4047 match self.parse_arm() {
4048 Ok(arm) => arms.push(arm),
4050 // Recover by skipping to the end of the block.
4052 self.recover_stmt();
4053 let span = lo.to(self.span);
4054 if self.token == token::CloseDelim(token::Brace) {
4057 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
4063 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
4066 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
4067 maybe_whole!(self, NtArm, |x| x);
4069 let attrs = self.parse_outer_attributes()?;
4070 let pats = self.parse_pats()?;
4071 let guard = if self.eat_keyword(keywords::If) {
4072 Some(Guard::If(self.parse_expr()?))
4076 let arrow_span = self.span;
4077 self.expect(&token::FatArrow)?;
4078 let arm_start_span = self.span;
4080 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
4081 .map_err(|mut err| {
4082 err.span_label(arrow_span, "while parsing the `match` arm starting here");
4086 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
4087 && self.token != token::CloseDelim(token::Brace);
4090 let cm = self.sess.source_map();
4091 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
4092 .map_err(|mut err| {
4093 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
4094 (Ok(ref expr_lines), Ok(ref arm_start_lines))
4095 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
4096 && expr_lines.lines.len() == 2
4097 && self.token == token::FatArrow => {
4098 // We check whether there's any trailing code in the parse span,
4099 // if there isn't, we very likely have the following:
4102 // | -- - missing comma
4108 // | parsed until here as `"y" & X`
4109 err.span_suggestion_short(
4110 cm.next_point(arm_start_span),
4111 "missing a comma here to end this `match` arm",
4113 Applicability::MachineApplicable
4117 err.span_label(arrow_span,
4118 "while parsing the `match` arm starting here");
4124 self.eat(&token::Comma);
4135 /// Parses an expression.
4137 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
4138 self.parse_expr_res(Restrictions::empty(), None)
4141 /// Evaluates the closure with restrictions in place.
4143 /// Afters the closure is evaluated, restrictions are reset.
4144 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
4145 where F: FnOnce(&mut Self) -> T
4147 let old = self.restrictions;
4148 self.restrictions = r;
4150 self.restrictions = old;
4155 /// Parses an expression, subject to the given restrictions.
4157 fn parse_expr_res(&mut self, r: Restrictions,
4158 already_parsed_attrs: Option<ThinVec<Attribute>>)
4159 -> PResult<'a, P<Expr>> {
4160 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
4163 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
4164 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
4165 if self.eat(&token::Eq) {
4166 Ok(Some(self.parse_expr()?))
4168 Ok(Some(self.parse_expr()?))
4174 /// Parses patterns, separated by '|' s.
4175 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
4176 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
4177 self.eat(&token::BinOp(token::Or));
4179 let mut pats = Vec::new();
4181 pats.push(self.parse_top_level_pat()?);
4183 if self.token == token::OrOr {
4184 let mut err = self.struct_span_err(self.span,
4185 "unexpected token `||` after pattern");
4186 err.span_suggestion(
4188 "use a single `|` to specify multiple patterns",
4190 Applicability::MachineApplicable
4194 } else if self.eat(&token::BinOp(token::Or)) {
4195 // This is a No-op. Continue the loop to parse the next
4203 // Parses a parenthesized list of patterns like
4204 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
4205 // - a vector of the patterns that were parsed
4206 // - an option indicating the index of the `..` element
4207 // - a boolean indicating whether a trailing comma was present.
4208 // Trailing commas are significant because (p) and (p,) are different patterns.
4209 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4210 self.expect(&token::OpenDelim(token::Paren))?;
4211 let result = self.parse_pat_list()?;
4212 self.expect(&token::CloseDelim(token::Paren))?;
4216 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4217 let mut fields = Vec::new();
4218 let mut ddpos = None;
4219 let mut trailing_comma = false;
4221 if self.eat(&token::DotDot) {
4222 if ddpos.is_none() {
4223 ddpos = Some(fields.len());
4225 // Emit a friendly error, ignore `..` and continue parsing
4226 self.struct_span_err(
4228 "`..` can only be used once per tuple or tuple struct pattern",
4230 .span_label(self.prev_span, "can only be used once per pattern")
4233 } else if !self.check(&token::CloseDelim(token::Paren)) {
4234 fields.push(self.parse_pat(None)?);
4239 trailing_comma = self.eat(&token::Comma);
4240 if !trailing_comma {
4245 if ddpos == Some(fields.len()) && trailing_comma {
4246 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
4247 let msg = "trailing comma is not permitted after `..`";
4248 self.struct_span_err(self.prev_span, msg)
4249 .span_label(self.prev_span, msg)
4253 Ok((fields, ddpos, trailing_comma))
4256 fn parse_pat_vec_elements(
4258 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
4259 let mut before = Vec::new();
4260 let mut slice = None;
4261 let mut after = Vec::new();
4262 let mut first = true;
4263 let mut before_slice = true;
4265 while self.token != token::CloseDelim(token::Bracket) {
4269 self.expect(&token::Comma)?;
4271 if self.token == token::CloseDelim(token::Bracket)
4272 && (before_slice || !after.is_empty()) {
4278 if self.eat(&token::DotDot) {
4280 if self.check(&token::Comma) ||
4281 self.check(&token::CloseDelim(token::Bracket)) {
4282 slice = Some(P(Pat {
4283 id: ast::DUMMY_NODE_ID,
4284 node: PatKind::Wild,
4285 span: self.prev_span,
4287 before_slice = false;
4293 let subpat = self.parse_pat(None)?;
4294 if before_slice && self.eat(&token::DotDot) {
4295 slice = Some(subpat);
4296 before_slice = false;
4297 } else if before_slice {
4298 before.push(subpat);
4304 Ok((before, slice, after))
4310 attrs: Vec<Attribute>
4311 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
4312 // Check if a colon exists one ahead. This means we're parsing a fieldname.
4314 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
4315 // Parsing a pattern of the form "fieldname: pat"
4316 let fieldname = self.parse_field_name()?;
4318 let pat = self.parse_pat(None)?;
4320 (pat, fieldname, false)
4322 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
4323 let is_box = self.eat_keyword(keywords::Box);
4324 let boxed_span = self.span;
4325 let is_ref = self.eat_keyword(keywords::Ref);
4326 let is_mut = self.eat_keyword(keywords::Mut);
4327 let fieldname = self.parse_ident()?;
4328 hi = self.prev_span;
4330 let bind_type = match (is_ref, is_mut) {
4331 (true, true) => BindingMode::ByRef(Mutability::Mutable),
4332 (true, false) => BindingMode::ByRef(Mutability::Immutable),
4333 (false, true) => BindingMode::ByValue(Mutability::Mutable),
4334 (false, false) => BindingMode::ByValue(Mutability::Immutable),
4336 let fieldpat = P(Pat {
4337 id: ast::DUMMY_NODE_ID,
4338 node: PatKind::Ident(bind_type, fieldname, None),
4339 span: boxed_span.to(hi),
4342 let subpat = if is_box {
4344 id: ast::DUMMY_NODE_ID,
4345 node: PatKind::Box(fieldpat),
4351 (subpat, fieldname, true)
4354 Ok(source_map::Spanned {
4356 node: ast::FieldPat {
4360 attrs: attrs.into(),
4365 /// Parses the fields of a struct-like pattern.
4366 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
4367 let mut fields = Vec::new();
4368 let mut etc = false;
4369 let mut ate_comma = true;
4370 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
4371 let mut etc_span = None;
4373 while self.token != token::CloseDelim(token::Brace) {
4374 let attrs = self.parse_outer_attributes()?;
4377 // check that a comma comes after every field
4379 let err = self.struct_span_err(self.prev_span, "expected `,`");
4380 if let Some(mut delayed) = delayed_err {
4387 if self.check(&token::DotDot) || self.token == token::DotDotDot {
4389 let mut etc_sp = self.span;
4391 if self.token == token::DotDotDot { // Issue #46718
4392 // Accept `...` as if it were `..` to avoid further errors
4393 let mut err = self.struct_span_err(self.span,
4394 "expected field pattern, found `...`");
4395 err.span_suggestion(
4397 "to omit remaining fields, use one fewer `.`",
4399 Applicability::MachineApplicable
4403 self.bump(); // `..` || `...`
4405 if self.token == token::CloseDelim(token::Brace) {
4406 etc_span = Some(etc_sp);
4409 let token_str = self.this_token_descr();
4410 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
4412 err.span_label(self.span, "expected `}`");
4413 let mut comma_sp = None;
4414 if self.token == token::Comma { // Issue #49257
4415 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
4416 err.span_label(etc_sp,
4417 "`..` must be at the end and cannot have a trailing comma");
4418 comma_sp = Some(self.span);
4423 etc_span = Some(etc_sp.until(self.span));
4424 if self.token == token::CloseDelim(token::Brace) {
4425 // If the struct looks otherwise well formed, recover and continue.
4426 if let Some(sp) = comma_sp {
4427 err.span_suggestion_short(
4429 "remove this comma",
4431 Applicability::MachineApplicable,
4436 } else if self.token.is_ident() && ate_comma {
4437 // Accept fields coming after `..,`.
4438 // This way we avoid "pattern missing fields" errors afterwards.
4439 // We delay this error until the end in order to have a span for a
4441 if let Some(mut delayed_err) = delayed_err {
4445 delayed_err = Some(err);
4448 if let Some(mut err) = delayed_err {
4455 fields.push(match self.parse_pat_field(lo, attrs) {
4458 if let Some(mut delayed_err) = delayed_err {
4464 ate_comma = self.eat(&token::Comma);
4467 if let Some(mut err) = delayed_err {
4468 if let Some(etc_span) = etc_span {
4469 err.multipart_suggestion(
4470 "move the `..` to the end of the field list",
4472 (etc_span, String::new()),
4473 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4475 Applicability::MachineApplicable,
4480 return Ok((fields, etc));
4483 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4484 if self.token.is_path_start() {
4486 let (qself, path) = if self.eat_lt() {
4487 // Parse a qualified path
4488 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4491 // Parse an unqualified path
4492 (None, self.parse_path(PathStyle::Expr)?)
4494 let hi = self.prev_span;
4495 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4497 self.parse_literal_maybe_minus()
4501 // helper function to decide whether to parse as ident binding or to try to do
4502 // something more complex like range patterns
4503 fn parse_as_ident(&mut self) -> bool {
4504 self.look_ahead(1, |t| match *t {
4505 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4506 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4507 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4508 // range pattern branch
4509 token::DotDot => None,
4511 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4512 token::Comma | token::CloseDelim(token::Bracket) => true,
4517 /// A wrapper around `parse_pat` with some special error handling for the
4518 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4519 /// to subpatterns within such).
4520 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4521 let pat = self.parse_pat(None)?;
4522 if self.token == token::Comma {
4523 // An unexpected comma after a top-level pattern is a clue that the
4524 // user (perhaps more accustomed to some other language) forgot the
4525 // parentheses in what should have been a tuple pattern; return a
4526 // suggestion-enhanced error here rather than choking on the comma
4528 let comma_span = self.span;
4530 if let Err(mut err) = self.parse_pat_list() {
4531 // We didn't expect this to work anyway; we just wanted
4532 // to advance to the end of the comma-sequence so we know
4533 // the span to suggest parenthesizing
4536 let seq_span = pat.span.to(self.prev_span);
4537 let mut err = self.struct_span_err(comma_span,
4538 "unexpected `,` in pattern");
4539 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4540 err.span_suggestion(
4542 "try adding parentheses to match on a tuple..",
4543 format!("({})", seq_snippet),
4544 Applicability::MachineApplicable
4547 "..or a vertical bar to match on multiple alternatives",
4548 format!("{}", seq_snippet.replace(",", " |")),
4549 Applicability::MachineApplicable
4557 /// Parses a pattern.
4558 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4559 self.parse_pat_with_range_pat(true, expected)
4562 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
4564 fn parse_pat_with_range_pat(
4566 allow_range_pat: bool,
4567 expected: Option<&'static str>,
4568 ) -> PResult<'a, P<Pat>> {
4569 maybe_whole!(self, NtPat, |x| x);
4574 token::BinOp(token::And) | token::AndAnd => {
4575 // Parse &pat / &mut pat
4577 let mutbl = self.parse_mutability();
4578 if let token::Lifetime(ident) = self.token {
4579 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4581 err.span_label(self.span, "unexpected lifetime");
4584 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4585 pat = PatKind::Ref(subpat, mutbl);
4587 token::OpenDelim(token::Paren) => {
4588 // Parse (pat,pat,pat,...) as tuple pattern
4589 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4590 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4591 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4593 PatKind::Tuple(fields, ddpos)
4596 token::OpenDelim(token::Bracket) => {
4597 // Parse [pat,pat,...] as slice pattern
4599 let (before, slice, after) = self.parse_pat_vec_elements()?;
4600 self.expect(&token::CloseDelim(token::Bracket))?;
4601 pat = PatKind::Slice(before, slice, after);
4603 // At this point, token != &, &&, (, [
4604 _ => if self.eat_keyword(keywords::Underscore) {
4606 pat = PatKind::Wild;
4607 } else if self.eat_keyword(keywords::Mut) {
4608 // Parse mut ident @ pat / mut ref ident @ pat
4609 let mutref_span = self.prev_span.to(self.span);
4610 let binding_mode = if self.eat_keyword(keywords::Ref) {
4612 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4615 "try switching the order",
4617 Applicability::MachineApplicable
4619 BindingMode::ByRef(Mutability::Mutable)
4621 BindingMode::ByValue(Mutability::Mutable)
4623 pat = self.parse_pat_ident(binding_mode)?;
4624 } else if self.eat_keyword(keywords::Ref) {
4625 // Parse ref ident @ pat / ref mut ident @ pat
4626 let mutbl = self.parse_mutability();
4627 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4628 } else if self.eat_keyword(keywords::Box) {
4630 let subpat = self.parse_pat_with_range_pat(false, None)?;
4631 pat = PatKind::Box(subpat);
4632 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4633 self.parse_as_ident() {
4634 // Parse ident @ pat
4635 // This can give false positives and parse nullary enums,
4636 // they are dealt with later in resolve
4637 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4638 pat = self.parse_pat_ident(binding_mode)?;
4639 } else if self.token.is_path_start() {
4640 // Parse pattern starting with a path
4641 let (qself, path) = if self.eat_lt() {
4642 // Parse a qualified path
4643 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4646 // Parse an unqualified path
4647 (None, self.parse_path(PathStyle::Expr)?)
4650 token::Not if qself.is_none() => {
4651 // Parse macro invocation
4653 let (delim, tts) = self.expect_delimited_token_tree()?;
4654 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4655 pat = PatKind::Mac(mac);
4657 token::DotDotDot | token::DotDotEq | token::DotDot => {
4658 let end_kind = match self.token {
4659 token::DotDot => RangeEnd::Excluded,
4660 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4661 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4662 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4665 let op_span = self.span;
4667 let span = lo.to(self.prev_span);
4668 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4670 let end = self.parse_pat_range_end()?;
4671 let op = Spanned { span: op_span, node: end_kind };
4672 pat = PatKind::Range(begin, end, op);
4674 token::OpenDelim(token::Brace) => {
4675 if qself.is_some() {
4676 let msg = "unexpected `{` after qualified path";
4677 let mut err = self.fatal(msg);
4678 err.span_label(self.span, msg);
4681 // Parse struct pattern
4683 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4685 self.recover_stmt();
4689 pat = PatKind::Struct(path, fields, etc);
4691 token::OpenDelim(token::Paren) => {
4692 if qself.is_some() {
4693 let msg = "unexpected `(` after qualified path";
4694 let mut err = self.fatal(msg);
4695 err.span_label(self.span, msg);
4698 // Parse tuple struct or enum pattern
4699 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4700 pat = PatKind::TupleStruct(path, fields, ddpos)
4702 _ => pat = PatKind::Path(qself, path),
4705 // Try to parse everything else as literal with optional minus
4706 match self.parse_literal_maybe_minus() {
4708 let op_span = self.span;
4709 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4710 self.check(&token::DotDotDot) {
4711 let end_kind = if self.eat(&token::DotDotDot) {
4712 RangeEnd::Included(RangeSyntax::DotDotDot)
4713 } else if self.eat(&token::DotDotEq) {
4714 RangeEnd::Included(RangeSyntax::DotDotEq)
4715 } else if self.eat(&token::DotDot) {
4718 panic!("impossible case: we already matched \
4719 on a range-operator token")
4721 let end = self.parse_pat_range_end()?;
4722 let op = Spanned { span: op_span, node: end_kind };
4723 pat = PatKind::Range(begin, end, op);
4725 pat = PatKind::Lit(begin);
4729 self.cancel(&mut err);
4730 let expected = expected.unwrap_or("pattern");
4732 "expected {}, found {}",
4734 self.this_token_descr(),
4736 let mut err = self.fatal(&msg);
4737 err.span_label(self.span, format!("expected {}", expected));
4744 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4745 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4747 if !allow_range_pat {
4750 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4752 PatKind::Range(..) => {
4753 let mut err = self.struct_span_err(
4755 "the range pattern here has ambiguous interpretation",
4757 err.span_suggestion(
4759 "add parentheses to clarify the precedence",
4760 format!("({})", pprust::pat_to_string(&pat)),
4761 // "ambiguous interpretation" implies that we have to be guessing
4762 Applicability::MaybeIncorrect
4773 /// Parses `ident` or `ident @ pat`.
4774 /// used by the copy foo and ref foo patterns to give a good
4775 /// error message when parsing mistakes like `ref foo(a, b)`.
4776 fn parse_pat_ident(&mut self,
4777 binding_mode: ast::BindingMode)
4778 -> PResult<'a, PatKind> {
4779 let ident = self.parse_ident()?;
4780 let sub = if self.eat(&token::At) {
4781 Some(self.parse_pat(Some("binding pattern"))?)
4786 // just to be friendly, if they write something like
4788 // we end up here with ( as the current token. This shortly
4789 // leads to a parse error. Note that if there is no explicit
4790 // binding mode then we do not end up here, because the lookahead
4791 // will direct us over to parse_enum_variant()
4792 if self.token == token::OpenDelim(token::Paren) {
4793 return Err(self.span_fatal(
4795 "expected identifier, found enum pattern"))
4798 Ok(PatKind::Ident(binding_mode, ident, sub))
4801 /// Parses a local variable declaration.
4802 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4803 let lo = self.prev_span;
4804 let pat = self.parse_top_level_pat()?;
4806 let (err, ty) = if self.eat(&token::Colon) {
4807 // Save the state of the parser before parsing type normally, in case there is a `:`
4808 // instead of an `=` typo.
4809 let parser_snapshot_before_type = self.clone();
4810 let colon_sp = self.prev_span;
4811 match self.parse_ty() {
4812 Ok(ty) => (None, Some(ty)),
4814 // Rewind to before attempting to parse the type and continue parsing
4815 let parser_snapshot_after_type = self.clone();
4816 mem::replace(self, parser_snapshot_before_type);
4818 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4819 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4820 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4826 let init = match (self.parse_initializer(err.is_some()), err) {
4827 (Ok(init), None) => { // init parsed, ty parsed
4830 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4831 // Could parse the type as if it were the initializer, it is likely there was a
4832 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4833 err.span_suggestion_short(
4835 "use `=` if you meant to assign",
4837 Applicability::MachineApplicable
4840 // As this was parsed successfully, continue as if the code has been fixed for the
4841 // rest of the file. It will still fail due to the emitted error, but we avoid
4845 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4847 // Couldn't parse the type nor the initializer, only raise the type error and
4848 // return to the parser state before parsing the type as the initializer.
4849 // let x: <parse_error>;
4850 mem::replace(self, snapshot);
4853 (Err(err), None) => { // init error, ty parsed
4854 // Couldn't parse the initializer and we're not attempting to recover a failed
4855 // parse of the type, return the error.
4859 let hi = if self.token == token::Semi {
4868 id: ast::DUMMY_NODE_ID,
4874 /// Parses a structure field.
4875 fn parse_name_and_ty(&mut self,
4878 attrs: Vec<Attribute>)
4879 -> PResult<'a, StructField> {
4880 let name = self.parse_ident()?;
4881 self.expect(&token::Colon)?;
4882 let ty = self.parse_ty()?;
4884 span: lo.to(self.prev_span),
4887 id: ast::DUMMY_NODE_ID,
4893 /// Emits an expected-item-after-attributes error.
4894 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
4895 let message = match attrs.last() {
4896 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4897 _ => "expected item after attributes",
4900 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
4901 if attrs.last().unwrap().is_sugared_doc {
4902 err.span_label(self.prev_span, "this doc comment doesn't document anything");
4907 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4908 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4909 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4910 Ok(self.parse_stmt_(true))
4913 // Eat tokens until we can be relatively sure we reached the end of the
4914 // statement. This is something of a best-effort heuristic.
4916 // We terminate when we find an unmatched `}` (without consuming it).
4917 fn recover_stmt(&mut self) {
4918 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4921 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4922 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4923 // approximate - it can mean we break too early due to macros, but that
4924 // should only lead to sub-optimal recovery, not inaccurate parsing).
4926 // If `break_on_block` is `Break`, then we will stop consuming tokens
4927 // after finding (and consuming) a brace-delimited block.
4928 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4929 let mut brace_depth = 0;
4930 let mut bracket_depth = 0;
4931 let mut in_block = false;
4932 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4933 break_on_semi, break_on_block);
4935 debug!("recover_stmt_ loop {:?}", self.token);
4937 token::OpenDelim(token::DelimToken::Brace) => {
4940 if break_on_block == BlockMode::Break &&
4942 bracket_depth == 0 {
4946 token::OpenDelim(token::DelimToken::Bracket) => {
4950 token::CloseDelim(token::DelimToken::Brace) => {
4951 if brace_depth == 0 {
4952 debug!("recover_stmt_ return - close delim {:?}", self.token);
4957 if in_block && bracket_depth == 0 && brace_depth == 0 {
4958 debug!("recover_stmt_ return - block end {:?}", self.token);
4962 token::CloseDelim(token::DelimToken::Bracket) => {
4964 if bracket_depth < 0 {
4970 debug!("recover_stmt_ return - Eof");
4975 if break_on_semi == SemiColonMode::Break &&
4977 bracket_depth == 0 {
4978 debug!("recover_stmt_ return - Semi");
4983 if break_on_semi == SemiColonMode::Comma &&
4985 bracket_depth == 0 {
4986 debug!("recover_stmt_ return - Semi");
4999 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
5000 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
5002 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5007 fn is_async_block(&mut self) -> bool {
5008 self.token.is_keyword(keywords::Async) &&
5011 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
5012 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
5014 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
5019 fn is_async_fn(&mut self) -> bool {
5020 self.token.is_keyword(keywords::Async) &&
5021 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
5024 fn is_do_catch_block(&mut self) -> bool {
5025 self.token.is_keyword(keywords::Do) &&
5026 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
5027 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
5028 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5031 fn is_try_block(&mut self) -> bool {
5032 self.token.is_keyword(keywords::Try) &&
5033 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
5034 self.span.rust_2018() &&
5035 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
5036 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5039 fn is_union_item(&self) -> bool {
5040 self.token.is_keyword(keywords::Union) &&
5041 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
5044 fn is_crate_vis(&self) -> bool {
5045 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
5048 fn is_existential_type_decl(&self) -> bool {
5049 self.token.is_keyword(keywords::Existential) &&
5050 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
5053 fn is_auto_trait_item(&mut self) -> bool {
5055 (self.token.is_keyword(keywords::Auto)
5056 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
5057 || // unsafe auto trait
5058 (self.token.is_keyword(keywords::Unsafe) &&
5059 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
5060 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
5063 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
5064 -> PResult<'a, Option<P<Item>>> {
5065 let token_lo = self.span;
5066 let (ident, def) = match self.token {
5067 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
5069 let ident = self.parse_ident()?;
5070 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
5071 match self.parse_token_tree() {
5072 TokenTree::Delimited(_, _, tts) => tts,
5073 _ => unreachable!(),
5075 } else if self.check(&token::OpenDelim(token::Paren)) {
5076 let args = self.parse_token_tree();
5077 let body = if self.check(&token::OpenDelim(token::Brace)) {
5078 self.parse_token_tree()
5083 TokenStream::new(vec![
5085 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
5093 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
5095 token::Ident(ident, _) if ident.name == "macro_rules" &&
5096 self.look_ahead(1, |t| *t == token::Not) => {
5097 let prev_span = self.prev_span;
5098 self.complain_if_pub_macro(&vis.node, prev_span);
5102 let ident = self.parse_ident()?;
5103 let (delim, tokens) = self.expect_delimited_token_tree()?;
5104 if delim != MacDelimiter::Brace {
5105 if !self.eat(&token::Semi) {
5106 let msg = "macros that expand to items must either \
5107 be surrounded with braces or followed by a semicolon";
5108 self.span_err(self.prev_span, msg);
5112 (ident, ast::MacroDef { tokens: tokens, legacy: true })
5114 _ => return Ok(None),
5117 let span = lo.to(self.prev_span);
5118 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
5121 fn parse_stmt_without_recovery(&mut self,
5122 macro_legacy_warnings: bool)
5123 -> PResult<'a, Option<Stmt>> {
5124 maybe_whole!(self, NtStmt, |x| Some(x));
5126 let attrs = self.parse_outer_attributes()?;
5129 Ok(Some(if self.eat_keyword(keywords::Let) {
5131 id: ast::DUMMY_NODE_ID,
5132 node: StmtKind::Local(self.parse_local(attrs.into())?),
5133 span: lo.to(self.prev_span),
5135 } else if let Some(macro_def) = self.eat_macro_def(
5137 &source_map::respan(lo, VisibilityKind::Inherited),
5141 id: ast::DUMMY_NODE_ID,
5142 node: StmtKind::Item(macro_def),
5143 span: lo.to(self.prev_span),
5145 // Starts like a simple path, being careful to avoid contextual keywords
5146 // such as a union items, item with `crate` visibility or auto trait items.
5147 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
5148 // like a path (1 token), but it fact not a path.
5149 // `union::b::c` - path, `union U { ... }` - not a path.
5150 // `crate::b::c` - path, `crate struct S;` - not a path.
5151 } else if self.token.is_path_start() &&
5152 !self.token.is_qpath_start() &&
5153 !self.is_union_item() &&
5154 !self.is_crate_vis() &&
5155 !self.is_existential_type_decl() &&
5156 !self.is_auto_trait_item() &&
5157 !self.is_async_fn() {
5158 let pth = self.parse_path(PathStyle::Expr)?;
5160 if !self.eat(&token::Not) {
5161 let expr = if self.check(&token::OpenDelim(token::Brace)) {
5162 self.parse_struct_expr(lo, pth, ThinVec::new())?
5164 let hi = self.prev_span;
5165 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
5168 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
5169 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
5170 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
5173 return Ok(Some(Stmt {
5174 id: ast::DUMMY_NODE_ID,
5175 node: StmtKind::Expr(expr),
5176 span: lo.to(self.prev_span),
5180 // it's a macro invocation
5181 let id = match self.token {
5182 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
5183 _ => self.parse_ident()?,
5186 // check that we're pointing at delimiters (need to check
5187 // again after the `if`, because of `parse_ident`
5188 // consuming more tokens).
5190 token::OpenDelim(_) => {}
5192 // we only expect an ident if we didn't parse one
5194 let ident_str = if id.name == keywords::Invalid.name() {
5199 let tok_str = self.this_token_descr();
5200 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
5203 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
5208 let (delim, tts) = self.expect_delimited_token_tree()?;
5209 let hi = self.prev_span;
5211 let style = if delim == MacDelimiter::Brace {
5212 MacStmtStyle::Braces
5214 MacStmtStyle::NoBraces
5217 if id.name == keywords::Invalid.name() {
5218 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
5219 let node = if delim == MacDelimiter::Brace ||
5220 self.token == token::Semi || self.token == token::Eof {
5221 StmtKind::Mac(P((mac, style, attrs.into())))
5223 // We used to incorrectly stop parsing macro-expanded statements here.
5224 // If the next token will be an error anyway but could have parsed with the
5225 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
5226 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
5227 // These can continue an expression, so we can't stop parsing and warn.
5228 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
5229 token::BinOp(token::Minus) | token::BinOp(token::Star) |
5230 token::BinOp(token::And) | token::BinOp(token::Or) |
5231 token::AndAnd | token::OrOr |
5232 token::DotDot | token::DotDotDot | token::DotDotEq => false,
5235 self.warn_missing_semicolon();
5236 StmtKind::Mac(P((mac, style, attrs.into())))
5238 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
5239 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
5240 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
5244 id: ast::DUMMY_NODE_ID,
5249 // if it has a special ident, it's definitely an item
5251 // Require a semicolon or braces.
5252 if style != MacStmtStyle::Braces {
5253 if !self.eat(&token::Semi) {
5254 self.span_err(self.prev_span,
5255 "macros that expand to items must \
5256 either be surrounded with braces or \
5257 followed by a semicolon");
5260 let span = lo.to(hi);
5262 id: ast::DUMMY_NODE_ID,
5264 node: StmtKind::Item({
5266 span, id /*id is good here*/,
5267 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
5268 respan(lo, VisibilityKind::Inherited),
5274 // FIXME: Bad copy of attrs
5275 let old_directory_ownership =
5276 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
5277 let item = self.parse_item_(attrs.clone(), false, true)?;
5278 self.directory.ownership = old_directory_ownership;
5282 id: ast::DUMMY_NODE_ID,
5283 span: lo.to(i.span),
5284 node: StmtKind::Item(i),
5287 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
5288 if !attrs.is_empty() {
5289 if s.prev_token_kind == PrevTokenKind::DocComment {
5290 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
5291 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
5292 s.span_err(s.span, "expected statement after outer attribute");
5297 // Do not attempt to parse an expression if we're done here.
5298 if self.token == token::Semi {
5299 unused_attrs(&attrs, self);
5304 if self.token == token::CloseDelim(token::Brace) {
5305 unused_attrs(&attrs, self);
5309 // Remainder are line-expr stmts.
5310 let e = self.parse_expr_res(
5311 Restrictions::STMT_EXPR, Some(attrs.into()))?;
5313 id: ast::DUMMY_NODE_ID,
5314 span: lo.to(e.span),
5315 node: StmtKind::Expr(e),
5322 /// Checks if this expression is a successfully parsed statement.
5323 fn expr_is_complete(&mut self, e: &Expr) -> bool {
5324 self.restrictions.contains(Restrictions::STMT_EXPR) &&
5325 !classify::expr_requires_semi_to_be_stmt(e)
5328 /// Parses a block. No inner attributes are allowed.
5329 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
5330 maybe_whole!(self, NtBlock, |x| x);
5334 if !self.eat(&token::OpenDelim(token::Brace)) {
5336 let tok = self.this_token_descr();
5337 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
5338 let do_not_suggest_help =
5339 self.token.is_keyword(keywords::In) || self.token == token::Colon;
5341 if self.token.is_ident_named("and") {
5342 e.span_suggestion_short(
5344 "use `&&` instead of `and` for the boolean operator",
5346 Applicability::MaybeIncorrect,
5349 if self.token.is_ident_named("or") {
5350 e.span_suggestion_short(
5352 "use `||` instead of `or` for the boolean operator",
5354 Applicability::MaybeIncorrect,
5358 // Check to see if the user has written something like
5363 // Which is valid in other languages, but not Rust.
5364 match self.parse_stmt_without_recovery(false) {
5366 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
5367 || do_not_suggest_help {
5368 // if the next token is an open brace (e.g., `if a b {`), the place-
5369 // inside-a-block suggestion would be more likely wrong than right
5370 e.span_label(sp, "expected `{`");
5373 let mut stmt_span = stmt.span;
5374 // expand the span to include the semicolon, if it exists
5375 if self.eat(&token::Semi) {
5376 stmt_span = stmt_span.with_hi(self.prev_span.hi());
5378 let sugg = pprust::to_string(|s| {
5379 use crate::print::pprust::{PrintState, INDENT_UNIT};
5380 s.ibox(INDENT_UNIT)?;
5382 s.print_stmt(&stmt)?;
5383 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
5387 "try placing this code inside a block",
5389 // speculative, has been misleading in the past (closed Issue #46836)
5390 Applicability::MaybeIncorrect
5394 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5395 self.cancel(&mut e);
5399 e.span_label(sp, "expected `{`");
5403 self.parse_block_tail(lo, BlockCheckMode::Default)
5406 /// Parses a block. Inner attributes are allowed.
5407 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
5408 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
5411 self.expect(&token::OpenDelim(token::Brace))?;
5412 Ok((self.parse_inner_attributes()?,
5413 self.parse_block_tail(lo, BlockCheckMode::Default)?))
5416 /// Parses the rest of a block expression or function body.
5417 /// Precondition: already parsed the '{'.
5418 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
5419 let mut stmts = vec![];
5420 while !self.eat(&token::CloseDelim(token::Brace)) {
5421 let stmt = match self.parse_full_stmt(false) {
5424 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
5426 id: ast::DUMMY_NODE_ID,
5427 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
5433 if let Some(stmt) = stmt {
5435 } else if self.token == token::Eof {
5438 // Found only `;` or `}`.
5444 id: ast::DUMMY_NODE_ID,
5446 span: lo.to(self.prev_span),
5450 /// Parses a statement, including the trailing semicolon.
5451 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5452 // skip looking for a trailing semicolon when we have an interpolated statement
5453 maybe_whole!(self, NtStmt, |x| Some(x));
5455 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5457 None => return Ok(None),
5461 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5462 // expression without semicolon
5463 if classify::expr_requires_semi_to_be_stmt(expr) {
5464 // Just check for errors and recover; do not eat semicolon yet.
5466 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5469 self.recover_stmt();
5473 StmtKind::Local(..) => {
5474 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5475 if macro_legacy_warnings && self.token != token::Semi {
5476 self.warn_missing_semicolon();
5478 self.expect_one_of(&[], &[token::Semi])?;
5484 if self.eat(&token::Semi) {
5485 stmt = stmt.add_trailing_semicolon();
5488 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5492 fn warn_missing_semicolon(&self) {
5493 self.diagnostic().struct_span_warn(self.span, {
5494 &format!("expected `;`, found {}", self.this_token_descr())
5496 "This was erroneously allowed and will become a hard error in a future release"
5500 fn err_dotdotdot_syntax(&self, span: Span) {
5501 self.diagnostic().struct_span_err(span, {
5502 "unexpected token: `...`"
5504 span, "use `..` for an exclusive range", "..".to_owned(),
5505 Applicability::MaybeIncorrect
5507 span, "or `..=` for an inclusive range", "..=".to_owned(),
5508 Applicability::MaybeIncorrect
5512 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
5515 /// BOUND = TY_BOUND | LT_BOUND
5516 /// LT_BOUND = LIFETIME (e.g., `'a`)
5517 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5518 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5520 fn parse_generic_bounds_common(&mut self,
5522 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5523 let mut bounds = Vec::new();
5524 let mut negative_bounds = Vec::new();
5525 let mut last_plus_span = None;
5527 // This needs to be synchronized with `Token::can_begin_bound`.
5528 let is_bound_start = self.check_path() || self.check_lifetime() ||
5529 self.check(&token::Not) || // used for error reporting only
5530 self.check(&token::Question) ||
5531 self.check_keyword(keywords::For) ||
5532 self.check(&token::OpenDelim(token::Paren));
5535 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5536 let inner_lo = self.span;
5537 let is_negative = self.eat(&token::Not);
5538 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5539 if self.token.is_lifetime() {
5540 if let Some(question_span) = question {
5541 self.span_err(question_span,
5542 "`?` may only modify trait bounds, not lifetime bounds");
5544 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5546 let inner_span = inner_lo.to(self.prev_span);
5547 self.expect(&token::CloseDelim(token::Paren))?;
5548 let mut err = self.struct_span_err(
5549 lo.to(self.prev_span),
5550 "parenthesized lifetime bounds are not supported"
5552 if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
5553 err.span_suggestion_short(
5554 lo.to(self.prev_span),
5555 "remove the parentheses",
5557 Applicability::MachineApplicable
5563 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5564 let path = self.parse_path(PathStyle::Type)?;
5566 self.expect(&token::CloseDelim(token::Paren))?;
5568 let poly_span = lo.to(self.prev_span);
5570 negative_bounds.push(
5571 last_plus_span.or(colon_span).unwrap()
5574 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
5575 let modifier = if question.is_some() {
5576 TraitBoundModifier::Maybe
5578 TraitBoundModifier::None
5580 bounds.push(GenericBound::Trait(poly_trait, modifier));
5587 if !allow_plus || !self.eat_plus() {
5590 last_plus_span = Some(self.prev_span);
5594 if !negative_bounds.is_empty() {
5595 let plural = negative_bounds.len() > 1;
5596 let mut err = self.struct_span_err(negative_bounds,
5597 "negative trait bounds are not supported");
5598 let bound_list = colon_span.unwrap().to(self.prev_span);
5599 let mut new_bound_list = String::new();
5600 if !bounds.is_empty() {
5601 let mut snippets = bounds.iter().map(|bound| bound.span())
5602 .map(|span| self.sess.source_map().span_to_snippet(span));
5603 while let Some(Ok(snippet)) = snippets.next() {
5604 new_bound_list.push_str(" + ");
5605 new_bound_list.push_str(&snippet);
5607 new_bound_list = new_bound_list.replacen(" +", ":", 1);
5609 err.span_suggestion_short(bound_list,
5610 &format!("remove the trait bound{}",
5611 if plural { "s" } else { "" }),
5613 Applicability::MachineApplicable);
5620 fn parse_generic_bounds(&mut self, colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5621 self.parse_generic_bounds_common(true, colon_span)
5624 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5627 /// BOUND = LT_BOUND (e.g., `'a`)
5629 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5630 let mut lifetimes = Vec::new();
5631 while self.check_lifetime() {
5632 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5634 if !self.eat_plus() {
5641 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
5642 fn parse_ty_param(&mut self,
5643 preceding_attrs: Vec<Attribute>)
5644 -> PResult<'a, GenericParam> {
5645 let ident = self.parse_ident()?;
5647 // Parse optional colon and param bounds.
5648 let bounds = if self.eat(&token::Colon) {
5649 self.parse_generic_bounds(None)?
5654 let default = if self.eat(&token::Eq) {
5655 Some(self.parse_ty()?)
5662 id: ast::DUMMY_NODE_ID,
5663 attrs: preceding_attrs.into(),
5665 kind: GenericParamKind::Type {
5671 /// Parses the following grammar:
5673 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5674 fn parse_trait_item_assoc_ty(&mut self)
5675 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5676 let ident = self.parse_ident()?;
5677 let mut generics = self.parse_generics()?;
5679 // Parse optional colon and param bounds.
5680 let bounds = if self.eat(&token::Colon) {
5681 self.parse_generic_bounds(None)?
5685 generics.where_clause = self.parse_where_clause()?;
5687 let default = if self.eat(&token::Eq) {
5688 Some(self.parse_ty()?)
5692 self.expect(&token::Semi)?;
5694 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5697 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
5698 self.expect_keyword(keywords::Const)?;
5699 let ident = self.parse_ident()?;
5700 self.expect(&token::Colon)?;
5701 let ty = self.parse_ty()?;
5705 id: ast::DUMMY_NODE_ID,
5706 attrs: preceding_attrs.into(),
5708 kind: GenericParamKind::Const {
5714 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
5715 /// a trailing comma and erroneous trailing attributes.
5716 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5717 let mut params = Vec::new();
5719 let attrs = self.parse_outer_attributes()?;
5720 if self.check_lifetime() {
5721 let lifetime = self.expect_lifetime();
5722 // Parse lifetime parameter.
5723 let bounds = if self.eat(&token::Colon) {
5724 self.parse_lt_param_bounds()
5728 params.push(ast::GenericParam {
5729 ident: lifetime.ident,
5731 attrs: attrs.into(),
5733 kind: ast::GenericParamKind::Lifetime,
5735 } else if self.check_keyword(keywords::Const) {
5736 // Parse const parameter.
5737 params.push(self.parse_const_param(attrs)?);
5738 } else if self.check_ident() {
5739 // Parse type parameter.
5740 params.push(self.parse_ty_param(attrs)?);
5742 // Check for trailing attributes and stop parsing.
5743 if !attrs.is_empty() {
5744 if !params.is_empty() {
5745 self.struct_span_err(
5747 &format!("trailing attribute after generic parameter"),
5749 .span_label(attrs[0].span, "attributes must go before parameters")
5752 self.struct_span_err(
5754 &format!("attribute without generic parameters"),
5758 "attributes are only permitted when preceding parameters",
5766 if !self.eat(&token::Comma) {
5773 /// Parses a set of optional generic type parameter declarations. Where
5774 /// clauses are not parsed here, and must be added later via
5775 /// `parse_where_clause()`.
5777 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5778 /// | ( < lifetimes , typaramseq ( , )? > )
5779 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5780 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5781 maybe_whole!(self, NtGenerics, |x| x);
5783 let span_lo = self.span;
5785 let params = self.parse_generic_params()?;
5789 where_clause: WhereClause {
5790 id: ast::DUMMY_NODE_ID,
5791 predicates: Vec::new(),
5792 span: syntax_pos::DUMMY_SP,
5794 span: span_lo.to(self.prev_span),
5797 Ok(ast::Generics::default())
5801 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5802 /// For the purposes of understanding the parsing logic of generic arguments, this function
5803 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5804 /// had the correct amount of leading angle brackets.
5806 /// ```ignore (diagnostics)
5807 /// bar::<<<<T as Foo>::Output>();
5808 /// ^^ help: remove extra angle brackets
5810 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5814 ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5815 // We need to detect whether there are extra leading left angle brackets and produce an
5816 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5817 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5818 // then there won't be matching `>` tokens to find.
5820 // To explain how this detection works, consider the following example:
5822 // ```ignore (diagnostics)
5823 // bar::<<<<T as Foo>::Output>();
5824 // ^^ help: remove extra angle brackets
5827 // Parsing of the left angle brackets starts in this function. We start by parsing the
5828 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5831 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5832 // *Unmatched count:* 1
5833 // *`parse_path_segment` calls deep:* 0
5835 // This has the effect of recursing as this function is called if a `<` character
5836 // is found within the expected generic arguments:
5838 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5839 // *Unmatched count:* 2
5840 // *`parse_path_segment` calls deep:* 1
5842 // Eventually we will have recursed until having consumed all of the `<` tokens and
5843 // this will be reflected in the count:
5845 // *Upcoming tokens:* `T as Foo>::Output>;`
5846 // *Unmatched count:* 4
5847 // `parse_path_segment` calls deep:* 3
5849 // The parser will continue until reaching the first `>` - this will decrement the
5850 // unmatched angle bracket count and return to the parent invocation of this function
5851 // having succeeded in parsing:
5853 // *Upcoming tokens:* `::Output>;`
5854 // *Unmatched count:* 3
5855 // *`parse_path_segment` calls deep:* 2
5857 // This will continue until the next `>` character which will also return successfully
5858 // to the parent invocation of this function and decrement the count:
5860 // *Upcoming tokens:* `;`
5861 // *Unmatched count:* 2
5862 // *`parse_path_segment` calls deep:* 1
5864 // At this point, this function will expect to find another matching `>` character but
5865 // won't be able to and will return an error. This will continue all the way up the
5866 // call stack until the first invocation:
5868 // *Upcoming tokens:* `;`
5869 // *Unmatched count:* 2
5870 // *`parse_path_segment` calls deep:* 0
5872 // In doing this, we have managed to work out how many unmatched leading left angle
5873 // brackets there are, but we cannot recover as the unmatched angle brackets have
5874 // already been consumed. To remedy this, we keep a snapshot of the parser state
5875 // before we do the above. We can then inspect whether we ended up with a parsing error
5876 // and unmatched left angle brackets and if so, restore the parser state before we
5877 // consumed any `<` characters to emit an error and consume the erroneous tokens to
5878 // recover by attempting to parse again.
5880 // In practice, the recursion of this function is indirect and there will be other
5881 // locations that consume some `<` characters - as long as we update the count when
5882 // this happens, it isn't an issue.
5884 let is_first_invocation = style == PathStyle::Expr;
5885 // Take a snapshot before attempting to parse - we can restore this later.
5886 let snapshot = if is_first_invocation {
5892 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
5893 match self.parse_generic_args() {
5894 Ok(value) => Ok(value),
5895 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
5896 // Cancel error from being unable to find `>`. We know the error
5897 // must have been this due to a non-zero unmatched angle bracket
5901 // Swap `self` with our backup of the parser state before attempting to parse
5902 // generic arguments.
5903 let snapshot = mem::replace(self, snapshot.unwrap());
5906 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
5907 snapshot.count={:?}",
5908 snapshot.unmatched_angle_bracket_count,
5911 // Eat the unmatched angle brackets.
5912 for _ in 0..snapshot.unmatched_angle_bracket_count {
5916 // Make a span over ${unmatched angle bracket count} characters.
5917 let span = lo.with_hi(
5918 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
5920 let plural = snapshot.unmatched_angle_bracket_count > 1;
5925 "unmatched angle bracket{}",
5926 if plural { "s" } else { "" }
5932 "remove extra angle bracket{}",
5933 if plural { "s" } else { "" }
5936 Applicability::MachineApplicable,
5940 // Try again without unmatched angle bracket characters.
5941 self.parse_generic_args()
5947 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5948 /// possibly including trailing comma.
5949 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5950 let mut args = Vec::new();
5951 let mut bindings = Vec::new();
5952 let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new();
5953 let mut assoc_ty_bindings: Vec<Span> = Vec::new();
5955 let args_lo = self.span;
5958 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5959 // Parse lifetime argument.
5960 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5961 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
5962 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5963 // Parse associated type binding.
5965 let ident = self.parse_ident()?;
5967 let ty = self.parse_ty()?;
5968 let span = lo.to(self.prev_span);
5969 bindings.push(TypeBinding {
5970 id: ast::DUMMY_NODE_ID,
5975 assoc_ty_bindings.push(span);
5976 } else if self.check_const_arg() {
5977 // FIXME(const_generics): to distinguish between idents for types and consts,
5978 // we should introduce a GenericArg::Ident in the AST and distinguish when
5979 // lowering to the HIR. For now, idents for const args are not permitted.
5981 // Parse const argument.
5982 let expr = if let token::OpenDelim(token::Brace) = self.token {
5983 self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
5984 } else if self.token.is_ident() {
5985 // FIXME(const_generics): to distinguish between idents for types and consts,
5986 // we should introduce a GenericArg::Ident in the AST and distinguish when
5987 // lowering to the HIR. For now, idents for const args are not permitted.
5989 self.fatal("identifiers may currently not be used for const generics")
5992 // FIXME(const_generics): this currently conflicts with emplacement syntax
5993 // with negative integer literals.
5994 self.parse_literal_maybe_minus()?
5996 let value = AnonConst {
5997 id: ast::DUMMY_NODE_ID,
6000 args.push(GenericArg::Const(value));
6001 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6002 } else if self.check_type() {
6003 // Parse type argument.
6004 args.push(GenericArg::Type(self.parse_ty()?));
6005 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6010 if !self.eat(&token::Comma) {
6015 // FIXME: we would like to report this in ast_validation instead, but we currently do not
6016 // preserve ordering of generic parameters with respect to associated type binding, so we
6017 // lose that information after parsing.
6018 if misplaced_assoc_ty_bindings.len() > 0 {
6019 let mut err = self.struct_span_err(
6020 args_lo.to(self.prev_span),
6021 "associated type bindings must be declared after generic parameters",
6023 for span in misplaced_assoc_ty_bindings {
6026 "this associated type binding should be moved after the generic parameters",
6032 Ok((args, bindings))
6035 /// Parses an optional where-clause and places it in `generics`.
6037 /// ```ignore (only-for-syntax-highlight)
6038 /// where T : Trait<U, V> + 'b, 'a : 'b
6040 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
6041 maybe_whole!(self, NtWhereClause, |x| x);
6043 let mut where_clause = WhereClause {
6044 id: ast::DUMMY_NODE_ID,
6045 predicates: Vec::new(),
6046 span: syntax_pos::DUMMY_SP,
6049 if !self.eat_keyword(keywords::Where) {
6050 return Ok(where_clause);
6052 let lo = self.prev_span;
6054 // We are considering adding generics to the `where` keyword as an alternative higher-rank
6055 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
6056 // change we parse those generics now, but report an error.
6057 if self.choose_generics_over_qpath() {
6058 let generics = self.parse_generics()?;
6059 self.struct_span_err(
6061 "generic parameters on `where` clauses are reserved for future use",
6063 .span_label(generics.span, "currently unsupported")
6069 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6070 let lifetime = self.expect_lifetime();
6071 // Bounds starting with a colon are mandatory, but possibly empty.
6072 self.expect(&token::Colon)?;
6073 let bounds = self.parse_lt_param_bounds();
6074 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
6075 ast::WhereRegionPredicate {
6076 span: lo.to(self.prev_span),
6081 } else if self.check_type() {
6082 // Parse optional `for<'a, 'b>`.
6083 // This `for` is parsed greedily and applies to the whole predicate,
6084 // the bounded type can have its own `for` applying only to it.
6085 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
6086 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
6087 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
6088 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
6090 // Parse type with mandatory colon and (possibly empty) bounds,
6091 // or with mandatory equality sign and the second type.
6092 let ty = self.parse_ty()?;
6093 if self.eat(&token::Colon) {
6094 let bounds = self.parse_generic_bounds(None)?;
6095 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
6096 ast::WhereBoundPredicate {
6097 span: lo.to(self.prev_span),
6098 bound_generic_params: lifetime_defs,
6103 // FIXME: Decide what should be used here, `=` or `==`.
6104 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
6105 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
6106 let rhs_ty = self.parse_ty()?;
6107 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
6108 ast::WhereEqPredicate {
6109 span: lo.to(self.prev_span),
6112 id: ast::DUMMY_NODE_ID,
6116 return self.unexpected();
6122 if !self.eat(&token::Comma) {
6127 where_clause.span = lo.to(self.prev_span);
6131 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
6132 -> PResult<'a, (Vec<Arg> , bool)> {
6133 self.expect(&token::OpenDelim(token::Paren))?;
6136 let mut c_variadic = false;
6137 let (args, recovered): (Vec<Option<Arg>>, bool) =
6138 self.parse_seq_to_before_end(
6139 &token::CloseDelim(token::Paren),
6140 SeqSep::trailing_allowed(token::Comma),
6142 // If the argument is a C-variadic argument we should not
6143 // enforce named arguments.
6144 let enforce_named_args = if p.token == token::DotDotDot {
6149 match p.parse_arg_general(enforce_named_args, false,
6152 if let TyKind::CVarArgs = arg.ty.node {
6154 if p.token != token::CloseDelim(token::Paren) {
6157 "`...` must be the last argument of a C-variadic function");
6168 let lo = p.prev_span;
6169 // Skip every token until next possible arg or end.
6170 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
6171 // Create a placeholder argument for proper arg count (issue #34264).
6172 let span = lo.to(p.prev_span);
6173 Ok(Some(dummy_arg(span)))
6180 self.eat(&token::CloseDelim(token::Paren));
6183 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
6185 if c_variadic && args.is_empty() {
6187 "C-variadic function must be declared with at least one named argument");
6190 Ok((args, c_variadic))
6193 /// Parses the argument list and result type of a function declaration.
6194 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
6196 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
6197 let ret_ty = self.parse_ret_ty(true)?;
6206 /// Returns the parsed optional self argument and whether a self shortcut was used.
6207 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
6208 let expect_ident = |this: &mut Self| match this.token {
6209 // Preserve hygienic context.
6210 token::Ident(ident, _) =>
6211 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
6214 let isolated_self = |this: &mut Self, n| {
6215 this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) &&
6216 this.look_ahead(n + 1, |t| t != &token::ModSep)
6219 // Parse optional self parameter of a method.
6220 // Only a limited set of initial token sequences is considered self parameters, anything
6221 // else is parsed as a normal function parameter list, so some lookahead is required.
6222 let eself_lo = self.span;
6223 let (eself, eself_ident, eself_hi) = match self.token {
6224 token::BinOp(token::And) => {
6230 (if isolated_self(self, 1) {
6232 SelfKind::Region(None, Mutability::Immutable)
6233 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
6234 isolated_self(self, 2) {
6237 SelfKind::Region(None, Mutability::Mutable)
6238 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6239 isolated_self(self, 2) {
6241 let lt = self.expect_lifetime();
6242 SelfKind::Region(Some(lt), Mutability::Immutable)
6243 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6244 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
6245 isolated_self(self, 3) {
6247 let lt = self.expect_lifetime();
6249 SelfKind::Region(Some(lt), Mutability::Mutable)
6252 }, expect_ident(self), self.prev_span)
6254 token::BinOp(token::Star) => {
6259 // Emit special error for `self` cases.
6260 let msg = "cannot pass `self` by raw pointer";
6261 (if isolated_self(self, 1) {
6263 self.struct_span_err(self.span, msg)
6264 .span_label(self.span, msg)
6266 SelfKind::Value(Mutability::Immutable)
6267 } else if self.look_ahead(1, |t| t.is_mutability()) &&
6268 isolated_self(self, 2) {
6271 self.struct_span_err(self.span, msg)
6272 .span_label(self.span, msg)
6274 SelfKind::Value(Mutability::Immutable)
6277 }, expect_ident(self), self.prev_span)
6279 token::Ident(..) => {
6280 if isolated_self(self, 0) {
6283 let eself_ident = expect_ident(self);
6284 let eself_hi = self.prev_span;
6285 (if self.eat(&token::Colon) {
6286 let ty = self.parse_ty()?;
6287 SelfKind::Explicit(ty, Mutability::Immutable)
6289 SelfKind::Value(Mutability::Immutable)
6290 }, eself_ident, eself_hi)
6291 } else if self.token.is_keyword(keywords::Mut) &&
6292 isolated_self(self, 1) {
6296 let eself_ident = expect_ident(self);
6297 let eself_hi = self.prev_span;
6298 (if self.eat(&token::Colon) {
6299 let ty = self.parse_ty()?;
6300 SelfKind::Explicit(ty, Mutability::Mutable)
6302 SelfKind::Value(Mutability::Mutable)
6303 }, eself_ident, eself_hi)
6308 _ => return Ok(None),
6311 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
6312 Ok(Some(Arg::from_self(eself, eself_ident)))
6315 /// Parses the parameter list and result type of a function that may have a `self` parameter.
6316 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
6317 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
6319 self.expect(&token::OpenDelim(token::Paren))?;
6321 // Parse optional self argument
6322 let self_arg = self.parse_self_arg()?;
6324 // Parse the rest of the function parameter list.
6325 let sep = SeqSep::trailing_allowed(token::Comma);
6326 let (fn_inputs, recovered) = if let Some(self_arg) = self_arg {
6327 if self.check(&token::CloseDelim(token::Paren)) {
6328 (vec![self_arg], false)
6329 } else if self.eat(&token::Comma) {
6330 let mut fn_inputs = vec![self_arg];
6331 let (mut input, recovered) = self.parse_seq_to_before_end(
6332 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
6333 fn_inputs.append(&mut input);
6334 (fn_inputs, recovered)
6336 return self.unexpected();
6339 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
6343 // Parse closing paren and return type.
6344 self.expect(&token::CloseDelim(token::Paren))?;
6348 output: self.parse_ret_ty(true)?,
6353 /// Parses the `|arg, arg|` header of a closure.
6354 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
6355 let inputs_captures = {
6356 if self.eat(&token::OrOr) {
6359 self.expect(&token::BinOp(token::Or))?;
6360 let args = self.parse_seq_to_before_tokens(
6361 &[&token::BinOp(token::Or), &token::OrOr],
6362 SeqSep::trailing_allowed(token::Comma),
6363 TokenExpectType::NoExpect,
6364 |p| p.parse_fn_block_arg()
6370 let output = self.parse_ret_ty(true)?;
6373 inputs: inputs_captures,
6379 /// Parses the name and optional generic types of a function header.
6380 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
6381 let id = self.parse_ident()?;
6382 let generics = self.parse_generics()?;
6386 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
6387 attrs: Vec<Attribute>) -> P<Item> {
6391 id: ast::DUMMY_NODE_ID,
6399 /// Parses an item-position function declaration.
6400 fn parse_item_fn(&mut self,
6402 asyncness: Spanned<IsAsync>,
6403 constness: Spanned<Constness>,
6405 -> PResult<'a, ItemInfo> {
6406 let (ident, mut generics) = self.parse_fn_header()?;
6407 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
6408 let decl = self.parse_fn_decl(allow_c_variadic)?;
6409 generics.where_clause = self.parse_where_clause()?;
6410 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6411 let header = FnHeader { unsafety, asyncness, constness, abi };
6412 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
6415 /// Returns `true` if we are looking at `const ID`
6416 /// (returns `false` for things like `const fn`, etc.).
6417 fn is_const_item(&mut self) -> bool {
6418 self.token.is_keyword(keywords::Const) &&
6419 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
6420 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
6423 /// Parses all the "front matter" for a `fn` declaration, up to
6424 /// and including the `fn` keyword:
6428 /// - `const unsafe fn`
6431 fn parse_fn_front_matter(&mut self)
6439 let is_const_fn = self.eat_keyword(keywords::Const);
6440 let const_span = self.prev_span;
6441 let unsafety = self.parse_unsafety();
6442 let asyncness = self.parse_asyncness();
6443 let asyncness = respan(self.prev_span, asyncness);
6444 let (constness, unsafety, abi) = if is_const_fn {
6445 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
6447 let abi = if self.eat_keyword(keywords::Extern) {
6448 self.parse_opt_abi()?.unwrap_or(Abi::C)
6452 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
6454 self.expect_keyword(keywords::Fn)?;
6455 Ok((constness, unsafety, asyncness, abi))
6458 /// Parses an impl item.
6459 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
6460 maybe_whole!(self, NtImplItem, |x| x);
6461 let attrs = self.parse_outer_attributes()?;
6462 let (mut item, tokens) = self.collect_tokens(|this| {
6463 this.parse_impl_item_(at_end, attrs)
6466 // See `parse_item` for why this clause is here.
6467 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6468 item.tokens = Some(tokens);
6473 fn parse_impl_item_(&mut self,
6475 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
6477 let vis = self.parse_visibility(false)?;
6478 let defaultness = self.parse_defaultness();
6479 let (name, node, generics) = if let Some(type_) = self.eat_type() {
6480 let (name, alias, generics) = type_?;
6481 let kind = match alias {
6482 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
6483 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
6485 (name, kind, generics)
6486 } else if self.is_const_item() {
6487 // This parses the grammar:
6488 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
6489 self.expect_keyword(keywords::Const)?;
6490 let name = self.parse_ident()?;
6491 self.expect(&token::Colon)?;
6492 let typ = self.parse_ty()?;
6493 self.expect(&token::Eq)?;
6494 let expr = self.parse_expr()?;
6495 self.expect(&token::Semi)?;
6496 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
6498 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
6499 attrs.extend(inner_attrs);
6500 (name, node, generics)
6504 id: ast::DUMMY_NODE_ID,
6505 span: lo.to(self.prev_span),
6516 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
6518 VisibilityKind::Inherited => {}
6520 let is_macro_rules: bool = match self.token {
6521 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
6524 let mut err = if is_macro_rules {
6525 let mut err = self.diagnostic()
6526 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
6527 err.span_suggestion(
6529 "try exporting the macro",
6530 "#[macro_export]".to_owned(),
6531 Applicability::MaybeIncorrect // speculative
6535 let mut err = self.diagnostic()
6536 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
6537 err.help("try adjusting the macro to put `pub` inside the invocation");
6545 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
6546 -> DiagnosticBuilder<'a>
6548 let expected_kinds = if item_type == "extern" {
6549 "missing `fn`, `type`, or `static`"
6551 "missing `fn`, `type`, or `const`"
6554 // Given this code `path(`, it seems like this is not
6555 // setting the visibility of a macro invocation, but rather
6556 // a mistyped method declaration.
6557 // Create a diagnostic pointing out that `fn` is missing.
6559 // x | pub path(&self) {
6560 // | ^ missing `fn`, `type`, or `const`
6562 // ^^ `sp` below will point to this
6563 let sp = prev_span.between(self.prev_span);
6564 let mut err = self.diagnostic().struct_span_err(
6566 &format!("{} for {}-item declaration",
6567 expected_kinds, item_type));
6568 err.span_label(sp, expected_kinds);
6572 /// Parse a method or a macro invocation in a trait impl.
6573 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
6574 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
6575 ast::ImplItemKind)> {
6576 // code copied from parse_macro_use_or_failure... abstraction!
6577 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
6579 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
6580 ast::ImplItemKind::Macro(mac)))
6582 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
6583 let ident = self.parse_ident()?;
6584 let mut generics = self.parse_generics()?;
6585 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
6586 generics.where_clause = self.parse_where_clause()?;
6588 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6589 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
6590 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
6591 ast::MethodSig { header, decl },
6597 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
6598 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
6599 let ident = self.parse_ident()?;
6600 let mut tps = self.parse_generics()?;
6602 // Parse optional colon and supertrait bounds.
6603 let bounds = if self.eat(&token::Colon) {
6604 self.parse_generic_bounds(Some(self.prev_span))?
6609 if self.eat(&token::Eq) {
6610 // it's a trait alias
6611 let bounds = self.parse_generic_bounds(None)?;
6612 tps.where_clause = self.parse_where_clause()?;
6613 self.expect(&token::Semi)?;
6614 if is_auto == IsAuto::Yes {
6615 let msg = "trait aliases cannot be `auto`";
6616 self.struct_span_err(self.prev_span, msg)
6617 .span_label(self.prev_span, msg)
6620 if unsafety != Unsafety::Normal {
6621 let msg = "trait aliases cannot be `unsafe`";
6622 self.struct_span_err(self.prev_span, msg)
6623 .span_label(self.prev_span, msg)
6626 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
6628 // it's a normal trait
6629 tps.where_clause = self.parse_where_clause()?;
6630 self.expect(&token::OpenDelim(token::Brace))?;
6631 let mut trait_items = vec![];
6632 while !self.eat(&token::CloseDelim(token::Brace)) {
6633 let mut at_end = false;
6634 match self.parse_trait_item(&mut at_end) {
6635 Ok(item) => trait_items.push(item),
6639 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6644 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
6648 fn choose_generics_over_qpath(&self) -> bool {
6649 // There's an ambiguity between generic parameters and qualified paths in impls.
6650 // If we see `<` it may start both, so we have to inspect some following tokens.
6651 // The following combinations can only start generics,
6652 // but not qualified paths (with one exception):
6653 // `<` `>` - empty generic parameters
6654 // `<` `#` - generic parameters with attributes
6655 // `<` (LIFETIME|IDENT) `>` - single generic parameter
6656 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
6657 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
6658 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
6659 // `<` const - generic const parameter
6660 // The only truly ambiguous case is
6661 // `<` IDENT `>` `::` IDENT ...
6662 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
6663 // because this is what almost always expected in practice, qualified paths in impls
6664 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
6665 self.token == token::Lt &&
6666 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
6667 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
6668 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
6669 t == &token::Colon || t == &token::Eq) ||
6670 self.look_ahead(1, |t| t.is_keyword(keywords::Const)))
6673 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6674 self.expect(&token::OpenDelim(token::Brace))?;
6675 let attrs = self.parse_inner_attributes()?;
6677 let mut impl_items = Vec::new();
6678 while !self.eat(&token::CloseDelim(token::Brace)) {
6679 let mut at_end = false;
6680 match self.parse_impl_item(&mut at_end) {
6681 Ok(impl_item) => impl_items.push(impl_item),
6685 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6690 Ok((impl_items, attrs))
6693 /// Parses an implementation item, `impl` keyword is already parsed.
6695 /// impl<'a, T> TYPE { /* impl items */ }
6696 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6697 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6699 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6700 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6701 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6702 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6703 -> PResult<'a, ItemInfo> {
6704 // First, parse generic parameters if necessary.
6705 let mut generics = if self.choose_generics_over_qpath() {
6706 self.parse_generics()?
6708 ast::Generics::default()
6711 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6712 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6714 ast::ImplPolarity::Negative
6716 ast::ImplPolarity::Positive
6719 // Parse both types and traits as a type, then reinterpret if necessary.
6720 let ty_first = self.parse_ty()?;
6722 // If `for` is missing we try to recover.
6723 let has_for = self.eat_keyword(keywords::For);
6724 let missing_for_span = self.prev_span.between(self.span);
6726 let ty_second = if self.token == token::DotDot {
6727 // We need to report this error after `cfg` expansion for compatibility reasons
6728 self.bump(); // `..`, do not add it to expected tokens
6729 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
6730 } else if has_for || self.token.can_begin_type() {
6731 Some(self.parse_ty()?)
6736 generics.where_clause = self.parse_where_clause()?;
6738 let (impl_items, attrs) = self.parse_impl_body()?;
6740 let item_kind = match ty_second {
6741 Some(ty_second) => {
6742 // impl Trait for Type
6744 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6745 .span_suggestion_short(
6748 " for ".to_string(),
6749 Applicability::MachineApplicable,
6753 let ty_first = ty_first.into_inner();
6754 let path = match ty_first.node {
6755 // This notably includes paths passed through `ty` macro fragments (#46438).
6756 TyKind::Path(None, path) => path,
6758 self.span_err(ty_first.span, "expected a trait, found type");
6759 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
6762 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6764 ItemKind::Impl(unsafety, polarity, defaultness,
6765 generics, Some(trait_ref), ty_second, impl_items)
6769 ItemKind::Impl(unsafety, polarity, defaultness,
6770 generics, None, ty_first, impl_items)
6774 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
6777 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6778 if self.eat_keyword(keywords::For) {
6780 let params = self.parse_generic_params()?;
6782 // We rely on AST validation to rule out invalid cases: There must not be type
6783 // parameters, and the lifetime parameters must not have bounds.
6790 /// Parses `struct Foo { ... }`.
6791 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6792 let class_name = self.parse_ident()?;
6794 let mut generics = self.parse_generics()?;
6796 // There is a special case worth noting here, as reported in issue #17904.
6797 // If we are parsing a tuple struct it is the case that the where clause
6798 // should follow the field list. Like so:
6800 // struct Foo<T>(T) where T: Copy;
6802 // If we are parsing a normal record-style struct it is the case
6803 // that the where clause comes before the body, and after the generics.
6804 // So if we look ahead and see a brace or a where-clause we begin
6805 // parsing a record style struct.
6807 // Otherwise if we look ahead and see a paren we parse a tuple-style
6810 let vdata = if self.token.is_keyword(keywords::Where) {
6811 generics.where_clause = self.parse_where_clause()?;
6812 if self.eat(&token::Semi) {
6813 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6814 VariantData::Unit(ast::DUMMY_NODE_ID)
6816 // If we see: `struct Foo<T> where T: Copy { ... }`
6817 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6819 // No `where` so: `struct Foo<T>;`
6820 } else if self.eat(&token::Semi) {
6821 VariantData::Unit(ast::DUMMY_NODE_ID)
6822 // Record-style struct definition
6823 } else if self.token == token::OpenDelim(token::Brace) {
6824 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6825 // Tuple-style struct definition with optional where-clause.
6826 } else if self.token == token::OpenDelim(token::Paren) {
6827 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6828 generics.where_clause = self.parse_where_clause()?;
6829 self.expect(&token::Semi)?;
6832 let token_str = self.this_token_descr();
6833 let mut err = self.fatal(&format!(
6834 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6837 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6841 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6844 /// Parses `union Foo { ... }`.
6845 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6846 let class_name = self.parse_ident()?;
6848 let mut generics = self.parse_generics()?;
6850 let vdata = if self.token.is_keyword(keywords::Where) {
6851 generics.where_clause = self.parse_where_clause()?;
6852 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6853 } else if self.token == token::OpenDelim(token::Brace) {
6854 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6856 let token_str = self.this_token_descr();
6857 let mut err = self.fatal(&format!(
6858 "expected `where` or `{{` after union name, found {}", token_str));
6859 err.span_label(self.span, "expected `where` or `{` after union name");
6863 Ok((class_name, ItemKind::Union(vdata, generics), None))
6866 fn consume_block(&mut self, delim: token::DelimToken) {
6867 let mut brace_depth = 0;
6869 if self.eat(&token::OpenDelim(delim)) {
6871 } else if self.eat(&token::CloseDelim(delim)) {
6872 if brace_depth == 0 {
6878 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
6886 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6887 let mut fields = Vec::new();
6888 if self.eat(&token::OpenDelim(token::Brace)) {
6889 while self.token != token::CloseDelim(token::Brace) {
6890 let field = self.parse_struct_decl_field().map_err(|e| {
6891 self.recover_stmt();
6895 Ok(field) => fields.push(field),
6901 self.eat(&token::CloseDelim(token::Brace));
6903 let token_str = self.this_token_descr();
6904 let mut err = self.fatal(&format!(
6905 "expected `where`, or `{{` after struct name, found {}", token_str));
6906 err.span_label(self.span, "expected `where`, or `{` after struct name");
6913 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6914 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6915 // Unit like structs are handled in parse_item_struct function
6916 let fields = self.parse_unspanned_seq(
6917 &token::OpenDelim(token::Paren),
6918 &token::CloseDelim(token::Paren),
6919 SeqSep::trailing_allowed(token::Comma),
6921 let attrs = p.parse_outer_attributes()?;
6923 let vis = p.parse_visibility(true)?;
6924 let ty = p.parse_ty()?;
6926 span: lo.to(ty.span),
6929 id: ast::DUMMY_NODE_ID,
6938 /// Parses a structure field declaration.
6939 fn parse_single_struct_field(&mut self,
6942 attrs: Vec<Attribute> )
6943 -> PResult<'a, StructField> {
6944 let mut seen_comma: bool = false;
6945 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6946 if self.token == token::Comma {
6953 token::CloseDelim(token::Brace) => {}
6954 token::DocComment(_) => {
6955 let previous_span = self.prev_span;
6956 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6957 self.bump(); // consume the doc comment
6958 let comma_after_doc_seen = self.eat(&token::Comma);
6959 // `seen_comma` is always false, because we are inside doc block
6960 // condition is here to make code more readable
6961 if seen_comma == false && comma_after_doc_seen == true {
6964 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6967 if seen_comma == false {
6968 let sp = self.sess.source_map().next_point(previous_span);
6969 err.span_suggestion(
6971 "missing comma here",
6973 Applicability::MachineApplicable
6980 let sp = self.sess.source_map().next_point(self.prev_span);
6981 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
6982 self.this_token_descr()));
6983 if self.token.is_ident() {
6984 // This is likely another field; emit the diagnostic and keep going
6985 err.span_suggestion(
6987 "try adding a comma",
6989 Applicability::MachineApplicable,
7000 /// Parses an element of a struct declaration.
7001 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
7002 let attrs = self.parse_outer_attributes()?;
7004 let vis = self.parse_visibility(false)?;
7005 self.parse_single_struct_field(lo, vis, attrs)
7008 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
7009 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
7010 /// If the following element can't be a tuple (i.e., it's a function definition), then
7011 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
7012 /// so emit a proper diagnostic.
7013 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
7014 maybe_whole!(self, NtVis, |x| x);
7016 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
7017 if self.is_crate_vis() {
7018 self.bump(); // `crate`
7019 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
7022 if !self.eat_keyword(keywords::Pub) {
7023 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
7024 // keyword to grab a span from for inherited visibility; an empty span at the
7025 // beginning of the current token would seem to be the "Schelling span".
7026 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
7028 let lo = self.prev_span;
7030 if self.check(&token::OpenDelim(token::Paren)) {
7031 // We don't `self.bump()` the `(` yet because this might be a struct definition where
7032 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
7033 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
7034 // by the following tokens.
7035 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
7038 self.bump(); // `crate`
7039 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7041 lo.to(self.prev_span),
7042 VisibilityKind::Crate(CrateSugar::PubCrate),
7045 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
7048 self.bump(); // `in`
7049 let path = self.parse_path(PathStyle::Mod)?; // `path`
7050 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7051 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7053 id: ast::DUMMY_NODE_ID,
7056 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
7057 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
7058 t.is_keyword(keywords::SelfLower))
7060 // `pub(self)` or `pub(super)`
7062 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
7063 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7064 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7066 id: ast::DUMMY_NODE_ID,
7069 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
7070 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
7072 let msg = "incorrect visibility restriction";
7073 let suggestion = r##"some possible visibility restrictions are:
7074 `pub(crate)`: visible only on the current crate
7075 `pub(super)`: visible only in the current module's parent
7076 `pub(in path::to::module)`: visible only on the specified path"##;
7077 let path = self.parse_path(PathStyle::Mod)?;
7078 let sp = self.prev_span;
7079 let help_msg = format!("make this visible only to module `{}` with `in`", path);
7080 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7081 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
7082 err.help(suggestion);
7083 err.span_suggestion(
7084 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
7086 err.emit(); // emit diagnostic, but continue with public visibility
7090 Ok(respan(lo, VisibilityKind::Public))
7093 /// Parses defaultness (i.e., `default` or nothing).
7094 fn parse_defaultness(&mut self) -> Defaultness {
7095 // `pub` is included for better error messages
7096 if self.check_keyword(keywords::Default) &&
7097 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
7098 t.is_keyword(keywords::Const) ||
7099 t.is_keyword(keywords::Fn) ||
7100 t.is_keyword(keywords::Unsafe) ||
7101 t.is_keyword(keywords::Extern) ||
7102 t.is_keyword(keywords::Type) ||
7103 t.is_keyword(keywords::Pub)) {
7104 self.bump(); // `default`
7105 Defaultness::Default
7111 fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
7112 if self.eat(&token::Semi) {
7113 let mut err = self.struct_span_err(self.prev_span, "expected item, found `;`");
7114 err.span_suggestion_short(
7116 "remove this semicolon",
7118 Applicability::MachineApplicable,
7120 if !items.is_empty() {
7121 let previous_item = &items[items.len()-1];
7122 let previous_item_kind_name = match previous_item.node {
7123 // say "braced struct" because tuple-structs and
7124 // braceless-empty-struct declarations do take a semicolon
7125 ItemKind::Struct(..) => Some("braced struct"),
7126 ItemKind::Enum(..) => Some("enum"),
7127 ItemKind::Trait(..) => Some("trait"),
7128 ItemKind::Union(..) => Some("union"),
7131 if let Some(name) = previous_item_kind_name {
7132 err.help(&format!("{} declarations are not followed by a semicolon", name));
7142 /// Given a termination token, parses all of the items in a module.
7143 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
7144 let mut items = vec![];
7145 while let Some(item) = self.parse_item()? {
7147 self.maybe_consume_incorrect_semicolon(&items);
7150 if !self.eat(term) {
7151 let token_str = self.this_token_descr();
7152 if !self.maybe_consume_incorrect_semicolon(&items) {
7153 let mut err = self.fatal(&format!("expected item, found {}", token_str));
7154 err.span_label(self.span, "expected item");
7159 let hi = if self.span.is_dummy() {
7166 inner: inner_lo.to(hi),
7172 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
7173 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
7174 self.expect(&token::Colon)?;
7175 let ty = self.parse_ty()?;
7176 self.expect(&token::Eq)?;
7177 let e = self.parse_expr()?;
7178 self.expect(&token::Semi)?;
7179 let item = match m {
7180 Some(m) => ItemKind::Static(ty, m, e),
7181 None => ItemKind::Const(ty, e),
7183 Ok((id, item, None))
7186 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
7187 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
7188 let (in_cfg, outer_attrs) = {
7189 let mut strip_unconfigured = crate::config::StripUnconfigured {
7191 features: None, // don't perform gated feature checking
7193 let mut outer_attrs = outer_attrs.to_owned();
7194 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
7195 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
7198 let id_span = self.span;
7199 let id = self.parse_ident()?;
7200 if self.eat(&token::Semi) {
7201 if in_cfg && self.recurse_into_file_modules {
7202 // This mod is in an external file. Let's go get it!
7203 let ModulePathSuccess { path, directory_ownership, warn } =
7204 self.submod_path(id, &outer_attrs, id_span)?;
7205 let (module, mut attrs) =
7206 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
7207 // Record that we fetched the mod from an external file
7209 let attr = Attribute {
7210 id: attr::mk_attr_id(),
7211 style: ast::AttrStyle::Outer,
7212 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
7213 tokens: TokenStream::empty(),
7214 is_sugared_doc: false,
7215 span: syntax_pos::DUMMY_SP,
7217 attr::mark_known(&attr);
7220 Ok((id, ItemKind::Mod(module), Some(attrs)))
7222 let placeholder = ast::Mod {
7223 inner: syntax_pos::DUMMY_SP,
7227 Ok((id, ItemKind::Mod(placeholder), None))
7230 let old_directory = self.directory.clone();
7231 self.push_directory(id, &outer_attrs);
7233 self.expect(&token::OpenDelim(token::Brace))?;
7234 let mod_inner_lo = self.span;
7235 let attrs = self.parse_inner_attributes()?;
7236 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
7238 self.directory = old_directory;
7239 Ok((id, ItemKind::Mod(module), Some(attrs)))
7243 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
7244 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
7245 self.directory.path.to_mut().push(&path.as_str());
7246 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
7248 // We have to push on the current module name in the case of relative
7249 // paths in order to ensure that any additional module paths from inline
7250 // `mod x { ... }` come after the relative extension.
7252 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
7253 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
7254 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
7255 if let Some(ident) = relative.take() { // remove the relative offset
7256 self.directory.path.to_mut().push(ident.as_str());
7259 self.directory.path.to_mut().push(&id.as_str());
7263 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
7264 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
7267 // On windows, the base path might have the form
7268 // `\\?\foo\bar` in which case it does not tolerate
7269 // mixed `/` and `\` separators, so canonicalize
7272 let s = s.replace("/", "\\");
7273 Some(dir_path.join(s))
7279 /// Returns a path to a module.
7280 pub fn default_submod_path(
7282 relative: Option<ast::Ident>,
7284 source_map: &SourceMap) -> ModulePath
7286 // If we're in a foo.rs file instead of a mod.rs file,
7287 // we need to look for submodules in
7288 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
7289 // `./<id>.rs` and `./<id>/mod.rs`.
7290 let relative_prefix_string;
7291 let relative_prefix = if let Some(ident) = relative {
7292 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
7293 &relative_prefix_string
7298 let mod_name = id.to_string();
7299 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
7300 let secondary_path_str = format!("{}{}{}mod.rs",
7301 relative_prefix, mod_name, path::MAIN_SEPARATOR);
7302 let default_path = dir_path.join(&default_path_str);
7303 let secondary_path = dir_path.join(&secondary_path_str);
7304 let default_exists = source_map.file_exists(&default_path);
7305 let secondary_exists = source_map.file_exists(&secondary_path);
7307 let result = match (default_exists, secondary_exists) {
7308 (true, false) => Ok(ModulePathSuccess {
7310 directory_ownership: DirectoryOwnership::Owned {
7315 (false, true) => Ok(ModulePathSuccess {
7316 path: secondary_path,
7317 directory_ownership: DirectoryOwnership::Owned {
7322 (false, false) => Err(Error::FileNotFoundForModule {
7323 mod_name: mod_name.clone(),
7324 default_path: default_path_str,
7325 secondary_path: secondary_path_str,
7326 dir_path: dir_path.display().to_string(),
7328 (true, true) => Err(Error::DuplicatePaths {
7329 mod_name: mod_name.clone(),
7330 default_path: default_path_str,
7331 secondary_path: secondary_path_str,
7337 path_exists: default_exists || secondary_exists,
7342 fn submod_path(&mut self,
7344 outer_attrs: &[Attribute],
7346 -> PResult<'a, ModulePathSuccess> {
7347 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
7348 return Ok(ModulePathSuccess {
7349 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
7350 // All `#[path]` files are treated as though they are a `mod.rs` file.
7351 // This means that `mod foo;` declarations inside `#[path]`-included
7352 // files are siblings,
7354 // Note that this will produce weirdness when a file named `foo.rs` is
7355 // `#[path]` included and contains a `mod foo;` declaration.
7356 // If you encounter this, it's your own darn fault :P
7357 Some(_) => DirectoryOwnership::Owned { relative: None },
7358 _ => DirectoryOwnership::UnownedViaMod(true),
7365 let relative = match self.directory.ownership {
7366 DirectoryOwnership::Owned { relative } => relative,
7367 DirectoryOwnership::UnownedViaBlock |
7368 DirectoryOwnership::UnownedViaMod(_) => None,
7370 let paths = Parser::default_submod_path(
7371 id, relative, &self.directory.path, self.sess.source_map());
7373 match self.directory.ownership {
7374 DirectoryOwnership::Owned { .. } => {
7375 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
7377 DirectoryOwnership::UnownedViaBlock => {
7379 "Cannot declare a non-inline module inside a block \
7380 unless it has a path attribute";
7381 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
7382 if paths.path_exists {
7383 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
7385 err.span_note(id_sp, &msg);
7389 DirectoryOwnership::UnownedViaMod(warn) => {
7391 if let Ok(result) = paths.result {
7392 return Ok(ModulePathSuccess { warn: true, ..result });
7395 let mut err = self.diagnostic().struct_span_err(id_sp,
7396 "cannot declare a new module at this location");
7397 if !id_sp.is_dummy() {
7398 let src_path = self.sess.source_map().span_to_filename(id_sp);
7399 if let FileName::Real(src_path) = src_path {
7400 if let Some(stem) = src_path.file_stem() {
7401 let mut dest_path = src_path.clone();
7402 dest_path.set_file_name(stem);
7403 dest_path.push("mod.rs");
7404 err.span_note(id_sp,
7405 &format!("maybe move this module `{}` to its own \
7406 directory via `{}`", src_path.display(),
7407 dest_path.display()));
7411 if paths.path_exists {
7412 err.span_note(id_sp,
7413 &format!("... or maybe `use` the module `{}` instead \
7414 of possibly redeclaring it",
7422 /// Reads a module from a source file.
7423 fn eval_src_mod(&mut self,
7425 directory_ownership: DirectoryOwnership,
7428 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
7429 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
7430 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
7431 let mut err = String::from("circular modules: ");
7432 let len = included_mod_stack.len();
7433 for p in &included_mod_stack[i.. len] {
7434 err.push_str(&p.to_string_lossy());
7435 err.push_str(" -> ");
7437 err.push_str(&path.to_string_lossy());
7438 return Err(self.span_fatal(id_sp, &err[..]));
7440 included_mod_stack.push(path.clone());
7441 drop(included_mod_stack);
7444 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
7445 p0.cfg_mods = self.cfg_mods;
7446 let mod_inner_lo = p0.span;
7447 let mod_attrs = p0.parse_inner_attributes()?;
7448 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
7450 self.sess.included_mod_stack.borrow_mut().pop();
7454 /// Parses a function declaration from a foreign module.
7455 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7456 -> PResult<'a, ForeignItem> {
7457 self.expect_keyword(keywords::Fn)?;
7459 let (ident, mut generics) = self.parse_fn_header()?;
7460 let decl = self.parse_fn_decl(true)?;
7461 generics.where_clause = self.parse_where_clause()?;
7463 self.expect(&token::Semi)?;
7464 Ok(ast::ForeignItem {
7467 node: ForeignItemKind::Fn(decl, generics),
7468 id: ast::DUMMY_NODE_ID,
7474 /// Parses a static item from a foreign module.
7475 /// Assumes that the `static` keyword is already parsed.
7476 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7477 -> PResult<'a, ForeignItem> {
7478 let mutbl = self.eat_keyword(keywords::Mut);
7479 let ident = self.parse_ident()?;
7480 self.expect(&token::Colon)?;
7481 let ty = self.parse_ty()?;
7483 self.expect(&token::Semi)?;
7487 node: ForeignItemKind::Static(ty, mutbl),
7488 id: ast::DUMMY_NODE_ID,
7494 /// Parses a type from a foreign module.
7495 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7496 -> PResult<'a, ForeignItem> {
7497 self.expect_keyword(keywords::Type)?;
7499 let ident = self.parse_ident()?;
7501 self.expect(&token::Semi)?;
7502 Ok(ast::ForeignItem {
7505 node: ForeignItemKind::Ty,
7506 id: ast::DUMMY_NODE_ID,
7512 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
7513 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
7514 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
7516 let mut ident = if self.token.is_keyword(keywords::SelfLower) {
7517 self.parse_path_segment_ident()
7521 let mut idents = vec![];
7522 let mut replacement = vec![];
7523 let mut fixed_crate_name = false;
7524 // Accept `extern crate name-like-this` for better diagnostics
7525 let dash = token::Token::BinOp(token::BinOpToken::Minus);
7526 if self.token == dash { // Do not include `-` as part of the expected tokens list
7527 while self.eat(&dash) {
7528 fixed_crate_name = true;
7529 replacement.push((self.prev_span, "_".to_string()));
7530 idents.push(self.parse_ident()?);
7533 if fixed_crate_name {
7534 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
7535 let mut fixed_name = format!("{}", ident.name);
7536 for part in idents {
7537 fixed_name.push_str(&format!("_{}", part.name));
7539 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
7541 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
7542 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
7543 err.multipart_suggestion(
7546 Applicability::MachineApplicable,
7553 /// Parses `extern crate` links.
7558 /// extern crate foo;
7559 /// extern crate bar as foo;
7561 fn parse_item_extern_crate(&mut self,
7563 visibility: Visibility,
7564 attrs: Vec<Attribute>)
7565 -> PResult<'a, P<Item>> {
7566 // Accept `extern crate name-like-this` for better diagnostics
7567 let orig_name = self.parse_crate_name_with_dashes()?;
7568 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
7569 (rename, Some(orig_name.name))
7573 self.expect(&token::Semi)?;
7575 let span = lo.to(self.prev_span);
7576 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
7579 /// Parses `extern` for foreign ABIs modules.
7581 /// `extern` is expected to have been
7582 /// consumed before calling this method.
7586 /// ```ignore (only-for-syntax-highlight)
7590 fn parse_item_foreign_mod(&mut self,
7592 opt_abi: Option<Abi>,
7593 visibility: Visibility,
7594 mut attrs: Vec<Attribute>)
7595 -> PResult<'a, P<Item>> {
7596 self.expect(&token::OpenDelim(token::Brace))?;
7598 let abi = opt_abi.unwrap_or(Abi::C);
7600 attrs.extend(self.parse_inner_attributes()?);
7602 let mut foreign_items = vec![];
7603 while !self.eat(&token::CloseDelim(token::Brace)) {
7604 foreign_items.push(self.parse_foreign_item()?);
7607 let prev_span = self.prev_span;
7608 let m = ast::ForeignMod {
7610 items: foreign_items
7612 let invalid = keywords::Invalid.ident();
7613 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
7616 /// Parses `type Foo = Bar;`
7618 /// `existential type Foo: Bar;`
7621 /// without modifying the parser state.
7622 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
7623 // This parses the grammar:
7624 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
7625 if self.check_keyword(keywords::Type) ||
7626 self.check_keyword(keywords::Existential) &&
7627 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
7628 let existential = self.eat_keyword(keywords::Existential);
7629 assert!(self.eat_keyword(keywords::Type));
7630 Some(self.parse_existential_or_alias(existential))
7636 /// Parses a type alias or existential type.
7637 fn parse_existential_or_alias(
7640 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
7641 let ident = self.parse_ident()?;
7642 let mut tps = self.parse_generics()?;
7643 tps.where_clause = self.parse_where_clause()?;
7644 let alias = if existential {
7645 self.expect(&token::Colon)?;
7646 let bounds = self.parse_generic_bounds(None)?;
7647 AliasKind::Existential(bounds)
7649 self.expect(&token::Eq)?;
7650 let ty = self.parse_ty()?;
7653 self.expect(&token::Semi)?;
7654 Ok((ident, alias, tps))
7657 /// Parses the part of an enum declaration following the `{`.
7658 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
7659 let mut variants = Vec::new();
7660 let mut all_nullary = true;
7661 let mut any_disr = vec![];
7662 while self.token != token::CloseDelim(token::Brace) {
7663 let variant_attrs = self.parse_outer_attributes()?;
7664 let vlo = self.span;
7667 let mut disr_expr = None;
7668 let ident = self.parse_ident()?;
7669 if self.check(&token::OpenDelim(token::Brace)) {
7670 // Parse a struct variant.
7671 all_nullary = false;
7672 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
7673 ast::DUMMY_NODE_ID);
7674 } else if self.check(&token::OpenDelim(token::Paren)) {
7675 all_nullary = false;
7676 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
7677 ast::DUMMY_NODE_ID);
7678 } else if self.eat(&token::Eq) {
7679 disr_expr = Some(AnonConst {
7680 id: ast::DUMMY_NODE_ID,
7681 value: self.parse_expr()?,
7683 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
7686 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7688 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7691 let vr = ast::Variant_ {
7693 attrs: variant_attrs,
7697 variants.push(respan(vlo.to(self.prev_span), vr));
7699 if !self.eat(&token::Comma) { break; }
7701 self.expect(&token::CloseDelim(token::Brace))?;
7702 if !any_disr.is_empty() && !all_nullary {
7703 let mut err =self.struct_span_err(
7705 "discriminator values can only be used with a field-less enum",
7707 for sp in any_disr {
7708 err.span_label(sp, "only valid in field-less enums");
7713 Ok(ast::EnumDef { variants })
7716 /// Parses an enum declaration.
7717 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7718 let id = self.parse_ident()?;
7719 let mut generics = self.parse_generics()?;
7720 generics.where_clause = self.parse_where_clause()?;
7721 self.expect(&token::OpenDelim(token::Brace))?;
7723 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7724 self.recover_stmt();
7725 self.eat(&token::CloseDelim(token::Brace));
7728 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7731 /// Parses a string as an ABI spec on an extern type or module. Consumes
7732 /// the `extern` keyword, if one is found.
7733 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7735 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
7737 self.expect_no_suffix(sp, "ABI spec", suf);
7739 match abi::lookup(&s.as_str()) {
7740 Some(abi) => Ok(Some(abi)),
7742 let prev_span = self.prev_span;
7743 let mut err = struct_span_err!(
7744 self.sess.span_diagnostic,
7747 "invalid ABI: found `{}`",
7749 err.span_label(prev_span, "invalid ABI");
7750 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7761 fn is_static_global(&mut self) -> bool {
7762 if self.check_keyword(keywords::Static) {
7763 // Check if this could be a closure
7764 !self.look_ahead(1, |token| {
7765 if token.is_keyword(keywords::Move) {
7769 token::BinOp(token::Or) | token::OrOr => true,
7780 attrs: Vec<Attribute>,
7781 macros_allowed: bool,
7782 attributes_allowed: bool,
7783 ) -> PResult<'a, Option<P<Item>>> {
7784 let (ret, tokens) = self.collect_tokens(|this| {
7785 this.parse_item_implementation(attrs, macros_allowed, attributes_allowed)
7788 // Once we've parsed an item and recorded the tokens we got while
7789 // parsing we may want to store `tokens` into the item we're about to
7790 // return. Note, though, that we specifically didn't capture tokens
7791 // related to outer attributes. The `tokens` field here may later be
7792 // used with procedural macros to convert this item back into a token
7793 // stream, but during expansion we may be removing attributes as we go
7796 // If we've got inner attributes then the `tokens` we've got above holds
7797 // these inner attributes. If an inner attribute is expanded we won't
7798 // actually remove it from the token stream, so we'll just keep yielding
7799 // it (bad!). To work around this case for now we just avoid recording
7800 // `tokens` if we detect any inner attributes. This should help keep
7801 // expansion correct, but we should fix this bug one day!
7804 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7805 i.tokens = Some(tokens);
7812 /// Parses one of the items allowed by the flags.
7813 fn parse_item_implementation(
7815 attrs: Vec<Attribute>,
7816 macros_allowed: bool,
7817 attributes_allowed: bool,
7818 ) -> PResult<'a, Option<P<Item>>> {
7819 maybe_whole!(self, NtItem, |item| {
7820 let mut item = item.into_inner();
7821 let mut attrs = attrs;
7822 mem::swap(&mut item.attrs, &mut attrs);
7823 item.attrs.extend(attrs);
7829 let visibility = self.parse_visibility(false)?;
7831 if self.eat_keyword(keywords::Use) {
7833 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7834 self.expect(&token::Semi)?;
7836 let span = lo.to(self.prev_span);
7837 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
7838 return Ok(Some(item));
7841 if self.eat_keyword(keywords::Extern) {
7842 if self.eat_keyword(keywords::Crate) {
7843 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7846 let opt_abi = self.parse_opt_abi()?;
7848 if self.eat_keyword(keywords::Fn) {
7849 // EXTERN FUNCTION ITEM
7850 let fn_span = self.prev_span;
7851 let abi = opt_abi.unwrap_or(Abi::C);
7852 let (ident, item_, extra_attrs) =
7853 self.parse_item_fn(Unsafety::Normal,
7854 respan(fn_span, IsAsync::NotAsync),
7855 respan(fn_span, Constness::NotConst),
7857 let prev_span = self.prev_span;
7858 let item = self.mk_item(lo.to(prev_span),
7862 maybe_append(attrs, extra_attrs));
7863 return Ok(Some(item));
7864 } else if self.check(&token::OpenDelim(token::Brace)) {
7865 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7871 if self.is_static_global() {
7874 let m = if self.eat_keyword(keywords::Mut) {
7877 Mutability::Immutable
7879 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7880 let prev_span = self.prev_span;
7881 let item = self.mk_item(lo.to(prev_span),
7885 maybe_append(attrs, extra_attrs));
7886 return Ok(Some(item));
7888 if self.eat_keyword(keywords::Const) {
7889 let const_span = self.prev_span;
7890 if self.check_keyword(keywords::Fn)
7891 || (self.check_keyword(keywords::Unsafe)
7892 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
7893 // CONST FUNCTION ITEM
7894 let unsafety = self.parse_unsafety();
7896 let (ident, item_, extra_attrs) =
7897 self.parse_item_fn(unsafety,
7898 respan(const_span, IsAsync::NotAsync),
7899 respan(const_span, Constness::Const),
7901 let prev_span = self.prev_span;
7902 let item = self.mk_item(lo.to(prev_span),
7906 maybe_append(attrs, extra_attrs));
7907 return Ok(Some(item));
7911 if self.eat_keyword(keywords::Mut) {
7912 let prev_span = self.prev_span;
7913 let mut err = self.diagnostic()
7914 .struct_span_err(prev_span, "const globals cannot be mutable");
7915 err.span_label(prev_span, "cannot be mutable");
7916 err.span_suggestion(
7918 "you might want to declare a static instead",
7919 "static".to_owned(),
7920 Applicability::MaybeIncorrect,
7924 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7925 let prev_span = self.prev_span;
7926 let item = self.mk_item(lo.to(prev_span),
7930 maybe_append(attrs, extra_attrs));
7931 return Ok(Some(item));
7934 // `unsafe async fn` or `async fn`
7936 self.check_keyword(keywords::Unsafe) &&
7937 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
7939 self.check_keyword(keywords::Async) &&
7940 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
7943 // ASYNC FUNCTION ITEM
7944 let unsafety = self.parse_unsafety();
7945 self.expect_keyword(keywords::Async)?;
7946 let async_span = self.prev_span;
7947 self.expect_keyword(keywords::Fn)?;
7948 let fn_span = self.prev_span;
7949 let (ident, item_, extra_attrs) =
7950 self.parse_item_fn(unsafety,
7951 respan(async_span, IsAsync::Async {
7952 closure_id: ast::DUMMY_NODE_ID,
7953 return_impl_trait_id: ast::DUMMY_NODE_ID,
7955 respan(fn_span, Constness::NotConst),
7957 let prev_span = self.prev_span;
7958 let item = self.mk_item(lo.to(prev_span),
7962 maybe_append(attrs, extra_attrs));
7963 if self.span.rust_2015() {
7964 self.diagnostic().struct_span_err_with_code(
7966 "`async fn` is not permitted in the 2015 edition",
7967 DiagnosticId::Error("E0670".into())
7970 return Ok(Some(item));
7972 if self.check_keyword(keywords::Unsafe) &&
7973 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
7974 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
7976 // UNSAFE TRAIT ITEM
7977 self.bump(); // `unsafe`
7978 let is_auto = if self.eat_keyword(keywords::Trait) {
7981 self.expect_keyword(keywords::Auto)?;
7982 self.expect_keyword(keywords::Trait)?;
7985 let (ident, item_, extra_attrs) =
7986 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7987 let prev_span = self.prev_span;
7988 let item = self.mk_item(lo.to(prev_span),
7992 maybe_append(attrs, extra_attrs));
7993 return Ok(Some(item));
7995 if self.check_keyword(keywords::Impl) ||
7996 self.check_keyword(keywords::Unsafe) &&
7997 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7998 self.check_keyword(keywords::Default) &&
7999 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8000 self.check_keyword(keywords::Default) &&
8001 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
8003 let defaultness = self.parse_defaultness();
8004 let unsafety = self.parse_unsafety();
8005 self.expect_keyword(keywords::Impl)?;
8006 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
8007 let span = lo.to(self.prev_span);
8008 return Ok(Some(self.mk_item(span, ident, item, visibility,
8009 maybe_append(attrs, extra_attrs))));
8011 if self.check_keyword(keywords::Fn) {
8014 let fn_span = self.prev_span;
8015 let (ident, item_, extra_attrs) =
8016 self.parse_item_fn(Unsafety::Normal,
8017 respan(fn_span, IsAsync::NotAsync),
8018 respan(fn_span, Constness::NotConst),
8020 let prev_span = self.prev_span;
8021 let item = self.mk_item(lo.to(prev_span),
8025 maybe_append(attrs, extra_attrs));
8026 return Ok(Some(item));
8028 if self.check_keyword(keywords::Unsafe)
8029 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
8030 // UNSAFE FUNCTION ITEM
8031 self.bump(); // `unsafe`
8032 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
8033 self.check(&token::OpenDelim(token::Brace));
8034 let abi = if self.eat_keyword(keywords::Extern) {
8035 self.parse_opt_abi()?.unwrap_or(Abi::C)
8039 self.expect_keyword(keywords::Fn)?;
8040 let fn_span = self.prev_span;
8041 let (ident, item_, extra_attrs) =
8042 self.parse_item_fn(Unsafety::Unsafe,
8043 respan(fn_span, IsAsync::NotAsync),
8044 respan(fn_span, Constness::NotConst),
8046 let prev_span = self.prev_span;
8047 let item = self.mk_item(lo.to(prev_span),
8051 maybe_append(attrs, extra_attrs));
8052 return Ok(Some(item));
8054 if self.eat_keyword(keywords::Mod) {
8056 let (ident, item_, extra_attrs) =
8057 self.parse_item_mod(&attrs[..])?;
8058 let prev_span = self.prev_span;
8059 let item = self.mk_item(lo.to(prev_span),
8063 maybe_append(attrs, extra_attrs));
8064 return Ok(Some(item));
8066 if let Some(type_) = self.eat_type() {
8067 let (ident, alias, generics) = type_?;
8069 let item_ = match alias {
8070 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
8071 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
8073 let prev_span = self.prev_span;
8074 let item = self.mk_item(lo.to(prev_span),
8079 return Ok(Some(item));
8081 if self.eat_keyword(keywords::Enum) {
8083 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
8084 let prev_span = self.prev_span;
8085 let item = self.mk_item(lo.to(prev_span),
8089 maybe_append(attrs, extra_attrs));
8090 return Ok(Some(item));
8092 if self.check_keyword(keywords::Trait)
8093 || (self.check_keyword(keywords::Auto)
8094 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
8096 let is_auto = if self.eat_keyword(keywords::Trait) {
8099 self.expect_keyword(keywords::Auto)?;
8100 self.expect_keyword(keywords::Trait)?;
8104 let (ident, item_, extra_attrs) =
8105 self.parse_item_trait(is_auto, Unsafety::Normal)?;
8106 let prev_span = self.prev_span;
8107 let item = self.mk_item(lo.to(prev_span),
8111 maybe_append(attrs, extra_attrs));
8112 return Ok(Some(item));
8114 if self.eat_keyword(keywords::Struct) {
8116 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
8117 let prev_span = self.prev_span;
8118 let item = self.mk_item(lo.to(prev_span),
8122 maybe_append(attrs, extra_attrs));
8123 return Ok(Some(item));
8125 if self.is_union_item() {
8128 let (ident, item_, extra_attrs) = self.parse_item_union()?;
8129 let prev_span = self.prev_span;
8130 let item = self.mk_item(lo.to(prev_span),
8134 maybe_append(attrs, extra_attrs));
8135 return Ok(Some(item));
8137 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
8138 return Ok(Some(macro_def));
8141 // Verify whether we have encountered a struct or method definition where the user forgot to
8142 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
8143 if visibility.node.is_pub() &&
8144 self.check_ident() &&
8145 self.look_ahead(1, |t| *t != token::Not)
8147 // Space between `pub` keyword and the identifier
8150 // ^^^ `sp` points here
8151 let sp = self.prev_span.between(self.span);
8152 let full_sp = self.prev_span.to(self.span);
8153 let ident_sp = self.span;
8154 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
8155 // possible public struct definition where `struct` was forgotten
8156 let ident = self.parse_ident().unwrap();
8157 let msg = format!("add `struct` here to parse `{}` as a public struct",
8159 let mut err = self.diagnostic()
8160 .struct_span_err(sp, "missing `struct` for struct definition");
8161 err.span_suggestion_short(
8162 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
8165 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
8166 let ident = self.parse_ident().unwrap();
8168 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
8173 self.consume_block(token::Paren);
8174 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
8175 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
8177 ("fn", kw_name, false)
8178 } else if self.check(&token::OpenDelim(token::Brace)) {
8180 ("fn", kw_name, false)
8181 } else if self.check(&token::Colon) {
8185 ("fn` or `struct", "function or struct", true)
8187 self.consume_block(token::Brace);
8189 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8190 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8192 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
8196 err.span_suggestion_short(
8197 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
8200 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
8201 err.span_suggestion(
8203 "if you meant to call a macro, try",
8204 format!("{}!", snippet),
8205 // this is the `ambiguous` conditional branch
8206 Applicability::MaybeIncorrect
8209 err.help("if you meant to call a macro, remove the `pub` \
8210 and add a trailing `!` after the identifier");
8214 } else if self.look_ahead(1, |t| *t == token::Lt) {
8215 let ident = self.parse_ident().unwrap();
8216 self.eat_to_tokens(&[&token::Gt]);
8218 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
8219 if let Ok(Some(_)) = self.parse_self_arg() {
8220 ("fn", "method", false)
8222 ("fn", "function", false)
8224 } else if self.check(&token::OpenDelim(token::Brace)) {
8225 ("struct", "struct", false)
8227 ("fn` or `struct", "function or struct", true)
8229 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8230 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8232 err.span_suggestion_short(
8234 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
8235 format!(" {} ", kw),
8236 Applicability::MachineApplicable,
8242 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
8245 /// Parses a foreign item.
8246 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
8247 maybe_whole!(self, NtForeignItem, |ni| ni);
8249 let attrs = self.parse_outer_attributes()?;
8251 let visibility = self.parse_visibility(false)?;
8253 // FOREIGN STATIC ITEM
8254 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
8255 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
8256 if self.token.is_keyword(keywords::Const) {
8258 .struct_span_err(self.span, "extern items cannot be `const`")
8261 "try using a static value",
8262 "static".to_owned(),
8263 Applicability::MachineApplicable
8266 self.bump(); // `static` or `const`
8267 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
8269 // FOREIGN FUNCTION ITEM
8270 if self.check_keyword(keywords::Fn) {
8271 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
8273 // FOREIGN TYPE ITEM
8274 if self.check_keyword(keywords::Type) {
8275 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
8278 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
8282 ident: keywords::Invalid.ident(),
8283 span: lo.to(self.prev_span),
8284 id: ast::DUMMY_NODE_ID,
8287 node: ForeignItemKind::Macro(mac),
8292 if !attrs.is_empty() {
8293 self.expected_item_err(&attrs)?;
8301 /// This is the fall-through for parsing items.
8302 fn parse_macro_use_or_failure(
8304 attrs: Vec<Attribute> ,
8305 macros_allowed: bool,
8306 attributes_allowed: bool,
8308 visibility: Visibility
8309 ) -> PResult<'a, Option<P<Item>>> {
8310 if macros_allowed && self.token.is_path_start() &&
8311 !(self.is_async_fn() && self.span.rust_2015()) {
8312 // MACRO INVOCATION ITEM
8314 let prev_span = self.prev_span;
8315 self.complain_if_pub_macro(&visibility.node, prev_span);
8317 let mac_lo = self.span;
8320 let pth = self.parse_path(PathStyle::Mod)?;
8321 self.expect(&token::Not)?;
8323 // a 'special' identifier (like what `macro_rules!` uses)
8324 // is optional. We should eventually unify invoc syntax
8326 let id = if self.token.is_ident() {
8329 keywords::Invalid.ident() // no special identifier
8331 // eat a matched-delimiter token tree:
8332 let (delim, tts) = self.expect_delimited_token_tree()?;
8333 if delim != MacDelimiter::Brace {
8334 if !self.eat(&token::Semi) {
8335 self.span_err(self.prev_span,
8336 "macros that expand to items must either \
8337 be surrounded with braces or followed by \
8342 let hi = self.prev_span;
8343 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
8344 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
8345 return Ok(Some(item));
8348 // FAILURE TO PARSE ITEM
8349 match visibility.node {
8350 VisibilityKind::Inherited => {}
8352 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
8356 if !attributes_allowed && !attrs.is_empty() {
8357 self.expected_item_err(&attrs)?;
8362 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
8363 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
8364 at_end: &mut bool) -> PResult<'a, Option<Mac>>
8366 if self.token.is_path_start() &&
8367 !(self.is_async_fn() && self.span.rust_2015()) {
8368 let prev_span = self.prev_span;
8370 let pth = self.parse_path(PathStyle::Mod)?;
8372 if pth.segments.len() == 1 {
8373 if !self.eat(&token::Not) {
8374 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
8377 self.expect(&token::Not)?;
8380 if let Some(vis) = vis {
8381 self.complain_if_pub_macro(&vis.node, prev_span);
8386 // eat a matched-delimiter token tree:
8387 let (delim, tts) = self.expect_delimited_token_tree()?;
8388 if delim != MacDelimiter::Brace {
8389 self.expect(&token::Semi)?;
8392 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
8398 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
8399 where F: FnOnce(&mut Self) -> PResult<'a, R>
8401 // Record all tokens we parse when parsing this item.
8402 let mut tokens = Vec::new();
8403 let prev_collecting = match self.token_cursor.frame.last_token {
8404 LastToken::Collecting(ref mut list) => {
8405 Some(mem::replace(list, Vec::new()))
8407 LastToken::Was(ref mut last) => {
8408 tokens.extend(last.take());
8412 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
8413 let prev = self.token_cursor.stack.len();
8415 let last_token = if self.token_cursor.stack.len() == prev {
8416 &mut self.token_cursor.frame.last_token
8418 &mut self.token_cursor.stack[prev].last_token
8421 // Pull out the tokens that we've collected from the call to `f` above.
8422 let mut collected_tokens = match *last_token {
8423 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
8424 LastToken::Was(_) => panic!("our vector went away?"),
8427 // If we're not at EOF our current token wasn't actually consumed by
8428 // `f`, but it'll still be in our list that we pulled out. In that case
8430 let extra_token = if self.token != token::Eof {
8431 collected_tokens.pop()
8436 // If we were previously collecting tokens, then this was a recursive
8437 // call. In that case we need to record all the tokens we collected in
8438 // our parent list as well. To do that we push a clone of our stream
8439 // onto the previous list.
8440 match prev_collecting {
8442 list.extend(collected_tokens.iter().cloned());
8443 list.extend(extra_token);
8444 *last_token = LastToken::Collecting(list);
8447 *last_token = LastToken::Was(extra_token);
8451 Ok((ret?, TokenStream::new(collected_tokens)))
8454 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
8455 let attrs = self.parse_outer_attributes()?;
8456 self.parse_item_(attrs, true, false)
8460 fn is_import_coupler(&mut self) -> bool {
8461 self.check(&token::ModSep) &&
8462 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
8463 *t == token::BinOp(token::Star))
8466 /// Parses a `UseTree`.
8469 /// USE_TREE = [`::`] `*` |
8470 /// [`::`] `{` USE_TREE_LIST `}` |
8472 /// PATH `::` `{` USE_TREE_LIST `}` |
8473 /// PATH [`as` IDENT]
8475 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
8478 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
8479 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
8480 self.check(&token::BinOp(token::Star)) ||
8481 self.is_import_coupler() {
8482 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
8483 let mod_sep_ctxt = self.span.ctxt();
8484 if self.eat(&token::ModSep) {
8485 prefix.segments.push(
8486 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
8490 if self.eat(&token::BinOp(token::Star)) {
8493 UseTreeKind::Nested(self.parse_use_tree_list()?)
8496 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
8497 prefix = self.parse_path(PathStyle::Mod)?;
8499 if self.eat(&token::ModSep) {
8500 if self.eat(&token::BinOp(token::Star)) {
8503 UseTreeKind::Nested(self.parse_use_tree_list()?)
8506 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
8510 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
8513 /// Parses a `UseTreeKind::Nested(list)`.
8516 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
8518 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
8519 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
8520 &token::CloseDelim(token::Brace),
8521 SeqSep::trailing_allowed(token::Comma), |this| {
8522 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
8526 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
8527 if self.eat_keyword(keywords::As) {
8528 self.parse_ident_or_underscore().map(Some)
8534 /// Parses a source module as a crate. This is the main entry point for the parser.
8535 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
8537 let krate = Ok(ast::Crate {
8538 attrs: self.parse_inner_attributes()?,
8539 module: self.parse_mod_items(&token::Eof, lo)?,
8540 span: lo.to(self.span),
8542 emit_unclosed_delims(&self.unclosed_delims, self.diagnostic());
8543 self.unclosed_delims.clear();
8547 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
8548 let ret = match self.token {
8549 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
8550 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
8557 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
8558 match self.parse_optional_str() {
8559 Some((s, style, suf)) => {
8560 let sp = self.prev_span;
8561 self.expect_no_suffix(sp, "string literal", suf);
8565 let msg = "expected string literal";
8566 let mut err = self.fatal(msg);
8567 err.span_label(self.span, msg);
8574 pub fn emit_unclosed_delims(unclosed_delims: &[UnmatchedBrace], handler: &errors::Handler) {
8575 for unmatched in unclosed_delims {
8576 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
8577 "incorrect close delimiter: `{}`",
8578 pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
8580 err.span_label(unmatched.found_span, "incorrect close delimiter");
8581 if let Some(sp) = unmatched.candidate_span {
8582 err.span_label(sp, "close delimiter possibly meant for this");
8584 if let Some(sp) = unmatched.unclosed_span {
8585 err.span_label(sp, "un-closed delimiter");