1 // ignore-tidy-filelength
3 use crate::ast::{AngleBracketedArgs, AsyncArgument, ParenthesizedArgs, AttrStyle, BareFnTy};
4 use crate::ast::{GenericBound, TraitBoundModifier};
5 use crate::ast::Unsafety;
6 use crate::ast::{Mod, AnonConst, Arg, ArgSource, Arm, Guard, Attribute, BindingMode, TraitItemKind};
8 use crate::ast::{BlockCheckMode, CaptureBy, Movability};
9 use crate::ast::{Constness, Crate};
10 use crate::ast::Defaultness;
11 use crate::ast::EnumDef;
12 use crate::ast::{Expr, ExprKind, RangeLimits};
13 use crate::ast::{Field, FnDecl, FnHeader};
14 use crate::ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
15 use crate::ast::{GenericParam, GenericParamKind};
16 use crate::ast::GenericArg;
17 use crate::ast::{Ident, ImplItem, IsAsync, IsAuto, Item, ItemKind};
18 use crate::ast::{Label, Lifetime, Lit, LitKind};
19 use crate::ast::{Local, LocalSource};
20 use crate::ast::MacStmtStyle;
21 use crate::ast::{Mac, Mac_, MacDelimiter};
22 use crate::ast::{MutTy, Mutability};
23 use crate::ast::{Pat, PatKind, PathSegment};
24 use crate::ast::{PolyTraitRef, QSelf};
25 use crate::ast::{Stmt, StmtKind};
26 use crate::ast::{VariantData, StructField};
27 use crate::ast::StrStyle;
28 use crate::ast::SelfKind;
29 use crate::ast::{TraitItem, TraitRef, TraitObjectSyntax};
30 use crate::ast::{Ty, TyKind, TypeBinding, GenericBounds};
31 use crate::ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
32 use crate::ast::{UseTree, UseTreeKind};
33 use crate::ast::{BinOpKind, UnOp};
34 use crate::ast::{RangeEnd, RangeSyntax};
35 use crate::{ast, attr};
36 use crate::ext::base::DummyResult;
37 use crate::source_map::{self, SourceMap, Spanned, respan};
38 use crate::parse::{self, SeqSep, classify, token};
39 use crate::parse::lexer::{TokenAndSpan, UnmatchedBrace};
40 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
41 use crate::parse::token::DelimToken;
42 use crate::parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
43 use crate::util::parser::{AssocOp, Fixity};
44 use crate::print::pprust;
46 use crate::parse::PResult;
48 use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
49 use crate::symbol::{Symbol, keywords};
51 use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError};
52 use rustc_target::spec::abi::{self, Abi};
53 use syntax_pos::{Span, MultiSpan, BytePos, FileName};
54 use log::{debug, trace};
59 use std::path::{self, Path, PathBuf};
63 /// Whether the type alias or associated type is a concrete type or an existential type
65 /// Just a new name for the same type
67 /// Only trait impls of the type will be usable, not the actual type itself
68 Existential(GenericBounds),
72 struct Restrictions: u8 {
73 const STMT_EXPR = 1 << 0;
74 const NO_STRUCT_LITERAL = 1 << 1;
78 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
80 /// Specifies how to parse a path.
81 #[derive(Copy, Clone, PartialEq)]
83 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
84 /// with something else. For example, in expressions `segment < ....` can be interpreted
85 /// as a comparison and `segment ( ....` can be interpreted as a function call.
86 /// In all such contexts the non-path interpretation is preferred by default for practical
87 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
88 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
90 /// In other contexts, notably in types, no ambiguity exists and paths can be written
91 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
92 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
94 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
95 /// visibilities or attributes.
96 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
97 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
98 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
99 /// tokens when something goes wrong.
103 #[derive(Clone, Copy, PartialEq, Debug)]
110 #[derive(Clone, Copy, PartialEq, Debug)]
116 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
117 /// dropped into the token stream, which happens while parsing the result of
118 /// macro expansion). Placement of these is not as complex as I feared it would
119 /// be. The important thing is to make sure that lookahead doesn't balk at
120 /// `token::Interpolated` tokens.
121 macro_rules! maybe_whole_expr {
123 if let token::Interpolated(nt) = &$p.token {
125 token::NtExpr(e) | token::NtLiteral(e) => {
130 token::NtPath(path) => {
131 let path = path.clone();
133 return Ok($p.mk_expr($p.span, ExprKind::Path(None, path), ThinVec::new()));
135 token::NtBlock(block) => {
136 let block = block.clone();
138 return Ok($p.mk_expr($p.span, ExprKind::Block(block, None), ThinVec::new()));
146 /// As maybe_whole_expr, but for things other than expressions
147 macro_rules! maybe_whole {
148 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
149 if let token::Interpolated(nt) = &$p.token {
150 if let token::$constructor(x) = &**nt {
159 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
160 macro_rules! maybe_recover_from_interpolated_ty_qpath {
161 ($self: expr, $allow_qpath_recovery: expr) => {
162 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
163 if let token::Interpolated(nt) = &$self.token {
164 if let token::NtTy(ty) = &**nt {
167 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
174 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
175 if let Some(ref mut rhs) = rhs {
181 #[derive(Debug, Clone, Copy, PartialEq)]
193 trait RecoverQPath: Sized + 'static {
194 const PATH_STYLE: PathStyle = PathStyle::Expr;
195 fn to_ty(&self) -> Option<P<Ty>>;
196 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self;
199 impl RecoverQPath for Ty {
200 const PATH_STYLE: PathStyle = PathStyle::Type;
201 fn to_ty(&self) -> Option<P<Ty>> {
202 Some(P(self.clone()))
204 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
205 Self { span: path.span, node: TyKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
209 impl RecoverQPath for Pat {
210 fn to_ty(&self) -> Option<P<Ty>> {
213 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
214 Self { span: path.span, node: PatKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
218 impl RecoverQPath for Expr {
219 fn to_ty(&self) -> Option<P<Ty>> {
222 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
223 Self { span: path.span, node: ExprKind::Path(qself, path),
224 attrs: ThinVec::new(), id: ast::DUMMY_NODE_ID }
228 /* ident is handled by common.rs */
231 pub struct Parser<'a> {
232 pub sess: &'a ParseSess,
233 /// the current token:
234 pub token: token::Token,
235 /// the span of the current token:
237 /// the span of the previous token:
238 meta_var_span: Option<Span>,
240 /// the previous token kind
241 prev_token_kind: PrevTokenKind,
242 restrictions: Restrictions,
243 /// Used to determine the path to externally loaded source files
244 crate directory: Directory<'a>,
245 /// Whether to parse sub-modules in other files.
246 pub recurse_into_file_modules: bool,
247 /// Name of the root module this parser originated from. If `None`, then the
248 /// name is not known. This does not change while the parser is descending
249 /// into modules, and sub-parsers have new values for this name.
250 pub root_module_name: Option<String>,
251 crate expected_tokens: Vec<TokenType>,
252 token_cursor: TokenCursor,
253 desugar_doc_comments: bool,
254 /// Whether we should configure out of line modules as we parse.
256 /// This field is used to keep track of how many left angle brackets we have seen. This is
257 /// required in order to detect extra leading left angle brackets (`<` characters) and error
260 /// See the comments in the `parse_path_segment` function for more details.
261 crate unmatched_angle_bracket_count: u32,
262 crate max_angle_bracket_count: u32,
263 /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
264 /// it gets removed from here. Every entry left at the end gets emitted as an independent
266 crate unclosed_delims: Vec<UnmatchedBrace>,
267 last_unexpected_token_span: Option<Span>,
270 impl<'a> Drop for Parser<'a> {
272 let diag = self.diagnostic();
273 emit_unclosed_delims(&mut self.unclosed_delims, diag);
279 frame: TokenCursorFrame,
280 stack: Vec<TokenCursorFrame>,
284 struct TokenCursorFrame {
285 delim: token::DelimToken,
288 tree_cursor: tokenstream::Cursor,
290 last_token: LastToken,
293 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
294 /// by the parser, and then that's transitively used to record the tokens that
295 /// each parse AST item is created with.
297 /// Right now this has two states, either collecting tokens or not collecting
298 /// tokens. If we're collecting tokens we just save everything off into a local
299 /// `Vec`. This should eventually though likely save tokens from the original
300 /// token stream and just use slicing of token streams to avoid creation of a
301 /// whole new vector.
303 /// The second state is where we're passively not recording tokens, but the last
304 /// token is still tracked for when we want to start recording tokens. This
305 /// "last token" means that when we start recording tokens we'll want to ensure
306 /// that this, the first token, is included in the output.
308 /// You can find some more example usage of this in the `collect_tokens` method
312 Collecting(Vec<TreeAndJoint>),
313 Was(Option<TreeAndJoint>),
316 impl TokenCursorFrame {
317 fn new(sp: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
321 open_delim: delim == token::NoDelim,
322 tree_cursor: tts.clone().into_trees(),
323 close_delim: delim == token::NoDelim,
324 last_token: LastToken::Was(None),
330 fn next(&mut self) -> TokenAndSpan {
332 let tree = if !self.frame.open_delim {
333 self.frame.open_delim = true;
334 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
335 } else if let Some(tree) = self.frame.tree_cursor.next() {
337 } else if !self.frame.close_delim {
338 self.frame.close_delim = true;
339 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
340 } else if let Some(frame) = self.stack.pop() {
344 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
347 match self.frame.last_token {
348 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
349 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
353 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
354 TokenTree::Delimited(sp, delim, tts) => {
355 let frame = TokenCursorFrame::new(sp, delim, &tts);
356 self.stack.push(mem::replace(&mut self.frame, frame));
362 fn next_desugared(&mut self) -> TokenAndSpan {
363 let (sp, name) = match self.next() {
364 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
368 let stripped = strip_doc_comment_decoration(&name.as_str());
370 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
371 // required to wrap the text.
372 let mut num_of_hashes = 0;
374 for ch in stripped.chars() {
377 '#' if count > 0 => count + 1,
380 num_of_hashes = cmp::max(num_of_hashes, count);
383 let delim_span = DelimSpan::from_single(sp);
384 let body = TokenTree::Delimited(
387 [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
388 TokenTree::Token(sp, token::Eq),
389 TokenTree::Token(sp, token::Literal(
390 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))
392 .iter().cloned().collect::<TokenStream>().into(),
395 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
398 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
399 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
400 .iter().cloned().collect::<TokenStream>().into()
402 [TokenTree::Token(sp, token::Pound), body]
403 .iter().cloned().collect::<TokenStream>().into()
411 #[derive(Clone, PartialEq)]
412 crate enum TokenType {
414 Keyword(keywords::Keyword),
424 fn to_string(&self) -> String {
426 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
427 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
428 TokenType::Operator => "an operator".to_string(),
429 TokenType::Lifetime => "lifetime".to_string(),
430 TokenType::Ident => "identifier".to_string(),
431 TokenType::Path => "path".to_string(),
432 TokenType::Type => "type".to_string(),
433 TokenType::Const => "const".to_string(),
438 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
439 /// `IDENT<<u8 as Trait>::AssocTy>`.
441 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
442 /// that `IDENT` is not the ident of a fn trait.
443 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
444 t == &token::ModSep || t == &token::Lt ||
445 t == &token::BinOp(token::Shl)
448 /// Information about the path to a module.
449 pub struct ModulePath {
452 pub result: Result<ModulePathSuccess, Error>,
455 pub struct ModulePathSuccess {
457 pub directory_ownership: DirectoryOwnership,
462 FileNotFoundForModule {
464 default_path: String,
465 secondary_path: String,
470 default_path: String,
471 secondary_path: String,
474 InclusiveRangeWithNoEnd,
478 fn span_err<S: Into<MultiSpan>>(self,
480 handler: &errors::Handler) -> DiagnosticBuilder<'_> {
482 Error::FileNotFoundForModule { ref mod_name,
486 let mut err = struct_span_err!(handler, sp, E0583,
487 "file not found for module `{}`", mod_name);
488 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
494 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
495 let mut err = struct_span_err!(handler, sp, E0584,
496 "file for module `{}` found at both {} and {}",
500 err.help("delete or rename one of them to remove the ambiguity");
503 Error::UselessDocComment => {
504 let mut err = struct_span_err!(handler, sp, E0585,
505 "found a documentation comment that doesn't document anything");
506 err.help("doc comments must come before what they document, maybe a comment was \
507 intended with `//`?");
510 Error::InclusiveRangeWithNoEnd => {
511 let mut err = struct_span_err!(handler, sp, E0586,
512 "inclusive range with no end");
513 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
523 AttributesParsed(ThinVec<Attribute>),
524 AlreadyParsed(P<Expr>),
527 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
528 fn from(o: Option<ThinVec<Attribute>>) -> Self {
529 if let Some(attrs) = o {
530 LhsExpr::AttributesParsed(attrs)
532 LhsExpr::NotYetParsed
537 impl From<P<Expr>> for LhsExpr {
538 fn from(expr: P<Expr>) -> Self {
539 LhsExpr::AlreadyParsed(expr)
543 /// Creates a placeholder argument.
544 fn dummy_arg(span: Span) -> Arg {
545 let ident = Ident::new(keywords::Invalid.name(), span);
547 id: ast::DUMMY_NODE_ID,
548 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
554 id: ast::DUMMY_NODE_ID
556 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal }
559 #[derive(Copy, Clone, Debug)]
560 enum TokenExpectType {
565 impl<'a> Parser<'a> {
566 pub fn new(sess: &'a ParseSess,
568 directory: Option<Directory<'a>>,
569 recurse_into_file_modules: bool,
570 desugar_doc_comments: bool)
572 let mut parser = Parser {
574 token: token::Whitespace,
575 span: syntax_pos::DUMMY_SP,
576 prev_span: syntax_pos::DUMMY_SP,
578 prev_token_kind: PrevTokenKind::Other,
579 restrictions: Restrictions::empty(),
580 recurse_into_file_modules,
581 directory: Directory {
582 path: Cow::from(PathBuf::new()),
583 ownership: DirectoryOwnership::Owned { relative: None }
585 root_module_name: None,
586 expected_tokens: Vec::new(),
587 token_cursor: TokenCursor {
588 frame: TokenCursorFrame::new(
595 desugar_doc_comments,
597 unmatched_angle_bracket_count: 0,
598 max_angle_bracket_count: 0,
599 unclosed_delims: Vec::new(),
600 last_unexpected_token_span: None,
603 let tok = parser.next_tok();
604 parser.token = tok.tok;
605 parser.span = tok.sp;
607 if let Some(directory) = directory {
608 parser.directory = directory;
609 } else if !parser.span.is_dummy() {
610 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
612 parser.directory.path = Cow::from(path);
616 parser.process_potential_macro_variable();
620 fn next_tok(&mut self) -> TokenAndSpan {
621 let mut next = if self.desugar_doc_comments {
622 self.token_cursor.next_desugared()
624 self.token_cursor.next()
626 if next.sp.is_dummy() {
627 // Tweak the location for better diagnostics, but keep syntactic context intact.
628 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
633 /// Converts the current token to a string using `self`'s reader.
634 pub fn this_token_to_string(&self) -> String {
635 pprust::token_to_string(&self.token)
638 fn token_descr(&self) -> Option<&'static str> {
639 Some(match &self.token {
640 t if t.is_special_ident() => "reserved identifier",
641 t if t.is_used_keyword() => "keyword",
642 t if t.is_unused_keyword() => "reserved keyword",
643 token::DocComment(..) => "doc comment",
648 fn this_token_descr(&self) -> String {
649 if let Some(prefix) = self.token_descr() {
650 format!("{} `{}`", prefix, self.this_token_to_string())
652 format!("`{}`", self.this_token_to_string())
656 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
657 let token_str = pprust::token_to_string(t);
658 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
661 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
662 match self.expect_one_of(&[], &[]) {
664 Ok(_) => unreachable!(),
668 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
669 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, bool /* recovered */> {
670 if self.expected_tokens.is_empty() {
671 if self.token == *t {
675 let token_str = pprust::token_to_string(t);
676 let this_token_str = self.this_token_descr();
677 let mut err = self.fatal(&format!("expected `{}`, found {}",
681 let sp = if self.token == token::Token::Eof {
682 // EOF, don't want to point at the following char, but rather the last token
685 self.sess.source_map().next_point(self.prev_span)
687 let label_exp = format!("expected `{}`", token_str);
688 match self.recover_closing_delimiter(&[t.clone()], err) {
691 return Ok(recovered);
694 let cm = self.sess.source_map();
695 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
696 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
697 // When the spans are in the same line, it means that the only content
698 // between them is whitespace, point only at the found token.
699 err.span_label(self.span, label_exp);
702 err.span_label(sp, label_exp);
703 err.span_label(self.span, "unexpected token");
709 self.expect_one_of(slice::from_ref(t), &[])
713 fn recover_closing_delimiter(
715 tokens: &[token::Token],
716 mut err: DiagnosticBuilder<'a>,
717 ) -> PResult<'a, bool> {
719 // we want to use the last closing delim that would apply
720 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
721 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
722 && Some(self.span) > unmatched.unclosed_span
729 // Recover and assume that the detected unclosed delimiter was meant for
730 // this location. Emit the diagnostic and act as if the delimiter was
731 // present for the parser's sake.
733 // Don't attempt to recover from this unclosed delimiter more than once.
734 let unmatched = self.unclosed_delims.remove(pos);
735 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
737 // We want to suggest the inclusion of the closing delimiter where it makes
738 // the most sense, which is immediately after the last token:
743 // | help: `)` may belong here (FIXME: #58270)
745 // unclosed delimiter
746 if let Some(sp) = unmatched.unclosed_span {
747 err.span_label(sp, "unclosed delimiter");
749 err.span_suggestion_short(
750 self.sess.source_map().next_point(self.prev_span),
751 &format!("{} may belong here", delim.to_string()),
753 Applicability::MaybeIncorrect,
756 self.expected_tokens.clear(); // reduce errors
763 /// Expect next token to be edible or inedible token. If edible,
764 /// then consume it; if inedible, then return without consuming
765 /// anything. Signal a fatal error if next token is unexpected.
766 pub fn expect_one_of(
768 edible: &[token::Token],
769 inedible: &[token::Token],
770 ) -> PResult<'a, bool /* recovered */> {
771 fn tokens_to_string(tokens: &[TokenType]) -> String {
772 let mut i = tokens.iter();
773 // This might be a sign we need a connect method on Iterator.
775 .map_or(String::new(), |t| t.to_string());
776 i.enumerate().fold(b, |mut b, (i, a)| {
777 if tokens.len() > 2 && i == tokens.len() - 2 {
779 } else if tokens.len() == 2 && i == tokens.len() - 2 {
784 b.push_str(&a.to_string());
788 if edible.contains(&self.token) {
791 } else if inedible.contains(&self.token) {
792 // leave it in the input
794 } else if self.last_unexpected_token_span == Some(self.span) {
797 let mut expected = edible.iter()
798 .map(|x| TokenType::Token(x.clone()))
799 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
800 .chain(self.expected_tokens.iter().cloned())
801 .collect::<Vec<_>>();
802 expected.sort_by_cached_key(|x| x.to_string());
804 let expect = tokens_to_string(&expected[..]);
805 let actual = self.this_token_to_string();
806 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
807 let short_expect = if expected.len() > 6 {
808 format!("{} possible tokens", expected.len())
812 (format!("expected one of {}, found `{}`", expect, actual),
813 (self.sess.source_map().next_point(self.prev_span),
814 format!("expected one of {} here", short_expect)))
815 } else if expected.is_empty() {
816 (format!("unexpected token: `{}`", actual),
817 (self.prev_span, "unexpected token after this".to_string()))
819 (format!("expected {}, found `{}`", expect, actual),
820 (self.sess.source_map().next_point(self.prev_span),
821 format!("expected {} here", expect)))
823 self.last_unexpected_token_span = Some(self.span);
824 let mut err = self.fatal(&msg_exp);
825 if self.token.is_ident_named("and") {
826 err.span_suggestion_short(
828 "use `&&` instead of `and` for the boolean operator",
830 Applicability::MaybeIncorrect,
833 if self.token.is_ident_named("or") {
834 err.span_suggestion_short(
836 "use `||` instead of `or` for the boolean operator",
838 Applicability::MaybeIncorrect,
841 let sp = if self.token == token::Token::Eof {
842 // This is EOF, don't want to point at the following char, but rather the last token
847 match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt {
848 TokenType::Token(t) => Some(t.clone()),
850 }).collect::<Vec<_>>(), err) {
853 return Ok(recovered);
857 let is_semi_suggestable = expected.iter().any(|t| match t {
858 TokenType::Token(token::Semi) => true, // we expect a `;` here
860 }) && ( // a `;` would be expected before the current keyword
861 self.token.is_keyword(keywords::Break) ||
862 self.token.is_keyword(keywords::Continue) ||
863 self.token.is_keyword(keywords::For) ||
864 self.token.is_keyword(keywords::If) ||
865 self.token.is_keyword(keywords::Let) ||
866 self.token.is_keyword(keywords::Loop) ||
867 self.token.is_keyword(keywords::Match) ||
868 self.token.is_keyword(keywords::Return) ||
869 self.token.is_keyword(keywords::While)
871 let cm = self.sess.source_map();
872 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
873 (Ok(ref a), Ok(ref b)) if a.line != b.line && is_semi_suggestable => {
874 // The spans are in different lines, expected `;` and found `let` or `return`.
875 // High likelihood that it is only a missing `;`.
876 err.span_suggestion_short(
878 "a semicolon may be missing here",
880 Applicability::MaybeIncorrect,
885 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
886 // When the spans are in the same line, it means that the only content between
887 // them is whitespace, point at the found token in that case:
889 // X | () => { syntax error };
890 // | ^^^^^ expected one of 8 possible tokens here
892 // instead of having:
894 // X | () => { syntax error };
895 // | -^^^^^ unexpected token
897 // | expected one of 8 possible tokens here
898 err.span_label(self.span, label_exp);
900 _ if self.prev_span == syntax_pos::DUMMY_SP => {
901 // Account for macro context where the previous span might not be
902 // available to avoid incorrect output (#54841).
903 err.span_label(self.span, "unexpected token");
906 err.span_label(sp, label_exp);
907 err.span_label(self.span, "unexpected token");
914 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
915 fn interpolated_or_expr_span(&self,
916 expr: PResult<'a, P<Expr>>)
917 -> PResult<'a, (Span, P<Expr>)> {
919 if self.prev_token_kind == PrevTokenKind::Interpolated {
927 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
928 let mut err = self.struct_span_err(self.span,
929 &format!("expected identifier, found {}",
930 self.this_token_descr()));
931 if let token::Ident(ident, false) = &self.token {
932 if ident.is_raw_guess() {
935 "you can escape reserved keywords to use them as identifiers",
936 format!("r#{}", ident),
937 Applicability::MaybeIncorrect,
941 if let Some(token_descr) = self.token_descr() {
942 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
944 err.span_label(self.span, "expected identifier");
945 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
950 Applicability::MachineApplicable,
957 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
958 self.parse_ident_common(true)
961 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
963 token::Ident(ident, _) => {
964 if self.token.is_reserved_ident() {
965 let mut err = self.expected_ident_found();
972 let span = self.span;
974 Ok(Ident::new(ident.name, span))
977 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
978 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
980 self.expected_ident_found()
986 /// Checks if the next token is `tok`, and returns `true` if so.
988 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
990 crate fn check(&mut self, tok: &token::Token) -> bool {
991 let is_present = self.token == *tok;
992 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
996 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
997 pub fn eat(&mut self, tok: &token::Token) -> bool {
998 let is_present = self.check(tok);
999 if is_present { self.bump() }
1003 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
1004 self.expected_tokens.push(TokenType::Keyword(kw));
1005 self.token.is_keyword(kw)
1008 /// If the next token is the given keyword, eats it and returns
1009 /// `true`. Otherwise, returns `false`.
1010 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
1011 if self.check_keyword(kw) {
1019 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
1020 if self.token.is_keyword(kw) {
1028 /// If the given word is not a keyword, signals an error.
1029 /// If the next token is not the given word, signals an error.
1030 /// Otherwise, eats it.
1031 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
1032 if !self.eat_keyword(kw) {
1039 fn check_ident(&mut self) -> bool {
1040 if self.token.is_ident() {
1043 self.expected_tokens.push(TokenType::Ident);
1048 fn check_path(&mut self) -> bool {
1049 if self.token.is_path_start() {
1052 self.expected_tokens.push(TokenType::Path);
1057 fn check_type(&mut self) -> bool {
1058 if self.token.can_begin_type() {
1061 self.expected_tokens.push(TokenType::Type);
1066 fn check_const_arg(&mut self) -> bool {
1067 if self.token.can_begin_const_arg() {
1070 self.expected_tokens.push(TokenType::Const);
1075 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
1076 /// and continues. If a `+` is not seen, returns `false`.
1078 /// This is used when token-splitting `+=` into `+`.
1079 /// See issue #47856 for an example of when this may occur.
1080 fn eat_plus(&mut self) -> bool {
1081 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1083 token::BinOp(token::Plus) => {
1087 token::BinOpEq(token::Plus) => {
1088 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1089 self.bump_with(token::Eq, span);
1097 /// Checks to see if the next token is either `+` or `+=`.
1098 /// Otherwise returns `false`.
1099 fn check_plus(&mut self) -> bool {
1100 if self.token.is_like_plus() {
1104 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1109 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
1110 /// `&` and continues. If an `&` is not seen, signals an error.
1111 fn expect_and(&mut self) -> PResult<'a, ()> {
1112 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
1114 token::BinOp(token::And) => {
1119 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1120 Ok(self.bump_with(token::BinOp(token::And), span))
1122 _ => self.unexpected()
1126 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
1127 /// `|` and continues. If an `|` is not seen, signals an error.
1128 fn expect_or(&mut self) -> PResult<'a, ()> {
1129 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
1131 token::BinOp(token::Or) => {
1136 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1137 Ok(self.bump_with(token::BinOp(token::Or), span))
1139 _ => self.unexpected()
1143 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
1145 None => {/* everything ok */}
1147 let text = suf.as_str();
1148 if text.is_empty() {
1149 self.span_bug(sp, "found empty literal suffix in Some")
1151 let mut err = if kind == "a tuple index" &&
1152 ["i32", "u32", "isize", "usize"].contains(&text.to_string().as_str())
1154 // #59553: warn instead of reject out of hand to allow the fix to percolate
1155 // through the ecosystem when people fix their macros
1156 let mut err = self.struct_span_warn(
1158 &format!("suffixes on {} are invalid", kind),
1161 "`{}` is *temporarily* accepted on tuple index fields as it was \
1162 incorrectly accepted on stable for a few releases",
1166 "on proc macros, you'll want to use `syn::Index::from` or \
1167 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1168 to tuple field access",
1171 "for more context, see https://github.com/rust-lang/rust/issues/60210",
1175 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1177 err.span_label(sp, format!("invalid suffix `{}`", text));
1183 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
1184 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
1185 /// and continue. If a `<` is not seen, returns false.
1187 /// This is meant to be used when parsing generics on a path to get the
1189 fn eat_lt(&mut self) -> bool {
1190 self.expected_tokens.push(TokenType::Token(token::Lt));
1191 let ate = match self.token {
1196 token::BinOp(token::Shl) => {
1197 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1198 self.bump_with(token::Lt, span);
1202 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1203 self.bump_with(token::BinOp(token::Minus), span);
1210 // See doc comment for `unmatched_angle_bracket_count`.
1211 self.unmatched_angle_bracket_count += 1;
1212 self.max_angle_bracket_count += 1;
1213 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
1219 fn expect_lt(&mut self) -> PResult<'a, ()> {
1227 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
1228 /// with a single `>` and continues. If a `>` is not seen, signals an error.
1229 fn expect_gt(&mut self) -> PResult<'a, ()> {
1230 self.expected_tokens.push(TokenType::Token(token::Gt));
1231 let ate = match self.token {
1236 token::BinOp(token::Shr) => {
1237 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1238 Some(self.bump_with(token::Gt, span))
1240 token::BinOpEq(token::Shr) => {
1241 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1242 Some(self.bump_with(token::Ge, span))
1245 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1246 Some(self.bump_with(token::Eq, span))
1253 // See doc comment for `unmatched_angle_bracket_count`.
1254 if self.unmatched_angle_bracket_count > 0 {
1255 self.unmatched_angle_bracket_count -= 1;
1256 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1261 None => self.unexpected(),
1265 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
1266 /// passes through any errors encountered. Used for error recovery.
1267 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1268 let handler = self.diagnostic();
1270 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1272 TokenExpectType::Expect,
1273 |p| Ok(p.parse_token_tree())) {
1274 handler.cancel(err);
1278 /// Parses a sequence, including the closing delimiter. The function
1279 /// `f` must consume tokens until reaching the next separator or
1280 /// closing bracket.
1281 pub fn parse_seq_to_end<T, F>(&mut self,
1285 -> PResult<'a, Vec<T>> where
1286 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1288 let (val, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1295 /// Parses a sequence, not including the closing delimiter. The function
1296 /// `f` must consume tokens until reaching the next separator or
1297 /// closing bracket.
1298 pub fn parse_seq_to_before_end<T, F>(
1303 ) -> PResult<'a, (Vec<T>, bool)>
1304 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1306 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1309 fn parse_seq_to_before_tokens<T, F>(
1311 kets: &[&token::Token],
1313 expect: TokenExpectType,
1315 ) -> PResult<'a, (Vec<T>, bool /* recovered */)>
1316 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1318 let mut first = true;
1319 let mut recovered = false;
1321 while !kets.iter().any(|k| {
1323 TokenExpectType::Expect => self.check(k),
1324 TokenExpectType::NoExpect => self.token == **k,
1328 token::CloseDelim(..) | token::Eof => break,
1331 if let Some(ref t) = sep.sep {
1335 match self.expect(t) {
1342 // Attempt to keep parsing if it was a similar separator
1343 if let Some(ref tokens) = t.similar_tokens() {
1344 if tokens.contains(&self.token) {
1349 // Attempt to keep parsing if it was an omitted separator
1364 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1366 TokenExpectType::Expect => self.check(k),
1367 TokenExpectType::NoExpect => self.token == **k,
1380 /// Parses a sequence, including the closing delimiter. The function
1381 /// `f` must consume tokens until reaching the next separator or
1382 /// closing bracket.
1383 fn parse_unspanned_seq<T, F>(
1389 ) -> PResult<'a, Vec<T>> where
1390 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1393 let (result, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1400 /// Advance the parser by one token
1401 pub fn bump(&mut self) {
1402 if self.prev_token_kind == PrevTokenKind::Eof {
1403 // Bumping after EOF is a bad sign, usually an infinite loop.
1404 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1407 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1409 // Record last token kind for possible error recovery.
1410 self.prev_token_kind = match self.token {
1411 token::DocComment(..) => PrevTokenKind::DocComment,
1412 token::Comma => PrevTokenKind::Comma,
1413 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1414 token::BinOp(token::Or) => PrevTokenKind::BitOr,
1415 token::Interpolated(..) => PrevTokenKind::Interpolated,
1416 token::Eof => PrevTokenKind::Eof,
1417 token::Ident(..) => PrevTokenKind::Ident,
1418 _ => PrevTokenKind::Other,
1421 let next = self.next_tok();
1422 self.span = next.sp;
1423 self.token = next.tok;
1424 self.expected_tokens.clear();
1425 // check after each token
1426 self.process_potential_macro_variable();
1429 /// Advance the parser using provided token as a next one. Use this when
1430 /// consuming a part of a token. For example a single `<` from `<<`.
1431 fn bump_with(&mut self, next: token::Token, span: Span) {
1432 self.prev_span = self.span.with_hi(span.lo());
1433 // It would be incorrect to record the kind of the current token, but
1434 // fortunately for tokens currently using `bump_with`, the
1435 // prev_token_kind will be of no use anyway.
1436 self.prev_token_kind = PrevTokenKind::Other;
1439 self.expected_tokens.clear();
1442 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1443 F: FnOnce(&token::Token) -> R,
1446 return f(&self.token)
1449 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1450 Some(tree) => match tree {
1451 TokenTree::Token(_, tok) => tok,
1452 TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim),
1454 None => token::CloseDelim(self.token_cursor.frame.delim),
1458 fn look_ahead_span(&self, dist: usize) -> Span {
1463 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1464 Some(TokenTree::Token(span, _)) => span,
1465 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1466 None => self.look_ahead_span(dist - 1),
1469 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1470 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1472 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1473 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1475 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1476 err.span_err(sp, self.diagnostic())
1478 fn bug(&self, m: &str) -> ! {
1479 self.sess.span_diagnostic.span_bug(self.span, m)
1481 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1482 self.sess.span_diagnostic.span_err(sp, m)
1484 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1485 self.sess.span_diagnostic.struct_span_err(sp, m)
1487 fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1488 self.sess.span_diagnostic.struct_span_warn(sp, m)
1490 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1491 self.sess.span_diagnostic.span_bug(sp, m)
1494 fn cancel(&self, err: &mut DiagnosticBuilder<'_>) {
1495 self.sess.span_diagnostic.cancel(err)
1498 crate fn diagnostic(&self) -> &'a errors::Handler {
1499 &self.sess.span_diagnostic
1502 /// Is the current token one of the keywords that signals a bare function type?
1503 fn token_is_bare_fn_keyword(&mut self) -> bool {
1504 self.check_keyword(keywords::Fn) ||
1505 self.check_keyword(keywords::Unsafe) ||
1506 self.check_keyword(keywords::Extern)
1509 /// Parses a `TyKind::BareFn` type.
1510 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1513 [unsafe] [extern "ABI"] fn (S) -> T
1523 let unsafety = self.parse_unsafety();
1524 let abi = if self.eat_keyword(keywords::Extern) {
1525 self.parse_opt_abi()?.unwrap_or(Abi::C)
1530 self.expect_keyword(keywords::Fn)?;
1531 let (inputs, c_variadic) = self.parse_fn_args(false, true)?;
1532 let ret_ty = self.parse_ret_ty(false)?;
1533 let decl = P(FnDecl {
1538 Ok(TyKind::BareFn(P(BareFnTy {
1546 /// Parses asyncness: `async` or nothing.
1547 fn parse_asyncness(&mut self) -> IsAsync {
1548 if self.eat_keyword(keywords::Async) {
1550 closure_id: ast::DUMMY_NODE_ID,
1551 return_impl_trait_id: ast::DUMMY_NODE_ID,
1552 arguments: Vec::new(),
1559 /// Parses unsafety: `unsafe` or nothing.
1560 fn parse_unsafety(&mut self) -> Unsafety {
1561 if self.eat_keyword(keywords::Unsafe) {
1568 /// Parses the items in a trait declaration.
1569 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1570 maybe_whole!(self, NtTraitItem, |x| x);
1571 let attrs = self.parse_outer_attributes()?;
1572 let mut unclosed_delims = vec![];
1573 let (mut item, tokens) = self.collect_tokens(|this| {
1574 let item = this.parse_trait_item_(at_end, attrs);
1575 unclosed_delims.append(&mut this.unclosed_delims);
1578 self.unclosed_delims.append(&mut unclosed_delims);
1579 // See `parse_item` for why this clause is here.
1580 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1581 item.tokens = Some(tokens);
1586 fn parse_trait_item_(&mut self,
1588 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1591 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1592 self.parse_trait_item_assoc_ty()?
1593 } else if self.is_const_item() {
1594 self.expect_keyword(keywords::Const)?;
1595 let ident = self.parse_ident()?;
1596 self.expect(&token::Colon)?;
1597 let ty = self.parse_ty()?;
1598 let default = if self.eat(&token::Eq) {
1599 let expr = self.parse_expr()?;
1600 self.expect(&token::Semi)?;
1603 self.expect(&token::Semi)?;
1606 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1607 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1608 // trait item macro.
1609 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1611 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
1613 let ident = self.parse_ident()?;
1614 let mut generics = self.parse_generics()?;
1616 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1617 // This is somewhat dubious; We don't want to allow
1618 // argument names to be left off if there is a
1621 // We don't allow argument names to be left off in edition 2018.
1622 p.parse_arg_general(p.span.rust_2018(), true, false)
1624 generics.where_clause = self.parse_where_clause()?;
1625 self.construct_async_arguments(&mut asyncness, &d);
1627 let sig = ast::MethodSig {
1637 let body = match self.token {
1641 debug!("parse_trait_methods(): parsing required method");
1644 token::OpenDelim(token::Brace) => {
1645 debug!("parse_trait_methods(): parsing provided method");
1647 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1648 attrs.extend(inner_attrs.iter().cloned());
1651 token::Interpolated(ref nt) => {
1653 token::NtBlock(..) => {
1655 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1656 attrs.extend(inner_attrs.iter().cloned());
1660 let token_str = self.this_token_descr();
1661 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1663 err.span_label(self.span, "expected `;` or `{`");
1669 let token_str = self.this_token_descr();
1670 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1672 err.span_label(self.span, "expected `;` or `{`");
1676 (ident, ast::TraitItemKind::Method(sig, body), generics)
1680 id: ast::DUMMY_NODE_ID,
1685 span: lo.to(self.prev_span),
1690 /// Parses an optional return type `[ -> TY ]` in a function declaration.
1691 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1692 if self.eat(&token::RArrow) {
1693 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?))
1695 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1700 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1701 self.parse_ty_common(true, true, false)
1704 /// Parses a type in restricted contexts where `+` is not permitted.
1706 /// Example 1: `&'a TYPE`
1707 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1708 /// Example 2: `value1 as TYPE + value2`
1709 /// `+` is prohibited to avoid interactions with expression grammar.
1710 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1711 self.parse_ty_common(false, true, false)
1714 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool,
1715 allow_c_variadic: bool) -> PResult<'a, P<Ty>> {
1716 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
1717 maybe_whole!(self, NtTy, |x| x);
1720 let mut impl_dyn_multi = false;
1721 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1722 // `(TYPE)` is a parenthesized type.
1723 // `(TYPE,)` is a tuple with a single field of type TYPE.
1724 let mut ts = vec![];
1725 let mut last_comma = false;
1726 while self.token != token::CloseDelim(token::Paren) {
1727 ts.push(self.parse_ty()?);
1728 if self.eat(&token::Comma) {
1735 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1736 self.expect(&token::CloseDelim(token::Paren))?;
1738 if ts.len() == 1 && !last_comma {
1739 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1740 let maybe_bounds = allow_plus && self.token.is_like_plus();
1742 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1743 TyKind::Path(None, ref path) if maybe_bounds => {
1744 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1746 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1747 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1748 let path = match bounds[0] {
1749 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1750 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1752 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1755 _ => TyKind::Paren(P(ty))
1760 } else if self.eat(&token::Not) {
1763 } else if self.eat(&token::BinOp(token::Star)) {
1765 TyKind::Ptr(self.parse_ptr()?)
1766 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1768 let t = self.parse_ty()?;
1769 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1770 let t = match self.maybe_parse_fixed_length_of_vec()? {
1771 None => TyKind::Slice(t),
1772 Some(length) => TyKind::Array(t, AnonConst {
1773 id: ast::DUMMY_NODE_ID,
1777 self.expect(&token::CloseDelim(token::Bracket))?;
1779 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1782 self.parse_borrowed_pointee()?
1783 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1785 // In order to not be ambiguous, the type must be surrounded by parens.
1786 self.expect(&token::OpenDelim(token::Paren))?;
1788 id: ast::DUMMY_NODE_ID,
1789 value: self.parse_expr()?,
1791 self.expect(&token::CloseDelim(token::Paren))?;
1793 } else if self.eat_keyword(keywords::Underscore) {
1794 // A type to be inferred `_`
1796 } else if self.token_is_bare_fn_keyword() {
1797 // Function pointer type
1798 self.parse_ty_bare_fn(Vec::new())?
1799 } else if self.check_keyword(keywords::For) {
1800 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1801 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1802 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1804 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1805 if self.token_is_bare_fn_keyword() {
1806 self.parse_ty_bare_fn(lifetime_defs)?
1808 let path = self.parse_path(PathStyle::Type)?;
1809 let parse_plus = allow_plus && self.check_plus();
1810 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1812 } else if self.eat_keyword(keywords::Impl) {
1813 // Always parse bounds greedily for better error recovery.
1814 let bounds = self.parse_generic_bounds(None)?;
1815 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1816 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1817 } else if self.check_keyword(keywords::Dyn) &&
1818 (self.span.rust_2018() ||
1819 self.look_ahead(1, |t| t.can_begin_bound() &&
1820 !can_continue_type_after_non_fn_ident(t))) {
1821 self.bump(); // `dyn`
1822 // Always parse bounds greedily for better error recovery.
1823 let bounds = self.parse_generic_bounds(None)?;
1824 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1825 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1826 } else if self.check(&token::Question) ||
1827 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1828 // Bound list (trait object type)
1829 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
1830 TraitObjectSyntax::None)
1831 } else if self.eat_lt() {
1833 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1834 TyKind::Path(Some(qself), path)
1835 } else if self.token.is_path_start() {
1837 let path = self.parse_path(PathStyle::Type)?;
1838 if self.eat(&token::Not) {
1839 // Macro invocation in type position
1840 let (delim, tts) = self.expect_delimited_token_tree()?;
1841 let node = Mac_ { path, tts, delim };
1842 TyKind::Mac(respan(lo.to(self.prev_span), node))
1844 // Just a type path or bound list (trait object type) starting with a trait.
1846 // `Trait1 + Trait2 + 'a`
1847 if allow_plus && self.check_plus() {
1848 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1850 TyKind::Path(None, path)
1853 } else if self.check(&token::DotDotDot) {
1854 if allow_c_variadic {
1855 self.eat(&token::DotDotDot);
1858 return Err(self.fatal(
1859 "only foreign functions are allowed to be C-variadic"
1863 let msg = format!("expected type, found {}", self.this_token_descr());
1864 return Err(self.fatal(&msg));
1867 let span = lo.to(self.prev_span);
1868 let ty = P(Ty { node, span, id: ast::DUMMY_NODE_ID });
1870 // Try to recover from use of `+` with incorrect priority.
1871 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1872 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1873 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
1876 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1877 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1878 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1879 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1881 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1882 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
1884 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1887 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1888 if !allow_plus && impl_dyn_multi {
1889 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1890 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1893 "use parentheses to disambiguate",
1895 Applicability::MachineApplicable
1900 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1901 // Do not add `+` to expected tokens.
1902 if !allow_plus || !self.token.is_like_plus() {
1907 let bounds = self.parse_generic_bounds(None)?;
1908 let sum_span = ty.span.to(self.prev_span);
1910 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1911 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1914 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1915 let sum_with_parens = pprust::to_string(|s| {
1916 use crate::print::pprust::PrintState;
1919 s.print_opt_lifetime(lifetime)?;
1920 s.print_mutability(mut_ty.mutbl)?;
1922 s.print_type(&mut_ty.ty)?;
1923 s.print_type_bounds(" +", &bounds)?;
1926 err.span_suggestion(
1928 "try adding parentheses",
1930 Applicability::MachineApplicable
1933 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1934 err.span_label(sum_span, "perhaps you forgot parentheses?");
1937 err.span_label(sum_span, "expected a path");
1944 /// Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1945 /// Attempt to convert the base expression/pattern/type into a type, parse the `::AssocItem`
1946 /// tail, and combine them into a `<Ty>::AssocItem` expression/pattern/type.
1947 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: P<T>, allow_recovery: bool)
1948 -> PResult<'a, P<T>> {
1949 // Do not add `::` to expected tokens.
1950 if allow_recovery && self.token == token::ModSep {
1951 if let Some(ty) = base.to_ty() {
1952 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1958 /// Given an already parsed `Ty` parse the `::AssocItem` tail and
1959 /// combine them into a `<Ty>::AssocItem` expression/pattern/type.
1960 fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(&mut self, ty_span: Span, ty: P<Ty>)
1961 -> PResult<'a, P<T>> {
1962 self.expect(&token::ModSep)?;
1964 let mut path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
1965 self.parse_path_segments(&mut path.segments, T::PATH_STYLE)?;
1966 path.span = ty_span.to(self.prev_span);
1968 let ty_str = self.sess.source_map().span_to_snippet(ty_span)
1969 .unwrap_or_else(|_| pprust::ty_to_string(&ty));
1971 .struct_span_err(path.span, "missing angle brackets in associated item path")
1972 .span_suggestion( // this is a best-effort recovery
1973 path.span, "try", format!("<{}>::{}", ty_str, path), Applicability::MaybeIncorrect
1976 let path_span = ty_span.shrink_to_hi(); // use an empty path since `position` == 0
1977 Ok(P(T::recovered(Some(QSelf { ty, path_span, position: 0 }), path)))
1980 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1981 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1982 let mutbl = self.parse_mutability();
1983 let ty = self.parse_ty_no_plus()?;
1984 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1987 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1988 let mutbl = if self.eat_keyword(keywords::Mut) {
1990 } else if self.eat_keyword(keywords::Const) {
1991 Mutability::Immutable
1993 let span = self.prev_span;
1994 let msg = "expected mut or const in raw pointer type";
1995 self.struct_span_err(span, msg)
1996 .span_label(span, msg)
1997 .help("use `*mut T` or `*const T` as appropriate")
1999 Mutability::Immutable
2001 let t = self.parse_ty_no_plus()?;
2002 Ok(MutTy { ty: t, mutbl: mutbl })
2005 fn is_named_argument(&mut self) -> bool {
2006 let offset = match self.token {
2007 token::Interpolated(ref nt) => match **nt {
2008 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2011 token::BinOp(token::And) | token::AndAnd => 1,
2012 _ if self.token.is_keyword(keywords::Mut) => 1,
2016 self.look_ahead(offset, |t| t.is_ident()) &&
2017 self.look_ahead(offset + 1, |t| t == &token::Colon)
2020 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
2022 fn eat_incorrect_doc_comment(&mut self, applied_to: &str) {
2023 if let token::DocComment(_) = self.token {
2024 let mut err = self.diagnostic().struct_span_err(
2026 &format!("documentation comments cannot be applied to {}", applied_to),
2028 err.span_label(self.span, "doc comments are not allowed here");
2031 } else if self.token == token::Pound && self.look_ahead(1, |t| {
2032 *t == token::OpenDelim(token::Bracket)
2035 // Skip every token until next possible arg.
2036 while self.token != token::CloseDelim(token::Bracket) {
2039 let sp = lo.to(self.span);
2041 let mut err = self.diagnostic().struct_span_err(
2043 &format!("attributes cannot be applied to {}", applied_to),
2045 err.span_label(sp, "attributes are not allowed here");
2050 /// This version of parse arg doesn't necessarily require identifier names.
2051 fn parse_arg_general(&mut self, require_name: bool, is_trait_item: bool,
2052 allow_c_variadic: bool) -> PResult<'a, Arg> {
2053 maybe_whole!(self, NtArg, |x| x);
2055 if let Ok(Some(_)) = self.parse_self_arg() {
2056 let mut err = self.struct_span_err(self.prev_span,
2057 "unexpected `self` argument in function");
2058 err.span_label(self.prev_span,
2059 "`self` is only valid as the first argument of an associated function");
2063 let (pat, ty) = if require_name || self.is_named_argument() {
2064 debug!("parse_arg_general parse_pat (require_name:{})",
2066 self.eat_incorrect_doc_comment("method arguments");
2067 let pat = self.parse_pat(Some("argument name"))?;
2069 if let Err(mut err) = self.expect(&token::Colon) {
2070 // If we find a pattern followed by an identifier, it could be an (incorrect)
2071 // C-style parameter declaration.
2072 if self.check_ident() && self.look_ahead(1, |t| {
2073 *t == token::Comma || *t == token::CloseDelim(token::Paren)
2075 let ident = self.parse_ident().unwrap();
2076 let span = pat.span.with_hi(ident.span.hi());
2078 err.span_suggestion(
2080 "declare the type after the parameter binding",
2081 String::from("<identifier>: <type>"),
2082 Applicability::HasPlaceholders,
2084 } else if require_name && is_trait_item {
2085 if let PatKind::Ident(_, ident, _) = pat.node {
2086 err.span_suggestion(
2088 "explicitly ignore parameter",
2089 format!("_: {}", ident),
2090 Applicability::MachineApplicable,
2094 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
2100 self.eat_incorrect_doc_comment("a method argument's type");
2101 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
2103 debug!("parse_arg_general ident_to_pat");
2104 let parser_snapshot_before_ty = self.clone();
2105 self.eat_incorrect_doc_comment("a method argument's type");
2106 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
2107 if ty.is_ok() && self.token != token::Comma &&
2108 self.token != token::CloseDelim(token::Paren) {
2109 // This wasn't actually a type, but a pattern looking like a type,
2110 // so we are going to rollback and re-parse for recovery.
2111 ty = self.unexpected();
2115 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
2117 id: ast::DUMMY_NODE_ID,
2118 node: PatKind::Ident(
2119 BindingMode::ByValue(Mutability::Immutable), ident, None),
2125 // If this is a C-variadic argument and we hit an error, return the
2127 if self.token == token::DotDotDot {
2130 // Recover from attempting to parse the argument as a type without pattern.
2132 mem::replace(self, parser_snapshot_before_ty);
2133 let pat = self.parse_pat(Some("argument name"))?;
2134 self.expect(&token::Colon)?;
2135 let ty = self.parse_ty()?;
2137 let mut err = self.diagnostic().struct_span_err_with_code(
2139 "patterns aren't allowed in methods without bodies",
2140 DiagnosticId::Error("E0642".into()),
2142 err.span_suggestion_short(
2144 "give this argument a name or use an underscore to ignore it",
2146 Applicability::MachineApplicable,
2150 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2152 node: PatKind::Wild,
2154 id: ast::DUMMY_NODE_ID
2161 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal })
2164 /// Parses a single function argument.
2165 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
2166 self.parse_arg_general(true, false, false)
2169 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
2170 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
2171 let pat = self.parse_pat(Some("argument name"))?;
2172 let t = if self.eat(&token::Colon) {
2176 id: ast::DUMMY_NODE_ID,
2177 node: TyKind::Infer,
2178 span: self.prev_span,
2184 id: ast::DUMMY_NODE_ID,
2185 source: ast::ArgSource::Normal,
2189 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
2190 if self.eat(&token::Semi) {
2191 Ok(Some(self.parse_expr()?))
2197 /// Matches `token_lit = LIT_INTEGER | ...`.
2198 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
2199 let out = match self.token {
2200 token::Interpolated(ref nt) => match **nt {
2201 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
2202 ExprKind::Lit(ref lit) => { lit.node.clone() }
2203 _ => { return self.unexpected_last(&self.token); }
2205 _ => { return self.unexpected_last(&self.token); }
2207 token::Literal(lit, suf) => {
2208 let diag = Some((self.span, &self.sess.span_diagnostic));
2209 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
2213 self.expect_no_suffix(sp, &format!("a {}", lit.literal_name()), suf)
2218 token::Dot if self.look_ahead(1, |t| match t {
2219 token::Literal(parse::token::Lit::Integer(_) , _) => true,
2221 }) => { // recover from `let x = .4;`
2224 if let token::Literal(
2225 parse::token::Lit::Integer(val),
2228 let suffix = suffix.and_then(|s| {
2232 } else if s == "f64" {
2239 let sp = lo.to(self.prev_span);
2240 let mut err = self.diagnostic()
2241 .struct_span_err(sp, "float literals must have an integer part");
2242 err.span_suggestion(
2244 "must have an integer part",
2245 format!("0.{}{}", val, suffix),
2246 Applicability::MachineApplicable,
2249 return Ok(match suffix {
2250 "f32" => ast::LitKind::Float(val, ast::FloatTy::F32),
2251 "f64" => ast::LitKind::Float(val, ast::FloatTy::F64),
2252 _ => ast::LitKind::FloatUnsuffixed(val),
2258 _ => { return self.unexpected_last(&self.token); }
2265 /// Matches `lit = true | false | token_lit`.
2266 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
2268 let lit = if self.eat_keyword(keywords::True) {
2270 } else if self.eat_keyword(keywords::False) {
2271 LitKind::Bool(false)
2273 let lit = self.parse_lit_token()?;
2276 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
2279 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
2280 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
2281 maybe_whole_expr!(self);
2283 let minus_lo = self.span;
2284 let minus_present = self.eat(&token::BinOp(token::Minus));
2286 let literal = self.parse_lit()?;
2287 let hi = self.prev_span;
2288 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
2291 let minus_hi = self.prev_span;
2292 let unary = self.mk_unary(UnOp::Neg, expr);
2293 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
2299 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2301 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2302 let span = self.span;
2304 Ok(Ident::new(ident.name, span))
2306 _ => self.parse_ident(),
2310 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
2312 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
2313 let span = self.span;
2315 Ok(Ident::new(ident.name, span))
2317 _ => self.parse_ident(),
2321 /// Parses a qualified path.
2322 /// Assumes that the leading `<` has been parsed already.
2324 /// `qualified_path = <type [as trait_ref]>::path`
2329 /// `<T as U>::F::a<S>` (without disambiguator)
2330 /// `<T as U>::F::a::<S>` (with disambiguator)
2331 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2332 let lo = self.prev_span;
2333 let ty = self.parse_ty()?;
2335 // `path` will contain the prefix of the path up to the `>`,
2336 // if any (e.g., `U` in the `<T as U>::*` examples
2337 // above). `path_span` has the span of that path, or an empty
2338 // span in the case of something like `<T>::Bar`.
2339 let (mut path, path_span);
2340 if self.eat_keyword(keywords::As) {
2341 let path_lo = self.span;
2342 path = self.parse_path(PathStyle::Type)?;
2343 path_span = path_lo.to(self.prev_span);
2345 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2346 path_span = self.span.to(self.span);
2349 // See doc comment for `unmatched_angle_bracket_count`.
2350 self.expect(&token::Gt)?;
2351 if self.unmatched_angle_bracket_count > 0 {
2352 self.unmatched_angle_bracket_count -= 1;
2353 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
2356 self.expect(&token::ModSep)?;
2358 let qself = QSelf { ty, path_span, position: path.segments.len() };
2359 self.parse_path_segments(&mut path.segments, style)?;
2361 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2364 /// Parses simple paths.
2366 /// `path = [::] segment+`
2367 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2370 /// `a::b::C<D>` (without disambiguator)
2371 /// `a::b::C::<D>` (with disambiguator)
2372 /// `Fn(Args)` (without disambiguator)
2373 /// `Fn::(Args)` (with disambiguator)
2374 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2375 maybe_whole!(self, NtPath, |path| {
2376 if style == PathStyle::Mod &&
2377 path.segments.iter().any(|segment| segment.args.is_some()) {
2378 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2383 let lo = self.meta_var_span.unwrap_or(self.span);
2384 let mut segments = Vec::new();
2385 let mod_sep_ctxt = self.span.ctxt();
2386 if self.eat(&token::ModSep) {
2387 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2389 self.parse_path_segments(&mut segments, style)?;
2391 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2394 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
2395 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
2397 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2398 let meta_ident = match self.token {
2399 token::Interpolated(ref nt) => match **nt {
2400 token::NtMeta(ref meta) => match meta.node {
2401 ast::MetaItemKind::Word => Some(meta.path.clone()),
2408 if let Some(path) = meta_ident {
2412 self.parse_path(style)
2415 fn parse_path_segments(&mut self,
2416 segments: &mut Vec<PathSegment>,
2418 -> PResult<'a, ()> {
2420 let segment = self.parse_path_segment(style)?;
2421 if style == PathStyle::Expr {
2422 // In order to check for trailing angle brackets, we must have finished
2423 // recursing (`parse_path_segment` can indirectly call this function),
2424 // that is, the next token must be the highlighted part of the below example:
2426 // `Foo::<Bar as Baz<T>>::Qux`
2429 // As opposed to the below highlight (if we had only finished the first
2432 // `Foo::<Bar as Baz<T>>::Qux`
2435 // `PathStyle::Expr` is only provided at the root invocation and never in
2436 // `parse_path_segment` to recurse and therefore can be checked to maintain
2438 self.check_trailing_angle_brackets(&segment, token::ModSep);
2440 segments.push(segment);
2442 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2448 fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
2449 let ident = self.parse_path_segment_ident()?;
2451 let is_args_start = |token: &token::Token| match *token {
2452 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2455 let check_args_start = |this: &mut Self| {
2456 this.expected_tokens.extend_from_slice(
2457 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2459 is_args_start(&this.token)
2462 Ok(if style == PathStyle::Type && check_args_start(self) ||
2463 style != PathStyle::Mod && self.check(&token::ModSep)
2464 && self.look_ahead(1, |t| is_args_start(t)) {
2465 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
2466 // it isn't, then we reset the unmatched angle bracket count as we're about to start
2467 // parsing a new path.
2468 if style == PathStyle::Expr {
2469 self.unmatched_angle_bracket_count = 0;
2470 self.max_angle_bracket_count = 0;
2473 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2474 self.eat(&token::ModSep);
2476 let args = if self.eat_lt() {
2478 let (args, bindings) =
2479 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
2481 let span = lo.to(self.prev_span);
2482 AngleBracketedArgs { args, bindings, span }.into()
2486 let (inputs, recovered) = self.parse_seq_to_before_tokens(
2487 &[&token::CloseDelim(token::Paren)],
2488 SeqSep::trailing_allowed(token::Comma),
2489 TokenExpectType::Expect,
2494 let span = lo.to(self.prev_span);
2495 let output = if self.eat(&token::RArrow) {
2496 Some(self.parse_ty_common(false, false, false)?)
2500 ParenthesizedArgs { inputs, output, span }.into()
2503 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2505 // Generic arguments are not found.
2506 PathSegment::from_ident(ident)
2510 crate fn check_lifetime(&mut self) -> bool {
2511 self.expected_tokens.push(TokenType::Lifetime);
2512 self.token.is_lifetime()
2515 /// Parses a single lifetime `'a` or panics.
2516 crate fn expect_lifetime(&mut self) -> Lifetime {
2517 if let Some(ident) = self.token.lifetime() {
2518 let span = self.span;
2520 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2522 self.span_bug(self.span, "not a lifetime")
2526 fn eat_label(&mut self) -> Option<Label> {
2527 if let Some(ident) = self.token.lifetime() {
2528 let span = self.span;
2530 Some(Label { ident: Ident::new(ident.name, span) })
2536 /// Parses mutability (`mut` or nothing).
2537 fn parse_mutability(&mut self) -> Mutability {
2538 if self.eat_keyword(keywords::Mut) {
2541 Mutability::Immutable
2545 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2546 if let token::Literal(token::Integer(name), suffix) = self.token {
2547 self.expect_no_suffix(self.span, "a tuple index", suffix);
2549 Ok(Ident::new(name, self.prev_span))
2551 self.parse_ident_common(false)
2555 /// Parse ident (COLON expr)?
2556 fn parse_field(&mut self) -> PResult<'a, Field> {
2557 let attrs = self.parse_outer_attributes()?;
2560 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2561 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
2562 t == &token::Colon || t == &token::Eq
2564 let fieldname = self.parse_field_name()?;
2566 // Check for an equals token. This means the source incorrectly attempts to
2567 // initialize a field with an eq rather than a colon.
2568 if self.token == token::Eq {
2570 .struct_span_err(self.span, "expected `:`, found `=`")
2572 fieldname.span.shrink_to_hi().to(self.span),
2573 "replace equals symbol with a colon",
2575 Applicability::MachineApplicable,
2580 (fieldname, self.parse_expr()?, false)
2582 let fieldname = self.parse_ident_common(false)?;
2584 // Mimic `x: x` for the `x` field shorthand.
2585 let path = ast::Path::from_ident(fieldname);
2586 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2587 (fieldname, expr, true)
2591 span: lo.to(expr.span),
2594 attrs: attrs.into(),
2598 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2599 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2602 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2603 ExprKind::Unary(unop, expr)
2606 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2607 ExprKind::Binary(binop, lhs, rhs)
2610 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2611 ExprKind::Call(f, args)
2614 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2615 ExprKind::Index(expr, idx)
2618 fn mk_range(&mut self,
2619 start: Option<P<Expr>>,
2620 end: Option<P<Expr>>,
2621 limits: RangeLimits)
2622 -> PResult<'a, ast::ExprKind> {
2623 if end.is_none() && limits == RangeLimits::Closed {
2624 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2626 Ok(ExprKind::Range(start, end, limits))
2630 fn mk_assign_op(&mut self, binop: ast::BinOp,
2631 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2632 ExprKind::AssignOp(binop, lhs, rhs)
2635 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
2636 let delim = match self.token {
2637 token::OpenDelim(delim) => delim,
2639 let msg = "expected open delimiter";
2640 let mut err = self.fatal(msg);
2641 err.span_label(self.span, msg);
2645 let tts = match self.parse_token_tree() {
2646 TokenTree::Delimited(_, _, tts) => tts,
2647 _ => unreachable!(),
2649 let delim = match delim {
2650 token::Paren => MacDelimiter::Parenthesis,
2651 token::Bracket => MacDelimiter::Bracket,
2652 token::Brace => MacDelimiter::Brace,
2653 token::NoDelim => self.bug("unexpected no delimiter"),
2655 Ok((delim, tts.into()))
2658 /// At the bottom (top?) of the precedence hierarchy,
2659 /// Parses things like parenthesized exprs, macros, `return`, etc.
2661 /// N.B., this does not parse outer attributes, and is private because it only works
2662 /// correctly if called from `parse_dot_or_call_expr()`.
2663 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2664 maybe_recover_from_interpolated_ty_qpath!(self, true);
2665 maybe_whole_expr!(self);
2667 // Outer attributes are already parsed and will be
2668 // added to the return value after the fact.
2670 // Therefore, prevent sub-parser from parsing
2671 // attributes by giving them a empty "already parsed" list.
2672 let mut attrs = ThinVec::new();
2675 let mut hi = self.span;
2679 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2681 token::OpenDelim(token::Paren) => {
2684 attrs.extend(self.parse_inner_attributes()?);
2686 // (e) is parenthesized e
2687 // (e,) is a tuple with only one field, e
2688 let mut es = vec![];
2689 let mut trailing_comma = false;
2690 let mut recovered = false;
2691 while self.token != token::CloseDelim(token::Paren) {
2692 es.push(match self.parse_expr() {
2695 // recover from parse error in tuple list
2696 return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2699 recovered = self.expect_one_of(
2701 &[token::Comma, token::CloseDelim(token::Paren)],
2703 if self.eat(&token::Comma) {
2704 trailing_comma = true;
2706 trailing_comma = false;
2714 hi = self.prev_span;
2715 ex = if es.len() == 1 && !trailing_comma {
2716 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2721 token::OpenDelim(token::Brace) => {
2722 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2724 token::BinOp(token::Or) | token::OrOr => {
2725 return self.parse_lambda_expr(attrs);
2727 token::OpenDelim(token::Bracket) => {
2730 attrs.extend(self.parse_inner_attributes()?);
2732 if self.eat(&token::CloseDelim(token::Bracket)) {
2734 ex = ExprKind::Array(Vec::new());
2737 let first_expr = self.parse_expr()?;
2738 if self.eat(&token::Semi) {
2739 // Repeating array syntax: [ 0; 512 ]
2740 let count = AnonConst {
2741 id: ast::DUMMY_NODE_ID,
2742 value: self.parse_expr()?,
2744 self.expect(&token::CloseDelim(token::Bracket))?;
2745 ex = ExprKind::Repeat(first_expr, count);
2746 } else if self.eat(&token::Comma) {
2747 // Vector with two or more elements.
2748 let remaining_exprs = self.parse_seq_to_end(
2749 &token::CloseDelim(token::Bracket),
2750 SeqSep::trailing_allowed(token::Comma),
2751 |p| Ok(p.parse_expr()?)
2753 let mut exprs = vec![first_expr];
2754 exprs.extend(remaining_exprs);
2755 ex = ExprKind::Array(exprs);
2757 // Vector with one element.
2758 self.expect(&token::CloseDelim(token::Bracket))?;
2759 ex = ExprKind::Array(vec![first_expr]);
2762 hi = self.prev_span;
2766 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2768 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2770 if self.span.rust_2018() && self.check_keyword(keywords::Async)
2772 if self.is_async_block() { // check for `async {` and `async move {`
2773 return self.parse_async_block(attrs);
2775 return self.parse_lambda_expr(attrs);
2778 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2779 return self.parse_lambda_expr(attrs);
2781 if self.eat_keyword(keywords::If) {
2782 return self.parse_if_expr(attrs);
2784 if self.eat_keyword(keywords::For) {
2785 let lo = self.prev_span;
2786 return self.parse_for_expr(None, lo, attrs);
2788 if self.eat_keyword(keywords::While) {
2789 let lo = self.prev_span;
2790 return self.parse_while_expr(None, lo, attrs);
2792 if let Some(label) = self.eat_label() {
2793 let lo = label.ident.span;
2794 self.expect(&token::Colon)?;
2795 if self.eat_keyword(keywords::While) {
2796 return self.parse_while_expr(Some(label), lo, attrs)
2798 if self.eat_keyword(keywords::For) {
2799 return self.parse_for_expr(Some(label), lo, attrs)
2801 if self.eat_keyword(keywords::Loop) {
2802 return self.parse_loop_expr(Some(label), lo, attrs)
2804 if self.token == token::OpenDelim(token::Brace) {
2805 return self.parse_block_expr(Some(label),
2807 BlockCheckMode::Default,
2810 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2811 let mut err = self.fatal(msg);
2812 err.span_label(self.span, msg);
2815 if self.eat_keyword(keywords::Loop) {
2816 let lo = self.prev_span;
2817 return self.parse_loop_expr(None, lo, attrs);
2819 if self.eat_keyword(keywords::Continue) {
2820 let label = self.eat_label();
2821 let ex = ExprKind::Continue(label);
2822 let hi = self.prev_span;
2823 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2825 if self.eat_keyword(keywords::Match) {
2826 let match_sp = self.prev_span;
2827 return self.parse_match_expr(attrs).map_err(|mut err| {
2828 err.span_label(match_sp, "while parsing this match expression");
2832 if self.eat_keyword(keywords::Unsafe) {
2833 return self.parse_block_expr(
2836 BlockCheckMode::Unsafe(ast::UserProvided),
2839 if self.is_do_catch_block() {
2840 let mut db = self.fatal("found removed `do catch` syntax");
2841 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2844 if self.is_try_block() {
2846 assert!(self.eat_keyword(keywords::Try));
2847 return self.parse_try_block(lo, attrs);
2849 if self.eat_keyword(keywords::Return) {
2850 if self.token.can_begin_expr() {
2851 let e = self.parse_expr()?;
2853 ex = ExprKind::Ret(Some(e));
2855 ex = ExprKind::Ret(None);
2857 } else if self.eat_keyword(keywords::Break) {
2858 let label = self.eat_label();
2859 let e = if self.token.can_begin_expr()
2860 && !(self.token == token::OpenDelim(token::Brace)
2861 && self.restrictions.contains(
2862 Restrictions::NO_STRUCT_LITERAL)) {
2863 Some(self.parse_expr()?)
2867 ex = ExprKind::Break(label, e);
2868 hi = self.prev_span;
2869 } else if self.eat_keyword(keywords::Yield) {
2870 if self.token.can_begin_expr() {
2871 let e = self.parse_expr()?;
2873 ex = ExprKind::Yield(Some(e));
2875 ex = ExprKind::Yield(None);
2877 } else if self.token.is_keyword(keywords::Let) {
2878 // Catch this syntax error here, instead of in `parse_ident`, so
2879 // that we can explicitly mention that let is not to be used as an expression
2880 let mut db = self.fatal("expected expression, found statement (`let`)");
2881 db.span_label(self.span, "expected expression");
2882 db.note("variable declaration using `let` is a statement");
2884 } else if self.token.is_path_start() {
2885 let path = self.parse_path(PathStyle::Expr)?;
2887 // `!`, as an operator, is prefix, so we know this isn't that
2888 if self.eat(&token::Not) {
2889 // MACRO INVOCATION expression
2890 let (delim, tts) = self.expect_delimited_token_tree()?;
2891 hi = self.prev_span;
2892 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2893 } else if self.check(&token::OpenDelim(token::Brace)) {
2894 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2898 ex = ExprKind::Path(None, path);
2902 ex = ExprKind::Path(None, path);
2905 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2906 // Don't complain about bare semicolons after unclosed braces
2907 // recovery in order to keep the error count down. Fixing the
2908 // delimiters will possibly also fix the bare semicolon found in
2909 // expression context. For example, silence the following error:
2911 // error: expected expression, found `;`
2915 // | ^ expected expression
2918 return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
2920 match self.parse_literal_maybe_minus() {
2923 ex = expr.node.clone();
2926 self.cancel(&mut err);
2927 let msg = format!("expected expression, found {}",
2928 self.this_token_descr());
2929 let mut err = self.fatal(&msg);
2930 let sp = self.sess.source_map().start_point(self.span);
2931 if let Some(sp) = self.sess.abiguous_block_expr_parse.borrow()
2934 if let Ok(snippet) = self.sess.source_map().span_to_snippet(*sp) {
2935 err.span_suggestion(
2937 "parenthesis are required to parse this as an expression",
2938 format!("({})", snippet),
2939 Applicability::MachineApplicable,
2943 err.span_label(self.span, "expected expression");
2951 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2952 self.maybe_recover_from_bad_qpath(expr, true)
2955 fn maybe_parse_struct_expr(
2959 attrs: &ThinVec<Attribute>,
2960 ) -> Option<PResult<'a, P<Expr>>> {
2961 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2962 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2963 // `{ ident, ` cannot start a block
2964 self.look_ahead(2, |t| t == &token::Comma) ||
2965 self.look_ahead(2, |t| t == &token::Colon) && (
2966 // `{ ident: token, ` cannot start a block
2967 self.look_ahead(4, |t| t == &token::Comma) ||
2968 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2969 self.look_ahead(3, |t| !t.can_begin_type())
2973 if struct_allowed || certainly_not_a_block() {
2974 // This is a struct literal, but we don't can't accept them here
2975 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2976 if let (Ok(expr), false) = (&expr, struct_allowed) {
2977 let mut err = self.diagnostic().struct_span_err(
2979 "struct literals are not allowed here",
2981 err.multipart_suggestion(
2982 "surround the struct literal with parenthesis",
2984 (lo.shrink_to_lo(), "(".to_string()),
2985 (expr.span.shrink_to_hi(), ")".to_string()),
2987 Applicability::MachineApplicable,
2996 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2997 -> PResult<'a, P<Expr>> {
2998 let struct_sp = lo.to(self.prev_span);
3000 let mut fields = Vec::new();
3001 let mut base = None;
3003 attrs.extend(self.parse_inner_attributes()?);
3005 while self.token != token::CloseDelim(token::Brace) {
3006 if self.eat(&token::DotDot) {
3007 let exp_span = self.prev_span;
3008 match self.parse_expr() {
3014 self.recover_stmt();
3017 if self.token == token::Comma {
3018 let mut err = self.sess.span_diagnostic.mut_span_err(
3019 exp_span.to(self.prev_span),
3020 "cannot use a comma after the base struct",
3022 err.span_suggestion_short(
3024 "remove this comma",
3026 Applicability::MachineApplicable
3028 err.note("the base struct must always be the last field");
3030 self.recover_stmt();
3035 let mut recovery_field = None;
3036 if let token::Ident(ident, _) = self.token {
3037 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
3038 // Use in case of error after field-looking code: `S { foo: () with a }`
3039 let mut ident = ident.clone();
3040 ident.span = self.span;
3041 recovery_field = Some(ast::Field {
3044 expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
3045 is_shorthand: false,
3046 attrs: ThinVec::new(),
3050 let mut parsed_field = None;
3051 match self.parse_field() {
3052 Ok(f) => parsed_field = Some(f),
3054 e.span_label(struct_sp, "while parsing this struct");
3057 // If the next token is a comma, then try to parse
3058 // what comes next as additional fields, rather than
3059 // bailing out until next `}`.
3060 if self.token != token::Comma {
3061 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
3062 if self.token != token::Comma {
3069 match self.expect_one_of(&[token::Comma],
3070 &[token::CloseDelim(token::Brace)]) {
3071 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
3072 // only include the field if there's no parse error for the field name
3076 if let Some(f) = recovery_field {
3079 e.span_label(struct_sp, "while parsing this struct");
3081 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
3082 self.eat(&token::Comma);
3087 let span = lo.to(self.span);
3088 self.expect(&token::CloseDelim(token::Brace))?;
3089 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
3092 fn parse_or_use_outer_attributes(&mut self,
3093 already_parsed_attrs: Option<ThinVec<Attribute>>)
3094 -> PResult<'a, ThinVec<Attribute>> {
3095 if let Some(attrs) = already_parsed_attrs {
3098 self.parse_outer_attributes().map(|a| a.into())
3102 /// Parses a block or unsafe block.
3103 fn parse_block_expr(&mut self, opt_label: Option<Label>,
3104 lo: Span, blk_mode: BlockCheckMode,
3105 outer_attrs: ThinVec<Attribute>)
3106 -> PResult<'a, P<Expr>> {
3107 self.expect(&token::OpenDelim(token::Brace))?;
3109 let mut attrs = outer_attrs;
3110 attrs.extend(self.parse_inner_attributes()?);
3112 let blk = self.parse_block_tail(lo, blk_mode)?;
3113 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
3116 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
3117 fn parse_dot_or_call_expr(&mut self,
3118 already_parsed_attrs: Option<ThinVec<Attribute>>)
3119 -> PResult<'a, P<Expr>> {
3120 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3122 let b = self.parse_bottom_expr();
3123 let (span, b) = self.interpolated_or_expr_span(b)?;
3124 self.parse_dot_or_call_expr_with(b, span, attrs)
3127 fn parse_dot_or_call_expr_with(&mut self,
3130 mut attrs: ThinVec<Attribute>)
3131 -> PResult<'a, P<Expr>> {
3132 // Stitch the list of outer attributes onto the return value.
3133 // A little bit ugly, but the best way given the current code
3135 self.parse_dot_or_call_expr_with_(e0, lo)
3137 expr.map(|mut expr| {
3138 attrs.extend::<Vec<_>>(expr.attrs.into());
3141 ExprKind::If(..) | ExprKind::IfLet(..) => {
3142 if !expr.attrs.is_empty() {
3143 // Just point to the first attribute in there...
3144 let span = expr.attrs[0].span;
3147 "attributes are not yet allowed on `if` \
3158 // Assuming we have just parsed `.`, continue parsing into an expression.
3159 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3160 let segment = self.parse_path_segment(PathStyle::Expr)?;
3161 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
3163 Ok(match self.token {
3164 token::OpenDelim(token::Paren) => {
3165 // Method call `expr.f()`
3166 let mut args = self.parse_unspanned_seq(
3167 &token::OpenDelim(token::Paren),
3168 &token::CloseDelim(token::Paren),
3169 SeqSep::trailing_allowed(token::Comma),
3170 |p| Ok(p.parse_expr()?)
3172 args.insert(0, self_arg);
3174 let span = lo.to(self.prev_span);
3175 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
3178 // Field access `expr.f`
3179 if let Some(args) = segment.args {
3180 self.span_err(args.span(),
3181 "field expressions may not have generic arguments");
3184 let span = lo.to(self.prev_span);
3185 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
3190 /// This function checks if there are trailing angle brackets and produces
3191 /// a diagnostic to suggest removing them.
3193 /// ```ignore (diagnostic)
3194 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
3195 /// ^^ help: remove extra angle brackets
3197 fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) {
3198 // This function is intended to be invoked after parsing a path segment where there are two
3201 // 1. A specific token is expected after the path segment.
3202 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
3203 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
3204 // 2. No specific token is expected after the path segment.
3205 // eg. `x.foo` (field access)
3207 // This function is called after parsing `.foo` and before parsing the token `end` (if
3208 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
3211 // We only care about trailing angle brackets if we previously parsed angle bracket
3212 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
3213 // removed in this case:
3215 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
3217 // This case is particularly tricky as we won't notice it just looking at the tokens -
3218 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
3219 // have already been parsed):
3221 // `x.foo::<u32>>>(3)`
3222 let parsed_angle_bracket_args = segment.args
3224 .map(|args| args.is_angle_bracketed())
3228 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
3229 parsed_angle_bracket_args,
3231 if !parsed_angle_bracket_args {
3235 // Keep the span at the start so we can highlight the sequence of `>` characters to be
3239 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
3240 // (since we might have the field access case and the characters we're eating are
3241 // actual operators and not trailing characters - ie `x.foo >> 3`).
3242 let mut position = 0;
3244 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
3245 // many of each (so we can correctly pluralize our error messages) and continue to
3247 let mut number_of_shr = 0;
3248 let mut number_of_gt = 0;
3249 while self.look_ahead(position, |t| {
3250 trace!("check_trailing_angle_brackets: t={:?}", t);
3251 if *t == token::BinOp(token::BinOpToken::Shr) {
3254 } else if *t == token::Gt {
3264 // If we didn't find any trailing `>` characters, then we have nothing to error about.
3266 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
3267 number_of_gt, number_of_shr,
3269 if number_of_gt < 1 && number_of_shr < 1 {
3273 // Finally, double check that we have our end token as otherwise this is the
3275 if self.look_ahead(position, |t| {
3276 trace!("check_trailing_angle_brackets: t={:?}", t);
3279 // Eat from where we started until the end token so that parsing can continue
3280 // as if we didn't have those extra angle brackets.
3281 self.eat_to_tokens(&[&end]);
3282 let span = lo.until(self.span);
3284 let plural = number_of_gt > 1 || number_of_shr >= 1;
3288 &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
3292 &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
3294 Applicability::MachineApplicable,
3300 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3305 while self.eat(&token::Question) {
3306 let hi = self.prev_span;
3307 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
3311 if self.eat(&token::Dot) {
3313 token::Ident(..) => {
3314 e = self.parse_dot_suffix(e, lo)?;
3316 token::Literal(token::Integer(name), suffix) => {
3317 let span = self.span;
3319 let field = ExprKind::Field(e, Ident::new(name, span));
3320 e = self.mk_expr(lo.to(span), field, ThinVec::new());
3322 self.expect_no_suffix(span, "a tuple index", suffix);
3324 token::Literal(token::Float(n), _suf) => {
3326 let fstr = n.as_str();
3327 let mut err = self.diagnostic()
3328 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
3329 err.span_label(self.prev_span, "unexpected token");
3330 if fstr.chars().all(|x| "0123456789.".contains(x)) {
3331 let float = match fstr.parse::<f64>().ok() {
3335 let sugg = pprust::to_string(|s| {
3336 use crate::print::pprust::PrintState;
3340 s.print_usize(float.trunc() as usize)?;
3343 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
3345 err.span_suggestion(
3346 lo.to(self.prev_span),
3347 "try parenthesizing the first index",
3349 Applicability::MachineApplicable
3356 // FIXME Could factor this out into non_fatal_unexpected or something.
3357 let actual = self.this_token_to_string();
3358 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
3363 if self.expr_is_complete(&e) { break; }
3366 token::OpenDelim(token::Paren) => {
3367 let seq = self.parse_unspanned_seq(
3368 &token::OpenDelim(token::Paren),
3369 &token::CloseDelim(token::Paren),
3370 SeqSep::trailing_allowed(token::Comma),
3371 |p| Ok(p.parse_expr()?)
3373 let nd = self.mk_call(e, es);
3374 let hi = self.prev_span;
3375 self.mk_expr(lo.to(hi), nd, ThinVec::new())
3377 e = self.recover_seq_parse_error(token::Paren, lo, seq);
3381 // Could be either an index expression or a slicing expression.
3382 token::OpenDelim(token::Bracket) => {
3384 let ix = self.parse_expr()?;
3386 self.expect(&token::CloseDelim(token::Bracket))?;
3387 let index = self.mk_index(e, ix);
3388 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
3396 fn recover_seq_parse_error(
3398 delim: token::DelimToken,
3400 result: PResult<'a, P<Expr>>,
3406 // recover from parse error
3407 self.consume_block(delim);
3408 self.mk_expr(lo.to(self.prev_span), ExprKind::Err, ThinVec::new())
3413 crate fn process_potential_macro_variable(&mut self) {
3414 let (token, span) = match self.token {
3415 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
3416 self.look_ahead(1, |t| t.is_ident()) => {
3418 let name = match self.token {
3419 token::Ident(ident, _) => ident,
3422 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
3423 err.span_label(self.span, "unknown macro variable");
3428 token::Interpolated(ref nt) => {
3429 self.meta_var_span = Some(self.span);
3430 // Interpolated identifier and lifetime tokens are replaced with usual identifier
3431 // and lifetime tokens, so the former are never encountered during normal parsing.
3433 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
3434 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
3444 /// Parses a single token tree from the input.
3445 crate fn parse_token_tree(&mut self) -> TokenTree {
3447 token::OpenDelim(..) => {
3448 let frame = mem::replace(&mut self.token_cursor.frame,
3449 self.token_cursor.stack.pop().unwrap());
3450 self.span = frame.span.entire();
3452 TokenTree::Delimited(
3455 frame.tree_cursor.stream.into(),
3458 token::CloseDelim(_) | token::Eof => unreachable!(),
3460 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
3462 TokenTree::Token(span, token)
3467 // parse a stream of tokens into a list of TokenTree's,
3469 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
3470 let mut tts = Vec::new();
3471 while self.token != token::Eof {
3472 tts.push(self.parse_token_tree());
3477 pub fn parse_tokens(&mut self) -> TokenStream {
3478 let mut result = Vec::new();
3481 token::Eof | token::CloseDelim(..) => break,
3482 _ => result.push(self.parse_token_tree().into()),
3485 TokenStream::new(result)
3488 /// Parse a prefix-unary-operator expr
3489 fn parse_prefix_expr(&mut self,
3490 already_parsed_attrs: Option<ThinVec<Attribute>>)
3491 -> PResult<'a, P<Expr>> {
3492 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3494 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
3495 let (hi, ex) = match self.token {
3498 let e = self.parse_prefix_expr(None);
3499 let (span, e) = self.interpolated_or_expr_span(e)?;
3500 (lo.to(span), self.mk_unary(UnOp::Not, e))
3502 // Suggest `!` for bitwise negation when encountering a `~`
3505 let e = self.parse_prefix_expr(None);
3506 let (span, e) = self.interpolated_or_expr_span(e)?;
3507 let span_of_tilde = lo;
3508 let mut err = self.diagnostic()
3509 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
3510 err.span_suggestion_short(
3512 "use `!` to perform bitwise negation",
3514 Applicability::MachineApplicable
3517 (lo.to(span), self.mk_unary(UnOp::Not, e))
3519 token::BinOp(token::Minus) => {
3521 let e = self.parse_prefix_expr(None);
3522 let (span, e) = self.interpolated_or_expr_span(e)?;
3523 (lo.to(span), self.mk_unary(UnOp::Neg, e))
3525 token::BinOp(token::Star) => {
3527 let e = self.parse_prefix_expr(None);
3528 let (span, e) = self.interpolated_or_expr_span(e)?;
3529 (lo.to(span), self.mk_unary(UnOp::Deref, e))
3531 token::BinOp(token::And) | token::AndAnd => {
3533 let m = self.parse_mutability();
3534 let e = self.parse_prefix_expr(None);
3535 let (span, e) = self.interpolated_or_expr_span(e)?;
3536 (lo.to(span), ExprKind::AddrOf(m, e))
3538 token::Ident(..) if self.token.is_keyword(keywords::In) => {
3540 let place = self.parse_expr_res(
3541 Restrictions::NO_STRUCT_LITERAL,
3544 let blk = self.parse_block()?;
3545 let span = blk.span;
3546 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
3547 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
3549 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
3551 let e = self.parse_prefix_expr(None);
3552 let (span, e) = self.interpolated_or_expr_span(e)?;
3553 (lo.to(span), ExprKind::Box(e))
3555 token::Ident(..) if self.token.is_ident_named("not") => {
3556 // `not` is just an ordinary identifier in Rust-the-language,
3557 // but as `rustc`-the-compiler, we can issue clever diagnostics
3558 // for confused users who really want to say `!`
3559 let token_cannot_continue_expr = |t: &token::Token| match *t {
3560 // These tokens can start an expression after `!`, but
3561 // can't continue an expression after an ident
3562 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3563 token::Literal(..) | token::Pound => true,
3564 token::Interpolated(ref nt) => match **nt {
3565 token::NtIdent(..) | token::NtExpr(..) |
3566 token::NtBlock(..) | token::NtPath(..) => true,
3571 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3572 if cannot_continue_expr {
3574 // Emit the error ...
3575 let mut err = self.diagnostic()
3576 .struct_span_err(self.span,
3577 &format!("unexpected {} after identifier",
3578 self.this_token_descr()));
3579 // span the `not` plus trailing whitespace to avoid
3580 // trailing whitespace after the `!` in our suggestion
3581 let to_replace = self.sess.source_map()
3582 .span_until_non_whitespace(lo.to(self.span));
3583 err.span_suggestion_short(
3585 "use `!` to perform logical negation",
3587 Applicability::MachineApplicable
3590 // —and recover! (just as if we were in the block
3591 // for the `token::Not` arm)
3592 let e = self.parse_prefix_expr(None);
3593 let (span, e) = self.interpolated_or_expr_span(e)?;
3594 (lo.to(span), self.mk_unary(UnOp::Not, e))
3596 return self.parse_dot_or_call_expr(Some(attrs));
3599 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3601 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3604 /// Parses an associative expression.
3606 /// This parses an expression accounting for associativity and precedence of the operators in
3609 fn parse_assoc_expr(&mut self,
3610 already_parsed_attrs: Option<ThinVec<Attribute>>)
3611 -> PResult<'a, P<Expr>> {
3612 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3615 /// Parses an associative expression with operators of at least `min_prec` precedence.
3616 fn parse_assoc_expr_with(&mut self,
3619 -> PResult<'a, P<Expr>> {
3620 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3623 let attrs = match lhs {
3624 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3627 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3628 return self.parse_prefix_range_expr(attrs);
3630 self.parse_prefix_expr(attrs)?
3634 match (self.expr_is_complete(&lhs), AssocOp::from_token(&self.token)) {
3636 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3639 (false, _) => {} // continue parsing the expression
3640 (true, Some(AssocOp::Multiply)) | // `{ 42 } *foo = bar;`
3641 (true, Some(AssocOp::Subtract)) | // `{ 42 } -5`
3642 (true, Some(AssocOp::Add)) => { // `{ 42 } + 42
3643 // These cases are ambiguous and can't be identified in the parser alone
3644 let sp = self.sess.source_map().start_point(self.span);
3645 self.sess.abiguous_block_expr_parse.borrow_mut().insert(sp, lhs.span);
3648 (true, Some(ref op)) if !op.can_continue_expr_unambiguously() => {
3651 (true, Some(_)) => {
3652 // #54186, #54482, #59975
3653 // We've found an expression that would be parsed as a statement, but the next
3654 // token implies this should be parsed as an expression.
3655 let mut err = self.sess.span_diagnostic.struct_span_err(
3659 let snippet = self.sess.source_map().span_to_snippet(lhs.span)
3660 .unwrap_or_else(|_| pprust::expr_to_string(&lhs));
3661 err.span_suggestion(
3663 "parenthesis are required to parse this as an expression",
3664 format!("({})", snippet),
3665 Applicability::MachineApplicable,
3670 self.expected_tokens.push(TokenType::Operator);
3671 while let Some(op) = AssocOp::from_token(&self.token) {
3673 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3674 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3675 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3676 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3677 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3678 (PrevTokenKind::Interpolated, _) => self.prev_span,
3679 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3680 if path.segments.len() == 1 => self.prev_span,
3684 let cur_op_span = self.span;
3685 let restrictions = if op.is_assign_like() {
3686 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3690 if op.precedence() < min_prec {
3693 // Check for deprecated `...` syntax
3694 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3695 self.err_dotdotdot_syntax(self.span);
3699 if op.is_comparison() {
3700 self.check_no_chained_comparison(&lhs, &op);
3703 if op == AssocOp::As {
3704 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3706 } else if op == AssocOp::Colon {
3707 let maybe_path = self.could_ascription_be_path(&lhs.node);
3708 let next_sp = self.span;
3710 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3713 self.bad_type_ascription(
3724 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3725 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3726 // generalise it to the Fixity::None code.
3728 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3729 // two variants are handled with `parse_prefix_range_expr` call above.
3730 let rhs = if self.is_at_start_of_range_notation_rhs() {
3731 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3732 LhsExpr::NotYetParsed)?)
3736 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3741 let limits = if op == AssocOp::DotDot {
3742 RangeLimits::HalfOpen
3747 let r = self.mk_range(Some(lhs), rhs, limits)?;
3748 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3752 let rhs = match op.fixity() {
3753 Fixity::Right => self.with_res(
3754 restrictions - Restrictions::STMT_EXPR,
3756 this.parse_assoc_expr_with(op.precedence(),
3757 LhsExpr::NotYetParsed)
3759 Fixity::Left => self.with_res(
3760 restrictions - Restrictions::STMT_EXPR,
3762 this.parse_assoc_expr_with(op.precedence() + 1,
3763 LhsExpr::NotYetParsed)
3765 // We currently have no non-associative operators that are not handled above by
3766 // the special cases. The code is here only for future convenience.
3767 Fixity::None => self.with_res(
3768 restrictions - Restrictions::STMT_EXPR,
3770 this.parse_assoc_expr_with(op.precedence() + 1,
3771 LhsExpr::NotYetParsed)
3775 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
3776 // including the attributes.
3780 .filter(|a| a.style == AttrStyle::Outer)
3782 .map_or(lhs_span, |a| a.span);
3783 let span = lhs_span.to(rhs.span);
3785 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3786 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3787 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3788 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3789 AssocOp::Greater | AssocOp::GreaterEqual => {
3790 let ast_op = op.to_ast_binop().unwrap();
3791 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3792 self.mk_expr(span, binary, ThinVec::new())
3795 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3796 AssocOp::ObsoleteInPlace =>
3797 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3798 AssocOp::AssignOp(k) => {
3800 token::Plus => BinOpKind::Add,
3801 token::Minus => BinOpKind::Sub,
3802 token::Star => BinOpKind::Mul,
3803 token::Slash => BinOpKind::Div,
3804 token::Percent => BinOpKind::Rem,
3805 token::Caret => BinOpKind::BitXor,
3806 token::And => BinOpKind::BitAnd,
3807 token::Or => BinOpKind::BitOr,
3808 token::Shl => BinOpKind::Shl,
3809 token::Shr => BinOpKind::Shr,
3811 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3812 self.mk_expr(span, aopexpr, ThinVec::new())
3814 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3815 self.bug("AssocOp should have been handled by special case")
3819 if op.fixity() == Fixity::None { break }
3824 fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
3825 self.token.is_ident() &&
3826 if let ast::ExprKind::Path(..) = node { true } else { false } &&
3827 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
3828 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren)) ||
3829 self.look_ahead(1, |t| t == &token::Lt) && // `foo:bar<baz`
3830 self.look_ahead(2, |t| t.is_ident()) ||
3831 self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
3832 self.look_ahead(2, |t| t.is_ident()) ||
3833 self.look_ahead(1, |t| t == &token::ModSep) && // `foo:bar::baz`
3834 self.look_ahead(2, |t| t.is_ident())
3837 fn bad_type_ascription(
3839 err: &mut DiagnosticBuilder<'a>,
3845 err.span_label(self.span, "expecting a type here because of type ascription");
3846 let cm = self.sess.source_map();
3847 let next_pos = cm.lookup_char_pos(next_sp.lo());
3848 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3849 if op_pos.line != next_pos.line {
3850 err.span_suggestion(
3852 "try using a semicolon",
3854 Applicability::MaybeIncorrect,
3858 err.span_suggestion(
3860 "maybe you meant to write a path separator here",
3862 Applicability::MaybeIncorrect,
3865 err.note("type ascription is a nightly-only feature that lets \
3866 you annotate an expression with a type: `<expr>: <type>`");
3869 "this expression expects an ascribed type after the colon",
3871 err.help("this might be indicative of a syntax error elsewhere");
3876 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3877 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3878 -> PResult<'a, P<Expr>> {
3879 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3880 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3883 // Save the state of the parser before parsing type normally, in case there is a
3884 // LessThan comparison after this cast.
3885 let parser_snapshot_before_type = self.clone();
3886 match self.parse_ty_no_plus() {
3888 Ok(mk_expr(self, rhs))
3890 Err(mut type_err) => {
3891 // Rewind to before attempting to parse the type with generics, to recover
3892 // from situations like `x as usize < y` in which we first tried to parse
3893 // `usize < y` as a type with generic arguments.
3894 let parser_snapshot_after_type = self.clone();
3895 mem::replace(self, parser_snapshot_before_type);
3897 match self.parse_path(PathStyle::Expr) {
3899 let (op_noun, op_verb) = match self.token {
3900 token::Lt => ("comparison", "comparing"),
3901 token::BinOp(token::Shl) => ("shift", "shifting"),
3903 // We can end up here even without `<` being the next token, for
3904 // example because `parse_ty_no_plus` returns `Err` on keywords,
3905 // but `parse_path` returns `Ok` on them due to error recovery.
3906 // Return original error and parser state.
3907 mem::replace(self, parser_snapshot_after_type);
3908 return Err(type_err);
3912 // Successfully parsed the type path leaving a `<` yet to parse.
3915 // Report non-fatal diagnostics, keep `x as usize` as an expression
3916 // in AST and continue parsing.
3917 let msg = format!("`<` is interpreted as a start of generic \
3918 arguments for `{}`, not a {}", path, op_noun);
3919 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3920 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3921 "interpreted as generic arguments");
3922 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3924 let expr = mk_expr(self, P(Ty {
3926 node: TyKind::Path(None, path),
3927 id: ast::DUMMY_NODE_ID
3930 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3931 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3932 err.span_suggestion(
3934 &format!("try {} the cast value", op_verb),
3935 format!("({})", expr_str),
3936 Applicability::MachineApplicable
3942 Err(mut path_err) => {
3943 // Couldn't parse as a path, return original error and parser state.
3945 mem::replace(self, parser_snapshot_after_type);
3953 /// Produce an error if comparison operators are chained (RFC #558).
3954 /// We only need to check lhs, not rhs, because all comparison ops
3955 /// have same precedence and are left-associative
3956 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3957 debug_assert!(outer_op.is_comparison(),
3958 "check_no_chained_comparison: {:?} is not comparison",
3961 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3962 // respan to include both operators
3963 let op_span = op.span.to(self.span);
3964 let mut err = self.diagnostic().struct_span_err(op_span,
3965 "chained comparison operators require parentheses");
3966 if op.node == BinOpKind::Lt &&
3967 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3968 *outer_op == AssocOp::Greater // even in a case like the following:
3969 { // Foo<Bar<Baz<Qux, ()>>>
3971 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3972 err.help("or use `(...)` if you meant to specify fn arguments");
3980 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3981 fn parse_prefix_range_expr(&mut self,
3982 already_parsed_attrs: Option<ThinVec<Attribute>>)
3983 -> PResult<'a, P<Expr>> {
3984 // Check for deprecated `...` syntax
3985 if self.token == token::DotDotDot {
3986 self.err_dotdotdot_syntax(self.span);
3989 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3990 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3992 let tok = self.token.clone();
3993 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3995 let mut hi = self.span;
3997 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3998 // RHS must be parsed with more associativity than the dots.
3999 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
4000 Some(self.parse_assoc_expr_with(next_prec,
4001 LhsExpr::NotYetParsed)
4009 let limits = if tok == token::DotDot {
4010 RangeLimits::HalfOpen
4015 let r = self.mk_range(None, opt_end, limits)?;
4016 Ok(self.mk_expr(lo.to(hi), r, attrs))
4019 fn is_at_start_of_range_notation_rhs(&self) -> bool {
4020 if self.token.can_begin_expr() {
4021 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
4022 if self.token == token::OpenDelim(token::Brace) {
4023 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
4031 /// Parses an `if` or `if let` expression (`if` token already eaten).
4032 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4033 if self.check_keyword(keywords::Let) {
4034 return self.parse_if_let_expr(attrs);
4036 let lo = self.prev_span;
4037 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4039 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
4040 // verify that the last statement is either an implicit return (no `;`) or an explicit
4041 // return. This won't catch blocks with an explicit `return`, but that would be caught by
4042 // the dead code lint.
4043 if self.eat_keyword(keywords::Else) || !cond.returns() {
4044 let sp = self.sess.source_map().next_point(lo);
4045 let mut err = self.diagnostic()
4046 .struct_span_err(sp, "missing condition for `if` statemement");
4047 err.span_label(sp, "expected if condition here");
4050 let not_block = self.token != token::OpenDelim(token::Brace);
4051 let thn = self.parse_block().map_err(|mut err| {
4053 err.span_label(lo, "this `if` statement has a condition, but no block");
4057 let mut els: Option<P<Expr>> = None;
4058 let mut hi = thn.span;
4059 if self.eat_keyword(keywords::Else) {
4060 let elexpr = self.parse_else_expr()?;
4064 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
4067 /// Parses an `if let` expression (`if` token already eaten).
4068 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
4069 -> PResult<'a, P<Expr>> {
4070 let lo = self.prev_span;
4071 self.expect_keyword(keywords::Let)?;
4072 let pats = self.parse_pats()?;
4073 self.expect(&token::Eq)?;
4074 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4075 let thn = self.parse_block()?;
4076 let (hi, els) = if self.eat_keyword(keywords::Else) {
4077 let expr = self.parse_else_expr()?;
4078 (expr.span, Some(expr))
4082 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
4085 /// Parses `move |args| expr`.
4086 fn parse_lambda_expr(&mut self,
4087 attrs: ThinVec<Attribute>)
4088 -> PResult<'a, P<Expr>>
4091 let movability = if self.eat_keyword(keywords::Static) {
4096 let asyncness = if self.span.rust_2018() {
4097 self.parse_asyncness()
4101 let capture_clause = if self.eat_keyword(keywords::Move) {
4106 let decl = self.parse_fn_block_decl()?;
4107 let decl_hi = self.prev_span;
4108 let body = match decl.output {
4109 FunctionRetTy::Default(_) => {
4110 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
4111 self.parse_expr_res(restrictions, None)?
4114 // If an explicit return type is given, require a
4115 // block to appear (RFC 968).
4116 let body_lo = self.span;
4117 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
4123 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
4127 // `else` token already eaten
4128 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
4129 if self.eat_keyword(keywords::If) {
4130 return self.parse_if_expr(ThinVec::new());
4132 let blk = self.parse_block()?;
4133 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
4137 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
4138 fn parse_for_expr(&mut self, opt_label: Option<Label>,
4140 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4141 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
4143 let pat = self.parse_top_level_pat()?;
4144 if !self.eat_keyword(keywords::In) {
4145 let in_span = self.prev_span.between(self.span);
4146 let mut err = self.sess.span_diagnostic
4147 .struct_span_err(in_span, "missing `in` in `for` loop");
4148 err.span_suggestion_short(
4149 in_span, "try adding `in` here", " in ".into(),
4150 // has been misleading, at least in the past (closed Issue #48492)
4151 Applicability::MaybeIncorrect
4155 let in_span = self.prev_span;
4156 if self.eat_keyword(keywords::In) {
4157 // a common typo: `for _ in in bar {}`
4158 let mut err = self.sess.span_diagnostic.struct_span_err(
4160 "expected iterable, found keyword `in`",
4162 err.span_suggestion_short(
4163 in_span.until(self.prev_span),
4164 "remove the duplicated `in`",
4166 Applicability::MachineApplicable,
4168 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
4169 err.note("for more information on the status of emplacement syntax, see <\
4170 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
4173 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4174 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
4175 attrs.extend(iattrs);
4177 let hi = self.prev_span;
4178 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
4181 /// Parses a `while` or `while let` expression (`while` token already eaten).
4182 fn parse_while_expr(&mut self, opt_label: Option<Label>,
4184 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4185 if self.token.is_keyword(keywords::Let) {
4186 return self.parse_while_let_expr(opt_label, span_lo, attrs);
4188 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4189 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4190 attrs.extend(iattrs);
4191 let span = span_lo.to(body.span);
4192 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
4195 /// Parses a `while let` expression (`while` token already eaten).
4196 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
4198 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4199 self.expect_keyword(keywords::Let)?;
4200 let pats = self.parse_pats()?;
4201 self.expect(&token::Eq)?;
4202 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4203 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4204 attrs.extend(iattrs);
4205 let span = span_lo.to(body.span);
4206 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
4209 // parse `loop {...}`, `loop` token already eaten
4210 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
4212 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4213 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4214 attrs.extend(iattrs);
4215 let span = span_lo.to(body.span);
4216 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
4219 /// Parses an `async move {...}` expression.
4220 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
4221 -> PResult<'a, P<Expr>>
4223 let span_lo = self.span;
4224 self.expect_keyword(keywords::Async)?;
4225 let capture_clause = if self.eat_keyword(keywords::Move) {
4230 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4231 attrs.extend(iattrs);
4233 span_lo.to(body.span),
4234 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
4237 /// Parses a `try {...}` expression (`try` token already eaten).
4238 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
4239 -> PResult<'a, P<Expr>>
4241 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4242 attrs.extend(iattrs);
4243 if self.eat_keyword(keywords::Catch) {
4244 let mut error = self.struct_span_err(self.prev_span,
4245 "keyword `catch` cannot follow a `try` block");
4246 error.help("try using `match` on the result of the `try` block instead");
4250 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
4254 // `match` token already eaten
4255 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4256 let match_span = self.prev_span;
4257 let lo = self.prev_span;
4258 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
4260 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
4261 if self.token == token::Token::Semi {
4262 e.span_suggestion_short(
4264 "try removing this `match`",
4266 Applicability::MaybeIncorrect // speculative
4271 attrs.extend(self.parse_inner_attributes()?);
4273 let mut arms: Vec<Arm> = Vec::new();
4274 while self.token != token::CloseDelim(token::Brace) {
4275 match self.parse_arm() {
4276 Ok(arm) => arms.push(arm),
4278 // Recover by skipping to the end of the block.
4280 self.recover_stmt();
4281 let span = lo.to(self.span);
4282 if self.token == token::CloseDelim(token::Brace) {
4285 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
4291 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
4294 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
4295 maybe_whole!(self, NtArm, |x| x);
4297 let attrs = self.parse_outer_attributes()?;
4298 let pats = self.parse_pats()?;
4299 let guard = if self.eat_keyword(keywords::If) {
4300 Some(Guard::If(self.parse_expr()?))
4304 let arrow_span = self.span;
4305 self.expect(&token::FatArrow)?;
4306 let arm_start_span = self.span;
4308 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
4309 .map_err(|mut err| {
4310 err.span_label(arrow_span, "while parsing the `match` arm starting here");
4314 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
4315 && self.token != token::CloseDelim(token::Brace);
4318 let cm = self.sess.source_map();
4319 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
4320 .map_err(|mut err| {
4321 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
4322 (Ok(ref expr_lines), Ok(ref arm_start_lines))
4323 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
4324 && expr_lines.lines.len() == 2
4325 && self.token == token::FatArrow => {
4326 // We check whether there's any trailing code in the parse span,
4327 // if there isn't, we very likely have the following:
4330 // | -- - missing comma
4336 // | parsed until here as `"y" & X`
4337 err.span_suggestion_short(
4338 cm.next_point(arm_start_span),
4339 "missing a comma here to end this `match` arm",
4341 Applicability::MachineApplicable
4345 err.span_label(arrow_span,
4346 "while parsing the `match` arm starting here");
4352 self.eat(&token::Comma);
4363 /// Parses an expression.
4365 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
4366 self.parse_expr_res(Restrictions::empty(), None)
4369 /// Evaluates the closure with restrictions in place.
4371 /// Afters the closure is evaluated, restrictions are reset.
4372 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
4373 where F: FnOnce(&mut Self) -> T
4375 let old = self.restrictions;
4376 self.restrictions = r;
4378 self.restrictions = old;
4383 /// Parses an expression, subject to the given restrictions.
4385 fn parse_expr_res(&mut self, r: Restrictions,
4386 already_parsed_attrs: Option<ThinVec<Attribute>>)
4387 -> PResult<'a, P<Expr>> {
4388 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
4391 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
4392 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
4393 if self.eat(&token::Eq) {
4394 Ok(Some(self.parse_expr()?))
4396 Ok(Some(self.parse_expr()?))
4402 /// Parses patterns, separated by '|' s.
4403 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
4404 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
4405 self.eat(&token::BinOp(token::Or));
4407 let mut pats = Vec::new();
4409 pats.push(self.parse_top_level_pat()?);
4411 if self.token == token::OrOr {
4412 let mut err = self.struct_span_err(self.span,
4413 "unexpected token `||` after pattern");
4414 err.span_suggestion(
4416 "use a single `|` to specify multiple patterns",
4418 Applicability::MachineApplicable
4422 } else if self.eat(&token::BinOp(token::Or)) {
4423 // This is a No-op. Continue the loop to parse the next
4431 // Parses a parenthesized list of patterns like
4432 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
4433 // - a vector of the patterns that were parsed
4434 // - an option indicating the index of the `..` element
4435 // - a boolean indicating whether a trailing comma was present.
4436 // Trailing commas are significant because (p) and (p,) are different patterns.
4437 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4438 self.expect(&token::OpenDelim(token::Paren))?;
4439 let result = match self.parse_pat_list() {
4440 Ok(result) => result,
4441 Err(mut err) => { // recover from parse error in tuple pattern list
4443 self.consume_block(token::Paren);
4444 return Ok((vec![], Some(0), false));
4447 self.expect(&token::CloseDelim(token::Paren))?;
4451 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4452 let mut fields = Vec::new();
4453 let mut ddpos = None;
4454 let mut prev_dd_sp = None;
4455 let mut trailing_comma = false;
4457 if self.eat(&token::DotDot) {
4458 if ddpos.is_none() {
4459 ddpos = Some(fields.len());
4460 prev_dd_sp = Some(self.prev_span);
4462 // Emit a friendly error, ignore `..` and continue parsing
4463 let mut err = self.struct_span_err(
4465 "`..` can only be used once per tuple or tuple struct pattern",
4467 err.span_label(self.prev_span, "can only be used once per pattern");
4468 if let Some(sp) = prev_dd_sp {
4469 err.span_label(sp, "previously present here");
4473 } else if !self.check(&token::CloseDelim(token::Paren)) {
4474 fields.push(self.parse_pat(None)?);
4479 trailing_comma = self.eat(&token::Comma);
4480 if !trailing_comma {
4485 if ddpos == Some(fields.len()) && trailing_comma {
4486 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
4487 let msg = "trailing comma is not permitted after `..`";
4488 self.struct_span_err(self.prev_span, msg)
4489 .span_label(self.prev_span, msg)
4493 Ok((fields, ddpos, trailing_comma))
4496 fn parse_pat_vec_elements(
4498 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
4499 let mut before = Vec::new();
4500 let mut slice = None;
4501 let mut after = Vec::new();
4502 let mut first = true;
4503 let mut before_slice = true;
4505 while self.token != token::CloseDelim(token::Bracket) {
4509 self.expect(&token::Comma)?;
4511 if self.token == token::CloseDelim(token::Bracket)
4512 && (before_slice || !after.is_empty()) {
4518 if self.eat(&token::DotDot) {
4520 if self.check(&token::Comma) ||
4521 self.check(&token::CloseDelim(token::Bracket)) {
4522 slice = Some(P(Pat {
4523 id: ast::DUMMY_NODE_ID,
4524 node: PatKind::Wild,
4525 span: self.prev_span,
4527 before_slice = false;
4533 let subpat = self.parse_pat(None)?;
4534 if before_slice && self.eat(&token::DotDot) {
4535 slice = Some(subpat);
4536 before_slice = false;
4537 } else if before_slice {
4538 before.push(subpat);
4544 Ok((before, slice, after))
4550 attrs: Vec<Attribute>
4551 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
4552 // Check if a colon exists one ahead. This means we're parsing a fieldname.
4554 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
4555 // Parsing a pattern of the form "fieldname: pat"
4556 let fieldname = self.parse_field_name()?;
4558 let pat = self.parse_pat(None)?;
4560 (pat, fieldname, false)
4562 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
4563 let is_box = self.eat_keyword(keywords::Box);
4564 let boxed_span = self.span;
4565 let is_ref = self.eat_keyword(keywords::Ref);
4566 let is_mut = self.eat_keyword(keywords::Mut);
4567 let fieldname = self.parse_ident()?;
4568 hi = self.prev_span;
4570 let bind_type = match (is_ref, is_mut) {
4571 (true, true) => BindingMode::ByRef(Mutability::Mutable),
4572 (true, false) => BindingMode::ByRef(Mutability::Immutable),
4573 (false, true) => BindingMode::ByValue(Mutability::Mutable),
4574 (false, false) => BindingMode::ByValue(Mutability::Immutable),
4576 let fieldpat = P(Pat {
4577 id: ast::DUMMY_NODE_ID,
4578 node: PatKind::Ident(bind_type, fieldname, None),
4579 span: boxed_span.to(hi),
4582 let subpat = if is_box {
4584 id: ast::DUMMY_NODE_ID,
4585 node: PatKind::Box(fieldpat),
4591 (subpat, fieldname, true)
4594 Ok(source_map::Spanned {
4596 node: ast::FieldPat {
4600 attrs: attrs.into(),
4605 /// Parses the fields of a struct-like pattern.
4606 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
4607 let mut fields = Vec::new();
4608 let mut etc = false;
4609 let mut ate_comma = true;
4610 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
4611 let mut etc_span = None;
4613 while self.token != token::CloseDelim(token::Brace) {
4614 let attrs = self.parse_outer_attributes()?;
4617 // check that a comma comes after every field
4619 let err = self.struct_span_err(self.prev_span, "expected `,`");
4620 if let Some(mut delayed) = delayed_err {
4627 if self.check(&token::DotDot) || self.token == token::DotDotDot {
4629 let mut etc_sp = self.span;
4631 if self.token == token::DotDotDot { // Issue #46718
4632 // Accept `...` as if it were `..` to avoid further errors
4633 let mut err = self.struct_span_err(self.span,
4634 "expected field pattern, found `...`");
4635 err.span_suggestion(
4637 "to omit remaining fields, use one fewer `.`",
4639 Applicability::MachineApplicable
4643 self.bump(); // `..` || `...`
4645 if self.token == token::CloseDelim(token::Brace) {
4646 etc_span = Some(etc_sp);
4649 let token_str = self.this_token_descr();
4650 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
4652 err.span_label(self.span, "expected `}`");
4653 let mut comma_sp = None;
4654 if self.token == token::Comma { // Issue #49257
4655 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
4656 err.span_label(etc_sp,
4657 "`..` must be at the end and cannot have a trailing comma");
4658 comma_sp = Some(self.span);
4663 etc_span = Some(etc_sp.until(self.span));
4664 if self.token == token::CloseDelim(token::Brace) {
4665 // If the struct looks otherwise well formed, recover and continue.
4666 if let Some(sp) = comma_sp {
4667 err.span_suggestion_short(
4669 "remove this comma",
4671 Applicability::MachineApplicable,
4676 } else if self.token.is_ident() && ate_comma {
4677 // Accept fields coming after `..,`.
4678 // This way we avoid "pattern missing fields" errors afterwards.
4679 // We delay this error until the end in order to have a span for a
4681 if let Some(mut delayed_err) = delayed_err {
4685 delayed_err = Some(err);
4688 if let Some(mut err) = delayed_err {
4695 fields.push(match self.parse_pat_field(lo, attrs) {
4698 if let Some(mut delayed_err) = delayed_err {
4704 ate_comma = self.eat(&token::Comma);
4707 if let Some(mut err) = delayed_err {
4708 if let Some(etc_span) = etc_span {
4709 err.multipart_suggestion(
4710 "move the `..` to the end of the field list",
4712 (etc_span, String::new()),
4713 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4715 Applicability::MachineApplicable,
4720 return Ok((fields, etc));
4723 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4724 if self.token.is_path_start() {
4726 let (qself, path) = if self.eat_lt() {
4727 // Parse a qualified path
4728 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4731 // Parse an unqualified path
4732 (None, self.parse_path(PathStyle::Expr)?)
4734 let hi = self.prev_span;
4735 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4737 self.parse_literal_maybe_minus()
4741 // helper function to decide whether to parse as ident binding or to try to do
4742 // something more complex like range patterns
4743 fn parse_as_ident(&mut self) -> bool {
4744 self.look_ahead(1, |t| match *t {
4745 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4746 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4747 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4748 // range pattern branch
4749 token::DotDot => None,
4751 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4752 token::Comma | token::CloseDelim(token::Bracket) => true,
4757 /// A wrapper around `parse_pat` with some special error handling for the
4758 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4759 /// to subpatterns within such).
4760 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4761 let pat = self.parse_pat(None)?;
4762 if self.token == token::Comma {
4763 // An unexpected comma after a top-level pattern is a clue that the
4764 // user (perhaps more accustomed to some other language) forgot the
4765 // parentheses in what should have been a tuple pattern; return a
4766 // suggestion-enhanced error here rather than choking on the comma
4768 let comma_span = self.span;
4770 if let Err(mut err) = self.parse_pat_list() {
4771 // We didn't expect this to work anyway; we just wanted
4772 // to advance to the end of the comma-sequence so we know
4773 // the span to suggest parenthesizing
4776 let seq_span = pat.span.to(self.prev_span);
4777 let mut err = self.struct_span_err(comma_span,
4778 "unexpected `,` in pattern");
4779 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4780 err.span_suggestion(
4782 "try adding parentheses to match on a tuple..",
4783 format!("({})", seq_snippet),
4784 Applicability::MachineApplicable
4787 "..or a vertical bar to match on multiple alternatives",
4788 format!("{}", seq_snippet.replace(",", " |")),
4789 Applicability::MachineApplicable
4797 /// Parses a pattern.
4798 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4799 self.parse_pat_with_range_pat(true, expected)
4802 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
4804 fn parse_pat_with_range_pat(
4806 allow_range_pat: bool,
4807 expected: Option<&'static str>,
4808 ) -> PResult<'a, P<Pat>> {
4809 maybe_recover_from_interpolated_ty_qpath!(self, true);
4810 maybe_whole!(self, NtPat, |x| x);
4815 token::BinOp(token::And) | token::AndAnd => {
4816 // Parse &pat / &mut pat
4818 let mutbl = self.parse_mutability();
4819 if let token::Lifetime(ident) = self.token {
4820 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4822 err.span_label(self.span, "unexpected lifetime");
4825 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4826 pat = PatKind::Ref(subpat, mutbl);
4828 token::OpenDelim(token::Paren) => {
4829 // Parse (pat,pat,pat,...) as tuple pattern
4830 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4831 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4832 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4834 PatKind::Tuple(fields, ddpos)
4837 token::OpenDelim(token::Bracket) => {
4838 // Parse [pat,pat,...] as slice pattern
4840 let (before, slice, after) = self.parse_pat_vec_elements()?;
4841 self.expect(&token::CloseDelim(token::Bracket))?;
4842 pat = PatKind::Slice(before, slice, after);
4844 // At this point, token != &, &&, (, [
4845 _ => if self.eat_keyword(keywords::Underscore) {
4847 pat = PatKind::Wild;
4848 } else if self.eat_keyword(keywords::Mut) {
4849 // Parse mut ident @ pat / mut ref ident @ pat
4850 let mutref_span = self.prev_span.to(self.span);
4851 let binding_mode = if self.eat_keyword(keywords::Ref) {
4853 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4856 "try switching the order",
4858 Applicability::MachineApplicable
4860 BindingMode::ByRef(Mutability::Mutable)
4862 BindingMode::ByValue(Mutability::Mutable)
4864 pat = self.parse_pat_ident(binding_mode)?;
4865 } else if self.eat_keyword(keywords::Ref) {
4866 // Parse ref ident @ pat / ref mut ident @ pat
4867 let mutbl = self.parse_mutability();
4868 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4869 } else if self.eat_keyword(keywords::Box) {
4871 let subpat = self.parse_pat_with_range_pat(false, None)?;
4872 pat = PatKind::Box(subpat);
4873 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4874 self.parse_as_ident() {
4875 // Parse ident @ pat
4876 // This can give false positives and parse nullary enums,
4877 // they are dealt with later in resolve
4878 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4879 pat = self.parse_pat_ident(binding_mode)?;
4880 } else if self.token.is_path_start() {
4881 // Parse pattern starting with a path
4882 let (qself, path) = if self.eat_lt() {
4883 // Parse a qualified path
4884 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4887 // Parse an unqualified path
4888 (None, self.parse_path(PathStyle::Expr)?)
4891 token::Not if qself.is_none() => {
4892 // Parse macro invocation
4894 let (delim, tts) = self.expect_delimited_token_tree()?;
4895 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4896 pat = PatKind::Mac(mac);
4898 token::DotDotDot | token::DotDotEq | token::DotDot => {
4899 let end_kind = match self.token {
4900 token::DotDot => RangeEnd::Excluded,
4901 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4902 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4903 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4906 let op_span = self.span;
4908 let span = lo.to(self.prev_span);
4909 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4911 let end = self.parse_pat_range_end()?;
4912 let op = Spanned { span: op_span, node: end_kind };
4913 pat = PatKind::Range(begin, end, op);
4915 token::OpenDelim(token::Brace) => {
4916 if qself.is_some() {
4917 let msg = "unexpected `{` after qualified path";
4918 let mut err = self.fatal(msg);
4919 err.span_label(self.span, msg);
4922 // Parse struct pattern
4924 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4926 self.recover_stmt();
4930 pat = PatKind::Struct(path, fields, etc);
4932 token::OpenDelim(token::Paren) => {
4933 if qself.is_some() {
4934 let msg = "unexpected `(` after qualified path";
4935 let mut err = self.fatal(msg);
4936 err.span_label(self.span, msg);
4939 // Parse tuple struct or enum pattern
4940 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4941 pat = PatKind::TupleStruct(path, fields, ddpos)
4943 _ => pat = PatKind::Path(qself, path),
4946 // Try to parse everything else as literal with optional minus
4947 match self.parse_literal_maybe_minus() {
4949 let op_span = self.span;
4950 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4951 self.check(&token::DotDotDot) {
4952 let end_kind = if self.eat(&token::DotDotDot) {
4953 RangeEnd::Included(RangeSyntax::DotDotDot)
4954 } else if self.eat(&token::DotDotEq) {
4955 RangeEnd::Included(RangeSyntax::DotDotEq)
4956 } else if self.eat(&token::DotDot) {
4959 panic!("impossible case: we already matched \
4960 on a range-operator token")
4962 let end = self.parse_pat_range_end()?;
4963 let op = Spanned { span: op_span, node: end_kind };
4964 pat = PatKind::Range(begin, end, op);
4966 pat = PatKind::Lit(begin);
4970 self.cancel(&mut err);
4971 let expected = expected.unwrap_or("pattern");
4973 "expected {}, found {}",
4975 self.this_token_descr(),
4977 let mut err = self.fatal(&msg);
4978 err.span_label(self.span, format!("expected {}", expected));
4979 let sp = self.sess.source_map().start_point(self.span);
4980 if let Some(sp) = self.sess.abiguous_block_expr_parse.borrow().get(&sp) {
4981 if let Ok(snippet) = self.sess.source_map().span_to_snippet(*sp) {
4982 err.span_suggestion(
4984 "parenthesis are required to parse this as an expression",
4985 format!("({})", snippet),
4986 Applicability::MachineApplicable,
4996 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4997 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4999 if !allow_range_pat {
5002 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
5004 PatKind::Range(..) => {
5005 let mut err = self.struct_span_err(
5007 "the range pattern here has ambiguous interpretation",
5009 err.span_suggestion(
5011 "add parentheses to clarify the precedence",
5012 format!("({})", pprust::pat_to_string(&pat)),
5013 // "ambiguous interpretation" implies that we have to be guessing
5014 Applicability::MaybeIncorrect
5025 /// Parses `ident` or `ident @ pat`.
5026 /// used by the copy foo and ref foo patterns to give a good
5027 /// error message when parsing mistakes like `ref foo(a, b)`.
5028 fn parse_pat_ident(&mut self,
5029 binding_mode: ast::BindingMode)
5030 -> PResult<'a, PatKind> {
5031 let ident = self.parse_ident()?;
5032 let sub = if self.eat(&token::At) {
5033 Some(self.parse_pat(Some("binding pattern"))?)
5038 // just to be friendly, if they write something like
5040 // we end up here with ( as the current token. This shortly
5041 // leads to a parse error. Note that if there is no explicit
5042 // binding mode then we do not end up here, because the lookahead
5043 // will direct us over to parse_enum_variant()
5044 if self.token == token::OpenDelim(token::Paren) {
5045 return Err(self.span_fatal(
5047 "expected identifier, found enum pattern"))
5050 Ok(PatKind::Ident(binding_mode, ident, sub))
5053 /// Parses a local variable declaration.
5054 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
5055 let lo = self.prev_span;
5056 let pat = self.parse_top_level_pat()?;
5058 let (err, ty) = if self.eat(&token::Colon) {
5059 // Save the state of the parser before parsing type normally, in case there is a `:`
5060 // instead of an `=` typo.
5061 let parser_snapshot_before_type = self.clone();
5062 let colon_sp = self.prev_span;
5063 match self.parse_ty() {
5064 Ok(ty) => (None, Some(ty)),
5066 // Rewind to before attempting to parse the type and continue parsing
5067 let parser_snapshot_after_type = self.clone();
5068 mem::replace(self, parser_snapshot_before_type);
5070 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
5071 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
5072 (Some((parser_snapshot_after_type, colon_sp, err)), None)
5078 let init = match (self.parse_initializer(err.is_some()), err) {
5079 (Ok(init), None) => { // init parsed, ty parsed
5082 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
5083 // Could parse the type as if it were the initializer, it is likely there was a
5084 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
5085 err.span_suggestion_short(
5087 "use `=` if you meant to assign",
5089 Applicability::MachineApplicable
5092 // As this was parsed successfully, continue as if the code has been fixed for the
5093 // rest of the file. It will still fail due to the emitted error, but we avoid
5097 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
5099 // Couldn't parse the type nor the initializer, only raise the type error and
5100 // return to the parser state before parsing the type as the initializer.
5101 // let x: <parse_error>;
5102 mem::replace(self, snapshot);
5105 (Err(err), None) => { // init error, ty parsed
5106 // Couldn't parse the initializer and we're not attempting to recover a failed
5107 // parse of the type, return the error.
5111 let hi = if self.token == token::Semi {
5120 id: ast::DUMMY_NODE_ID,
5123 source: LocalSource::Normal,
5127 /// Parses a structure field.
5128 fn parse_name_and_ty(&mut self,
5131 attrs: Vec<Attribute>)
5132 -> PResult<'a, StructField> {
5133 let name = self.parse_ident()?;
5134 self.expect(&token::Colon)?;
5135 let ty = self.parse_ty()?;
5137 span: lo.to(self.prev_span),
5140 id: ast::DUMMY_NODE_ID,
5146 /// Emits an expected-item-after-attributes error.
5147 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
5148 let message = match attrs.last() {
5149 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
5150 _ => "expected item after attributes",
5153 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
5154 if attrs.last().unwrap().is_sugared_doc {
5155 err.span_label(self.prev_span, "this doc comment doesn't document anything");
5160 /// Parse a statement. This stops just before trailing semicolons on everything but items.
5161 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
5162 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
5163 Ok(self.parse_stmt_(true))
5166 // Eat tokens until we can be relatively sure we reached the end of the
5167 // statement. This is something of a best-effort heuristic.
5169 // We terminate when we find an unmatched `}` (without consuming it).
5170 fn recover_stmt(&mut self) {
5171 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
5174 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
5175 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
5176 // approximate - it can mean we break too early due to macros, but that
5177 // should only lead to sub-optimal recovery, not inaccurate parsing).
5179 // If `break_on_block` is `Break`, then we will stop consuming tokens
5180 // after finding (and consuming) a brace-delimited block.
5181 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
5182 let mut brace_depth = 0;
5183 let mut bracket_depth = 0;
5184 let mut in_block = false;
5185 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
5186 break_on_semi, break_on_block);
5188 debug!("recover_stmt_ loop {:?}", self.token);
5190 token::OpenDelim(token::DelimToken::Brace) => {
5193 if break_on_block == BlockMode::Break &&
5195 bracket_depth == 0 {
5199 token::OpenDelim(token::DelimToken::Bracket) => {
5203 token::CloseDelim(token::DelimToken::Brace) => {
5204 if brace_depth == 0 {
5205 debug!("recover_stmt_ return - close delim {:?}", self.token);
5210 if in_block && bracket_depth == 0 && brace_depth == 0 {
5211 debug!("recover_stmt_ return - block end {:?}", self.token);
5215 token::CloseDelim(token::DelimToken::Bracket) => {
5217 if bracket_depth < 0 {
5223 debug!("recover_stmt_ return - Eof");
5228 if break_on_semi == SemiColonMode::Break &&
5230 bracket_depth == 0 {
5231 debug!("recover_stmt_ return - Semi");
5236 if break_on_semi == SemiColonMode::Comma &&
5238 bracket_depth == 0 {
5239 debug!("recover_stmt_ return - Semi");
5252 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
5253 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
5255 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5260 fn is_async_block(&mut self) -> bool {
5261 self.token.is_keyword(keywords::Async) &&
5264 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
5265 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
5267 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
5272 fn is_async_fn(&mut self) -> bool {
5273 self.token.is_keyword(keywords::Async) &&
5274 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
5277 fn is_do_catch_block(&mut self) -> bool {
5278 self.token.is_keyword(keywords::Do) &&
5279 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
5280 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
5281 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5284 fn is_try_block(&mut self) -> bool {
5285 self.token.is_keyword(keywords::Try) &&
5286 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
5287 self.span.rust_2018() &&
5288 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
5289 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5292 fn is_union_item(&self) -> bool {
5293 self.token.is_keyword(keywords::Union) &&
5294 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
5297 fn is_crate_vis(&self) -> bool {
5298 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
5301 fn is_existential_type_decl(&self) -> bool {
5302 self.token.is_keyword(keywords::Existential) &&
5303 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
5306 fn is_auto_trait_item(&mut self) -> bool {
5308 (self.token.is_keyword(keywords::Auto)
5309 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
5310 || // unsafe auto trait
5311 (self.token.is_keyword(keywords::Unsafe) &&
5312 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
5313 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
5316 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
5317 -> PResult<'a, Option<P<Item>>> {
5318 let token_lo = self.span;
5319 let (ident, def) = match self.token {
5320 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
5322 let ident = self.parse_ident()?;
5323 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
5324 match self.parse_token_tree() {
5325 TokenTree::Delimited(_, _, tts) => tts,
5326 _ => unreachable!(),
5328 } else if self.check(&token::OpenDelim(token::Paren)) {
5329 let args = self.parse_token_tree();
5330 let body = if self.check(&token::OpenDelim(token::Brace)) {
5331 self.parse_token_tree()
5336 TokenStream::new(vec![
5338 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
5346 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
5348 token::Ident(ident, _) if ident.name == "macro_rules" &&
5349 self.look_ahead(1, |t| *t == token::Not) => {
5350 let prev_span = self.prev_span;
5351 self.complain_if_pub_macro(&vis.node, prev_span);
5355 let ident = self.parse_ident()?;
5356 let (delim, tokens) = self.expect_delimited_token_tree()?;
5357 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
5358 self.report_invalid_macro_expansion_item();
5361 (ident, ast::MacroDef { tokens: tokens, legacy: true })
5363 _ => return Ok(None),
5366 let span = lo.to(self.prev_span);
5367 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
5370 fn parse_stmt_without_recovery(&mut self,
5371 macro_legacy_warnings: bool)
5372 -> PResult<'a, Option<Stmt>> {
5373 maybe_whole!(self, NtStmt, |x| Some(x));
5375 let attrs = self.parse_outer_attributes()?;
5378 Ok(Some(if self.eat_keyword(keywords::Let) {
5380 id: ast::DUMMY_NODE_ID,
5381 node: StmtKind::Local(self.parse_local(attrs.into())?),
5382 span: lo.to(self.prev_span),
5384 } else if let Some(macro_def) = self.eat_macro_def(
5386 &source_map::respan(lo, VisibilityKind::Inherited),
5390 id: ast::DUMMY_NODE_ID,
5391 node: StmtKind::Item(macro_def),
5392 span: lo.to(self.prev_span),
5394 // Starts like a simple path, being careful to avoid contextual keywords
5395 // such as a union items, item with `crate` visibility or auto trait items.
5396 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
5397 // like a path (1 token), but it fact not a path.
5398 // `union::b::c` - path, `union U { ... }` - not a path.
5399 // `crate::b::c` - path, `crate struct S;` - not a path.
5400 } else if self.token.is_path_start() &&
5401 !self.token.is_qpath_start() &&
5402 !self.is_union_item() &&
5403 !self.is_crate_vis() &&
5404 !self.is_existential_type_decl() &&
5405 !self.is_auto_trait_item() &&
5406 !self.is_async_fn() {
5407 let pth = self.parse_path(PathStyle::Expr)?;
5409 if !self.eat(&token::Not) {
5410 let expr = if self.check(&token::OpenDelim(token::Brace)) {
5411 self.parse_struct_expr(lo, pth, ThinVec::new())?
5413 let hi = self.prev_span;
5414 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
5417 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
5418 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
5419 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
5422 return Ok(Some(Stmt {
5423 id: ast::DUMMY_NODE_ID,
5424 node: StmtKind::Expr(expr),
5425 span: lo.to(self.prev_span),
5429 // it's a macro invocation
5430 let id = match self.token {
5431 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
5432 _ => self.parse_ident()?,
5435 // check that we're pointing at delimiters (need to check
5436 // again after the `if`, because of `parse_ident`
5437 // consuming more tokens).
5439 token::OpenDelim(_) => {}
5441 // we only expect an ident if we didn't parse one
5443 let ident_str = if id.name == keywords::Invalid.name() {
5448 let tok_str = self.this_token_descr();
5449 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
5452 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
5457 let (delim, tts) = self.expect_delimited_token_tree()?;
5458 let hi = self.prev_span;
5460 let style = if delim == MacDelimiter::Brace {
5461 MacStmtStyle::Braces
5463 MacStmtStyle::NoBraces
5466 if id.name == keywords::Invalid.name() {
5467 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
5468 let node = if delim == MacDelimiter::Brace ||
5469 self.token == token::Semi || self.token == token::Eof {
5470 StmtKind::Mac(P((mac, style, attrs.into())))
5472 // We used to incorrectly stop parsing macro-expanded statements here.
5473 // If the next token will be an error anyway but could have parsed with the
5474 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
5475 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
5476 // These can continue an expression, so we can't stop parsing and warn.
5477 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
5478 token::BinOp(token::Minus) | token::BinOp(token::Star) |
5479 token::BinOp(token::And) | token::BinOp(token::Or) |
5480 token::AndAnd | token::OrOr |
5481 token::DotDot | token::DotDotDot | token::DotDotEq => false,
5484 self.warn_missing_semicolon();
5485 StmtKind::Mac(P((mac, style, attrs.into())))
5487 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
5488 let e = self.maybe_recover_from_bad_qpath(e, true)?;
5489 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
5490 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
5494 id: ast::DUMMY_NODE_ID,
5499 // if it has a special ident, it's definitely an item
5501 // Require a semicolon or braces.
5502 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
5503 self.report_invalid_macro_expansion_item();
5505 let span = lo.to(hi);
5507 id: ast::DUMMY_NODE_ID,
5509 node: StmtKind::Item({
5511 span, id /*id is good here*/,
5512 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
5513 respan(lo, VisibilityKind::Inherited),
5519 // FIXME: Bad copy of attrs
5520 let old_directory_ownership =
5521 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
5522 let item = self.parse_item_(attrs.clone(), false, true)?;
5523 self.directory.ownership = old_directory_ownership;
5527 id: ast::DUMMY_NODE_ID,
5528 span: lo.to(i.span),
5529 node: StmtKind::Item(i),
5532 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
5533 if !attrs.is_empty() {
5534 if s.prev_token_kind == PrevTokenKind::DocComment {
5535 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
5536 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
5537 s.span_err(s.span, "expected statement after outer attribute");
5542 // Do not attempt to parse an expression if we're done here.
5543 if self.token == token::Semi {
5544 unused_attrs(&attrs, self);
5549 if self.token == token::CloseDelim(token::Brace) {
5550 unused_attrs(&attrs, self);
5554 // Remainder are line-expr stmts.
5555 let e = self.parse_expr_res(
5556 Restrictions::STMT_EXPR, Some(attrs.into()))?;
5558 id: ast::DUMMY_NODE_ID,
5559 span: lo.to(e.span),
5560 node: StmtKind::Expr(e),
5567 /// Checks if this expression is a successfully parsed statement.
5568 fn expr_is_complete(&mut self, e: &Expr) -> bool {
5569 self.restrictions.contains(Restrictions::STMT_EXPR) &&
5570 !classify::expr_requires_semi_to_be_stmt(e)
5573 /// Parses a block. No inner attributes are allowed.
5574 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
5575 maybe_whole!(self, NtBlock, |x| x);
5579 if !self.eat(&token::OpenDelim(token::Brace)) {
5581 let tok = self.this_token_descr();
5582 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
5583 let do_not_suggest_help =
5584 self.token.is_keyword(keywords::In) || self.token == token::Colon;
5586 if self.token.is_ident_named("and") {
5587 e.span_suggestion_short(
5589 "use `&&` instead of `and` for the boolean operator",
5591 Applicability::MaybeIncorrect,
5594 if self.token.is_ident_named("or") {
5595 e.span_suggestion_short(
5597 "use `||` instead of `or` for the boolean operator",
5599 Applicability::MaybeIncorrect,
5603 // Check to see if the user has written something like
5608 // Which is valid in other languages, but not Rust.
5609 match self.parse_stmt_without_recovery(false) {
5611 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
5612 || do_not_suggest_help {
5613 // if the next token is an open brace (e.g., `if a b {`), the place-
5614 // inside-a-block suggestion would be more likely wrong than right
5615 e.span_label(sp, "expected `{`");
5618 let mut stmt_span = stmt.span;
5619 // expand the span to include the semicolon, if it exists
5620 if self.eat(&token::Semi) {
5621 stmt_span = stmt_span.with_hi(self.prev_span.hi());
5623 let sugg = pprust::to_string(|s| {
5624 use crate::print::pprust::{PrintState, INDENT_UNIT};
5625 s.ibox(INDENT_UNIT)?;
5627 s.print_stmt(&stmt)?;
5628 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
5632 "try placing this code inside a block",
5634 // speculative, has been misleading in the past (closed Issue #46836)
5635 Applicability::MaybeIncorrect
5639 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5640 self.cancel(&mut e);
5644 e.span_label(sp, "expected `{`");
5648 self.parse_block_tail(lo, BlockCheckMode::Default)
5651 /// Parses a block. Inner attributes are allowed.
5652 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
5653 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
5656 self.expect(&token::OpenDelim(token::Brace))?;
5657 Ok((self.parse_inner_attributes()?,
5658 self.parse_block_tail(lo, BlockCheckMode::Default)?))
5661 /// Parses the rest of a block expression or function body.
5662 /// Precondition: already parsed the '{'.
5663 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
5664 let mut stmts = vec![];
5665 while !self.eat(&token::CloseDelim(token::Brace)) {
5666 let stmt = match self.parse_full_stmt(false) {
5669 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
5671 id: ast::DUMMY_NODE_ID,
5672 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
5678 if let Some(stmt) = stmt {
5680 } else if self.token == token::Eof {
5683 // Found only `;` or `}`.
5689 id: ast::DUMMY_NODE_ID,
5691 span: lo.to(self.prev_span),
5695 /// Parses a statement, including the trailing semicolon.
5696 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5697 // skip looking for a trailing semicolon when we have an interpolated statement
5698 maybe_whole!(self, NtStmt, |x| Some(x));
5700 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5702 None => return Ok(None),
5706 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5707 // expression without semicolon
5708 if classify::expr_requires_semi_to_be_stmt(expr) {
5709 // Just check for errors and recover; do not eat semicolon yet.
5711 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5714 self.recover_stmt();
5718 StmtKind::Local(..) => {
5719 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5720 if macro_legacy_warnings && self.token != token::Semi {
5721 self.warn_missing_semicolon();
5723 self.expect_one_of(&[], &[token::Semi])?;
5729 if self.eat(&token::Semi) {
5730 stmt = stmt.add_trailing_semicolon();
5733 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5737 fn warn_missing_semicolon(&self) {
5738 self.diagnostic().struct_span_warn(self.span, {
5739 &format!("expected `;`, found {}", self.this_token_descr())
5741 "This was erroneously allowed and will become a hard error in a future release"
5745 fn err_dotdotdot_syntax(&self, span: Span) {
5746 self.diagnostic().struct_span_err(span, {
5747 "unexpected token: `...`"
5749 span, "use `..` for an exclusive range", "..".to_owned(),
5750 Applicability::MaybeIncorrect
5752 span, "or `..=` for an inclusive range", "..=".to_owned(),
5753 Applicability::MaybeIncorrect
5757 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
5760 /// BOUND = TY_BOUND | LT_BOUND
5761 /// LT_BOUND = LIFETIME (e.g., `'a`)
5762 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5763 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5765 fn parse_generic_bounds_common(&mut self,
5767 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5768 let mut bounds = Vec::new();
5769 let mut negative_bounds = Vec::new();
5770 let mut last_plus_span = None;
5771 let mut was_negative = false;
5773 // This needs to be synchronized with `Token::can_begin_bound`.
5774 let is_bound_start = self.check_path() || self.check_lifetime() ||
5775 self.check(&token::Not) || // used for error reporting only
5776 self.check(&token::Question) ||
5777 self.check_keyword(keywords::For) ||
5778 self.check(&token::OpenDelim(token::Paren));
5781 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5782 let inner_lo = self.span;
5783 let is_negative = self.eat(&token::Not);
5784 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5785 if self.token.is_lifetime() {
5786 if let Some(question_span) = question {
5787 self.span_err(question_span,
5788 "`?` may only modify trait bounds, not lifetime bounds");
5790 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5792 let inner_span = inner_lo.to(self.prev_span);
5793 self.expect(&token::CloseDelim(token::Paren))?;
5794 let mut err = self.struct_span_err(
5795 lo.to(self.prev_span),
5796 "parenthesized lifetime bounds are not supported"
5798 if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
5799 err.span_suggestion_short(
5800 lo.to(self.prev_span),
5801 "remove the parentheses",
5803 Applicability::MachineApplicable
5809 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5810 let path = self.parse_path(PathStyle::Type)?;
5812 self.expect(&token::CloseDelim(token::Paren))?;
5814 let poly_span = lo.to(self.prev_span);
5816 was_negative = true;
5817 if let Some(sp) = last_plus_span.or(colon_span) {
5818 negative_bounds.push(sp.to(poly_span));
5821 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
5822 let modifier = if question.is_some() {
5823 TraitBoundModifier::Maybe
5825 TraitBoundModifier::None
5827 bounds.push(GenericBound::Trait(poly_trait, modifier));
5834 if !allow_plus || !self.eat_plus() {
5837 last_plus_span = Some(self.prev_span);
5841 if !negative_bounds.is_empty() || was_negative {
5842 let plural = negative_bounds.len() > 1;
5843 let last_span = negative_bounds.last().map(|sp| *sp);
5844 let mut err = self.struct_span_err(
5846 "negative trait bounds are not supported",
5848 if let Some(sp) = last_span {
5849 err.span_label(sp, "negative trait bounds are not supported");
5851 if let Some(bound_list) = colon_span {
5852 let bound_list = bound_list.to(self.prev_span);
5853 let mut new_bound_list = String::new();
5854 if !bounds.is_empty() {
5855 let mut snippets = bounds.iter().map(|bound| bound.span())
5856 .map(|span| self.sess.source_map().span_to_snippet(span));
5857 while let Some(Ok(snippet)) = snippets.next() {
5858 new_bound_list.push_str(" + ");
5859 new_bound_list.push_str(&snippet);
5861 new_bound_list = new_bound_list.replacen(" +", ":", 1);
5863 err.span_suggestion_hidden(
5865 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
5867 Applicability::MachineApplicable,
5876 fn parse_generic_bounds(&mut self, colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5877 self.parse_generic_bounds_common(true, colon_span)
5880 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5883 /// BOUND = LT_BOUND (e.g., `'a`)
5885 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5886 let mut lifetimes = Vec::new();
5887 while self.check_lifetime() {
5888 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5890 if !self.eat_plus() {
5897 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
5898 fn parse_ty_param(&mut self,
5899 preceding_attrs: Vec<Attribute>)
5900 -> PResult<'a, GenericParam> {
5901 let ident = self.parse_ident()?;
5903 // Parse optional colon and param bounds.
5904 let bounds = if self.eat(&token::Colon) {
5905 self.parse_generic_bounds(Some(self.prev_span))?
5910 let default = if self.eat(&token::Eq) {
5911 Some(self.parse_ty()?)
5918 id: ast::DUMMY_NODE_ID,
5919 attrs: preceding_attrs.into(),
5921 kind: GenericParamKind::Type {
5927 /// Parses the following grammar:
5929 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5930 fn parse_trait_item_assoc_ty(&mut self)
5931 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5932 let ident = self.parse_ident()?;
5933 let mut generics = self.parse_generics()?;
5935 // Parse optional colon and param bounds.
5936 let bounds = if self.eat(&token::Colon) {
5937 self.parse_generic_bounds(None)?
5941 generics.where_clause = self.parse_where_clause()?;
5943 let default = if self.eat(&token::Eq) {
5944 Some(self.parse_ty()?)
5948 self.expect(&token::Semi)?;
5950 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5953 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
5954 self.expect_keyword(keywords::Const)?;
5955 let ident = self.parse_ident()?;
5956 self.expect(&token::Colon)?;
5957 let ty = self.parse_ty()?;
5961 id: ast::DUMMY_NODE_ID,
5962 attrs: preceding_attrs.into(),
5964 kind: GenericParamKind::Const {
5970 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
5971 /// a trailing comma and erroneous trailing attributes.
5972 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5973 let mut params = Vec::new();
5975 let attrs = self.parse_outer_attributes()?;
5976 if self.check_lifetime() {
5977 let lifetime = self.expect_lifetime();
5978 // Parse lifetime parameter.
5979 let bounds = if self.eat(&token::Colon) {
5980 self.parse_lt_param_bounds()
5984 params.push(ast::GenericParam {
5985 ident: lifetime.ident,
5987 attrs: attrs.into(),
5989 kind: ast::GenericParamKind::Lifetime,
5991 } else if self.check_keyword(keywords::Const) {
5992 // Parse const parameter.
5993 params.push(self.parse_const_param(attrs)?);
5994 } else if self.check_ident() {
5995 // Parse type parameter.
5996 params.push(self.parse_ty_param(attrs)?);
5998 // Check for trailing attributes and stop parsing.
5999 if !attrs.is_empty() {
6000 if !params.is_empty() {
6001 self.struct_span_err(
6003 &format!("trailing attribute after generic parameter"),
6005 .span_label(attrs[0].span, "attributes must go before parameters")
6008 self.struct_span_err(
6010 &format!("attribute without generic parameters"),
6014 "attributes are only permitted when preceding parameters",
6022 if !self.eat(&token::Comma) {
6029 /// Parses a set of optional generic type parameter declarations. Where
6030 /// clauses are not parsed here, and must be added later via
6031 /// `parse_where_clause()`.
6033 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
6034 /// | ( < lifetimes , typaramseq ( , )? > )
6035 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
6036 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
6037 maybe_whole!(self, NtGenerics, |x| x);
6039 let span_lo = self.span;
6041 let params = self.parse_generic_params()?;
6045 where_clause: WhereClause {
6046 id: ast::DUMMY_NODE_ID,
6047 predicates: Vec::new(),
6048 span: syntax_pos::DUMMY_SP,
6050 span: span_lo.to(self.prev_span),
6053 Ok(ast::Generics::default())
6057 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
6058 /// For the purposes of understanding the parsing logic of generic arguments, this function
6059 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
6060 /// had the correct amount of leading angle brackets.
6062 /// ```ignore (diagnostics)
6063 /// bar::<<<<T as Foo>::Output>();
6064 /// ^^ help: remove extra angle brackets
6066 fn parse_generic_args_with_leaning_angle_bracket_recovery(
6070 ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
6071 // We need to detect whether there are extra leading left angle brackets and produce an
6072 // appropriate error and suggestion. This cannot be implemented by looking ahead at
6073 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
6074 // then there won't be matching `>` tokens to find.
6076 // To explain how this detection works, consider the following example:
6078 // ```ignore (diagnostics)
6079 // bar::<<<<T as Foo>::Output>();
6080 // ^^ help: remove extra angle brackets
6083 // Parsing of the left angle brackets starts in this function. We start by parsing the
6084 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
6087 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
6088 // *Unmatched count:* 1
6089 // *`parse_path_segment` calls deep:* 0
6091 // This has the effect of recursing as this function is called if a `<` character
6092 // is found within the expected generic arguments:
6094 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
6095 // *Unmatched count:* 2
6096 // *`parse_path_segment` calls deep:* 1
6098 // Eventually we will have recursed until having consumed all of the `<` tokens and
6099 // this will be reflected in the count:
6101 // *Upcoming tokens:* `T as Foo>::Output>;`
6102 // *Unmatched count:* 4
6103 // `parse_path_segment` calls deep:* 3
6105 // The parser will continue until reaching the first `>` - this will decrement the
6106 // unmatched angle bracket count and return to the parent invocation of this function
6107 // having succeeded in parsing:
6109 // *Upcoming tokens:* `::Output>;`
6110 // *Unmatched count:* 3
6111 // *`parse_path_segment` calls deep:* 2
6113 // This will continue until the next `>` character which will also return successfully
6114 // to the parent invocation of this function and decrement the count:
6116 // *Upcoming tokens:* `;`
6117 // *Unmatched count:* 2
6118 // *`parse_path_segment` calls deep:* 1
6120 // At this point, this function will expect to find another matching `>` character but
6121 // won't be able to and will return an error. This will continue all the way up the
6122 // call stack until the first invocation:
6124 // *Upcoming tokens:* `;`
6125 // *Unmatched count:* 2
6126 // *`parse_path_segment` calls deep:* 0
6128 // In doing this, we have managed to work out how many unmatched leading left angle
6129 // brackets there are, but we cannot recover as the unmatched angle brackets have
6130 // already been consumed. To remedy this, we keep a snapshot of the parser state
6131 // before we do the above. We can then inspect whether we ended up with a parsing error
6132 // and unmatched left angle brackets and if so, restore the parser state before we
6133 // consumed any `<` characters to emit an error and consume the erroneous tokens to
6134 // recover by attempting to parse again.
6136 // In practice, the recursion of this function is indirect and there will be other
6137 // locations that consume some `<` characters - as long as we update the count when
6138 // this happens, it isn't an issue.
6140 let is_first_invocation = style == PathStyle::Expr;
6141 // Take a snapshot before attempting to parse - we can restore this later.
6142 let snapshot = if is_first_invocation {
6148 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
6149 match self.parse_generic_args() {
6150 Ok(value) => Ok(value),
6151 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
6152 // Cancel error from being unable to find `>`. We know the error
6153 // must have been this due to a non-zero unmatched angle bracket
6157 // Swap `self` with our backup of the parser state before attempting to parse
6158 // generic arguments.
6159 let snapshot = mem::replace(self, snapshot.unwrap());
6162 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
6163 snapshot.count={:?}",
6164 snapshot.unmatched_angle_bracket_count,
6167 // Eat the unmatched angle brackets.
6168 for _ in 0..snapshot.unmatched_angle_bracket_count {
6172 // Make a span over ${unmatched angle bracket count} characters.
6173 let span = lo.with_hi(
6174 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
6176 let plural = snapshot.unmatched_angle_bracket_count > 1;
6181 "unmatched angle bracket{}",
6182 if plural { "s" } else { "" }
6188 "remove extra angle bracket{}",
6189 if plural { "s" } else { "" }
6192 Applicability::MachineApplicable,
6196 // Try again without unmatched angle bracket characters.
6197 self.parse_generic_args()
6203 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
6204 /// possibly including trailing comma.
6205 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
6206 let mut args = Vec::new();
6207 let mut bindings = Vec::new();
6208 let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new();
6209 let mut assoc_ty_bindings: Vec<Span> = Vec::new();
6211 let args_lo = self.span;
6214 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6215 // Parse lifetime argument.
6216 args.push(GenericArg::Lifetime(self.expect_lifetime()));
6217 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6218 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
6219 // Parse associated type binding.
6221 let ident = self.parse_ident()?;
6223 let ty = self.parse_ty()?;
6224 let span = lo.to(self.prev_span);
6225 bindings.push(TypeBinding {
6226 id: ast::DUMMY_NODE_ID,
6231 assoc_ty_bindings.push(span);
6232 } else if self.check_const_arg() {
6233 // FIXME(const_generics): to distinguish between idents for types and consts,
6234 // we should introduce a GenericArg::Ident in the AST and distinguish when
6235 // lowering to the HIR. For now, idents for const args are not permitted.
6237 // Parse const argument.
6238 let expr = if let token::OpenDelim(token::Brace) = self.token {
6239 self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
6240 } else if self.token.is_ident() {
6241 // FIXME(const_generics): to distinguish between idents for types and consts,
6242 // we should introduce a GenericArg::Ident in the AST and distinguish when
6243 // lowering to the HIR. For now, idents for const args are not permitted.
6245 self.fatal("identifiers may currently not be used for const generics")
6248 // FIXME(const_generics): this currently conflicts with emplacement syntax
6249 // with negative integer literals.
6250 self.parse_literal_maybe_minus()?
6252 let value = AnonConst {
6253 id: ast::DUMMY_NODE_ID,
6256 args.push(GenericArg::Const(value));
6257 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6258 } else if self.check_type() {
6259 // Parse type argument.
6260 args.push(GenericArg::Type(self.parse_ty()?));
6261 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6266 if !self.eat(&token::Comma) {
6271 // FIXME: we would like to report this in ast_validation instead, but we currently do not
6272 // preserve ordering of generic parameters with respect to associated type binding, so we
6273 // lose that information after parsing.
6274 if misplaced_assoc_ty_bindings.len() > 0 {
6275 let mut err = self.struct_span_err(
6276 args_lo.to(self.prev_span),
6277 "associated type bindings must be declared after generic parameters",
6279 for span in misplaced_assoc_ty_bindings {
6282 "this associated type binding should be moved after the generic parameters",
6288 Ok((args, bindings))
6291 /// Parses an optional where-clause and places it in `generics`.
6293 /// ```ignore (only-for-syntax-highlight)
6294 /// where T : Trait<U, V> + 'b, 'a : 'b
6296 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
6297 maybe_whole!(self, NtWhereClause, |x| x);
6299 let mut where_clause = WhereClause {
6300 id: ast::DUMMY_NODE_ID,
6301 predicates: Vec::new(),
6302 span: syntax_pos::DUMMY_SP,
6305 if !self.eat_keyword(keywords::Where) {
6306 return Ok(where_clause);
6308 let lo = self.prev_span;
6310 // We are considering adding generics to the `where` keyword as an alternative higher-rank
6311 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
6312 // change we parse those generics now, but report an error.
6313 if self.choose_generics_over_qpath() {
6314 let generics = self.parse_generics()?;
6315 self.struct_span_err(
6317 "generic parameters on `where` clauses are reserved for future use",
6319 .span_label(generics.span, "currently unsupported")
6325 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6326 let lifetime = self.expect_lifetime();
6327 // Bounds starting with a colon are mandatory, but possibly empty.
6328 self.expect(&token::Colon)?;
6329 let bounds = self.parse_lt_param_bounds();
6330 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
6331 ast::WhereRegionPredicate {
6332 span: lo.to(self.prev_span),
6337 } else if self.check_type() {
6338 // Parse optional `for<'a, 'b>`.
6339 // This `for` is parsed greedily and applies to the whole predicate,
6340 // the bounded type can have its own `for` applying only to it.
6341 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
6342 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
6343 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
6344 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
6346 // Parse type with mandatory colon and (possibly empty) bounds,
6347 // or with mandatory equality sign and the second type.
6348 let ty = self.parse_ty()?;
6349 if self.eat(&token::Colon) {
6350 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6351 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
6352 ast::WhereBoundPredicate {
6353 span: lo.to(self.prev_span),
6354 bound_generic_params: lifetime_defs,
6359 // FIXME: Decide what should be used here, `=` or `==`.
6360 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
6361 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
6362 let rhs_ty = self.parse_ty()?;
6363 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
6364 ast::WhereEqPredicate {
6365 span: lo.to(self.prev_span),
6368 id: ast::DUMMY_NODE_ID,
6372 return self.unexpected();
6378 if !self.eat(&token::Comma) {
6383 where_clause.span = lo.to(self.prev_span);
6387 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
6388 -> PResult<'a, (Vec<Arg> , bool)> {
6389 self.expect(&token::OpenDelim(token::Paren))?;
6392 let mut c_variadic = false;
6393 let (args, recovered): (Vec<Option<Arg>>, bool) =
6394 self.parse_seq_to_before_end(
6395 &token::CloseDelim(token::Paren),
6396 SeqSep::trailing_allowed(token::Comma),
6398 // If the argument is a C-variadic argument we should not
6399 // enforce named arguments.
6400 let enforce_named_args = if p.token == token::DotDotDot {
6405 match p.parse_arg_general(enforce_named_args, false,
6408 if let TyKind::CVarArgs = arg.ty.node {
6410 if p.token != token::CloseDelim(token::Paren) {
6413 "`...` must be the last argument of a C-variadic function");
6424 let lo = p.prev_span;
6425 // Skip every token until next possible arg or end.
6426 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
6427 // Create a placeholder argument for proper arg count (issue #34264).
6428 let span = lo.to(p.prev_span);
6429 Ok(Some(dummy_arg(span)))
6436 self.eat(&token::CloseDelim(token::Paren));
6439 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
6441 if c_variadic && args.is_empty() {
6443 "C-variadic function must be declared with at least one named argument");
6446 Ok((args, c_variadic))
6449 /// Parses the argument list and result type of a function declaration.
6450 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
6452 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
6453 let ret_ty = self.parse_ret_ty(true)?;
6462 /// Returns the parsed optional self argument and whether a self shortcut was used.
6463 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
6464 let expect_ident = |this: &mut Self| match this.token {
6465 // Preserve hygienic context.
6466 token::Ident(ident, _) =>
6467 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
6470 let isolated_self = |this: &mut Self, n| {
6471 this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) &&
6472 this.look_ahead(n + 1, |t| t != &token::ModSep)
6475 // Parse optional self parameter of a method.
6476 // Only a limited set of initial token sequences is considered self parameters, anything
6477 // else is parsed as a normal function parameter list, so some lookahead is required.
6478 let eself_lo = self.span;
6479 let (eself, eself_ident, eself_hi) = match self.token {
6480 token::BinOp(token::And) => {
6486 (if isolated_self(self, 1) {
6488 SelfKind::Region(None, Mutability::Immutable)
6489 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
6490 isolated_self(self, 2) {
6493 SelfKind::Region(None, Mutability::Mutable)
6494 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6495 isolated_self(self, 2) {
6497 let lt = self.expect_lifetime();
6498 SelfKind::Region(Some(lt), Mutability::Immutable)
6499 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6500 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
6501 isolated_self(self, 3) {
6503 let lt = self.expect_lifetime();
6505 SelfKind::Region(Some(lt), Mutability::Mutable)
6508 }, expect_ident(self), self.prev_span)
6510 token::BinOp(token::Star) => {
6515 // Emit special error for `self` cases.
6516 let msg = "cannot pass `self` by raw pointer";
6517 (if isolated_self(self, 1) {
6519 self.struct_span_err(self.span, msg)
6520 .span_label(self.span, msg)
6522 SelfKind::Value(Mutability::Immutable)
6523 } else if self.look_ahead(1, |t| t.is_mutability()) &&
6524 isolated_self(self, 2) {
6527 self.struct_span_err(self.span, msg)
6528 .span_label(self.span, msg)
6530 SelfKind::Value(Mutability::Immutable)
6533 }, expect_ident(self), self.prev_span)
6535 token::Ident(..) => {
6536 if isolated_self(self, 0) {
6539 let eself_ident = expect_ident(self);
6540 let eself_hi = self.prev_span;
6541 (if self.eat(&token::Colon) {
6542 let ty = self.parse_ty()?;
6543 SelfKind::Explicit(ty, Mutability::Immutable)
6545 SelfKind::Value(Mutability::Immutable)
6546 }, eself_ident, eself_hi)
6547 } else if self.token.is_keyword(keywords::Mut) &&
6548 isolated_self(self, 1) {
6552 let eself_ident = expect_ident(self);
6553 let eself_hi = self.prev_span;
6554 (if self.eat(&token::Colon) {
6555 let ty = self.parse_ty()?;
6556 SelfKind::Explicit(ty, Mutability::Mutable)
6558 SelfKind::Value(Mutability::Mutable)
6559 }, eself_ident, eself_hi)
6564 _ => return Ok(None),
6567 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
6568 Ok(Some(Arg::from_self(eself, eself_ident)))
6571 /// Parses the parameter list and result type of a function that may have a `self` parameter.
6572 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
6573 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
6575 self.expect(&token::OpenDelim(token::Paren))?;
6577 // Parse optional self argument
6578 let self_arg = self.parse_self_arg()?;
6580 // Parse the rest of the function parameter list.
6581 let sep = SeqSep::trailing_allowed(token::Comma);
6582 let (fn_inputs, recovered) = if let Some(self_arg) = self_arg {
6583 if self.check(&token::CloseDelim(token::Paren)) {
6584 (vec![self_arg], false)
6585 } else if self.eat(&token::Comma) {
6586 let mut fn_inputs = vec![self_arg];
6587 let (mut input, recovered) = self.parse_seq_to_before_end(
6588 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
6589 fn_inputs.append(&mut input);
6590 (fn_inputs, recovered)
6592 match self.expect_one_of(&[], &[]) {
6593 Err(err) => return Err(err),
6594 Ok(recovered) => (vec![self_arg], recovered),
6598 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
6602 // Parse closing paren and return type.
6603 self.expect(&token::CloseDelim(token::Paren))?;
6607 output: self.parse_ret_ty(true)?,
6612 /// Parses the `|arg, arg|` header of a closure.
6613 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
6614 let inputs_captures = {
6615 if self.eat(&token::OrOr) {
6618 self.expect(&token::BinOp(token::Or))?;
6619 let args = self.parse_seq_to_before_tokens(
6620 &[&token::BinOp(token::Or), &token::OrOr],
6621 SeqSep::trailing_allowed(token::Comma),
6622 TokenExpectType::NoExpect,
6623 |p| p.parse_fn_block_arg()
6629 let output = self.parse_ret_ty(true)?;
6632 inputs: inputs_captures,
6638 /// Parses the name and optional generic types of a function header.
6639 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
6640 let id = self.parse_ident()?;
6641 let generics = self.parse_generics()?;
6645 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
6646 attrs: Vec<Attribute>) -> P<Item> {
6650 id: ast::DUMMY_NODE_ID,
6658 /// Parses an item-position function declaration.
6659 fn parse_item_fn(&mut self,
6661 mut asyncness: Spanned<IsAsync>,
6662 constness: Spanned<Constness>,
6664 -> PResult<'a, ItemInfo> {
6665 let (ident, mut generics) = self.parse_fn_header()?;
6666 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
6667 let decl = self.parse_fn_decl(allow_c_variadic)?;
6668 generics.where_clause = self.parse_where_clause()?;
6669 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6670 self.construct_async_arguments(&mut asyncness, &decl);
6671 let header = FnHeader { unsafety, asyncness, constness, abi };
6672 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
6675 /// Returns `true` if we are looking at `const ID`
6676 /// (returns `false` for things like `const fn`, etc.).
6677 fn is_const_item(&mut self) -> bool {
6678 self.token.is_keyword(keywords::Const) &&
6679 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
6680 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
6683 /// Parses all the "front matter" for a `fn` declaration, up to
6684 /// and including the `fn` keyword:
6688 /// - `const unsafe fn`
6691 fn parse_fn_front_matter(&mut self)
6699 let is_const_fn = self.eat_keyword(keywords::Const);
6700 let const_span = self.prev_span;
6701 let unsafety = self.parse_unsafety();
6702 let asyncness = self.parse_asyncness();
6703 let asyncness = respan(self.prev_span, asyncness);
6704 let (constness, unsafety, abi) = if is_const_fn {
6705 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
6707 let abi = if self.eat_keyword(keywords::Extern) {
6708 self.parse_opt_abi()?.unwrap_or(Abi::C)
6712 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
6714 if !self.eat_keyword(keywords::Fn) {
6715 // It is possible for `expect_one_of` to recover given the contents of
6716 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
6717 // account for this.
6718 if !self.expect_one_of(&[], &[])? { unreachable!() }
6720 Ok((constness, unsafety, asyncness, abi))
6723 /// Parses an impl item.
6724 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
6725 maybe_whole!(self, NtImplItem, |x| x);
6726 let attrs = self.parse_outer_attributes()?;
6727 let mut unclosed_delims = vec![];
6728 let (mut item, tokens) = self.collect_tokens(|this| {
6729 let item = this.parse_impl_item_(at_end, attrs);
6730 unclosed_delims.append(&mut this.unclosed_delims);
6733 self.unclosed_delims.append(&mut unclosed_delims);
6735 // See `parse_item` for why this clause is here.
6736 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6737 item.tokens = Some(tokens);
6742 fn parse_impl_item_(&mut self,
6744 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
6746 let vis = self.parse_visibility(false)?;
6747 let defaultness = self.parse_defaultness();
6748 let (name, node, generics) = if let Some(type_) = self.eat_type() {
6749 let (name, alias, generics) = type_?;
6750 let kind = match alias {
6751 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
6752 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
6754 (name, kind, generics)
6755 } else if self.is_const_item() {
6756 // This parses the grammar:
6757 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
6758 self.expect_keyword(keywords::Const)?;
6759 let name = self.parse_ident()?;
6760 self.expect(&token::Colon)?;
6761 let typ = self.parse_ty()?;
6762 self.expect(&token::Eq)?;
6763 let expr = self.parse_expr()?;
6764 self.expect(&token::Semi)?;
6765 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
6767 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
6768 attrs.extend(inner_attrs);
6769 (name, node, generics)
6773 id: ast::DUMMY_NODE_ID,
6774 span: lo.to(self.prev_span),
6785 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
6787 VisibilityKind::Inherited => {}
6789 let is_macro_rules: bool = match self.token {
6790 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
6793 let mut err = if is_macro_rules {
6794 let mut err = self.diagnostic()
6795 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
6796 err.span_suggestion(
6798 "try exporting the macro",
6799 "#[macro_export]".to_owned(),
6800 Applicability::MaybeIncorrect // speculative
6804 let mut err = self.diagnostic()
6805 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
6806 err.help("try adjusting the macro to put `pub` inside the invocation");
6814 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
6815 -> DiagnosticBuilder<'a>
6817 let expected_kinds = if item_type == "extern" {
6818 "missing `fn`, `type`, or `static`"
6820 "missing `fn`, `type`, or `const`"
6823 // Given this code `path(`, it seems like this is not
6824 // setting the visibility of a macro invocation, but rather
6825 // a mistyped method declaration.
6826 // Create a diagnostic pointing out that `fn` is missing.
6828 // x | pub path(&self) {
6829 // | ^ missing `fn`, `type`, or `const`
6831 // ^^ `sp` below will point to this
6832 let sp = prev_span.between(self.prev_span);
6833 let mut err = self.diagnostic().struct_span_err(
6835 &format!("{} for {}-item declaration",
6836 expected_kinds, item_type));
6837 err.span_label(sp, expected_kinds);
6841 /// Parse a method or a macro invocation in a trait impl.
6842 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
6843 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
6844 ast::ImplItemKind)> {
6845 // code copied from parse_macro_use_or_failure... abstraction!
6846 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
6848 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
6849 ast::ImplItemKind::Macro(mac)))
6851 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
6852 let ident = self.parse_ident()?;
6853 let mut generics = self.parse_generics()?;
6854 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
6855 generics.where_clause = self.parse_where_clause()?;
6856 self.construct_async_arguments(&mut asyncness, &decl);
6858 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6859 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
6860 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
6861 ast::MethodSig { header, decl },
6867 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
6868 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
6869 let ident = self.parse_ident()?;
6870 let mut tps = self.parse_generics()?;
6872 // Parse optional colon and supertrait bounds.
6873 let bounds = if self.eat(&token::Colon) {
6874 self.parse_generic_bounds(Some(self.prev_span))?
6879 if self.eat(&token::Eq) {
6880 // it's a trait alias
6881 let bounds = self.parse_generic_bounds(None)?;
6882 tps.where_clause = self.parse_where_clause()?;
6883 self.expect(&token::Semi)?;
6884 if is_auto == IsAuto::Yes {
6885 let msg = "trait aliases cannot be `auto`";
6886 self.struct_span_err(self.prev_span, msg)
6887 .span_label(self.prev_span, msg)
6890 if unsafety != Unsafety::Normal {
6891 let msg = "trait aliases cannot be `unsafe`";
6892 self.struct_span_err(self.prev_span, msg)
6893 .span_label(self.prev_span, msg)
6896 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
6898 // it's a normal trait
6899 tps.where_clause = self.parse_where_clause()?;
6900 self.expect(&token::OpenDelim(token::Brace))?;
6901 let mut trait_items = vec![];
6902 while !self.eat(&token::CloseDelim(token::Brace)) {
6903 if let token::DocComment(_) = self.token {
6904 if self.look_ahead(1,
6905 |tok| tok == &token::Token::CloseDelim(token::Brace)) {
6906 let mut err = self.diagnostic().struct_span_err_with_code(
6908 "found a documentation comment that doesn't document anything",
6909 DiagnosticId::Error("E0584".into()),
6911 err.help("doc comments must come before what they document, maybe a \
6912 comment was intended with `//`?",
6919 let mut at_end = false;
6920 match self.parse_trait_item(&mut at_end) {
6921 Ok(item) => trait_items.push(item),
6925 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6930 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
6934 fn choose_generics_over_qpath(&self) -> bool {
6935 // There's an ambiguity between generic parameters and qualified paths in impls.
6936 // If we see `<` it may start both, so we have to inspect some following tokens.
6937 // The following combinations can only start generics,
6938 // but not qualified paths (with one exception):
6939 // `<` `>` - empty generic parameters
6940 // `<` `#` - generic parameters with attributes
6941 // `<` (LIFETIME|IDENT) `>` - single generic parameter
6942 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
6943 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
6944 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
6945 // `<` const - generic const parameter
6946 // The only truly ambiguous case is
6947 // `<` IDENT `>` `::` IDENT ...
6948 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
6949 // because this is what almost always expected in practice, qualified paths in impls
6950 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
6951 self.token == token::Lt &&
6952 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
6953 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
6954 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
6955 t == &token::Colon || t == &token::Eq) ||
6956 self.look_ahead(1, |t| t.is_keyword(keywords::Const)))
6959 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6960 self.expect(&token::OpenDelim(token::Brace))?;
6961 let attrs = self.parse_inner_attributes()?;
6963 let mut impl_items = Vec::new();
6964 while !self.eat(&token::CloseDelim(token::Brace)) {
6965 let mut at_end = false;
6966 match self.parse_impl_item(&mut at_end) {
6967 Ok(impl_item) => impl_items.push(impl_item),
6971 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6976 Ok((impl_items, attrs))
6979 /// Parses an implementation item, `impl` keyword is already parsed.
6981 /// impl<'a, T> TYPE { /* impl items */ }
6982 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6983 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6985 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6986 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6987 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6988 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6989 -> PResult<'a, ItemInfo> {
6990 // First, parse generic parameters if necessary.
6991 let mut generics = if self.choose_generics_over_qpath() {
6992 self.parse_generics()?
6994 ast::Generics::default()
6997 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6998 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
7000 ast::ImplPolarity::Negative
7002 ast::ImplPolarity::Positive
7005 // Parse both types and traits as a type, then reinterpret if necessary.
7006 let err_path = |span| ast::Path::from_ident(Ident::new(keywords::Invalid.name(), span));
7007 let ty_first = if self.token.is_keyword(keywords::For) &&
7008 self.look_ahead(1, |t| t != &token::Lt) {
7009 let span = self.prev_span.between(self.span);
7010 self.struct_span_err(span, "missing trait in a trait impl").emit();
7011 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
7016 // If `for` is missing we try to recover.
7017 let has_for = self.eat_keyword(keywords::For);
7018 let missing_for_span = self.prev_span.between(self.span);
7020 let ty_second = if self.token == token::DotDot {
7021 // We need to report this error after `cfg` expansion for compatibility reasons
7022 self.bump(); // `..`, do not add it to expected tokens
7023 Some(DummyResult::raw_ty(self.prev_span, true))
7024 } else if has_for || self.token.can_begin_type() {
7025 Some(self.parse_ty()?)
7030 generics.where_clause = self.parse_where_clause()?;
7032 let (impl_items, attrs) = self.parse_impl_body()?;
7034 let item_kind = match ty_second {
7035 Some(ty_second) => {
7036 // impl Trait for Type
7038 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
7039 .span_suggestion_short(
7042 " for ".to_string(),
7043 Applicability::MachineApplicable,
7047 let ty_first = ty_first.into_inner();
7048 let path = match ty_first.node {
7049 // This notably includes paths passed through `ty` macro fragments (#46438).
7050 TyKind::Path(None, path) => path,
7052 self.span_err(ty_first.span, "expected a trait, found type");
7053 err_path(ty_first.span)
7056 let trait_ref = TraitRef { path, ref_id: ty_first.id };
7058 ItemKind::Impl(unsafety, polarity, defaultness,
7059 generics, Some(trait_ref), ty_second, impl_items)
7063 ItemKind::Impl(unsafety, polarity, defaultness,
7064 generics, None, ty_first, impl_items)
7068 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
7071 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
7072 if self.eat_keyword(keywords::For) {
7074 let params = self.parse_generic_params()?;
7076 // We rely on AST validation to rule out invalid cases: There must not be type
7077 // parameters, and the lifetime parameters must not have bounds.
7084 /// Parses `struct Foo { ... }`.
7085 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
7086 let class_name = self.parse_ident()?;
7088 let mut generics = self.parse_generics()?;
7090 // There is a special case worth noting here, as reported in issue #17904.
7091 // If we are parsing a tuple struct it is the case that the where clause
7092 // should follow the field list. Like so:
7094 // struct Foo<T>(T) where T: Copy;
7096 // If we are parsing a normal record-style struct it is the case
7097 // that the where clause comes before the body, and after the generics.
7098 // So if we look ahead and see a brace or a where-clause we begin
7099 // parsing a record style struct.
7101 // Otherwise if we look ahead and see a paren we parse a tuple-style
7104 let vdata = if self.token.is_keyword(keywords::Where) {
7105 generics.where_clause = self.parse_where_clause()?;
7106 if self.eat(&token::Semi) {
7107 // If we see a: `struct Foo<T> where T: Copy;` style decl.
7108 VariantData::Unit(ast::DUMMY_NODE_ID)
7110 // If we see: `struct Foo<T> where T: Copy { ... }`
7111 let (fields, recovered) = self.parse_record_struct_body()?;
7112 VariantData::Struct(fields, recovered)
7114 // No `where` so: `struct Foo<T>;`
7115 } else if self.eat(&token::Semi) {
7116 VariantData::Unit(ast::DUMMY_NODE_ID)
7117 // Record-style struct definition
7118 } else if self.token == token::OpenDelim(token::Brace) {
7119 let (fields, recovered) = self.parse_record_struct_body()?;
7120 VariantData::Struct(fields, recovered)
7121 // Tuple-style struct definition with optional where-clause.
7122 } else if self.token == token::OpenDelim(token::Paren) {
7123 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
7124 generics.where_clause = self.parse_where_clause()?;
7125 self.expect(&token::Semi)?;
7128 let token_str = self.this_token_descr();
7129 let mut err = self.fatal(&format!(
7130 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
7133 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
7137 Ok((class_name, ItemKind::Struct(vdata, generics), None))
7140 /// Parses `union Foo { ... }`.
7141 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
7142 let class_name = self.parse_ident()?;
7144 let mut generics = self.parse_generics()?;
7146 let vdata = if self.token.is_keyword(keywords::Where) {
7147 generics.where_clause = self.parse_where_clause()?;
7148 let (fields, recovered) = self.parse_record_struct_body()?;
7149 VariantData::Struct(fields, recovered)
7150 } else if self.token == token::OpenDelim(token::Brace) {
7151 let (fields, recovered) = self.parse_record_struct_body()?;
7152 VariantData::Struct(fields, recovered)
7154 let token_str = self.this_token_descr();
7155 let mut err = self.fatal(&format!(
7156 "expected `where` or `{{` after union name, found {}", token_str));
7157 err.span_label(self.span, "expected `where` or `{` after union name");
7161 Ok((class_name, ItemKind::Union(vdata, generics), None))
7164 fn consume_block(&mut self, delim: token::DelimToken) {
7165 let mut brace_depth = 0;
7167 if self.eat(&token::OpenDelim(delim)) {
7169 } else if self.eat(&token::CloseDelim(delim)) {
7170 if brace_depth == 0 {
7176 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
7184 fn parse_record_struct_body(
7186 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
7187 let mut fields = Vec::new();
7188 let mut recovered = false;
7189 if self.eat(&token::OpenDelim(token::Brace)) {
7190 while self.token != token::CloseDelim(token::Brace) {
7191 let field = self.parse_struct_decl_field().map_err(|e| {
7192 self.recover_stmt();
7197 Ok(field) => fields.push(field),
7203 self.eat(&token::CloseDelim(token::Brace));
7205 let token_str = self.this_token_descr();
7206 let mut err = self.fatal(&format!(
7207 "expected `where`, or `{{` after struct name, found {}", token_str));
7208 err.span_label(self.span, "expected `where`, or `{` after struct name");
7212 Ok((fields, recovered))
7215 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
7216 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
7217 // Unit like structs are handled in parse_item_struct function
7218 let fields = self.parse_unspanned_seq(
7219 &token::OpenDelim(token::Paren),
7220 &token::CloseDelim(token::Paren),
7221 SeqSep::trailing_allowed(token::Comma),
7223 let attrs = p.parse_outer_attributes()?;
7225 let vis = p.parse_visibility(true)?;
7226 let ty = p.parse_ty()?;
7228 span: lo.to(ty.span),
7231 id: ast::DUMMY_NODE_ID,
7240 /// Parses a structure field declaration.
7241 fn parse_single_struct_field(&mut self,
7244 attrs: Vec<Attribute> )
7245 -> PResult<'a, StructField> {
7246 let mut seen_comma: bool = false;
7247 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
7248 if self.token == token::Comma {
7255 token::CloseDelim(token::Brace) => {}
7256 token::DocComment(_) => {
7257 let previous_span = self.prev_span;
7258 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
7259 self.bump(); // consume the doc comment
7260 let comma_after_doc_seen = self.eat(&token::Comma);
7261 // `seen_comma` is always false, because we are inside doc block
7262 // condition is here to make code more readable
7263 if seen_comma == false && comma_after_doc_seen == true {
7266 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
7269 if seen_comma == false {
7270 let sp = self.sess.source_map().next_point(previous_span);
7271 err.span_suggestion(
7273 "missing comma here",
7275 Applicability::MachineApplicable
7282 let sp = self.sess.source_map().next_point(self.prev_span);
7283 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
7284 self.this_token_descr()));
7285 if self.token.is_ident() {
7286 // This is likely another field; emit the diagnostic and keep going
7287 err.span_suggestion(
7289 "try adding a comma",
7291 Applicability::MachineApplicable,
7302 /// Parses an element of a struct declaration.
7303 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
7304 let attrs = self.parse_outer_attributes()?;
7306 let vis = self.parse_visibility(false)?;
7307 self.parse_single_struct_field(lo, vis, attrs)
7310 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
7311 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
7312 /// If the following element can't be a tuple (i.e., it's a function definition), then
7313 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
7314 /// so emit a proper diagnostic.
7315 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
7316 maybe_whole!(self, NtVis, |x| x);
7318 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
7319 if self.is_crate_vis() {
7320 self.bump(); // `crate`
7321 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
7324 if !self.eat_keyword(keywords::Pub) {
7325 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
7326 // keyword to grab a span from for inherited visibility; an empty span at the
7327 // beginning of the current token would seem to be the "Schelling span".
7328 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
7330 let lo = self.prev_span;
7332 if self.check(&token::OpenDelim(token::Paren)) {
7333 // We don't `self.bump()` the `(` yet because this might be a struct definition where
7334 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
7335 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
7336 // by the following tokens.
7337 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
7340 self.bump(); // `crate`
7341 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7343 lo.to(self.prev_span),
7344 VisibilityKind::Crate(CrateSugar::PubCrate),
7347 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
7350 self.bump(); // `in`
7351 let path = self.parse_path(PathStyle::Mod)?; // `path`
7352 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7353 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7355 id: ast::DUMMY_NODE_ID,
7358 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
7359 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
7360 t.is_keyword(keywords::SelfLower))
7362 // `pub(self)` or `pub(super)`
7364 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
7365 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7366 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7368 id: ast::DUMMY_NODE_ID,
7371 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
7372 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
7374 let msg = "incorrect visibility restriction";
7375 let suggestion = r##"some possible visibility restrictions are:
7376 `pub(crate)`: visible only on the current crate
7377 `pub(super)`: visible only in the current module's parent
7378 `pub(in path::to::module)`: visible only on the specified path"##;
7379 let path = self.parse_path(PathStyle::Mod)?;
7380 let sp = self.prev_span;
7381 let help_msg = format!("make this visible only to module `{}` with `in`", path);
7382 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7383 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
7384 err.help(suggestion);
7385 err.span_suggestion(
7386 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
7388 err.emit(); // emit diagnostic, but continue with public visibility
7392 Ok(respan(lo, VisibilityKind::Public))
7395 /// Parses defaultness (i.e., `default` or nothing).
7396 fn parse_defaultness(&mut self) -> Defaultness {
7397 // `pub` is included for better error messages
7398 if self.check_keyword(keywords::Default) &&
7399 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
7400 t.is_keyword(keywords::Const) ||
7401 t.is_keyword(keywords::Fn) ||
7402 t.is_keyword(keywords::Unsafe) ||
7403 t.is_keyword(keywords::Extern) ||
7404 t.is_keyword(keywords::Type) ||
7405 t.is_keyword(keywords::Pub)) {
7406 self.bump(); // `default`
7407 Defaultness::Default
7413 fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
7414 if self.eat(&token::Semi) {
7415 let mut err = self.struct_span_err(self.prev_span, "expected item, found `;`");
7416 err.span_suggestion_short(
7418 "remove this semicolon",
7420 Applicability::MachineApplicable,
7422 if !items.is_empty() {
7423 let previous_item = &items[items.len()-1];
7424 let previous_item_kind_name = match previous_item.node {
7425 // say "braced struct" because tuple-structs and
7426 // braceless-empty-struct declarations do take a semicolon
7427 ItemKind::Struct(..) => Some("braced struct"),
7428 ItemKind::Enum(..) => Some("enum"),
7429 ItemKind::Trait(..) => Some("trait"),
7430 ItemKind::Union(..) => Some("union"),
7433 if let Some(name) = previous_item_kind_name {
7434 err.help(&format!("{} declarations are not followed by a semicolon", name));
7444 /// Given a termination token, parses all of the items in a module.
7445 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
7446 let mut items = vec![];
7447 while let Some(item) = self.parse_item()? {
7449 self.maybe_consume_incorrect_semicolon(&items);
7452 if !self.eat(term) {
7453 let token_str = self.this_token_descr();
7454 if !self.maybe_consume_incorrect_semicolon(&items) {
7455 let mut err = self.fatal(&format!("expected item, found {}", token_str));
7456 err.span_label(self.span, "expected item");
7461 let hi = if self.span.is_dummy() {
7468 inner: inner_lo.to(hi),
7474 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
7475 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
7476 self.expect(&token::Colon)?;
7477 let ty = self.parse_ty()?;
7478 self.expect(&token::Eq)?;
7479 let e = self.parse_expr()?;
7480 self.expect(&token::Semi)?;
7481 let item = match m {
7482 Some(m) => ItemKind::Static(ty, m, e),
7483 None => ItemKind::Const(ty, e),
7485 Ok((id, item, None))
7488 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
7489 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
7490 let (in_cfg, outer_attrs) = {
7491 let mut strip_unconfigured = crate::config::StripUnconfigured {
7493 features: None, // don't perform gated feature checking
7495 let mut outer_attrs = outer_attrs.to_owned();
7496 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
7497 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
7500 let id_span = self.span;
7501 let id = self.parse_ident()?;
7502 if self.eat(&token::Semi) {
7503 if in_cfg && self.recurse_into_file_modules {
7504 // This mod is in an external file. Let's go get it!
7505 let ModulePathSuccess { path, directory_ownership, warn } =
7506 self.submod_path(id, &outer_attrs, id_span)?;
7507 let (module, mut attrs) =
7508 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
7509 // Record that we fetched the mod from an external file
7511 let attr = Attribute {
7512 id: attr::mk_attr_id(),
7513 style: ast::AttrStyle::Outer,
7514 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
7515 tokens: TokenStream::empty(),
7516 is_sugared_doc: false,
7517 span: syntax_pos::DUMMY_SP,
7519 attr::mark_known(&attr);
7522 Ok((id, ItemKind::Mod(module), Some(attrs)))
7524 let placeholder = ast::Mod {
7525 inner: syntax_pos::DUMMY_SP,
7529 Ok((id, ItemKind::Mod(placeholder), None))
7532 let old_directory = self.directory.clone();
7533 self.push_directory(id, &outer_attrs);
7535 self.expect(&token::OpenDelim(token::Brace))?;
7536 let mod_inner_lo = self.span;
7537 let attrs = self.parse_inner_attributes()?;
7538 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
7540 self.directory = old_directory;
7541 Ok((id, ItemKind::Mod(module), Some(attrs)))
7545 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
7546 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
7547 self.directory.path.to_mut().push(&path.as_str());
7548 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
7550 // We have to push on the current module name in the case of relative
7551 // paths in order to ensure that any additional module paths from inline
7552 // `mod x { ... }` come after the relative extension.
7554 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
7555 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
7556 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
7557 if let Some(ident) = relative.take() { // remove the relative offset
7558 self.directory.path.to_mut().push(ident.as_str());
7561 self.directory.path.to_mut().push(&id.as_str());
7565 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
7566 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
7569 // On windows, the base path might have the form
7570 // `\\?\foo\bar` in which case it does not tolerate
7571 // mixed `/` and `\` separators, so canonicalize
7574 let s = s.replace("/", "\\");
7575 Some(dir_path.join(s))
7581 /// Returns a path to a module.
7582 pub fn default_submod_path(
7584 relative: Option<ast::Ident>,
7586 source_map: &SourceMap) -> ModulePath
7588 // If we're in a foo.rs file instead of a mod.rs file,
7589 // we need to look for submodules in
7590 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
7591 // `./<id>.rs` and `./<id>/mod.rs`.
7592 let relative_prefix_string;
7593 let relative_prefix = if let Some(ident) = relative {
7594 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
7595 &relative_prefix_string
7600 let mod_name = id.to_string();
7601 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
7602 let secondary_path_str = format!("{}{}{}mod.rs",
7603 relative_prefix, mod_name, path::MAIN_SEPARATOR);
7604 let default_path = dir_path.join(&default_path_str);
7605 let secondary_path = dir_path.join(&secondary_path_str);
7606 let default_exists = source_map.file_exists(&default_path);
7607 let secondary_exists = source_map.file_exists(&secondary_path);
7609 let result = match (default_exists, secondary_exists) {
7610 (true, false) => Ok(ModulePathSuccess {
7612 directory_ownership: DirectoryOwnership::Owned {
7617 (false, true) => Ok(ModulePathSuccess {
7618 path: secondary_path,
7619 directory_ownership: DirectoryOwnership::Owned {
7624 (false, false) => Err(Error::FileNotFoundForModule {
7625 mod_name: mod_name.clone(),
7626 default_path: default_path_str,
7627 secondary_path: secondary_path_str,
7628 dir_path: dir_path.display().to_string(),
7630 (true, true) => Err(Error::DuplicatePaths {
7631 mod_name: mod_name.clone(),
7632 default_path: default_path_str,
7633 secondary_path: secondary_path_str,
7639 path_exists: default_exists || secondary_exists,
7644 fn submod_path(&mut self,
7646 outer_attrs: &[Attribute],
7648 -> PResult<'a, ModulePathSuccess> {
7649 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
7650 return Ok(ModulePathSuccess {
7651 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
7652 // All `#[path]` files are treated as though they are a `mod.rs` file.
7653 // This means that `mod foo;` declarations inside `#[path]`-included
7654 // files are siblings,
7656 // Note that this will produce weirdness when a file named `foo.rs` is
7657 // `#[path]` included and contains a `mod foo;` declaration.
7658 // If you encounter this, it's your own darn fault :P
7659 Some(_) => DirectoryOwnership::Owned { relative: None },
7660 _ => DirectoryOwnership::UnownedViaMod(true),
7667 let relative = match self.directory.ownership {
7668 DirectoryOwnership::Owned { relative } => relative,
7669 DirectoryOwnership::UnownedViaBlock |
7670 DirectoryOwnership::UnownedViaMod(_) => None,
7672 let paths = Parser::default_submod_path(
7673 id, relative, &self.directory.path, self.sess.source_map());
7675 match self.directory.ownership {
7676 DirectoryOwnership::Owned { .. } => {
7677 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
7679 DirectoryOwnership::UnownedViaBlock => {
7681 "Cannot declare a non-inline module inside a block \
7682 unless it has a path attribute";
7683 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
7684 if paths.path_exists {
7685 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
7687 err.span_note(id_sp, &msg);
7691 DirectoryOwnership::UnownedViaMod(warn) => {
7693 if let Ok(result) = paths.result {
7694 return Ok(ModulePathSuccess { warn: true, ..result });
7697 let mut err = self.diagnostic().struct_span_err(id_sp,
7698 "cannot declare a new module at this location");
7699 if !id_sp.is_dummy() {
7700 let src_path = self.sess.source_map().span_to_filename(id_sp);
7701 if let FileName::Real(src_path) = src_path {
7702 if let Some(stem) = src_path.file_stem() {
7703 let mut dest_path = src_path.clone();
7704 dest_path.set_file_name(stem);
7705 dest_path.push("mod.rs");
7706 err.span_note(id_sp,
7707 &format!("maybe move this module `{}` to its own \
7708 directory via `{}`", src_path.display(),
7709 dest_path.display()));
7713 if paths.path_exists {
7714 err.span_note(id_sp,
7715 &format!("... or maybe `use` the module `{}` instead \
7716 of possibly redeclaring it",
7724 /// Reads a module from a source file.
7725 fn eval_src_mod(&mut self,
7727 directory_ownership: DirectoryOwnership,
7730 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
7731 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
7732 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
7733 let mut err = String::from("circular modules: ");
7734 let len = included_mod_stack.len();
7735 for p in &included_mod_stack[i.. len] {
7736 err.push_str(&p.to_string_lossy());
7737 err.push_str(" -> ");
7739 err.push_str(&path.to_string_lossy());
7740 return Err(self.span_fatal(id_sp, &err[..]));
7742 included_mod_stack.push(path.clone());
7743 drop(included_mod_stack);
7746 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
7747 p0.cfg_mods = self.cfg_mods;
7748 let mod_inner_lo = p0.span;
7749 let mod_attrs = p0.parse_inner_attributes()?;
7750 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
7752 self.sess.included_mod_stack.borrow_mut().pop();
7756 /// Parses a function declaration from a foreign module.
7757 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7758 -> PResult<'a, ForeignItem> {
7759 self.expect_keyword(keywords::Fn)?;
7761 let (ident, mut generics) = self.parse_fn_header()?;
7762 let decl = self.parse_fn_decl(true)?;
7763 generics.where_clause = self.parse_where_clause()?;
7765 self.expect(&token::Semi)?;
7766 Ok(ast::ForeignItem {
7769 node: ForeignItemKind::Fn(decl, generics),
7770 id: ast::DUMMY_NODE_ID,
7776 /// Parses a static item from a foreign module.
7777 /// Assumes that the `static` keyword is already parsed.
7778 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7779 -> PResult<'a, ForeignItem> {
7780 let mutbl = self.parse_mutability();
7781 let ident = self.parse_ident()?;
7782 self.expect(&token::Colon)?;
7783 let ty = self.parse_ty()?;
7785 self.expect(&token::Semi)?;
7789 node: ForeignItemKind::Static(ty, mutbl),
7790 id: ast::DUMMY_NODE_ID,
7796 /// Parses a type from a foreign module.
7797 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7798 -> PResult<'a, ForeignItem> {
7799 self.expect_keyword(keywords::Type)?;
7801 let ident = self.parse_ident()?;
7803 self.expect(&token::Semi)?;
7804 Ok(ast::ForeignItem {
7807 node: ForeignItemKind::Ty,
7808 id: ast::DUMMY_NODE_ID,
7814 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
7815 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
7816 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
7818 let mut ident = if self.token.is_keyword(keywords::SelfLower) {
7819 self.parse_path_segment_ident()
7823 let mut idents = vec![];
7824 let mut replacement = vec![];
7825 let mut fixed_crate_name = false;
7826 // Accept `extern crate name-like-this` for better diagnostics
7827 let dash = token::Token::BinOp(token::BinOpToken::Minus);
7828 if self.token == dash { // Do not include `-` as part of the expected tokens list
7829 while self.eat(&dash) {
7830 fixed_crate_name = true;
7831 replacement.push((self.prev_span, "_".to_string()));
7832 idents.push(self.parse_ident()?);
7835 if fixed_crate_name {
7836 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
7837 let mut fixed_name = format!("{}", ident.name);
7838 for part in idents {
7839 fixed_name.push_str(&format!("_{}", part.name));
7841 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
7843 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
7844 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
7845 err.multipart_suggestion(
7848 Applicability::MachineApplicable,
7855 /// Parses `extern crate` links.
7860 /// extern crate foo;
7861 /// extern crate bar as foo;
7863 fn parse_item_extern_crate(&mut self,
7865 visibility: Visibility,
7866 attrs: Vec<Attribute>)
7867 -> PResult<'a, P<Item>> {
7868 // Accept `extern crate name-like-this` for better diagnostics
7869 let orig_name = self.parse_crate_name_with_dashes()?;
7870 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
7871 (rename, Some(orig_name.name))
7875 self.expect(&token::Semi)?;
7877 let span = lo.to(self.prev_span);
7878 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
7881 /// Parses `extern` for foreign ABIs modules.
7883 /// `extern` is expected to have been
7884 /// consumed before calling this method.
7888 /// ```ignore (only-for-syntax-highlight)
7892 fn parse_item_foreign_mod(&mut self,
7894 opt_abi: Option<Abi>,
7895 visibility: Visibility,
7896 mut attrs: Vec<Attribute>)
7897 -> PResult<'a, P<Item>> {
7898 self.expect(&token::OpenDelim(token::Brace))?;
7900 let abi = opt_abi.unwrap_or(Abi::C);
7902 attrs.extend(self.parse_inner_attributes()?);
7904 let mut foreign_items = vec![];
7905 while !self.eat(&token::CloseDelim(token::Brace)) {
7906 foreign_items.push(self.parse_foreign_item()?);
7909 let prev_span = self.prev_span;
7910 let m = ast::ForeignMod {
7912 items: foreign_items
7914 let invalid = keywords::Invalid.ident();
7915 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
7918 /// Parses `type Foo = Bar;`
7920 /// `existential type Foo: Bar;`
7923 /// without modifying the parser state.
7924 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
7925 // This parses the grammar:
7926 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
7927 if self.check_keyword(keywords::Type) ||
7928 self.check_keyword(keywords::Existential) &&
7929 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
7930 let existential = self.eat_keyword(keywords::Existential);
7931 assert!(self.eat_keyword(keywords::Type));
7932 Some(self.parse_existential_or_alias(existential))
7938 /// Parses a type alias or existential type.
7939 fn parse_existential_or_alias(
7942 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
7943 let ident = self.parse_ident()?;
7944 let mut tps = self.parse_generics()?;
7945 tps.where_clause = self.parse_where_clause()?;
7946 let alias = if existential {
7947 self.expect(&token::Colon)?;
7948 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
7949 AliasKind::Existential(bounds)
7951 self.expect(&token::Eq)?;
7952 let ty = self.parse_ty()?;
7955 self.expect(&token::Semi)?;
7956 Ok((ident, alias, tps))
7959 /// Parses the part of an enum declaration following the `{`.
7960 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
7961 let mut variants = Vec::new();
7962 let mut all_nullary = true;
7963 let mut any_disr = vec![];
7964 while self.token != token::CloseDelim(token::Brace) {
7965 let variant_attrs = self.parse_outer_attributes()?;
7966 let vlo = self.span;
7969 let mut disr_expr = None;
7971 let ident = self.parse_ident()?;
7972 if self.check(&token::OpenDelim(token::Brace)) {
7973 // Parse a struct variant.
7974 all_nullary = false;
7975 let (fields, recovered) = self.parse_record_struct_body()?;
7976 struct_def = VariantData::Struct(fields, recovered);
7977 } else if self.check(&token::OpenDelim(token::Paren)) {
7978 all_nullary = false;
7979 struct_def = VariantData::Tuple(
7980 self.parse_tuple_struct_body()?,
7983 } else if self.eat(&token::Eq) {
7984 disr_expr = Some(AnonConst {
7985 id: ast::DUMMY_NODE_ID,
7986 value: self.parse_expr()?,
7988 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
7991 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7993 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7996 let vr = ast::Variant_ {
7998 id: ast::DUMMY_NODE_ID,
7999 attrs: variant_attrs,
8003 variants.push(respan(vlo.to(self.prev_span), vr));
8005 if !self.eat(&token::Comma) {
8006 if self.token.is_ident() && !self.token.is_reserved_ident() {
8007 let sp = self.sess.source_map().next_point(self.prev_span);
8008 let mut err = self.struct_span_err(sp, "missing comma");
8009 err.span_suggestion_short(
8013 Applicability::MaybeIncorrect,
8021 self.expect(&token::CloseDelim(token::Brace))?;
8022 if !any_disr.is_empty() && !all_nullary {
8023 let mut err = self.struct_span_err(
8025 "discriminator values can only be used with a field-less enum",
8027 for sp in any_disr {
8028 err.span_label(sp, "only valid in field-less enums");
8033 Ok(ast::EnumDef { variants })
8036 /// Parses an enum declaration.
8037 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
8038 let id = self.parse_ident()?;
8039 let mut generics = self.parse_generics()?;
8040 generics.where_clause = self.parse_where_clause()?;
8041 self.expect(&token::OpenDelim(token::Brace))?;
8043 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
8044 self.recover_stmt();
8045 self.eat(&token::CloseDelim(token::Brace));
8048 Ok((id, ItemKind::Enum(enum_definition, generics), None))
8051 /// Parses a string as an ABI spec on an extern type or module. Consumes
8052 /// the `extern` keyword, if one is found.
8053 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
8055 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
8057 self.expect_no_suffix(sp, "an ABI spec", suf);
8059 match abi::lookup(&s.as_str()) {
8060 Some(abi) => Ok(Some(abi)),
8062 let prev_span = self.prev_span;
8063 let mut err = struct_span_err!(
8064 self.sess.span_diagnostic,
8067 "invalid ABI: found `{}`",
8069 err.span_label(prev_span, "invalid ABI");
8070 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
8081 fn is_static_global(&mut self) -> bool {
8082 if self.check_keyword(keywords::Static) {
8083 // Check if this could be a closure
8084 !self.look_ahead(1, |token| {
8085 if token.is_keyword(keywords::Move) {
8089 token::BinOp(token::Or) | token::OrOr => true,
8100 attrs: Vec<Attribute>,
8101 macros_allowed: bool,
8102 attributes_allowed: bool,
8103 ) -> PResult<'a, Option<P<Item>>> {
8104 let mut unclosed_delims = vec![];
8105 let (ret, tokens) = self.collect_tokens(|this| {
8106 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
8107 unclosed_delims.append(&mut this.unclosed_delims);
8110 self.unclosed_delims.append(&mut unclosed_delims);
8112 // Once we've parsed an item and recorded the tokens we got while
8113 // parsing we may want to store `tokens` into the item we're about to
8114 // return. Note, though, that we specifically didn't capture tokens
8115 // related to outer attributes. The `tokens` field here may later be
8116 // used with procedural macros to convert this item back into a token
8117 // stream, but during expansion we may be removing attributes as we go
8120 // If we've got inner attributes then the `tokens` we've got above holds
8121 // these inner attributes. If an inner attribute is expanded we won't
8122 // actually remove it from the token stream, so we'll just keep yielding
8123 // it (bad!). To work around this case for now we just avoid recording
8124 // `tokens` if we detect any inner attributes. This should help keep
8125 // expansion correct, but we should fix this bug one day!
8128 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
8129 i.tokens = Some(tokens);
8136 /// Parses one of the items allowed by the flags.
8137 fn parse_item_implementation(
8139 attrs: Vec<Attribute>,
8140 macros_allowed: bool,
8141 attributes_allowed: bool,
8142 ) -> PResult<'a, Option<P<Item>>> {
8143 maybe_whole!(self, NtItem, |item| {
8144 let mut item = item.into_inner();
8145 let mut attrs = attrs;
8146 mem::swap(&mut item.attrs, &mut attrs);
8147 item.attrs.extend(attrs);
8153 let visibility = self.parse_visibility(false)?;
8155 if self.eat_keyword(keywords::Use) {
8157 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
8158 self.expect(&token::Semi)?;
8160 let span = lo.to(self.prev_span);
8161 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
8162 return Ok(Some(item));
8165 if self.eat_keyword(keywords::Extern) {
8166 if self.eat_keyword(keywords::Crate) {
8167 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
8170 let opt_abi = self.parse_opt_abi()?;
8172 if self.eat_keyword(keywords::Fn) {
8173 // EXTERN FUNCTION ITEM
8174 let fn_span = self.prev_span;
8175 let abi = opt_abi.unwrap_or(Abi::C);
8176 let (ident, item_, extra_attrs) =
8177 self.parse_item_fn(Unsafety::Normal,
8178 respan(fn_span, IsAsync::NotAsync),
8179 respan(fn_span, Constness::NotConst),
8181 let prev_span = self.prev_span;
8182 let item = self.mk_item(lo.to(prev_span),
8186 maybe_append(attrs, extra_attrs));
8187 return Ok(Some(item));
8188 } else if self.check(&token::OpenDelim(token::Brace)) {
8189 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
8195 if self.is_static_global() {
8198 let m = if self.eat_keyword(keywords::Mut) {
8201 Mutability::Immutable
8203 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
8204 let prev_span = self.prev_span;
8205 let item = self.mk_item(lo.to(prev_span),
8209 maybe_append(attrs, extra_attrs));
8210 return Ok(Some(item));
8212 if self.eat_keyword(keywords::Const) {
8213 let const_span = self.prev_span;
8214 if self.check_keyword(keywords::Fn)
8215 || (self.check_keyword(keywords::Unsafe)
8216 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
8217 // CONST FUNCTION ITEM
8218 let unsafety = self.parse_unsafety();
8220 let (ident, item_, extra_attrs) =
8221 self.parse_item_fn(unsafety,
8222 respan(const_span, IsAsync::NotAsync),
8223 respan(const_span, Constness::Const),
8225 let prev_span = self.prev_span;
8226 let item = self.mk_item(lo.to(prev_span),
8230 maybe_append(attrs, extra_attrs));
8231 return Ok(Some(item));
8235 if self.eat_keyword(keywords::Mut) {
8236 let prev_span = self.prev_span;
8237 let mut err = self.diagnostic()
8238 .struct_span_err(prev_span, "const globals cannot be mutable");
8239 err.span_label(prev_span, "cannot be mutable");
8240 err.span_suggestion(
8242 "you might want to declare a static instead",
8243 "static".to_owned(),
8244 Applicability::MaybeIncorrect,
8248 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
8249 let prev_span = self.prev_span;
8250 let item = self.mk_item(lo.to(prev_span),
8254 maybe_append(attrs, extra_attrs));
8255 return Ok(Some(item));
8258 // `unsafe async fn` or `async fn`
8260 self.check_keyword(keywords::Unsafe) &&
8261 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
8263 self.check_keyword(keywords::Async) &&
8264 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
8267 // ASYNC FUNCTION ITEM
8268 let unsafety = self.parse_unsafety();
8269 self.expect_keyword(keywords::Async)?;
8270 let async_span = self.prev_span;
8271 self.expect_keyword(keywords::Fn)?;
8272 let fn_span = self.prev_span;
8273 let (ident, item_, extra_attrs) =
8274 self.parse_item_fn(unsafety,
8275 respan(async_span, IsAsync::Async {
8276 closure_id: ast::DUMMY_NODE_ID,
8277 return_impl_trait_id: ast::DUMMY_NODE_ID,
8278 arguments: Vec::new(),
8280 respan(fn_span, Constness::NotConst),
8282 let prev_span = self.prev_span;
8283 let item = self.mk_item(lo.to(prev_span),
8287 maybe_append(attrs, extra_attrs));
8288 if self.span.rust_2015() {
8289 self.diagnostic().struct_span_err_with_code(
8291 "`async fn` is not permitted in the 2015 edition",
8292 DiagnosticId::Error("E0670".into())
8295 return Ok(Some(item));
8297 if self.check_keyword(keywords::Unsafe) &&
8298 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
8299 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
8301 // UNSAFE TRAIT ITEM
8302 self.bump(); // `unsafe`
8303 let is_auto = if self.eat_keyword(keywords::Trait) {
8306 self.expect_keyword(keywords::Auto)?;
8307 self.expect_keyword(keywords::Trait)?;
8310 let (ident, item_, extra_attrs) =
8311 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
8312 let prev_span = self.prev_span;
8313 let item = self.mk_item(lo.to(prev_span),
8317 maybe_append(attrs, extra_attrs));
8318 return Ok(Some(item));
8320 if self.check_keyword(keywords::Impl) ||
8321 self.check_keyword(keywords::Unsafe) &&
8322 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8323 self.check_keyword(keywords::Default) &&
8324 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8325 self.check_keyword(keywords::Default) &&
8326 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
8328 let defaultness = self.parse_defaultness();
8329 let unsafety = self.parse_unsafety();
8330 self.expect_keyword(keywords::Impl)?;
8331 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
8332 let span = lo.to(self.prev_span);
8333 return Ok(Some(self.mk_item(span, ident, item, visibility,
8334 maybe_append(attrs, extra_attrs))));
8336 if self.check_keyword(keywords::Fn) {
8339 let fn_span = self.prev_span;
8340 let (ident, item_, extra_attrs) =
8341 self.parse_item_fn(Unsafety::Normal,
8342 respan(fn_span, IsAsync::NotAsync),
8343 respan(fn_span, Constness::NotConst),
8345 let prev_span = self.prev_span;
8346 let item = self.mk_item(lo.to(prev_span),
8350 maybe_append(attrs, extra_attrs));
8351 return Ok(Some(item));
8353 if self.check_keyword(keywords::Unsafe)
8354 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
8355 // UNSAFE FUNCTION ITEM
8356 self.bump(); // `unsafe`
8357 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
8358 self.check(&token::OpenDelim(token::Brace));
8359 let abi = if self.eat_keyword(keywords::Extern) {
8360 self.parse_opt_abi()?.unwrap_or(Abi::C)
8364 self.expect_keyword(keywords::Fn)?;
8365 let fn_span = self.prev_span;
8366 let (ident, item_, extra_attrs) =
8367 self.parse_item_fn(Unsafety::Unsafe,
8368 respan(fn_span, IsAsync::NotAsync),
8369 respan(fn_span, Constness::NotConst),
8371 let prev_span = self.prev_span;
8372 let item = self.mk_item(lo.to(prev_span),
8376 maybe_append(attrs, extra_attrs));
8377 return Ok(Some(item));
8379 if self.eat_keyword(keywords::Mod) {
8381 let (ident, item_, extra_attrs) =
8382 self.parse_item_mod(&attrs[..])?;
8383 let prev_span = self.prev_span;
8384 let item = self.mk_item(lo.to(prev_span),
8388 maybe_append(attrs, extra_attrs));
8389 return Ok(Some(item));
8391 if let Some(type_) = self.eat_type() {
8392 let (ident, alias, generics) = type_?;
8394 let item_ = match alias {
8395 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
8396 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
8398 let prev_span = self.prev_span;
8399 let item = self.mk_item(lo.to(prev_span),
8404 return Ok(Some(item));
8406 if self.eat_keyword(keywords::Enum) {
8408 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
8409 let prev_span = self.prev_span;
8410 let item = self.mk_item(lo.to(prev_span),
8414 maybe_append(attrs, extra_attrs));
8415 return Ok(Some(item));
8417 if self.check_keyword(keywords::Trait)
8418 || (self.check_keyword(keywords::Auto)
8419 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
8421 let is_auto = if self.eat_keyword(keywords::Trait) {
8424 self.expect_keyword(keywords::Auto)?;
8425 self.expect_keyword(keywords::Trait)?;
8429 let (ident, item_, extra_attrs) =
8430 self.parse_item_trait(is_auto, Unsafety::Normal)?;
8431 let prev_span = self.prev_span;
8432 let item = self.mk_item(lo.to(prev_span),
8436 maybe_append(attrs, extra_attrs));
8437 return Ok(Some(item));
8439 if self.eat_keyword(keywords::Struct) {
8441 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
8442 let prev_span = self.prev_span;
8443 let item = self.mk_item(lo.to(prev_span),
8447 maybe_append(attrs, extra_attrs));
8448 return Ok(Some(item));
8450 if self.is_union_item() {
8453 let (ident, item_, extra_attrs) = self.parse_item_union()?;
8454 let prev_span = self.prev_span;
8455 let item = self.mk_item(lo.to(prev_span),
8459 maybe_append(attrs, extra_attrs));
8460 return Ok(Some(item));
8462 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
8463 return Ok(Some(macro_def));
8466 // Verify whether we have encountered a struct or method definition where the user forgot to
8467 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
8468 if visibility.node.is_pub() &&
8469 self.check_ident() &&
8470 self.look_ahead(1, |t| *t != token::Not)
8472 // Space between `pub` keyword and the identifier
8475 // ^^^ `sp` points here
8476 let sp = self.prev_span.between(self.span);
8477 let full_sp = self.prev_span.to(self.span);
8478 let ident_sp = self.span;
8479 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
8480 // possible public struct definition where `struct` was forgotten
8481 let ident = self.parse_ident().unwrap();
8482 let msg = format!("add `struct` here to parse `{}` as a public struct",
8484 let mut err = self.diagnostic()
8485 .struct_span_err(sp, "missing `struct` for struct definition");
8486 err.span_suggestion_short(
8487 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
8490 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
8491 let ident = self.parse_ident().unwrap();
8493 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
8498 self.consume_block(token::Paren);
8499 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
8500 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
8502 ("fn", kw_name, false)
8503 } else if self.check(&token::OpenDelim(token::Brace)) {
8505 ("fn", kw_name, false)
8506 } else if self.check(&token::Colon) {
8510 ("fn` or `struct", "function or struct", true)
8513 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8514 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8516 self.consume_block(token::Brace);
8517 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
8521 err.span_suggestion_short(
8522 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
8525 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
8526 err.span_suggestion(
8528 "if you meant to call a macro, try",
8529 format!("{}!", snippet),
8530 // this is the `ambiguous` conditional branch
8531 Applicability::MaybeIncorrect
8534 err.help("if you meant to call a macro, remove the `pub` \
8535 and add a trailing `!` after the identifier");
8539 } else if self.look_ahead(1, |t| *t == token::Lt) {
8540 let ident = self.parse_ident().unwrap();
8541 self.eat_to_tokens(&[&token::Gt]);
8543 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
8544 if let Ok(Some(_)) = self.parse_self_arg() {
8545 ("fn", "method", false)
8547 ("fn", "function", false)
8549 } else if self.check(&token::OpenDelim(token::Brace)) {
8550 ("struct", "struct", false)
8552 ("fn` or `struct", "function or struct", true)
8554 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8555 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8557 err.span_suggestion_short(
8559 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
8560 format!(" {} ", kw),
8561 Applicability::MachineApplicable,
8567 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
8570 /// Parses a foreign item.
8571 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
8572 maybe_whole!(self, NtForeignItem, |ni| ni);
8574 let attrs = self.parse_outer_attributes()?;
8576 let visibility = self.parse_visibility(false)?;
8578 // FOREIGN STATIC ITEM
8579 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
8580 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
8581 if self.token.is_keyword(keywords::Const) {
8583 .struct_span_err(self.span, "extern items cannot be `const`")
8586 "try using a static value",
8587 "static".to_owned(),
8588 Applicability::MachineApplicable
8591 self.bump(); // `static` or `const`
8592 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
8594 // FOREIGN FUNCTION ITEM
8595 if self.check_keyword(keywords::Fn) {
8596 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
8598 // FOREIGN TYPE ITEM
8599 if self.check_keyword(keywords::Type) {
8600 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
8603 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
8607 ident: keywords::Invalid.ident(),
8608 span: lo.to(self.prev_span),
8609 id: ast::DUMMY_NODE_ID,
8612 node: ForeignItemKind::Macro(mac),
8617 if !attrs.is_empty() {
8618 self.expected_item_err(&attrs)?;
8626 /// This is the fall-through for parsing items.
8627 fn parse_macro_use_or_failure(
8629 attrs: Vec<Attribute> ,
8630 macros_allowed: bool,
8631 attributes_allowed: bool,
8633 visibility: Visibility
8634 ) -> PResult<'a, Option<P<Item>>> {
8635 if macros_allowed && self.token.is_path_start() &&
8636 !(self.is_async_fn() && self.span.rust_2015()) {
8637 // MACRO INVOCATION ITEM
8639 let prev_span = self.prev_span;
8640 self.complain_if_pub_macro(&visibility.node, prev_span);
8642 let mac_lo = self.span;
8645 let pth = self.parse_path(PathStyle::Mod)?;
8646 self.expect(&token::Not)?;
8648 // a 'special' identifier (like what `macro_rules!` uses)
8649 // is optional. We should eventually unify invoc syntax
8651 let id = if self.token.is_ident() {
8654 keywords::Invalid.ident() // no special identifier
8656 // eat a matched-delimiter token tree:
8657 let (delim, tts) = self.expect_delimited_token_tree()?;
8658 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
8659 self.report_invalid_macro_expansion_item();
8662 let hi = self.prev_span;
8663 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
8664 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
8665 return Ok(Some(item));
8668 // FAILURE TO PARSE ITEM
8669 match visibility.node {
8670 VisibilityKind::Inherited => {}
8672 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
8676 if !attributes_allowed && !attrs.is_empty() {
8677 self.expected_item_err(&attrs)?;
8682 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
8683 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
8684 at_end: &mut bool) -> PResult<'a, Option<Mac>>
8686 if self.token.is_path_start() &&
8687 !(self.is_async_fn() && self.span.rust_2015()) {
8688 let prev_span = self.prev_span;
8690 let pth = self.parse_path(PathStyle::Mod)?;
8692 if pth.segments.len() == 1 {
8693 if !self.eat(&token::Not) {
8694 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
8697 self.expect(&token::Not)?;
8700 if let Some(vis) = vis {
8701 self.complain_if_pub_macro(&vis.node, prev_span);
8706 // eat a matched-delimiter token tree:
8707 let (delim, tts) = self.expect_delimited_token_tree()?;
8708 if delim != MacDelimiter::Brace {
8709 self.expect(&token::Semi)?;
8712 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
8718 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
8719 where F: FnOnce(&mut Self) -> PResult<'a, R>
8721 // Record all tokens we parse when parsing this item.
8722 let mut tokens = Vec::new();
8723 let prev_collecting = match self.token_cursor.frame.last_token {
8724 LastToken::Collecting(ref mut list) => {
8725 Some(mem::replace(list, Vec::new()))
8727 LastToken::Was(ref mut last) => {
8728 tokens.extend(last.take());
8732 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
8733 let prev = self.token_cursor.stack.len();
8735 let last_token = if self.token_cursor.stack.len() == prev {
8736 &mut self.token_cursor.frame.last_token
8738 &mut self.token_cursor.stack[prev].last_token
8741 // Pull out the tokens that we've collected from the call to `f` above.
8742 let mut collected_tokens = match *last_token {
8743 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
8744 LastToken::Was(_) => panic!("our vector went away?"),
8747 // If we're not at EOF our current token wasn't actually consumed by
8748 // `f`, but it'll still be in our list that we pulled out. In that case
8750 let extra_token = if self.token != token::Eof {
8751 collected_tokens.pop()
8756 // If we were previously collecting tokens, then this was a recursive
8757 // call. In that case we need to record all the tokens we collected in
8758 // our parent list as well. To do that we push a clone of our stream
8759 // onto the previous list.
8760 match prev_collecting {
8762 list.extend(collected_tokens.iter().cloned());
8763 list.extend(extra_token);
8764 *last_token = LastToken::Collecting(list);
8767 *last_token = LastToken::Was(extra_token);
8771 Ok((ret?, TokenStream::new(collected_tokens)))
8774 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
8775 let attrs = self.parse_outer_attributes()?;
8776 self.parse_item_(attrs, true, false)
8780 fn is_import_coupler(&mut self) -> bool {
8781 self.check(&token::ModSep) &&
8782 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
8783 *t == token::BinOp(token::Star))
8786 /// Parses a `UseTree`.
8789 /// USE_TREE = [`::`] `*` |
8790 /// [`::`] `{` USE_TREE_LIST `}` |
8792 /// PATH `::` `{` USE_TREE_LIST `}` |
8793 /// PATH [`as` IDENT]
8795 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
8798 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
8799 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
8800 self.check(&token::BinOp(token::Star)) ||
8801 self.is_import_coupler() {
8802 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
8803 let mod_sep_ctxt = self.span.ctxt();
8804 if self.eat(&token::ModSep) {
8805 prefix.segments.push(
8806 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
8810 if self.eat(&token::BinOp(token::Star)) {
8813 UseTreeKind::Nested(self.parse_use_tree_list()?)
8816 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
8817 prefix = self.parse_path(PathStyle::Mod)?;
8819 if self.eat(&token::ModSep) {
8820 if self.eat(&token::BinOp(token::Star)) {
8823 UseTreeKind::Nested(self.parse_use_tree_list()?)
8826 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
8830 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
8833 /// Parses a `UseTreeKind::Nested(list)`.
8836 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
8838 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
8839 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
8840 &token::CloseDelim(token::Brace),
8841 SeqSep::trailing_allowed(token::Comma), |this| {
8842 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
8846 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
8847 if self.eat_keyword(keywords::As) {
8848 self.parse_ident_or_underscore().map(Some)
8854 /// Parses a source module as a crate. This is the main entry point for the parser.
8855 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
8857 let krate = Ok(ast::Crate {
8858 attrs: self.parse_inner_attributes()?,
8859 module: self.parse_mod_items(&token::Eof, lo)?,
8860 span: lo.to(self.span),
8865 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
8866 let ret = match self.token {
8867 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
8868 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
8875 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
8876 match self.parse_optional_str() {
8877 Some((s, style, suf)) => {
8878 let sp = self.prev_span;
8879 self.expect_no_suffix(sp, "a string literal", suf);
8883 let msg = "expected string literal";
8884 let mut err = self.fatal(msg);
8885 err.span_label(self.span, msg);
8891 fn report_invalid_macro_expansion_item(&self) {
8892 self.struct_span_err(
8894 "macros that expand to items must be delimited with braces or followed by a semicolon",
8895 ).multipart_suggestion(
8896 "change the delimiters to curly braces",
8898 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
8899 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
8901 Applicability::MaybeIncorrect,
8903 self.sess.source_map.next_point(self.prev_span),
8906 Applicability::MaybeIncorrect,
8910 /// Recover from `pub` keyword in places where it seems _reasonable_ but isn't valid.
8911 fn eat_bad_pub(&mut self) {
8912 if self.token.is_keyword(keywords::Pub) {
8913 match self.parse_visibility(false) {
8915 let mut err = self.diagnostic()
8916 .struct_span_err(vis.span, "unnecessary visibility qualifier");
8917 err.span_label(vis.span, "`pub` not permitted here");
8920 Err(mut err) => err.emit(),
8925 /// When lowering a `async fn` to the HIR, we need to move all of the arguments of the function
8926 /// into the generated closure so that they are dropped when the future is polled and not when
8929 /// The arguments of the function are replaced in HIR lowering with the arguments created by
8930 /// this function and the statements created here are inserted at the top of the closure body.
8931 fn construct_async_arguments(&mut self, asyncness: &mut Spanned<IsAsync>, decl: &FnDecl) {
8932 if let IsAsync::Async { ref mut arguments, .. } = asyncness.node {
8933 for (index, input) in decl.inputs.iter().enumerate() {
8934 let id = ast::DUMMY_NODE_ID;
8935 let span = input.pat.span;
8937 // Construct a name for our temporary argument.
8938 let name = format!("__arg{}", index);
8939 let ident = Ident::from_str(&name);
8941 // Construct an argument representing `__argN: <ty>` to replace the argument of the
8944 ty: input.ty.clone(),
8948 node: PatKind::Ident(
8949 BindingMode::ByValue(Mutability::Immutable), ident, None,
8953 source: ArgSource::AsyncFn(input.pat.clone()),
8956 // Construct a `let <pat> = __argN;` statement to insert at the top of the
8958 let local = P(Local {
8959 pat: input.pat.clone(),
8960 // We explicitly do not specify the type for this statement. When the user's
8961 // argument type is `impl Trait` then this would require the
8962 // `impl_trait_in_bindings` feature to also be present for that same type to
8963 // be valid in this binding. At the time of writing (13 Mar 19),
8964 // `impl_trait_in_bindings` is not stable.
8968 node: ExprKind::Path(None, ast::Path {
8970 segments: vec![PathSegment { ident, id, args: None }],
8973 attrs: ThinVec::new(),
8977 attrs: ThinVec::new(),
8978 source: LocalSource::AsyncFn,
8980 let stmt = Stmt { id, node: StmtKind::Local(local), span, };
8982 arguments.push(AsyncArgument { ident, arg, stmt });
8988 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
8989 for unmatched in unclosed_delims.iter() {
8990 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
8991 "incorrect close delimiter: `{}`",
8992 pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
8994 err.span_label(unmatched.found_span, "incorrect close delimiter");
8995 if let Some(sp) = unmatched.candidate_span {
8996 err.span_label(sp, "close delimiter possibly meant for this");
8998 if let Some(sp) = unmatched.unclosed_span {
8999 err.span_label(sp, "un-closed delimiter");
9003 unclosed_delims.clear();