1 use rustc_target::spec::abi::{self, Abi};
2 use ast::{AngleBracketedArgs, ParenthesizedArgs, AttrStyle, BareFnTy};
3 use ast::{GenericBound, TraitBoundModifier};
5 use ast::{Mod, AnonConst, Arg, Arm, Guard, Attribute, BindingMode, TraitItemKind};
7 use ast::{BlockCheckMode, CaptureBy, Movability};
8 use ast::{Constness, Crate};
11 use ast::{Expr, ExprKind, RangeLimits};
12 use ast::{Field, FnDecl, FnHeader};
13 use ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
14 use ast::{GenericParam, GenericParamKind};
16 use ast::{Ident, ImplItem, IsAsync, IsAuto, Item, ItemKind};
17 use ast::{Label, Lifetime, Lit, LitKind};
19 use ast::MacStmtStyle;
20 use ast::{Mac, Mac_, MacDelimiter};
21 use ast::{MutTy, Mutability};
22 use ast::{Pat, PatKind, PathSegment};
23 use ast::{PolyTraitRef, QSelf};
24 use ast::{Stmt, StmtKind};
25 use ast::{VariantData, StructField};
28 use ast::{TraitItem, TraitRef, TraitObjectSyntax};
29 use ast::{Ty, TyKind, TypeBinding, GenericBounds};
30 use ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
31 use ast::{UseTree, UseTreeKind};
32 use ast::{BinOpKind, UnOp};
33 use ast::{RangeEnd, RangeSyntax};
35 use ext::base::DummyResult;
36 use source_map::{self, SourceMap, Spanned, respan};
37 use syntax_pos::{self, Span, MultiSpan, BytePos, FileName};
38 use errors::{self, Applicability, DiagnosticBuilder, DiagnosticId};
39 use parse::{self, SeqSep, classify, token};
40 use parse::lexer::TokenAndSpan;
41 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
42 use parse::token::DelimToken;
43 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
44 use util::parser::{AssocOp, Fixity};
49 use tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
50 use symbol::{Symbol, keywords};
55 use std::path::{self, Path, PathBuf};
59 /// Whether the type alias or associated type is a concrete type or an existential type
61 /// Just a new name for the same type
63 /// Only trait impls of the type will be usable, not the actual type itself
64 Existential(GenericBounds),
68 struct Restrictions: u8 {
69 const STMT_EXPR = 1 << 0;
70 const NO_STRUCT_LITERAL = 1 << 1;
74 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
76 /// How to parse a path.
77 #[derive(Copy, Clone, PartialEq)]
79 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
80 /// with something else. For example, in expressions `segment < ....` can be interpreted
81 /// as a comparison and `segment ( ....` can be interpreted as a function call.
82 /// In all such contexts the non-path interpretation is preferred by default for practical
83 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
84 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
86 /// In other contexts, notably in types, no ambiguity exists and paths can be written
87 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
88 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
90 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
91 /// visibilities or attributes.
92 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
93 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
94 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
95 /// tokens when something goes wrong.
99 #[derive(Clone, Copy, PartialEq, Debug)]
106 #[derive(Clone, Copy, PartialEq, Debug)]
112 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
113 /// dropped into the token stream, which happens while parsing the result of
114 /// macro expansion). Placement of these is not as complex as I feared it would
115 /// be. The important thing is to make sure that lookahead doesn't balk at
116 /// `token::Interpolated` tokens.
117 macro_rules! maybe_whole_expr {
119 if let token::Interpolated(nt) = $p.token.clone() {
121 token::NtExpr(ref e) | token::NtLiteral(ref e) => {
123 return Ok((*e).clone());
125 token::NtPath(ref path) => {
128 let kind = ExprKind::Path(None, (*path).clone());
129 return Ok($p.mk_expr(span, kind, ThinVec::new()));
131 token::NtBlock(ref block) => {
134 let kind = ExprKind::Block((*block).clone(), None);
135 return Ok($p.mk_expr(span, kind, ThinVec::new()));
143 /// As maybe_whole_expr, but for things other than expressions
144 macro_rules! maybe_whole {
145 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
146 if let token::Interpolated(nt) = $p.token.clone() {
147 if let token::$constructor($x) = nt.0.clone() {
155 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
156 if let Some(ref mut rhs) = rhs {
162 #[derive(Debug, Clone, Copy, PartialEq)]
173 trait RecoverQPath: Sized {
174 const PATH_STYLE: PathStyle = PathStyle::Expr;
175 fn to_ty(&self) -> Option<P<Ty>>;
176 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self;
177 fn to_string(&self) -> String;
180 impl RecoverQPath for Ty {
181 const PATH_STYLE: PathStyle = PathStyle::Type;
182 fn to_ty(&self) -> Option<P<Ty>> {
183 Some(P(self.clone()))
185 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
186 Self { span: path.span, node: TyKind::Path(qself, path), id: self.id }
188 fn to_string(&self) -> String {
189 pprust::ty_to_string(self)
193 impl RecoverQPath for Pat {
194 fn to_ty(&self) -> Option<P<Ty>> {
197 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
198 Self { span: path.span, node: PatKind::Path(qself, path), id: self.id }
200 fn to_string(&self) -> String {
201 pprust::pat_to_string(self)
205 impl RecoverQPath for Expr {
206 fn to_ty(&self) -> Option<P<Ty>> {
209 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
210 Self { span: path.span, node: ExprKind::Path(qself, path),
211 id: self.id, attrs: self.attrs.clone() }
213 fn to_string(&self) -> String {
214 pprust::expr_to_string(self)
218 /* ident is handled by common.rs */
221 pub struct Parser<'a> {
222 pub sess: &'a ParseSess,
223 /// the current token:
224 pub token: token::Token,
225 /// the span of the current token:
227 /// the span of the previous token:
228 meta_var_span: Option<Span>,
230 /// the previous token kind
231 prev_token_kind: PrevTokenKind,
232 restrictions: Restrictions,
233 /// Used to determine the path to externally loaded source files
234 crate directory: Directory<'a>,
235 /// Whether to parse sub-modules in other files.
236 pub recurse_into_file_modules: bool,
237 /// Name of the root module this parser originated from. If `None`, then the
238 /// name is not known. This does not change while the parser is descending
239 /// into modules, and sub-parsers have new values for this name.
240 pub root_module_name: Option<String>,
241 crate expected_tokens: Vec<TokenType>,
242 token_cursor: TokenCursor,
243 desugar_doc_comments: bool,
244 /// Whether we should configure out of line modules as we parse.
246 /// This field is used to keep track of how many left angle brackets we have seen. This is
247 /// required in order to detect extra leading left angle brackets (`<` characters) and error
250 /// See the comments in the `parse_path_segment` function for more details.
251 crate unmatched_angle_bracket_count: u32,
257 frame: TokenCursorFrame,
258 stack: Vec<TokenCursorFrame>,
262 struct TokenCursorFrame {
263 delim: token::DelimToken,
266 tree_cursor: tokenstream::Cursor,
268 last_token: LastToken,
271 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
272 /// by the parser, and then that's transitively used to record the tokens that
273 /// each parse AST item is created with.
275 /// Right now this has two states, either collecting tokens or not collecting
276 /// tokens. If we're collecting tokens we just save everything off into a local
277 /// `Vec`. This should eventually though likely save tokens from the original
278 /// token stream and just use slicing of token streams to avoid creation of a
279 /// whole new vector.
281 /// The second state is where we're passively not recording tokens, but the last
282 /// token is still tracked for when we want to start recording tokens. This
283 /// "last token" means that when we start recording tokens we'll want to ensure
284 /// that this, the first token, is included in the output.
286 /// You can find some more example usage of this in the `collect_tokens` method
290 Collecting(Vec<TreeAndJoint>),
291 Was(Option<TreeAndJoint>),
294 impl TokenCursorFrame {
295 fn new(sp: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
299 open_delim: delim == token::NoDelim,
300 tree_cursor: tts.clone().into_trees(),
301 close_delim: delim == token::NoDelim,
302 last_token: LastToken::Was(None),
308 fn next(&mut self) -> TokenAndSpan {
310 let tree = if !self.frame.open_delim {
311 self.frame.open_delim = true;
312 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
313 } else if let Some(tree) = self.frame.tree_cursor.next() {
315 } else if !self.frame.close_delim {
316 self.frame.close_delim = true;
317 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
318 } else if let Some(frame) = self.stack.pop() {
322 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
325 match self.frame.last_token {
326 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
327 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
331 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
332 TokenTree::Delimited(sp, delim, tts) => {
333 let frame = TokenCursorFrame::new(sp, delim, &tts);
334 self.stack.push(mem::replace(&mut self.frame, frame));
340 fn next_desugared(&mut self) -> TokenAndSpan {
341 let (sp, name) = match self.next() {
342 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
346 let stripped = strip_doc_comment_decoration(&name.as_str());
348 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
349 // required to wrap the text.
350 let mut num_of_hashes = 0;
352 for ch in stripped.chars() {
355 '#' if count > 0 => count + 1,
358 num_of_hashes = cmp::max(num_of_hashes, count);
361 let delim_span = DelimSpan::from_single(sp);
362 let body = TokenTree::Delimited(
365 [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
366 TokenTree::Token(sp, token::Eq),
367 TokenTree::Token(sp, token::Literal(
368 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))
370 .iter().cloned().collect::<TokenStream>().into(),
373 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
376 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
377 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
378 .iter().cloned().collect::<TokenStream>().into()
380 [TokenTree::Token(sp, token::Pound), body]
381 .iter().cloned().collect::<TokenStream>().into()
389 #[derive(Clone, PartialEq)]
390 crate enum TokenType {
392 Keyword(keywords::Keyword),
401 fn to_string(&self) -> String {
403 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
404 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
405 TokenType::Operator => "an operator".to_string(),
406 TokenType::Lifetime => "lifetime".to_string(),
407 TokenType::Ident => "identifier".to_string(),
408 TokenType::Path => "path".to_string(),
409 TokenType::Type => "type".to_string(),
414 /// Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
415 /// `IDENT<<u8 as Trait>::AssocTy>`.
417 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
418 /// that IDENT is not the ident of a fn trait
419 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
420 t == &token::ModSep || t == &token::Lt ||
421 t == &token::BinOp(token::Shl)
424 /// Information about the path to a module.
425 pub struct ModulePath {
428 pub result: Result<ModulePathSuccess, Error>,
431 pub struct ModulePathSuccess {
433 pub directory_ownership: DirectoryOwnership,
438 FileNotFoundForModule {
440 default_path: String,
441 secondary_path: String,
446 default_path: String,
447 secondary_path: String,
450 InclusiveRangeWithNoEnd,
454 fn span_err<S: Into<MultiSpan>>(self,
456 handler: &errors::Handler) -> DiagnosticBuilder {
458 Error::FileNotFoundForModule { ref mod_name,
462 let mut err = struct_span_err!(handler, sp, E0583,
463 "file not found for module `{}`", mod_name);
464 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
470 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
471 let mut err = struct_span_err!(handler, sp, E0584,
472 "file for module `{}` found at both {} and {}",
476 err.help("delete or rename one of them to remove the ambiguity");
479 Error::UselessDocComment => {
480 let mut err = struct_span_err!(handler, sp, E0585,
481 "found a documentation comment that doesn't document anything");
482 err.help("doc comments must come before what they document, maybe a comment was \
483 intended with `//`?");
486 Error::InclusiveRangeWithNoEnd => {
487 let mut err = struct_span_err!(handler, sp, E0586,
488 "inclusive range with no end");
489 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
499 AttributesParsed(ThinVec<Attribute>),
500 AlreadyParsed(P<Expr>),
503 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
504 fn from(o: Option<ThinVec<Attribute>>) -> Self {
505 if let Some(attrs) = o {
506 LhsExpr::AttributesParsed(attrs)
508 LhsExpr::NotYetParsed
513 impl From<P<Expr>> for LhsExpr {
514 fn from(expr: P<Expr>) -> Self {
515 LhsExpr::AlreadyParsed(expr)
519 /// Create a placeholder argument.
520 fn dummy_arg(span: Span) -> Arg {
521 let ident = Ident::new(keywords::Invalid.name(), span);
523 id: ast::DUMMY_NODE_ID,
524 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
530 id: ast::DUMMY_NODE_ID
532 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
535 #[derive(Copy, Clone, Debug)]
536 enum TokenExpectType {
541 impl<'a> Parser<'a> {
542 pub fn new(sess: &'a ParseSess,
544 directory: Option<Directory<'a>>,
545 recurse_into_file_modules: bool,
546 desugar_doc_comments: bool)
548 let mut parser = Parser {
550 token: token::Whitespace,
551 span: syntax_pos::DUMMY_SP,
552 prev_span: syntax_pos::DUMMY_SP,
554 prev_token_kind: PrevTokenKind::Other,
555 restrictions: Restrictions::empty(),
556 recurse_into_file_modules,
557 directory: Directory {
558 path: Cow::from(PathBuf::new()),
559 ownership: DirectoryOwnership::Owned { relative: None }
561 root_module_name: None,
562 expected_tokens: Vec::new(),
563 token_cursor: TokenCursor {
564 frame: TokenCursorFrame::new(
571 desugar_doc_comments,
573 unmatched_angle_bracket_count: 0,
576 let tok = parser.next_tok();
577 parser.token = tok.tok;
578 parser.span = tok.sp;
580 if let Some(directory) = directory {
581 parser.directory = directory;
582 } else if !parser.span.is_dummy() {
583 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
585 parser.directory.path = Cow::from(path);
589 parser.process_potential_macro_variable();
593 fn next_tok(&mut self) -> TokenAndSpan {
594 let mut next = if self.desugar_doc_comments {
595 self.token_cursor.next_desugared()
597 self.token_cursor.next()
599 if next.sp.is_dummy() {
600 // Tweak the location for better diagnostics, but keep syntactic context intact.
601 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
606 /// Convert the current token to a string using self's reader
607 pub fn this_token_to_string(&self) -> String {
608 pprust::token_to_string(&self.token)
611 fn token_descr(&self) -> Option<&'static str> {
612 Some(match &self.token {
613 t if t.is_special_ident() => "reserved identifier",
614 t if t.is_used_keyword() => "keyword",
615 t if t.is_unused_keyword() => "reserved keyword",
616 token::DocComment(..) => "doc comment",
621 fn this_token_descr(&self) -> String {
622 if let Some(prefix) = self.token_descr() {
623 format!("{} `{}`", prefix, self.this_token_to_string())
625 format!("`{}`", self.this_token_to_string())
629 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
630 let token_str = pprust::token_to_string(t);
631 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
634 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
635 match self.expect_one_of(&[], &[]) {
637 Ok(_) => unreachable!(),
641 /// Expect and consume the token t. Signal an error if
642 /// the next token is not t.
643 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
644 if self.expected_tokens.is_empty() {
645 if self.token == *t {
649 let token_str = pprust::token_to_string(t);
650 let this_token_str = self.this_token_descr();
651 let mut err = self.fatal(&format!("expected `{}`, found {}",
655 let sp = if self.token == token::Token::Eof {
656 // EOF, don't want to point at the following char, but rather the last token
659 self.sess.source_map().next_point(self.prev_span)
661 let label_exp = format!("expected `{}`", token_str);
662 let cm = self.sess.source_map();
663 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
664 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
665 // When the spans are in the same line, it means that the only content
666 // between them is whitespace, point only at the found token.
667 err.span_label(self.span, label_exp);
670 err.span_label(sp, label_exp);
671 err.span_label(self.span, "unexpected token");
677 self.expect_one_of(slice::from_ref(t), &[])
681 /// Expect next token to be edible or inedible token. If edible,
682 /// then consume it; if inedible, then return without consuming
683 /// anything. Signal a fatal error if next token is unexpected.
684 pub fn expect_one_of(&mut self,
685 edible: &[token::Token],
686 inedible: &[token::Token]) -> PResult<'a, ()>{
687 fn tokens_to_string(tokens: &[TokenType]) -> String {
688 let mut i = tokens.iter();
689 // This might be a sign we need a connect method on Iterator.
691 .map_or(String::new(), |t| t.to_string());
692 i.enumerate().fold(b, |mut b, (i, a)| {
693 if tokens.len() > 2 && i == tokens.len() - 2 {
695 } else if tokens.len() == 2 && i == tokens.len() - 2 {
700 b.push_str(&a.to_string());
704 if edible.contains(&self.token) {
707 } else if inedible.contains(&self.token) {
708 // leave it in the input
711 let mut expected = edible.iter()
712 .map(|x| TokenType::Token(x.clone()))
713 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
714 .chain(self.expected_tokens.iter().cloned())
715 .collect::<Vec<_>>();
716 expected.sort_by_cached_key(|x| x.to_string());
718 let expect = tokens_to_string(&expected[..]);
719 let actual = self.this_token_to_string();
720 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
721 let short_expect = if expected.len() > 6 {
722 format!("{} possible tokens", expected.len())
726 (format!("expected one of {}, found `{}`", expect, actual),
727 (self.sess.source_map().next_point(self.prev_span),
728 format!("expected one of {} here", short_expect)))
729 } else if expected.is_empty() {
730 (format!("unexpected token: `{}`", actual),
731 (self.prev_span, "unexpected token after this".to_string()))
733 (format!("expected {}, found `{}`", expect, actual),
734 (self.sess.source_map().next_point(self.prev_span),
735 format!("expected {} here", expect)))
737 let mut err = self.fatal(&msg_exp);
738 if self.token.is_ident_named("and") {
739 err.span_suggestion_short_with_applicability(
741 "use `&&` instead of `and` for the boolean operator",
743 Applicability::MaybeIncorrect,
746 if self.token.is_ident_named("or") {
747 err.span_suggestion_short_with_applicability(
749 "use `||` instead of `or` for the boolean operator",
751 Applicability::MaybeIncorrect,
754 let sp = if self.token == token::Token::Eof {
755 // This is EOF, don't want to point at the following char, but rather the last token
761 let cm = self.sess.source_map();
762 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
763 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
764 // When the spans are in the same line, it means that the only content between
765 // them is whitespace, point at the found token in that case:
767 // X | () => { syntax error };
768 // | ^^^^^ expected one of 8 possible tokens here
770 // instead of having:
772 // X | () => { syntax error };
773 // | -^^^^^ unexpected token
775 // | expected one of 8 possible tokens here
776 err.span_label(self.span, label_exp);
778 _ if self.prev_span == syntax_pos::DUMMY_SP => {
779 // Account for macro context where the previous span might not be
780 // available to avoid incorrect output (#54841).
781 err.span_label(self.span, "unexpected token");
784 err.span_label(sp, label_exp);
785 err.span_label(self.span, "unexpected token");
792 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
793 fn interpolated_or_expr_span(&self,
794 expr: PResult<'a, P<Expr>>)
795 -> PResult<'a, (Span, P<Expr>)> {
797 if self.prev_token_kind == PrevTokenKind::Interpolated {
805 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
806 let mut err = self.struct_span_err(self.span,
807 &format!("expected identifier, found {}",
808 self.this_token_descr()));
809 if let token::Ident(ident, false) = &self.token {
810 if ident.is_reserved() && !ident.is_path_segment_keyword() &&
811 ident.name != keywords::Underscore.name()
813 err.span_suggestion_with_applicability(
815 "you can escape reserved keywords to use them as identifiers",
816 format!("r#{}", ident),
817 Applicability::MaybeIncorrect,
821 if let Some(token_descr) = self.token_descr() {
822 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
824 err.span_label(self.span, "expected identifier");
825 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
826 err.span_suggestion_with_applicability(
830 Applicability::MachineApplicable,
837 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
838 self.parse_ident_common(true)
841 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
843 token::Ident(ident, _) => {
844 if self.token.is_reserved_ident() {
845 let mut err = self.expected_ident_found();
852 let span = self.span;
854 Ok(Ident::new(ident.name, span))
857 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
858 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
860 self.expected_ident_found()
866 /// Check if the next token is `tok`, and return `true` if so.
868 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
870 crate fn check(&mut self, tok: &token::Token) -> bool {
871 let is_present = self.token == *tok;
872 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
876 /// Consume token 'tok' if it exists. Returns true if the given
877 /// token was present, false otherwise.
878 pub fn eat(&mut self, tok: &token::Token) -> bool {
879 let is_present = self.check(tok);
880 if is_present { self.bump() }
884 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
885 self.expected_tokens.push(TokenType::Keyword(kw));
886 self.token.is_keyword(kw)
889 /// If the next token is the given keyword, eat it and return
890 /// true. Otherwise, return false.
891 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
892 if self.check_keyword(kw) {
900 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
901 if self.token.is_keyword(kw) {
909 /// If the given word is not a keyword, signal an error.
910 /// If the next token is not the given word, signal an error.
911 /// Otherwise, eat it.
912 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
913 if !self.eat_keyword(kw) {
920 fn check_ident(&mut self) -> bool {
921 if self.token.is_ident() {
924 self.expected_tokens.push(TokenType::Ident);
929 fn check_path(&mut self) -> bool {
930 if self.token.is_path_start() {
933 self.expected_tokens.push(TokenType::Path);
938 fn check_type(&mut self) -> bool {
939 if self.token.can_begin_type() {
942 self.expected_tokens.push(TokenType::Type);
947 /// Expect and consume a `+`. if `+=` is seen, replace it with a `=`
948 /// and continue. If a `+` is not seen, return false.
950 /// This is using when token splitting += into +.
951 /// See issue 47856 for an example of when this may occur.
952 fn eat_plus(&mut self) -> bool {
953 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
955 token::BinOp(token::Plus) => {
959 token::BinOpEq(token::Plus) => {
960 let span = self.span.with_lo(self.span.lo() + BytePos(1));
961 self.bump_with(token::Eq, span);
969 /// Checks to see if the next token is either `+` or `+=`.
970 /// Otherwise returns false.
971 fn check_plus(&mut self) -> bool {
972 if self.token.is_like_plus() {
976 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
981 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
982 /// `&` and continue. If an `&` is not seen, signal an error.
983 fn expect_and(&mut self) -> PResult<'a, ()> {
984 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
986 token::BinOp(token::And) => {
991 let span = self.span.with_lo(self.span.lo() + BytePos(1));
992 Ok(self.bump_with(token::BinOp(token::And), span))
994 _ => self.unexpected()
998 /// Expect and consume an `|`. If `||` is seen, replace it with a single
999 /// `|` and continue. If an `|` is not seen, signal an error.
1000 fn expect_or(&mut self) -> PResult<'a, ()> {
1001 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
1003 token::BinOp(token::Or) => {
1008 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1009 Ok(self.bump_with(token::BinOp(token::Or), span))
1011 _ => self.unexpected()
1015 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
1017 None => {/* everything ok */}
1019 let text = suf.as_str();
1020 if text.is_empty() {
1021 self.span_bug(sp, "found empty literal suffix in Some")
1023 let msg = format!("{} with a suffix is invalid", kind);
1024 self.struct_span_err(sp, &msg)
1025 .span_label(sp, msg)
1031 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
1032 /// `<` and continue. If a `<` is not seen, return false.
1034 /// This is meant to be used when parsing generics on a path to get the
1036 fn eat_lt(&mut self) -> bool {
1037 self.expected_tokens.push(TokenType::Token(token::Lt));
1038 let ate = match self.token {
1043 token::BinOp(token::Shl) => {
1044 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1045 self.bump_with(token::Lt, span);
1052 // See doc comment for `unmatched_angle_bracket_count`.
1053 self.unmatched_angle_bracket_count += 1;
1054 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
1060 fn expect_lt(&mut self) -> PResult<'a, ()> {
1068 /// Expect and consume a GT. if a >> is seen, replace it
1069 /// with a single > and continue. If a GT is not seen,
1070 /// signal an error.
1071 fn expect_gt(&mut self) -> PResult<'a, ()> {
1072 self.expected_tokens.push(TokenType::Token(token::Gt));
1073 let ate = match self.token {
1078 token::BinOp(token::Shr) => {
1079 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1080 Some(self.bump_with(token::Gt, span))
1082 token::BinOpEq(token::Shr) => {
1083 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1084 Some(self.bump_with(token::Ge, span))
1087 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1088 Some(self.bump_with(token::Eq, span))
1095 // See doc comment for `unmatched_angle_bracket_count`.
1096 self.unmatched_angle_bracket_count -= 1;
1097 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1101 None => self.unexpected(),
1105 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1106 /// passes through any errors encountered. Used for error recovery.
1107 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1108 let handler = self.diagnostic();
1110 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1112 TokenExpectType::Expect,
1113 |p| Ok(p.parse_token_tree())) {
1114 handler.cancel(err);
1118 /// Parse a sequence, including the closing delimiter. The function
1119 /// f must consume tokens until reaching the next separator or
1120 /// closing bracket.
1121 pub fn parse_seq_to_end<T, F>(&mut self,
1125 -> PResult<'a, Vec<T>> where
1126 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1128 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1133 /// Parse a sequence, not including the closing delimiter. The function
1134 /// f must consume tokens until reaching the next separator or
1135 /// closing bracket.
1136 pub fn parse_seq_to_before_end<T, F>(&mut self,
1140 -> PResult<'a, Vec<T>>
1141 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1143 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1146 fn parse_seq_to_before_tokens<T, F>(
1148 kets: &[&token::Token],
1150 expect: TokenExpectType,
1152 ) -> PResult<'a, Vec<T>>
1153 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1155 let mut first: bool = true;
1157 while !kets.iter().any(|k| {
1159 TokenExpectType::Expect => self.check(k),
1160 TokenExpectType::NoExpect => self.token == **k,
1164 token::CloseDelim(..) | token::Eof => break,
1167 if let Some(ref t) = sep.sep {
1171 if let Err(mut e) = self.expect(t) {
1172 // Attempt to keep parsing if it was a similar separator
1173 if let Some(ref tokens) = t.similar_tokens() {
1174 if tokens.contains(&self.token) {
1179 // Attempt to keep parsing if it was an omitted separator
1193 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1195 TokenExpectType::Expect => self.check(k),
1196 TokenExpectType::NoExpect => self.token == **k,
1209 /// Parse a sequence, including the closing delimiter. The function
1210 /// f must consume tokens until reaching the next separator or
1211 /// closing bracket.
1212 fn parse_unspanned_seq<T, F>(&mut self,
1217 -> PResult<'a, Vec<T>> where
1218 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1221 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1226 /// Advance the parser by one token
1227 pub fn bump(&mut self) {
1228 if self.prev_token_kind == PrevTokenKind::Eof {
1229 // Bumping after EOF is a bad sign, usually an infinite loop.
1230 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1233 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1235 // Record last token kind for possible error recovery.
1236 self.prev_token_kind = match self.token {
1237 token::DocComment(..) => PrevTokenKind::DocComment,
1238 token::Comma => PrevTokenKind::Comma,
1239 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1240 token::Interpolated(..) => PrevTokenKind::Interpolated,
1241 token::Eof => PrevTokenKind::Eof,
1242 token::Ident(..) => PrevTokenKind::Ident,
1243 _ => PrevTokenKind::Other,
1246 let next = self.next_tok();
1247 self.span = next.sp;
1248 self.token = next.tok;
1249 self.expected_tokens.clear();
1250 // check after each token
1251 self.process_potential_macro_variable();
1254 /// Advance the parser using provided token as a next one. Use this when
1255 /// consuming a part of a token. For example a single `<` from `<<`.
1256 fn bump_with(&mut self, next: token::Token, span: Span) {
1257 self.prev_span = self.span.with_hi(span.lo());
1258 // It would be incorrect to record the kind of the current token, but
1259 // fortunately for tokens currently using `bump_with`, the
1260 // prev_token_kind will be of no use anyway.
1261 self.prev_token_kind = PrevTokenKind::Other;
1264 self.expected_tokens.clear();
1267 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1268 F: FnOnce(&token::Token) -> R,
1271 return f(&self.token)
1274 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1275 Some(tree) => match tree {
1276 TokenTree::Token(_, tok) => tok,
1277 TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim),
1279 None => token::CloseDelim(self.token_cursor.frame.delim),
1283 fn look_ahead_span(&self, dist: usize) -> Span {
1288 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1289 Some(TokenTree::Token(span, _)) => span,
1290 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1291 None => self.look_ahead_span(dist - 1),
1294 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1295 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1297 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1298 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1300 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1301 err.span_err(sp, self.diagnostic())
1303 fn bug(&self, m: &str) -> ! {
1304 self.sess.span_diagnostic.span_bug(self.span, m)
1306 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1307 self.sess.span_diagnostic.span_err(sp, m)
1309 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1310 self.sess.span_diagnostic.struct_span_err(sp, m)
1312 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1313 self.sess.span_diagnostic.span_bug(sp, m)
1316 fn cancel(&self, err: &mut DiagnosticBuilder) {
1317 self.sess.span_diagnostic.cancel(err)
1320 crate fn diagnostic(&self) -> &'a errors::Handler {
1321 &self.sess.span_diagnostic
1324 /// Is the current token one of the keywords that signals a bare function
1326 fn token_is_bare_fn_keyword(&mut self) -> bool {
1327 self.check_keyword(keywords::Fn) ||
1328 self.check_keyword(keywords::Unsafe) ||
1329 self.check_keyword(keywords::Extern)
1332 /// parse a `TyKind::BareFn` type:
1333 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1336 [unsafe] [extern "ABI"] fn (S) -> T
1346 let unsafety = self.parse_unsafety();
1347 let abi = if self.eat_keyword(keywords::Extern) {
1348 self.parse_opt_abi()?.unwrap_or(Abi::C)
1353 self.expect_keyword(keywords::Fn)?;
1354 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1355 let ret_ty = self.parse_ret_ty(false)?;
1356 let decl = P(FnDecl {
1361 Ok(TyKind::BareFn(P(BareFnTy {
1369 /// Parse asyncness: `async` or nothing
1370 fn parse_asyncness(&mut self) -> IsAsync {
1371 if self.eat_keyword(keywords::Async) {
1373 closure_id: ast::DUMMY_NODE_ID,
1374 return_impl_trait_id: ast::DUMMY_NODE_ID,
1381 /// Parse unsafety: `unsafe` or nothing.
1382 fn parse_unsafety(&mut self) -> Unsafety {
1383 if self.eat_keyword(keywords::Unsafe) {
1390 /// Parse the items in a trait declaration
1391 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1392 maybe_whole!(self, NtTraitItem, |x| x);
1393 let attrs = self.parse_outer_attributes()?;
1394 let (mut item, tokens) = self.collect_tokens(|this| {
1395 this.parse_trait_item_(at_end, attrs)
1397 // See `parse_item` for why this clause is here.
1398 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1399 item.tokens = Some(tokens);
1404 fn parse_trait_item_(&mut self,
1406 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1409 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1410 self.parse_trait_item_assoc_ty()?
1411 } else if self.is_const_item() {
1412 self.expect_keyword(keywords::Const)?;
1413 let ident = self.parse_ident()?;
1414 self.expect(&token::Colon)?;
1415 let ty = self.parse_ty()?;
1416 let default = if self.eat(&token::Eq) {
1417 let expr = self.parse_expr()?;
1418 self.expect(&token::Semi)?;
1421 self.expect(&token::Semi)?;
1424 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1425 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1426 // trait item macro.
1427 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1429 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1431 let ident = self.parse_ident()?;
1432 let mut generics = self.parse_generics()?;
1434 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1435 // This is somewhat dubious; We don't want to allow
1436 // argument names to be left off if there is a
1439 // We don't allow argument names to be left off in edition 2018.
1440 p.parse_arg_general(p.span.rust_2018(), true)
1442 generics.where_clause = self.parse_where_clause()?;
1444 let sig = ast::MethodSig {
1454 let body = match self.token {
1458 debug!("parse_trait_methods(): parsing required method");
1461 token::OpenDelim(token::Brace) => {
1462 debug!("parse_trait_methods(): parsing provided method");
1464 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1465 attrs.extend(inner_attrs.iter().cloned());
1468 token::Interpolated(ref nt) => {
1470 token::NtBlock(..) => {
1472 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1473 attrs.extend(inner_attrs.iter().cloned());
1477 let token_str = self.this_token_descr();
1478 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1480 err.span_label(self.span, "expected `;` or `{`");
1486 let token_str = self.this_token_descr();
1487 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1489 err.span_label(self.span, "expected `;` or `{`");
1493 (ident, ast::TraitItemKind::Method(sig, body), generics)
1497 id: ast::DUMMY_NODE_ID,
1502 span: lo.to(self.prev_span),
1507 /// Parse optional return type [ -> TY ] in function decl
1508 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1509 if self.eat(&token::RArrow) {
1510 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1512 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1517 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1518 self.parse_ty_common(true, true)
1521 /// Parse a type in restricted contexts where `+` is not permitted.
1522 /// Example 1: `&'a TYPE`
1523 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1524 /// Example 2: `value1 as TYPE + value2`
1525 /// `+` is prohibited to avoid interactions with expression grammar.
1526 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1527 self.parse_ty_common(false, true)
1530 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1531 -> PResult<'a, P<Ty>> {
1532 maybe_whole!(self, NtTy, |x| x);
1535 let mut impl_dyn_multi = false;
1536 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1537 // `(TYPE)` is a parenthesized type.
1538 // `(TYPE,)` is a tuple with a single field of type TYPE.
1539 let mut ts = vec![];
1540 let mut last_comma = false;
1541 while self.token != token::CloseDelim(token::Paren) {
1542 ts.push(self.parse_ty()?);
1543 if self.eat(&token::Comma) {
1550 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1551 self.expect(&token::CloseDelim(token::Paren))?;
1553 if ts.len() == 1 && !last_comma {
1554 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1555 let maybe_bounds = allow_plus && self.token.is_like_plus();
1557 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1558 TyKind::Path(None, ref path) if maybe_bounds => {
1559 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1561 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1562 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1563 let path = match bounds[0] {
1564 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1565 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1567 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1570 _ => TyKind::Paren(P(ty))
1575 } else if self.eat(&token::Not) {
1578 } else if self.eat(&token::BinOp(token::Star)) {
1580 TyKind::Ptr(self.parse_ptr()?)
1581 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1583 let t = self.parse_ty()?;
1584 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1585 let t = match self.maybe_parse_fixed_length_of_vec()? {
1586 None => TyKind::Slice(t),
1587 Some(length) => TyKind::Array(t, AnonConst {
1588 id: ast::DUMMY_NODE_ID,
1592 self.expect(&token::CloseDelim(token::Bracket))?;
1594 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1597 self.parse_borrowed_pointee()?
1598 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1600 // In order to not be ambiguous, the type must be surrounded by parens.
1601 self.expect(&token::OpenDelim(token::Paren))?;
1603 id: ast::DUMMY_NODE_ID,
1604 value: self.parse_expr()?,
1606 self.expect(&token::CloseDelim(token::Paren))?;
1608 } else if self.eat_keyword(keywords::Underscore) {
1609 // A type to be inferred `_`
1611 } else if self.token_is_bare_fn_keyword() {
1612 // Function pointer type
1613 self.parse_ty_bare_fn(Vec::new())?
1614 } else if self.check_keyword(keywords::For) {
1615 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1616 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1617 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1619 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1620 if self.token_is_bare_fn_keyword() {
1621 self.parse_ty_bare_fn(lifetime_defs)?
1623 let path = self.parse_path(PathStyle::Type)?;
1624 let parse_plus = allow_plus && self.check_plus();
1625 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1627 } else if self.eat_keyword(keywords::Impl) {
1628 // Always parse bounds greedily for better error recovery.
1629 let bounds = self.parse_generic_bounds()?;
1630 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1631 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1632 } else if self.check_keyword(keywords::Dyn) &&
1633 (self.span.rust_2018() ||
1634 self.look_ahead(1, |t| t.can_begin_bound() &&
1635 !can_continue_type_after_non_fn_ident(t))) {
1636 self.bump(); // `dyn`
1637 // Always parse bounds greedily for better error recovery.
1638 let bounds = self.parse_generic_bounds()?;
1639 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1640 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1641 } else if self.check(&token::Question) ||
1642 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1643 // Bound list (trait object type)
1644 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
1645 TraitObjectSyntax::None)
1646 } else if self.eat_lt() {
1648 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1649 TyKind::Path(Some(qself), path)
1650 } else if self.token.is_path_start() {
1652 let path = self.parse_path(PathStyle::Type)?;
1653 if self.eat(&token::Not) {
1654 // Macro invocation in type position
1655 let (delim, tts) = self.expect_delimited_token_tree()?;
1656 let node = Mac_ { path, tts, delim };
1657 TyKind::Mac(respan(lo.to(self.prev_span), node))
1659 // Just a type path or bound list (trait object type) starting with a trait.
1661 // `Trait1 + Trait2 + 'a`
1662 if allow_plus && self.check_plus() {
1663 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1665 TyKind::Path(None, path)
1669 let msg = format!("expected type, found {}", self.this_token_descr());
1670 return Err(self.fatal(&msg));
1673 let span = lo.to(self.prev_span);
1674 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1676 // Try to recover from use of `+` with incorrect priority.
1677 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1678 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1679 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1684 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1685 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1686 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1687 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1689 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1690 bounds.append(&mut self.parse_generic_bounds()?);
1692 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1695 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1696 if !allow_plus && impl_dyn_multi {
1697 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1698 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1699 .span_suggestion_with_applicability(
1701 "use parentheses to disambiguate",
1703 Applicability::MachineApplicable
1708 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1709 // Do not add `+` to expected tokens.
1710 if !allow_plus || !self.token.is_like_plus() {
1715 let bounds = self.parse_generic_bounds()?;
1716 let sum_span = ty.span.to(self.prev_span);
1718 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1719 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1722 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1723 let sum_with_parens = pprust::to_string(|s| {
1724 use print::pprust::PrintState;
1727 s.print_opt_lifetime(lifetime)?;
1728 s.print_mutability(mut_ty.mutbl)?;
1730 s.print_type(&mut_ty.ty)?;
1731 s.print_type_bounds(" +", &bounds)?;
1734 err.span_suggestion_with_applicability(
1736 "try adding parentheses",
1738 Applicability::MachineApplicable
1741 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1742 err.span_label(sum_span, "perhaps you forgot parentheses?");
1745 err.span_label(sum_span, "expected a path");
1752 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1753 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1755 // Do not add `::` to expected tokens.
1756 if !allow_recovery || self.token != token::ModSep {
1759 let ty = match base.to_ty() {
1761 None => return Ok(base),
1764 self.bump(); // `::`
1765 let mut segments = Vec::new();
1766 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1768 let span = ty.span.to(self.prev_span);
1769 let path_span = span.to(span); // use an empty path since `position` == 0
1770 let recovered = base.to_recovered(
1771 Some(QSelf { ty, path_span, position: 0 }),
1772 ast::Path { segments, span },
1776 .struct_span_err(span, "missing angle brackets in associated item path")
1777 .span_suggestion_with_applicability( // this is a best-effort recovery
1778 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1784 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1785 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1786 let mutbl = self.parse_mutability();
1787 let ty = self.parse_ty_no_plus()?;
1788 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1791 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1792 let mutbl = if self.eat_keyword(keywords::Mut) {
1794 } else if self.eat_keyword(keywords::Const) {
1795 Mutability::Immutable
1797 let span = self.prev_span;
1798 let msg = "expected mut or const in raw pointer type";
1799 self.struct_span_err(span, msg)
1800 .span_label(span, msg)
1801 .help("use `*mut T` or `*const T` as appropriate")
1803 Mutability::Immutable
1805 let t = self.parse_ty_no_plus()?;
1806 Ok(MutTy { ty: t, mutbl: mutbl })
1809 fn is_named_argument(&mut self) -> bool {
1810 let offset = match self.token {
1811 token::Interpolated(ref nt) => match nt.0 {
1812 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1815 token::BinOp(token::And) | token::AndAnd => 1,
1816 _ if self.token.is_keyword(keywords::Mut) => 1,
1820 self.look_ahead(offset, |t| t.is_ident()) &&
1821 self.look_ahead(offset + 1, |t| t == &token::Colon)
1824 /// Skip unexpected attributes and doc comments in this position and emit an appropriate error.
1825 fn eat_incorrect_doc_comment(&mut self, applied_to: &str) {
1826 if let token::DocComment(_) = self.token {
1827 let mut err = self.diagnostic().struct_span_err(
1829 &format!("documentation comments cannot be applied to {}", applied_to),
1831 err.span_label(self.span, "doc comments are not allowed here");
1834 } else if self.token == token::Pound && self.look_ahead(1, |t| {
1835 *t == token::OpenDelim(token::Bracket)
1838 // Skip every token until next possible arg.
1839 while self.token != token::CloseDelim(token::Bracket) {
1842 let sp = lo.to(self.span);
1844 let mut err = self.diagnostic().struct_span_err(
1846 &format!("attributes cannot be applied to {}", applied_to),
1848 err.span_label(sp, "attributes are not allowed here");
1853 /// This version of parse arg doesn't necessarily require
1854 /// identifier names.
1855 fn parse_arg_general(&mut self, require_name: bool, is_trait_item: bool) -> PResult<'a, Arg> {
1856 maybe_whole!(self, NtArg, |x| x);
1858 if let Ok(Some(_)) = self.parse_self_arg() {
1859 let mut err = self.struct_span_err(self.prev_span,
1860 "unexpected `self` argument in function");
1861 err.span_label(self.prev_span,
1862 "`self` is only valid as the first argument of an associated function");
1866 let (pat, ty) = if require_name || self.is_named_argument() {
1867 debug!("parse_arg_general parse_pat (require_name:{})",
1869 self.eat_incorrect_doc_comment("method arguments");
1870 let pat = self.parse_pat(Some("argument name"))?;
1872 if let Err(mut err) = self.expect(&token::Colon) {
1873 // If we find a pattern followed by an identifier, it could be an (incorrect)
1874 // C-style parameter declaration.
1875 if self.check_ident() && self.look_ahead(1, |t| {
1876 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1878 let ident = self.parse_ident().unwrap();
1879 let span = pat.span.with_hi(ident.span.hi());
1881 err.span_suggestion_with_applicability(
1883 "declare the type after the parameter binding",
1884 String::from("<identifier>: <type>"),
1885 Applicability::HasPlaceholders,
1887 } else if require_name && is_trait_item {
1888 if let PatKind::Ident(_, ident, _) = pat.node {
1889 err.span_suggestion_with_applicability(
1891 "explicitly ignore parameter",
1892 format!("_: {}", ident),
1893 Applicability::MachineApplicable,
1897 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
1903 self.eat_incorrect_doc_comment("a method argument's type");
1904 (pat, self.parse_ty()?)
1906 debug!("parse_arg_general ident_to_pat");
1907 let parser_snapshot_before_ty = self.clone();
1908 self.eat_incorrect_doc_comment("a method argument's type");
1909 let mut ty = self.parse_ty();
1910 if ty.is_ok() && self.token != token::Comma &&
1911 self.token != token::CloseDelim(token::Paren) {
1912 // This wasn't actually a type, but a pattern looking like a type,
1913 // so we are going to rollback and re-parse for recovery.
1914 ty = self.unexpected();
1918 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1920 id: ast::DUMMY_NODE_ID,
1921 node: PatKind::Ident(
1922 BindingMode::ByValue(Mutability::Immutable), ident, None),
1928 // Recover from attempting to parse the argument as a type without pattern.
1930 mem::replace(self, parser_snapshot_before_ty);
1931 let pat = self.parse_pat(Some("argument name"))?;
1932 self.expect(&token::Colon)?;
1933 let ty = self.parse_ty()?;
1935 let mut err = self.diagnostic().struct_span_err_with_code(
1937 "patterns aren't allowed in methods without bodies",
1938 DiagnosticId::Error("E0642".into()),
1940 err.span_suggestion_short_with_applicability(
1942 "give this argument a name or use an underscore to ignore it",
1944 Applicability::MachineApplicable,
1948 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
1950 node: PatKind::Wild,
1952 id: ast::DUMMY_NODE_ID
1959 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
1962 /// Parse a single function argument
1963 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1964 self.parse_arg_general(true, false)
1967 /// Parse an argument in a lambda header e.g., |arg, arg|
1968 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1969 let pat = self.parse_pat(Some("argument name"))?;
1970 let t = if self.eat(&token::Colon) {
1974 id: ast::DUMMY_NODE_ID,
1975 node: TyKind::Infer,
1976 span: self.prev_span,
1982 id: ast::DUMMY_NODE_ID
1986 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1987 if self.eat(&token::Semi) {
1988 Ok(Some(self.parse_expr()?))
1994 /// Matches token_lit = LIT_INTEGER | ...
1995 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1996 let out = match self.token {
1997 token::Interpolated(ref nt) => match nt.0 {
1998 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
1999 ExprKind::Lit(ref lit) => { lit.node.clone() }
2000 _ => { return self.unexpected_last(&self.token); }
2002 _ => { return self.unexpected_last(&self.token); }
2004 token::Literal(lit, suf) => {
2005 let diag = Some((self.span, &self.sess.span_diagnostic));
2006 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
2010 self.expect_no_suffix(sp, lit.literal_name(), suf)
2015 token::Dot if self.look_ahead(1, |t| match t {
2016 token::Literal(parse::token::Lit::Integer(_) , _) => true,
2018 }) => { // recover from `let x = .4;`
2021 if let token::Literal(
2022 parse::token::Lit::Integer(val),
2025 let suffix = suffix.and_then(|s| {
2026 let s = s.as_str().get();
2027 if ["f32", "f64"].contains(&s) {
2034 let sp = lo.to(self.prev_span);
2035 let mut err = self.diagnostic()
2036 .struct_span_err(sp, "float literals must have an integer part");
2037 err.span_suggestion_with_applicability(
2039 "must have an integer part",
2040 format!("0.{}{}", val, suffix),
2041 Applicability::MachineApplicable,
2044 return Ok(match suffix {
2045 "f32" => ast::LitKind::Float(val, ast::FloatTy::F32),
2046 "f64" => ast::LitKind::Float(val, ast::FloatTy::F64),
2047 _ => ast::LitKind::FloatUnsuffixed(val),
2053 _ => { return self.unexpected_last(&self.token); }
2060 /// Matches lit = true | false | token_lit
2061 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
2063 let lit = if self.eat_keyword(keywords::True) {
2065 } else if self.eat_keyword(keywords::False) {
2066 LitKind::Bool(false)
2068 let lit = self.parse_lit_token()?;
2071 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
2074 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
2075 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
2076 maybe_whole_expr!(self);
2078 let minus_lo = self.span;
2079 let minus_present = self.eat(&token::BinOp(token::Minus));
2081 let literal = self.parse_lit()?;
2082 let hi = self.prev_span;
2083 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
2086 let minus_hi = self.prev_span;
2087 let unary = self.mk_unary(UnOp::Neg, expr);
2088 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
2094 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2096 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2097 let span = self.span;
2099 Ok(Ident::new(ident.name, span))
2101 _ => self.parse_ident(),
2105 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
2107 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
2108 let span = self.span;
2110 Ok(Ident::new(ident.name, span))
2112 _ => self.parse_ident(),
2116 /// Parses qualified path.
2117 /// Assumes that the leading `<` has been parsed already.
2119 /// `qualified_path = <type [as trait_ref]>::path`
2124 /// `<T as U>::F::a<S>` (without disambiguator)
2125 /// `<T as U>::F::a::<S>` (with disambiguator)
2126 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2127 let lo = self.prev_span;
2128 let ty = self.parse_ty()?;
2130 // `path` will contain the prefix of the path up to the `>`,
2131 // if any (e.g., `U` in the `<T as U>::*` examples
2132 // above). `path_span` has the span of that path, or an empty
2133 // span in the case of something like `<T>::Bar`.
2134 let (mut path, path_span);
2135 if self.eat_keyword(keywords::As) {
2136 let path_lo = self.span;
2137 path = self.parse_path(PathStyle::Type)?;
2138 path_span = path_lo.to(self.prev_span);
2140 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2141 path_span = self.span.to(self.span);
2144 // See doc comment for `unmatched_angle_bracket_count`.
2145 self.expect(&token::Gt)?;
2146 self.unmatched_angle_bracket_count -= 1;
2147 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
2149 self.expect(&token::ModSep)?;
2151 let qself = QSelf { ty, path_span, position: path.segments.len() };
2152 self.parse_path_segments(&mut path.segments, style, true)?;
2154 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2157 /// Parses simple paths.
2159 /// `path = [::] segment+`
2160 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2163 /// `a::b::C<D>` (without disambiguator)
2164 /// `a::b::C::<D>` (with disambiguator)
2165 /// `Fn(Args)` (without disambiguator)
2166 /// `Fn::(Args)` (with disambiguator)
2167 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2168 self.parse_path_common(style, true)
2171 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
2172 -> PResult<'a, ast::Path> {
2173 maybe_whole!(self, NtPath, |path| {
2174 if style == PathStyle::Mod &&
2175 path.segments.iter().any(|segment| segment.args.is_some()) {
2176 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2181 let lo = self.meta_var_span.unwrap_or(self.span);
2182 let mut segments = Vec::new();
2183 let mod_sep_ctxt = self.span.ctxt();
2184 if self.eat(&token::ModSep) {
2185 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2187 self.parse_path_segments(&mut segments, style, enable_warning)?;
2189 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2192 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
2193 /// This is used when parsing derive macro paths in `#[derive]` attributes.
2194 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2195 let meta_ident = match self.token {
2196 token::Interpolated(ref nt) => match nt.0 {
2197 token::NtMeta(ref meta) => match meta.node {
2198 ast::MetaItemKind::Word => Some(meta.ident.clone()),
2205 if let Some(path) = meta_ident {
2209 self.parse_path(style)
2212 fn parse_path_segments(&mut self,
2213 segments: &mut Vec<PathSegment>,
2215 enable_warning: bool)
2216 -> PResult<'a, ()> {
2218 let segment = self.parse_path_segment(style, enable_warning)?;
2219 if style == PathStyle::Expr {
2220 // In order to check for trailing angle brackets, we must have finished
2221 // recursing (`parse_path_segment` can indirectly call this function),
2222 // that is, the next token must be the highlighted part of the below example:
2224 // `Foo::<Bar as Baz<T>>::Qux`
2227 // As opposed to the below highlight (if we had only finished the first
2230 // `Foo::<Bar as Baz<T>>::Qux`
2233 // `PathStyle::Expr` is only provided at the root invocation and never in
2234 // `parse_path_segment` to recurse and therefore can be checked to maintain
2236 self.check_trailing_angle_brackets(&segment, token::ModSep);
2238 segments.push(segment);
2240 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2246 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2247 -> PResult<'a, PathSegment> {
2248 let ident = self.parse_path_segment_ident()?;
2250 let is_args_start = |token: &token::Token| match *token {
2251 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2254 let check_args_start = |this: &mut Self| {
2255 this.expected_tokens.extend_from_slice(
2256 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2258 is_args_start(&this.token)
2261 Ok(if style == PathStyle::Type && check_args_start(self) ||
2262 style != PathStyle::Mod && self.check(&token::ModSep)
2263 && self.look_ahead(1, |t| is_args_start(t)) {
2264 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2265 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2266 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2267 .span_label(self.prev_span, "try removing `::`").emit();
2271 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
2272 // it isn't, then we reset the unmatched angle bracket count as we're about to start
2273 // parsing a new path.
2274 if style == PathStyle::Expr { self.unmatched_angle_bracket_count = 0; }
2276 let args = if self.eat_lt() {
2278 let (args, bindings) =
2279 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
2281 let span = lo.to(self.prev_span);
2282 AngleBracketedArgs { args, bindings, span }.into()
2286 let inputs = self.parse_seq_to_before_tokens(
2287 &[&token::CloseDelim(token::Paren)],
2288 SeqSep::trailing_allowed(token::Comma),
2289 TokenExpectType::Expect,
2292 let span = lo.to(self.prev_span);
2293 let output = if self.eat(&token::RArrow) {
2294 Some(self.parse_ty_common(false, false)?)
2298 ParenthesizedArgs { inputs, output, span }.into()
2301 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2303 // Generic arguments are not found.
2304 PathSegment::from_ident(ident)
2308 crate fn check_lifetime(&mut self) -> bool {
2309 self.expected_tokens.push(TokenType::Lifetime);
2310 self.token.is_lifetime()
2313 /// Parse single lifetime 'a or panic.
2314 crate fn expect_lifetime(&mut self) -> Lifetime {
2315 if let Some(ident) = self.token.lifetime() {
2316 let span = self.span;
2318 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2320 self.span_bug(self.span, "not a lifetime")
2324 fn eat_label(&mut self) -> Option<Label> {
2325 if let Some(ident) = self.token.lifetime() {
2326 let span = self.span;
2328 Some(Label { ident: Ident::new(ident.name, span) })
2334 /// Parse mutability (`mut` or nothing).
2335 fn parse_mutability(&mut self) -> Mutability {
2336 if self.eat_keyword(keywords::Mut) {
2339 Mutability::Immutable
2343 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2344 if let token::Literal(token::Integer(name), None) = self.token {
2346 Ok(Ident::new(name, self.prev_span))
2348 self.parse_ident_common(false)
2352 /// Parse ident (COLON expr)?
2353 fn parse_field(&mut self) -> PResult<'a, Field> {
2354 let attrs = self.parse_outer_attributes()?;
2357 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2358 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
2359 t == &token::Colon || t == &token::Eq
2361 let fieldname = self.parse_field_name()?;
2363 // Check for an equals token. This means the source incorrectly attempts to
2364 // initialize a field with an eq rather than a colon.
2365 if self.token == token::Eq {
2367 .struct_span_err(self.span, "expected `:`, found `=`")
2368 .span_suggestion_with_applicability(
2369 fieldname.span.shrink_to_hi().to(self.span),
2370 "replace equals symbol with a colon",
2372 Applicability::MachineApplicable,
2377 (fieldname, self.parse_expr()?, false)
2379 let fieldname = self.parse_ident_common(false)?;
2381 // Mimic `x: x` for the `x` field shorthand.
2382 let path = ast::Path::from_ident(fieldname);
2383 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2384 (fieldname, expr, true)
2388 span: lo.to(expr.span),
2391 attrs: attrs.into(),
2395 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2396 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2399 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2400 ExprKind::Unary(unop, expr)
2403 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2404 ExprKind::Binary(binop, lhs, rhs)
2407 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2408 ExprKind::Call(f, args)
2411 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2412 ExprKind::Index(expr, idx)
2415 fn mk_range(&mut self,
2416 start: Option<P<Expr>>,
2417 end: Option<P<Expr>>,
2418 limits: RangeLimits)
2419 -> PResult<'a, ast::ExprKind> {
2420 if end.is_none() && limits == RangeLimits::Closed {
2421 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2423 Ok(ExprKind::Range(start, end, limits))
2427 fn mk_assign_op(&mut self, binop: ast::BinOp,
2428 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2429 ExprKind::AssignOp(binop, lhs, rhs)
2432 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2434 id: ast::DUMMY_NODE_ID,
2435 node: ExprKind::Mac(source_map::Spanned {node: m, span: span}),
2441 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
2442 let delim = match self.token {
2443 token::OpenDelim(delim) => delim,
2445 let msg = "expected open delimiter";
2446 let mut err = self.fatal(msg);
2447 err.span_label(self.span, msg);
2451 let tts = match self.parse_token_tree() {
2452 TokenTree::Delimited(_, _, tts) => tts,
2453 _ => unreachable!(),
2455 let delim = match delim {
2456 token::Paren => MacDelimiter::Parenthesis,
2457 token::Bracket => MacDelimiter::Bracket,
2458 token::Brace => MacDelimiter::Brace,
2459 token::NoDelim => self.bug("unexpected no delimiter"),
2461 Ok((delim, tts.into()))
2464 /// At the bottom (top?) of the precedence hierarchy,
2465 /// parse things like parenthesized exprs,
2466 /// macros, return, etc.
2468 /// N.B., this does not parse outer attributes,
2469 /// and is private because it only works
2470 /// correctly if called from parse_dot_or_call_expr().
2471 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2472 maybe_whole_expr!(self);
2474 // Outer attributes are already parsed and will be
2475 // added to the return value after the fact.
2477 // Therefore, prevent sub-parser from parsing
2478 // attributes by giving them a empty "already parsed" list.
2479 let mut attrs = ThinVec::new();
2482 let mut hi = self.span;
2486 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2488 token::OpenDelim(token::Paren) => {
2491 attrs.extend(self.parse_inner_attributes()?);
2493 // (e) is parenthesized e
2494 // (e,) is a tuple with only one field, e
2495 let mut es = vec![];
2496 let mut trailing_comma = false;
2497 while self.token != token::CloseDelim(token::Paren) {
2498 es.push(self.parse_expr()?);
2499 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2500 if self.eat(&token::Comma) {
2501 trailing_comma = true;
2503 trailing_comma = false;
2509 hi = self.prev_span;
2510 ex = if es.len() == 1 && !trailing_comma {
2511 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2516 token::OpenDelim(token::Brace) => {
2517 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2519 token::BinOp(token::Or) | token::OrOr => {
2520 return self.parse_lambda_expr(attrs);
2522 token::OpenDelim(token::Bracket) => {
2525 attrs.extend(self.parse_inner_attributes()?);
2527 if self.eat(&token::CloseDelim(token::Bracket)) {
2529 ex = ExprKind::Array(Vec::new());
2532 let first_expr = self.parse_expr()?;
2533 if self.eat(&token::Semi) {
2534 // Repeating array syntax: [ 0; 512 ]
2535 let count = AnonConst {
2536 id: ast::DUMMY_NODE_ID,
2537 value: self.parse_expr()?,
2539 self.expect(&token::CloseDelim(token::Bracket))?;
2540 ex = ExprKind::Repeat(first_expr, count);
2541 } else if self.eat(&token::Comma) {
2542 // Vector with two or more elements.
2543 let remaining_exprs = self.parse_seq_to_end(
2544 &token::CloseDelim(token::Bracket),
2545 SeqSep::trailing_allowed(token::Comma),
2546 |p| Ok(p.parse_expr()?)
2548 let mut exprs = vec![first_expr];
2549 exprs.extend(remaining_exprs);
2550 ex = ExprKind::Array(exprs);
2552 // Vector with one element.
2553 self.expect(&token::CloseDelim(token::Bracket))?;
2554 ex = ExprKind::Array(vec![first_expr]);
2557 hi = self.prev_span;
2561 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2563 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2565 if self.span.rust_2018() && self.check_keyword(keywords::Async)
2567 if self.is_async_block() { // check for `async {` and `async move {`
2568 return self.parse_async_block(attrs);
2570 return self.parse_lambda_expr(attrs);
2573 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2574 return self.parse_lambda_expr(attrs);
2576 if self.eat_keyword(keywords::If) {
2577 return self.parse_if_expr(attrs);
2579 if self.eat_keyword(keywords::For) {
2580 let lo = self.prev_span;
2581 return self.parse_for_expr(None, lo, attrs);
2583 if self.eat_keyword(keywords::While) {
2584 let lo = self.prev_span;
2585 return self.parse_while_expr(None, lo, attrs);
2587 if let Some(label) = self.eat_label() {
2588 let lo = label.ident.span;
2589 self.expect(&token::Colon)?;
2590 if self.eat_keyword(keywords::While) {
2591 return self.parse_while_expr(Some(label), lo, attrs)
2593 if self.eat_keyword(keywords::For) {
2594 return self.parse_for_expr(Some(label), lo, attrs)
2596 if self.eat_keyword(keywords::Loop) {
2597 return self.parse_loop_expr(Some(label), lo, attrs)
2599 if self.token == token::OpenDelim(token::Brace) {
2600 return self.parse_block_expr(Some(label),
2602 BlockCheckMode::Default,
2605 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2606 let mut err = self.fatal(msg);
2607 err.span_label(self.span, msg);
2610 if self.eat_keyword(keywords::Loop) {
2611 let lo = self.prev_span;
2612 return self.parse_loop_expr(None, lo, attrs);
2614 if self.eat_keyword(keywords::Continue) {
2615 let label = self.eat_label();
2616 let ex = ExprKind::Continue(label);
2617 let hi = self.prev_span;
2618 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2620 if self.eat_keyword(keywords::Match) {
2621 let match_sp = self.prev_span;
2622 return self.parse_match_expr(attrs).map_err(|mut err| {
2623 err.span_label(match_sp, "while parsing this match expression");
2627 if self.eat_keyword(keywords::Unsafe) {
2628 return self.parse_block_expr(
2631 BlockCheckMode::Unsafe(ast::UserProvided),
2634 if self.is_do_catch_block() {
2635 let mut db = self.fatal("found removed `do catch` syntax");
2636 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2639 if self.is_try_block() {
2641 assert!(self.eat_keyword(keywords::Try));
2642 return self.parse_try_block(lo, attrs);
2644 if self.eat_keyword(keywords::Return) {
2645 if self.token.can_begin_expr() {
2646 let e = self.parse_expr()?;
2648 ex = ExprKind::Ret(Some(e));
2650 ex = ExprKind::Ret(None);
2652 } else if self.eat_keyword(keywords::Break) {
2653 let label = self.eat_label();
2654 let e = if self.token.can_begin_expr()
2655 && !(self.token == token::OpenDelim(token::Brace)
2656 && self.restrictions.contains(
2657 Restrictions::NO_STRUCT_LITERAL)) {
2658 Some(self.parse_expr()?)
2662 ex = ExprKind::Break(label, e);
2663 hi = self.prev_span;
2664 } else if self.eat_keyword(keywords::Yield) {
2665 if self.token.can_begin_expr() {
2666 let e = self.parse_expr()?;
2668 ex = ExprKind::Yield(Some(e));
2670 ex = ExprKind::Yield(None);
2672 } else if self.token.is_keyword(keywords::Let) {
2673 // Catch this syntax error here, instead of in `parse_ident`, so
2674 // that we can explicitly mention that let is not to be used as an expression
2675 let mut db = self.fatal("expected expression, found statement (`let`)");
2676 db.span_label(self.span, "expected expression");
2677 db.note("variable declaration using `let` is a statement");
2679 } else if self.token.is_path_start() {
2680 let pth = self.parse_path(PathStyle::Expr)?;
2682 // `!`, as an operator, is prefix, so we know this isn't that
2683 if self.eat(&token::Not) {
2684 // MACRO INVOCATION expression
2685 let (delim, tts) = self.expect_delimited_token_tree()?;
2686 let hi = self.prev_span;
2687 let node = Mac_ { path: pth, tts, delim };
2688 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2690 if self.check(&token::OpenDelim(token::Brace)) {
2691 // This is a struct literal, unless we're prohibited
2692 // from parsing struct literals here.
2693 let prohibited = self.restrictions.contains(
2694 Restrictions::NO_STRUCT_LITERAL
2697 return self.parse_struct_expr(lo, pth, attrs);
2702 ex = ExprKind::Path(None, pth);
2704 match self.parse_literal_maybe_minus() {
2707 ex = expr.node.clone();
2710 self.cancel(&mut err);
2711 let msg = format!("expected expression, found {}",
2712 self.this_token_descr());
2713 let mut err = self.fatal(&msg);
2714 err.span_label(self.span, "expected expression");
2722 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2723 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2728 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2729 -> PResult<'a, P<Expr>> {
2730 let struct_sp = lo.to(self.prev_span);
2732 let mut fields = Vec::new();
2733 let mut base = None;
2735 attrs.extend(self.parse_inner_attributes()?);
2737 while self.token != token::CloseDelim(token::Brace) {
2738 if self.eat(&token::DotDot) {
2739 let exp_span = self.prev_span;
2740 match self.parse_expr() {
2746 self.recover_stmt();
2749 if self.token == token::Comma {
2750 let mut err = self.sess.span_diagnostic.mut_span_err(
2751 exp_span.to(self.prev_span),
2752 "cannot use a comma after the base struct",
2754 err.span_suggestion_short_with_applicability(
2756 "remove this comma",
2758 Applicability::MachineApplicable
2760 err.note("the base struct must always be the last field");
2762 self.recover_stmt();
2767 let mut recovery_field = None;
2768 if let token::Ident(ident, _) = self.token {
2769 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2770 // Use in case of error after field-looking code: `S { foo: () with a }`
2771 let mut ident = ident.clone();
2772 ident.span = self.span;
2773 recovery_field = Some(ast::Field {
2776 expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
2777 is_shorthand: false,
2778 attrs: ThinVec::new(),
2782 let mut parsed_field = None;
2783 match self.parse_field() {
2784 Ok(f) => parsed_field = Some(f),
2786 e.span_label(struct_sp, "while parsing this struct");
2789 // If the next token is a comma, then try to parse
2790 // what comes next as additional fields, rather than
2791 // bailing out until next `}`.
2792 if self.token != token::Comma {
2793 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2794 if self.token != token::Comma {
2801 match self.expect_one_of(&[token::Comma],
2802 &[token::CloseDelim(token::Brace)]) {
2803 Ok(()) => if let Some(f) = parsed_field.or(recovery_field) {
2804 // only include the field if there's no parse error for the field name
2808 if let Some(f) = recovery_field {
2811 e.span_label(struct_sp, "while parsing this struct");
2813 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2814 self.eat(&token::Comma);
2819 let span = lo.to(self.span);
2820 self.expect(&token::CloseDelim(token::Brace))?;
2821 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2824 fn parse_or_use_outer_attributes(&mut self,
2825 already_parsed_attrs: Option<ThinVec<Attribute>>)
2826 -> PResult<'a, ThinVec<Attribute>> {
2827 if let Some(attrs) = already_parsed_attrs {
2830 self.parse_outer_attributes().map(|a| a.into())
2834 /// Parse a block or unsafe block
2835 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2836 lo: Span, blk_mode: BlockCheckMode,
2837 outer_attrs: ThinVec<Attribute>)
2838 -> PResult<'a, P<Expr>> {
2839 self.expect(&token::OpenDelim(token::Brace))?;
2841 let mut attrs = outer_attrs;
2842 attrs.extend(self.parse_inner_attributes()?);
2844 let blk = self.parse_block_tail(lo, blk_mode)?;
2845 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2848 /// parse a.b or a(13) or a[4] or just a
2849 fn parse_dot_or_call_expr(&mut self,
2850 already_parsed_attrs: Option<ThinVec<Attribute>>)
2851 -> PResult<'a, P<Expr>> {
2852 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2854 let b = self.parse_bottom_expr();
2855 let (span, b) = self.interpolated_or_expr_span(b)?;
2856 self.parse_dot_or_call_expr_with(b, span, attrs)
2859 fn parse_dot_or_call_expr_with(&mut self,
2862 mut attrs: ThinVec<Attribute>)
2863 -> PResult<'a, P<Expr>> {
2864 // Stitch the list of outer attributes onto the return value.
2865 // A little bit ugly, but the best way given the current code
2867 self.parse_dot_or_call_expr_with_(e0, lo)
2869 expr.map(|mut expr| {
2870 attrs.extend::<Vec<_>>(expr.attrs.into());
2873 ExprKind::If(..) | ExprKind::IfLet(..) => {
2874 if !expr.attrs.is_empty() {
2875 // Just point to the first attribute in there...
2876 let span = expr.attrs[0].span;
2879 "attributes are not yet allowed on `if` \
2890 // Assuming we have just parsed `.`, continue parsing into an expression.
2891 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2892 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2893 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
2895 Ok(match self.token {
2896 token::OpenDelim(token::Paren) => {
2897 // Method call `expr.f()`
2898 let mut args = self.parse_unspanned_seq(
2899 &token::OpenDelim(token::Paren),
2900 &token::CloseDelim(token::Paren),
2901 SeqSep::trailing_allowed(token::Comma),
2902 |p| Ok(p.parse_expr()?)
2904 args.insert(0, self_arg);
2906 let span = lo.to(self.prev_span);
2907 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2910 // Field access `expr.f`
2911 if let Some(args) = segment.args {
2912 self.span_err(args.span(),
2913 "field expressions may not have generic arguments");
2916 let span = lo.to(self.prev_span);
2917 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2922 /// This function checks if there are trailing angle brackets and produces
2923 /// a diagnostic to suggest removing them.
2925 /// ```ignore (diagnostic)
2926 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
2927 /// ^^ help: remove extra angle brackets
2929 fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) {
2930 // This function is intended to be invoked after parsing a path segment where there are two
2933 // 1. A specific token is expected after the path segment.
2934 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
2935 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
2936 // 2. No specific token is expected after the path segment.
2937 // eg. `x.foo` (field access)
2939 // This function is called after parsing `.foo` and before parsing the token `end` (if
2940 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
2943 // We only care about trailing angle brackets if we previously parsed angle bracket
2944 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
2945 // removed in this case:
2947 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
2949 // This case is particularly tricky as we won't notice it just looking at the tokens -
2950 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
2951 // have already been parsed):
2953 // `x.foo::<u32>>>(3)`
2954 let parsed_angle_bracket_args = segment.args
2956 .map(|args| args.is_angle_bracketed())
2960 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
2961 parsed_angle_bracket_args,
2963 if !parsed_angle_bracket_args {
2967 // Keep the span at the start so we can highlight the sequence of `>` characters to be
2971 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
2972 // (since we might have the field access case and the characters we're eating are
2973 // actual operators and not trailing characters - ie `x.foo >> 3`).
2974 let mut position = 0;
2976 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
2977 // many of each (so we can correctly pluralize our error messages) and continue to
2979 let mut number_of_shr = 0;
2980 let mut number_of_gt = 0;
2981 while self.look_ahead(position, |t| {
2982 trace!("check_trailing_angle_brackets: t={:?}", t);
2983 if *t == token::BinOp(token::BinOpToken::Shr) {
2986 } else if *t == token::Gt {
2996 // If we didn't find any trailing `>` characters, then we have nothing to error about.
2998 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
2999 number_of_gt, number_of_shr,
3001 if number_of_gt < 1 && number_of_shr < 1 {
3005 // Finally, double check that we have our end token as otherwise this is the
3007 if self.look_ahead(position, |t| {
3008 trace!("check_trailing_angle_brackets: t={:?}", t);
3011 // Eat from where we started until the end token so that parsing can continue
3012 // as if we didn't have those extra angle brackets.
3013 self.eat_to_tokens(&[&end]);
3014 let span = lo.until(self.span);
3016 let plural = number_of_gt > 1 || number_of_shr >= 1;
3020 &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
3022 .span_suggestion_with_applicability(
3024 &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
3026 Applicability::MachineApplicable,
3032 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3037 while self.eat(&token::Question) {
3038 let hi = self.prev_span;
3039 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
3043 if self.eat(&token::Dot) {
3045 token::Ident(..) => {
3046 e = self.parse_dot_suffix(e, lo)?;
3048 token::Literal(token::Integer(name), _) => {
3049 let span = self.span;
3051 let field = ExprKind::Field(e, Ident::new(name, span));
3052 e = self.mk_expr(lo.to(span), field, ThinVec::new());
3054 token::Literal(token::Float(n), _suf) => {
3056 let fstr = n.as_str();
3057 let mut err = self.diagnostic()
3058 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
3059 err.span_label(self.prev_span, "unexpected token");
3060 if fstr.chars().all(|x| "0123456789.".contains(x)) {
3061 let float = match fstr.parse::<f64>().ok() {
3065 let sugg = pprust::to_string(|s| {
3066 use print::pprust::PrintState;
3070 s.print_usize(float.trunc() as usize)?;
3073 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
3075 err.span_suggestion_with_applicability(
3076 lo.to(self.prev_span),
3077 "try parenthesizing the first index",
3079 Applicability::MachineApplicable
3086 // FIXME Could factor this out into non_fatal_unexpected or something.
3087 let actual = self.this_token_to_string();
3088 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
3093 if self.expr_is_complete(&e) { break; }
3096 token::OpenDelim(token::Paren) => {
3097 let es = self.parse_unspanned_seq(
3098 &token::OpenDelim(token::Paren),
3099 &token::CloseDelim(token::Paren),
3100 SeqSep::trailing_allowed(token::Comma),
3101 |p| Ok(p.parse_expr()?)
3103 hi = self.prev_span;
3105 let nd = self.mk_call(e, es);
3106 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
3110 // Could be either an index expression or a slicing expression.
3111 token::OpenDelim(token::Bracket) => {
3113 let ix = self.parse_expr()?;
3115 self.expect(&token::CloseDelim(token::Bracket))?;
3116 let index = self.mk_index(e, ix);
3117 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
3125 crate fn process_potential_macro_variable(&mut self) {
3126 let (token, span) = match self.token {
3127 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
3128 self.look_ahead(1, |t| t.is_ident()) => {
3130 let name = match self.token {
3131 token::Ident(ident, _) => ident,
3134 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
3135 err.span_label(self.span, "unknown macro variable");
3140 token::Interpolated(ref nt) => {
3141 self.meta_var_span = Some(self.span);
3142 // Interpolated identifier and lifetime tokens are replaced with usual identifier
3143 // and lifetime tokens, so the former are never encountered during normal parsing.
3145 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
3146 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
3156 /// parse a single token tree from the input.
3157 crate fn parse_token_tree(&mut self) -> TokenTree {
3159 token::OpenDelim(..) => {
3160 let frame = mem::replace(&mut self.token_cursor.frame,
3161 self.token_cursor.stack.pop().unwrap());
3162 self.span = frame.span.entire();
3164 TokenTree::Delimited(
3167 frame.tree_cursor.stream.into(),
3170 token::CloseDelim(_) | token::Eof => unreachable!(),
3172 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
3174 TokenTree::Token(span, token)
3179 // parse a stream of tokens into a list of TokenTree's,
3181 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
3182 let mut tts = Vec::new();
3183 while self.token != token::Eof {
3184 tts.push(self.parse_token_tree());
3189 pub fn parse_tokens(&mut self) -> TokenStream {
3190 let mut result = Vec::new();
3193 token::Eof | token::CloseDelim(..) => break,
3194 _ => result.push(self.parse_token_tree().into()),
3197 TokenStream::new(result)
3200 /// Parse a prefix-unary-operator expr
3201 fn parse_prefix_expr(&mut self,
3202 already_parsed_attrs: Option<ThinVec<Attribute>>)
3203 -> PResult<'a, P<Expr>> {
3204 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3206 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
3207 let (hi, ex) = match self.token {
3210 let e = self.parse_prefix_expr(None);
3211 let (span, e) = self.interpolated_or_expr_span(e)?;
3212 (lo.to(span), self.mk_unary(UnOp::Not, e))
3214 // Suggest `!` for bitwise negation when encountering a `~`
3217 let e = self.parse_prefix_expr(None);
3218 let (span, e) = self.interpolated_or_expr_span(e)?;
3219 let span_of_tilde = lo;
3220 let mut err = self.diagnostic()
3221 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
3222 err.span_suggestion_short_with_applicability(
3224 "use `!` to perform bitwise negation",
3226 Applicability::MachineApplicable
3229 (lo.to(span), self.mk_unary(UnOp::Not, e))
3231 token::BinOp(token::Minus) => {
3233 let e = self.parse_prefix_expr(None);
3234 let (span, e) = self.interpolated_or_expr_span(e)?;
3235 (lo.to(span), self.mk_unary(UnOp::Neg, e))
3237 token::BinOp(token::Star) => {
3239 let e = self.parse_prefix_expr(None);
3240 let (span, e) = self.interpolated_or_expr_span(e)?;
3241 (lo.to(span), self.mk_unary(UnOp::Deref, e))
3243 token::BinOp(token::And) | token::AndAnd => {
3245 let m = self.parse_mutability();
3246 let e = self.parse_prefix_expr(None);
3247 let (span, e) = self.interpolated_or_expr_span(e)?;
3248 (lo.to(span), ExprKind::AddrOf(m, e))
3250 token::Ident(..) if self.token.is_keyword(keywords::In) => {
3252 let place = self.parse_expr_res(
3253 Restrictions::NO_STRUCT_LITERAL,
3256 let blk = self.parse_block()?;
3257 let span = blk.span;
3258 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
3259 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
3261 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
3263 let e = self.parse_prefix_expr(None);
3264 let (span, e) = self.interpolated_or_expr_span(e)?;
3265 (lo.to(span), ExprKind::Box(e))
3267 token::Ident(..) if self.token.is_ident_named("not") => {
3268 // `not` is just an ordinary identifier in Rust-the-language,
3269 // but as `rustc`-the-compiler, we can issue clever diagnostics
3270 // for confused users who really want to say `!`
3271 let token_cannot_continue_expr = |t: &token::Token| match *t {
3272 // These tokens can start an expression after `!`, but
3273 // can't continue an expression after an ident
3274 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3275 token::Literal(..) | token::Pound => true,
3276 token::Interpolated(ref nt) => match nt.0 {
3277 token::NtIdent(..) | token::NtExpr(..) |
3278 token::NtBlock(..) | token::NtPath(..) => true,
3283 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3284 if cannot_continue_expr {
3286 // Emit the error ...
3287 let mut err = self.diagnostic()
3288 .struct_span_err(self.span,
3289 &format!("unexpected {} after identifier",
3290 self.this_token_descr()));
3291 // span the `not` plus trailing whitespace to avoid
3292 // trailing whitespace after the `!` in our suggestion
3293 let to_replace = self.sess.source_map()
3294 .span_until_non_whitespace(lo.to(self.span));
3295 err.span_suggestion_short_with_applicability(
3297 "use `!` to perform logical negation",
3299 Applicability::MachineApplicable
3302 // —and recover! (just as if we were in the block
3303 // for the `token::Not` arm)
3304 let e = self.parse_prefix_expr(None);
3305 let (span, e) = self.interpolated_or_expr_span(e)?;
3306 (lo.to(span), self.mk_unary(UnOp::Not, e))
3308 return self.parse_dot_or_call_expr(Some(attrs));
3311 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3313 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3316 /// Parse an associative expression
3318 /// This parses an expression accounting for associativity and precedence of the operators in
3321 fn parse_assoc_expr(&mut self,
3322 already_parsed_attrs: Option<ThinVec<Attribute>>)
3323 -> PResult<'a, P<Expr>> {
3324 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3327 /// Parse an associative expression with operators of at least `min_prec` precedence
3328 fn parse_assoc_expr_with(&mut self,
3331 -> PResult<'a, P<Expr>> {
3332 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3335 let attrs = match lhs {
3336 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3339 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3340 return self.parse_prefix_range_expr(attrs);
3342 self.parse_prefix_expr(attrs)?
3346 if self.expr_is_complete(&lhs) {
3347 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3350 self.expected_tokens.push(TokenType::Operator);
3351 while let Some(op) = AssocOp::from_token(&self.token) {
3353 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3354 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3355 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3356 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3357 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3358 (PrevTokenKind::Interpolated, _) => self.prev_span,
3359 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3360 if path.segments.len() == 1 => self.prev_span,
3364 let cur_op_span = self.span;
3365 let restrictions = if op.is_assign_like() {
3366 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3370 if op.precedence() < min_prec {
3373 // Check for deprecated `...` syntax
3374 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3375 self.err_dotdotdot_syntax(self.span);
3379 if op.is_comparison() {
3380 self.check_no_chained_comparison(&lhs, &op);
3383 if op == AssocOp::As {
3384 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3386 } else if op == AssocOp::Colon {
3387 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3390 err.span_label(self.span,
3391 "expecting a type here because of type ascription");
3392 let cm = self.sess.source_map();
3393 let cur_pos = cm.lookup_char_pos(self.span.lo());
3394 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3395 if cur_pos.line != op_pos.line {
3396 err.span_suggestion_with_applicability(
3398 "try using a semicolon",
3400 Applicability::MaybeIncorrect // speculative
3407 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3408 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3409 // generalise it to the Fixity::None code.
3411 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3412 // two variants are handled with `parse_prefix_range_expr` call above.
3413 let rhs = if self.is_at_start_of_range_notation_rhs() {
3414 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3415 LhsExpr::NotYetParsed)?)
3419 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3424 let limits = if op == AssocOp::DotDot {
3425 RangeLimits::HalfOpen
3430 let r = self.mk_range(Some(lhs), rhs, limits)?;
3431 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3435 let rhs = match op.fixity() {
3436 Fixity::Right => self.with_res(
3437 restrictions - Restrictions::STMT_EXPR,
3439 this.parse_assoc_expr_with(op.precedence(),
3440 LhsExpr::NotYetParsed)
3442 Fixity::Left => self.with_res(
3443 restrictions - Restrictions::STMT_EXPR,
3445 this.parse_assoc_expr_with(op.precedence() + 1,
3446 LhsExpr::NotYetParsed)
3448 // We currently have no non-associative operators that are not handled above by
3449 // the special cases. The code is here only for future convenience.
3450 Fixity::None => self.with_res(
3451 restrictions - Restrictions::STMT_EXPR,
3453 this.parse_assoc_expr_with(op.precedence() + 1,
3454 LhsExpr::NotYetParsed)
3458 let span = lhs_span.to(rhs.span);
3460 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3461 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3462 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3463 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3464 AssocOp::Greater | AssocOp::GreaterEqual => {
3465 let ast_op = op.to_ast_binop().unwrap();
3466 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3467 self.mk_expr(span, binary, ThinVec::new())
3470 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3471 AssocOp::ObsoleteInPlace =>
3472 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3473 AssocOp::AssignOp(k) => {
3475 token::Plus => BinOpKind::Add,
3476 token::Minus => BinOpKind::Sub,
3477 token::Star => BinOpKind::Mul,
3478 token::Slash => BinOpKind::Div,
3479 token::Percent => BinOpKind::Rem,
3480 token::Caret => BinOpKind::BitXor,
3481 token::And => BinOpKind::BitAnd,
3482 token::Or => BinOpKind::BitOr,
3483 token::Shl => BinOpKind::Shl,
3484 token::Shr => BinOpKind::Shr,
3486 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3487 self.mk_expr(span, aopexpr, ThinVec::new())
3489 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3490 self.bug("AssocOp should have been handled by special case")
3494 if op.fixity() == Fixity::None { break }
3499 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3500 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3501 -> PResult<'a, P<Expr>> {
3502 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3503 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3506 // Save the state of the parser before parsing type normally, in case there is a
3507 // LessThan comparison after this cast.
3508 let parser_snapshot_before_type = self.clone();
3509 match self.parse_ty_no_plus() {
3511 Ok(mk_expr(self, rhs))
3513 Err(mut type_err) => {
3514 // Rewind to before attempting to parse the type with generics, to recover
3515 // from situations like `x as usize < y` in which we first tried to parse
3516 // `usize < y` as a type with generic arguments.
3517 let parser_snapshot_after_type = self.clone();
3518 mem::replace(self, parser_snapshot_before_type);
3520 match self.parse_path(PathStyle::Expr) {
3522 let (op_noun, op_verb) = match self.token {
3523 token::Lt => ("comparison", "comparing"),
3524 token::BinOp(token::Shl) => ("shift", "shifting"),
3526 // We can end up here even without `<` being the next token, for
3527 // example because `parse_ty_no_plus` returns `Err` on keywords,
3528 // but `parse_path` returns `Ok` on them due to error recovery.
3529 // Return original error and parser state.
3530 mem::replace(self, parser_snapshot_after_type);
3531 return Err(type_err);
3535 // Successfully parsed the type path leaving a `<` yet to parse.
3538 // Report non-fatal diagnostics, keep `x as usize` as an expression
3539 // in AST and continue parsing.
3540 let msg = format!("`<` is interpreted as a start of generic \
3541 arguments for `{}`, not a {}", path, op_noun);
3542 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3543 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3544 "interpreted as generic arguments");
3545 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3547 let expr = mk_expr(self, P(Ty {
3549 node: TyKind::Path(None, path),
3550 id: ast::DUMMY_NODE_ID
3553 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3554 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3555 err.span_suggestion_with_applicability(
3557 &format!("try {} the cast value", op_verb),
3558 format!("({})", expr_str),
3559 Applicability::MachineApplicable
3565 Err(mut path_err) => {
3566 // Couldn't parse as a path, return original error and parser state.
3568 mem::replace(self, parser_snapshot_after_type);
3576 /// Produce an error if comparison operators are chained (RFC #558).
3577 /// We only need to check lhs, not rhs, because all comparison ops
3578 /// have same precedence and are left-associative
3579 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3580 debug_assert!(outer_op.is_comparison(),
3581 "check_no_chained_comparison: {:?} is not comparison",
3584 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3585 // respan to include both operators
3586 let op_span = op.span.to(self.span);
3587 let mut err = self.diagnostic().struct_span_err(op_span,
3588 "chained comparison operators require parentheses");
3589 if op.node == BinOpKind::Lt &&
3590 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3591 *outer_op == AssocOp::Greater // even in a case like the following:
3592 { // Foo<Bar<Baz<Qux, ()>>>
3594 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3595 err.help("or use `(...)` if you meant to specify fn arguments");
3603 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3604 fn parse_prefix_range_expr(&mut self,
3605 already_parsed_attrs: Option<ThinVec<Attribute>>)
3606 -> PResult<'a, P<Expr>> {
3607 // Check for deprecated `...` syntax
3608 if self.token == token::DotDotDot {
3609 self.err_dotdotdot_syntax(self.span);
3612 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3613 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3615 let tok = self.token.clone();
3616 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3618 let mut hi = self.span;
3620 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3621 // RHS must be parsed with more associativity than the dots.
3622 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3623 Some(self.parse_assoc_expr_with(next_prec,
3624 LhsExpr::NotYetParsed)
3632 let limits = if tok == token::DotDot {
3633 RangeLimits::HalfOpen
3638 let r = self.mk_range(None, opt_end, limits)?;
3639 Ok(self.mk_expr(lo.to(hi), r, attrs))
3642 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3643 if self.token.can_begin_expr() {
3644 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3645 if self.token == token::OpenDelim(token::Brace) {
3646 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3654 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3655 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3656 if self.check_keyword(keywords::Let) {
3657 return self.parse_if_let_expr(attrs);
3659 let lo = self.prev_span;
3660 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3662 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3663 // verify that the last statement is either an implicit return (no `;`) or an explicit
3664 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3665 // the dead code lint.
3666 if self.eat_keyword(keywords::Else) || !cond.returns() {
3667 let sp = self.sess.source_map().next_point(lo);
3668 let mut err = self.diagnostic()
3669 .struct_span_err(sp, "missing condition for `if` statemement");
3670 err.span_label(sp, "expected if condition here");
3673 let not_block = self.token != token::OpenDelim(token::Brace);
3674 let thn = self.parse_block().map_err(|mut err| {
3676 err.span_label(lo, "this `if` statement has a condition, but no block");
3680 let mut els: Option<P<Expr>> = None;
3681 let mut hi = thn.span;
3682 if self.eat_keyword(keywords::Else) {
3683 let elexpr = self.parse_else_expr()?;
3687 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3690 /// Parse an 'if let' expression ('if' token already eaten)
3691 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3692 -> PResult<'a, P<Expr>> {
3693 let lo = self.prev_span;
3694 self.expect_keyword(keywords::Let)?;
3695 let pats = self.parse_pats()?;
3696 self.expect(&token::Eq)?;
3697 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3698 let thn = self.parse_block()?;
3699 let (hi, els) = if self.eat_keyword(keywords::Else) {
3700 let expr = self.parse_else_expr()?;
3701 (expr.span, Some(expr))
3705 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3708 // `move |args| expr`
3709 fn parse_lambda_expr(&mut self,
3710 attrs: ThinVec<Attribute>)
3711 -> PResult<'a, P<Expr>>
3714 let movability = if self.eat_keyword(keywords::Static) {
3719 let asyncness = if self.span.rust_2018() {
3720 self.parse_asyncness()
3724 let capture_clause = if self.eat_keyword(keywords::Move) {
3729 let decl = self.parse_fn_block_decl()?;
3730 let decl_hi = self.prev_span;
3731 let body = match decl.output {
3732 FunctionRetTy::Default(_) => {
3733 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3734 self.parse_expr_res(restrictions, None)?
3737 // If an explicit return type is given, require a
3738 // block to appear (RFC 968).
3739 let body_lo = self.span;
3740 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3746 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3750 // `else` token already eaten
3751 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3752 if self.eat_keyword(keywords::If) {
3753 return self.parse_if_expr(ThinVec::new());
3755 let blk = self.parse_block()?;
3756 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3760 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3761 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3763 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3764 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3766 let pat = self.parse_top_level_pat()?;
3767 if !self.eat_keyword(keywords::In) {
3768 let in_span = self.prev_span.between(self.span);
3769 let mut err = self.sess.span_diagnostic
3770 .struct_span_err(in_span, "missing `in` in `for` loop");
3771 err.span_suggestion_short_with_applicability(
3772 in_span, "try adding `in` here", " in ".into(),
3773 // has been misleading, at least in the past (closed Issue #48492)
3774 Applicability::MaybeIncorrect
3778 let in_span = self.prev_span;
3779 if self.eat_keyword(keywords::In) {
3780 // a common typo: `for _ in in bar {}`
3781 let mut err = self.sess.span_diagnostic.struct_span_err(
3783 "expected iterable, found keyword `in`",
3785 err.span_suggestion_short_with_applicability(
3786 in_span.until(self.prev_span),
3787 "remove the duplicated `in`",
3789 Applicability::MachineApplicable,
3791 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
3792 err.note("for more information on the status of emplacement syntax, see <\
3793 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
3796 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3797 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3798 attrs.extend(iattrs);
3800 let hi = self.prev_span;
3801 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3804 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3805 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3807 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3808 if self.token.is_keyword(keywords::Let) {
3809 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3811 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3812 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3813 attrs.extend(iattrs);
3814 let span = span_lo.to(body.span);
3815 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3818 /// Parse a 'while let' expression ('while' token already eaten)
3819 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3821 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3822 self.expect_keyword(keywords::Let)?;
3823 let pats = self.parse_pats()?;
3824 self.expect(&token::Eq)?;
3825 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3826 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3827 attrs.extend(iattrs);
3828 let span = span_lo.to(body.span);
3829 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3832 // parse `loop {...}`, `loop` token already eaten
3833 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3835 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3836 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3837 attrs.extend(iattrs);
3838 let span = span_lo.to(body.span);
3839 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3842 /// Parse an `async move {...}` expression
3843 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3844 -> PResult<'a, P<Expr>>
3846 let span_lo = self.span;
3847 self.expect_keyword(keywords::Async)?;
3848 let capture_clause = if self.eat_keyword(keywords::Move) {
3853 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3854 attrs.extend(iattrs);
3856 span_lo.to(body.span),
3857 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3860 /// Parse a `try {...}` expression (`try` token already eaten)
3861 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3862 -> PResult<'a, P<Expr>>
3864 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3865 attrs.extend(iattrs);
3866 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
3869 // `match` token already eaten
3870 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3871 let match_span = self.prev_span;
3872 let lo = self.prev_span;
3873 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3875 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3876 if self.token == token::Token::Semi {
3877 e.span_suggestion_short_with_applicability(
3879 "try removing this `match`",
3881 Applicability::MaybeIncorrect // speculative
3886 attrs.extend(self.parse_inner_attributes()?);
3888 let mut arms: Vec<Arm> = Vec::new();
3889 while self.token != token::CloseDelim(token::Brace) {
3890 match self.parse_arm() {
3891 Ok(arm) => arms.push(arm),
3893 // Recover by skipping to the end of the block.
3895 self.recover_stmt();
3896 let span = lo.to(self.span);
3897 if self.token == token::CloseDelim(token::Brace) {
3900 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3906 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3909 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3910 maybe_whole!(self, NtArm, |x| x);
3912 let attrs = self.parse_outer_attributes()?;
3913 let pats = self.parse_pats()?;
3914 let guard = if self.eat_keyword(keywords::If) {
3915 Some(Guard::If(self.parse_expr()?))
3919 let arrow_span = self.span;
3920 self.expect(&token::FatArrow)?;
3921 let arm_start_span = self.span;
3923 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3924 .map_err(|mut err| {
3925 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3929 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3930 && self.token != token::CloseDelim(token::Brace);
3933 let cm = self.sess.source_map();
3934 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3935 .map_err(|mut err| {
3936 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3937 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3938 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3939 && expr_lines.lines.len() == 2
3940 && self.token == token::FatArrow => {
3941 // We check whether there's any trailing code in the parse span,
3942 // if there isn't, we very likely have the following:
3945 // | -- - missing comma
3951 // | parsed until here as `"y" & X`
3952 err.span_suggestion_short_with_applicability(
3953 cm.next_point(arm_start_span),
3954 "missing a comma here to end this `match` arm",
3956 Applicability::MachineApplicable
3960 err.span_label(arrow_span,
3961 "while parsing the `match` arm starting here");
3967 self.eat(&token::Comma);
3978 /// Parse an expression
3980 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3981 self.parse_expr_res(Restrictions::empty(), None)
3984 /// Evaluate the closure with restrictions in place.
3986 /// After the closure is evaluated, restrictions are reset.
3987 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3988 where F: FnOnce(&mut Self) -> T
3990 let old = self.restrictions;
3991 self.restrictions = r;
3993 self.restrictions = old;
3998 /// Parse an expression, subject to the given restrictions
4000 fn parse_expr_res(&mut self, r: Restrictions,
4001 already_parsed_attrs: Option<ThinVec<Attribute>>)
4002 -> PResult<'a, P<Expr>> {
4003 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
4006 /// Parse the RHS of a local variable declaration (e.g., '= 14;')
4007 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
4008 if self.eat(&token::Eq) {
4009 Ok(Some(self.parse_expr()?))
4011 Ok(Some(self.parse_expr()?))
4017 /// Parse patterns, separated by '|' s
4018 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
4019 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
4020 self.eat(&token::BinOp(token::Or));
4022 let mut pats = Vec::new();
4024 pats.push(self.parse_top_level_pat()?);
4026 if self.token == token::OrOr {
4027 let mut err = self.struct_span_err(self.span,
4028 "unexpected token `||` after pattern");
4029 err.span_suggestion_with_applicability(
4031 "use a single `|` to specify multiple patterns",
4033 Applicability::MachineApplicable
4037 } else if self.eat(&token::BinOp(token::Or)) {
4045 // Parses a parenthesized list of patterns like
4046 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
4047 // - a vector of the patterns that were parsed
4048 // - an option indicating the index of the `..` element
4049 // - a boolean indicating whether a trailing comma was present.
4050 // Trailing commas are significant because (p) and (p,) are different patterns.
4051 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4052 self.expect(&token::OpenDelim(token::Paren))?;
4053 let result = self.parse_pat_list()?;
4054 self.expect(&token::CloseDelim(token::Paren))?;
4058 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4059 let mut fields = Vec::new();
4060 let mut ddpos = None;
4061 let mut trailing_comma = false;
4063 if self.eat(&token::DotDot) {
4064 if ddpos.is_none() {
4065 ddpos = Some(fields.len());
4067 // Emit a friendly error, ignore `..` and continue parsing
4068 self.struct_span_err(
4070 "`..` can only be used once per tuple or tuple struct pattern",
4072 .span_label(self.prev_span, "can only be used once per pattern")
4075 } else if !self.check(&token::CloseDelim(token::Paren)) {
4076 fields.push(self.parse_pat(None)?);
4081 trailing_comma = self.eat(&token::Comma);
4082 if !trailing_comma {
4087 if ddpos == Some(fields.len()) && trailing_comma {
4088 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
4089 let msg = "trailing comma is not permitted after `..`";
4090 self.struct_span_err(self.prev_span, msg)
4091 .span_label(self.prev_span, msg)
4095 Ok((fields, ddpos, trailing_comma))
4098 fn parse_pat_vec_elements(
4100 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
4101 let mut before = Vec::new();
4102 let mut slice = None;
4103 let mut after = Vec::new();
4104 let mut first = true;
4105 let mut before_slice = true;
4107 while self.token != token::CloseDelim(token::Bracket) {
4111 self.expect(&token::Comma)?;
4113 if self.token == token::CloseDelim(token::Bracket)
4114 && (before_slice || !after.is_empty()) {
4120 if self.eat(&token::DotDot) {
4122 if self.check(&token::Comma) ||
4123 self.check(&token::CloseDelim(token::Bracket)) {
4124 slice = Some(P(Pat {
4125 id: ast::DUMMY_NODE_ID,
4126 node: PatKind::Wild,
4127 span: self.prev_span,
4129 before_slice = false;
4135 let subpat = self.parse_pat(None)?;
4136 if before_slice && self.eat(&token::DotDot) {
4137 slice = Some(subpat);
4138 before_slice = false;
4139 } else if before_slice {
4140 before.push(subpat);
4146 Ok((before, slice, after))
4152 attrs: Vec<Attribute>
4153 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
4154 // Check if a colon exists one ahead. This means we're parsing a fieldname.
4156 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
4157 // Parsing a pattern of the form "fieldname: pat"
4158 let fieldname = self.parse_field_name()?;
4160 let pat = self.parse_pat(None)?;
4162 (pat, fieldname, false)
4164 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
4165 let is_box = self.eat_keyword(keywords::Box);
4166 let boxed_span = self.span;
4167 let is_ref = self.eat_keyword(keywords::Ref);
4168 let is_mut = self.eat_keyword(keywords::Mut);
4169 let fieldname = self.parse_ident()?;
4170 hi = self.prev_span;
4172 let bind_type = match (is_ref, is_mut) {
4173 (true, true) => BindingMode::ByRef(Mutability::Mutable),
4174 (true, false) => BindingMode::ByRef(Mutability::Immutable),
4175 (false, true) => BindingMode::ByValue(Mutability::Mutable),
4176 (false, false) => BindingMode::ByValue(Mutability::Immutable),
4178 let fieldpat = P(Pat {
4179 id: ast::DUMMY_NODE_ID,
4180 node: PatKind::Ident(bind_type, fieldname, None),
4181 span: boxed_span.to(hi),
4184 let subpat = if is_box {
4186 id: ast::DUMMY_NODE_ID,
4187 node: PatKind::Box(fieldpat),
4193 (subpat, fieldname, true)
4196 Ok(source_map::Spanned {
4198 node: ast::FieldPat {
4202 attrs: attrs.into(),
4207 /// Parse the fields of a struct-like pattern
4208 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
4209 let mut fields = Vec::new();
4210 let mut etc = false;
4211 let mut ate_comma = true;
4212 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
4213 let mut etc_span = None;
4215 while self.token != token::CloseDelim(token::Brace) {
4216 let attrs = self.parse_outer_attributes()?;
4219 // check that a comma comes after every field
4221 let err = self.struct_span_err(self.prev_span, "expected `,`");
4222 if let Some(mut delayed) = delayed_err {
4229 if self.check(&token::DotDot) || self.token == token::DotDotDot {
4231 let mut etc_sp = self.span;
4233 if self.token == token::DotDotDot { // Issue #46718
4234 // Accept `...` as if it were `..` to avoid further errors
4235 let mut err = self.struct_span_err(self.span,
4236 "expected field pattern, found `...`");
4237 err.span_suggestion_with_applicability(
4239 "to omit remaining fields, use one fewer `.`",
4241 Applicability::MachineApplicable
4245 self.bump(); // `..` || `...`
4247 if self.token == token::CloseDelim(token::Brace) {
4248 etc_span = Some(etc_sp);
4251 let token_str = self.this_token_descr();
4252 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
4254 err.span_label(self.span, "expected `}`");
4255 let mut comma_sp = None;
4256 if self.token == token::Comma { // Issue #49257
4257 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
4258 err.span_label(etc_sp,
4259 "`..` must be at the end and cannot have a trailing comma");
4260 comma_sp = Some(self.span);
4265 etc_span = Some(etc_sp.until(self.span));
4266 if self.token == token::CloseDelim(token::Brace) {
4267 // If the struct looks otherwise well formed, recover and continue.
4268 if let Some(sp) = comma_sp {
4269 err.span_suggestion_short_with_applicability(
4271 "remove this comma",
4273 Applicability::MachineApplicable,
4278 } else if self.token.is_ident() && ate_comma {
4279 // Accept fields coming after `..,`.
4280 // This way we avoid "pattern missing fields" errors afterwards.
4281 // We delay this error until the end in order to have a span for a
4283 if let Some(mut delayed_err) = delayed_err {
4287 delayed_err = Some(err);
4290 if let Some(mut err) = delayed_err {
4297 fields.push(match self.parse_pat_field(lo, attrs) {
4300 if let Some(mut delayed_err) = delayed_err {
4306 ate_comma = self.eat(&token::Comma);
4309 if let Some(mut err) = delayed_err {
4310 if let Some(etc_span) = etc_span {
4311 err.multipart_suggestion_with_applicability(
4312 "move the `..` to the end of the field list",
4314 (etc_span, String::new()),
4315 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4317 Applicability::MachineApplicable,
4322 return Ok((fields, etc));
4325 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4326 if self.token.is_path_start() {
4328 let (qself, path) = if self.eat_lt() {
4329 // Parse a qualified path
4330 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4333 // Parse an unqualified path
4334 (None, self.parse_path(PathStyle::Expr)?)
4336 let hi = self.prev_span;
4337 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4339 self.parse_literal_maybe_minus()
4343 // helper function to decide whether to parse as ident binding or to try to do
4344 // something more complex like range patterns
4345 fn parse_as_ident(&mut self) -> bool {
4346 self.look_ahead(1, |t| match *t {
4347 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4348 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4349 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4350 // range pattern branch
4351 token::DotDot => None,
4353 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4354 token::Comma | token::CloseDelim(token::Bracket) => true,
4359 /// A wrapper around `parse_pat` with some special error handling for the
4360 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4361 /// to subpatterns within such).
4362 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4363 let pat = self.parse_pat(None)?;
4364 if self.token == token::Comma {
4365 // An unexpected comma after a top-level pattern is a clue that the
4366 // user (perhaps more accustomed to some other language) forgot the
4367 // parentheses in what should have been a tuple pattern; return a
4368 // suggestion-enhanced error here rather than choking on the comma
4370 let comma_span = self.span;
4372 if let Err(mut err) = self.parse_pat_list() {
4373 // We didn't expect this to work anyway; we just wanted
4374 // to advance to the end of the comma-sequence so we know
4375 // the span to suggest parenthesizing
4378 let seq_span = pat.span.to(self.prev_span);
4379 let mut err = self.struct_span_err(comma_span,
4380 "unexpected `,` in pattern");
4381 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4382 err.span_suggestion_with_applicability(
4384 "try adding parentheses",
4385 format!("({})", seq_snippet),
4386 Applicability::MachineApplicable
4394 /// Parse a pattern.
4395 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4396 self.parse_pat_with_range_pat(true, expected)
4399 /// Parse a pattern, with a setting whether modern range patterns e.g., `a..=b`, `a..b` are
4401 fn parse_pat_with_range_pat(
4403 allow_range_pat: bool,
4404 expected: Option<&'static str>,
4405 ) -> PResult<'a, P<Pat>> {
4406 maybe_whole!(self, NtPat, |x| x);
4411 token::BinOp(token::And) | token::AndAnd => {
4412 // Parse &pat / &mut pat
4414 let mutbl = self.parse_mutability();
4415 if let token::Lifetime(ident) = self.token {
4416 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4418 err.span_label(self.span, "unexpected lifetime");
4421 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4422 pat = PatKind::Ref(subpat, mutbl);
4424 token::OpenDelim(token::Paren) => {
4425 // Parse (pat,pat,pat,...) as tuple pattern
4426 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4427 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4428 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4430 PatKind::Tuple(fields, ddpos)
4433 token::OpenDelim(token::Bracket) => {
4434 // Parse [pat,pat,...] as slice pattern
4436 let (before, slice, after) = self.parse_pat_vec_elements()?;
4437 self.expect(&token::CloseDelim(token::Bracket))?;
4438 pat = PatKind::Slice(before, slice, after);
4440 // At this point, token != &, &&, (, [
4441 _ => if self.eat_keyword(keywords::Underscore) {
4443 pat = PatKind::Wild;
4444 } else if self.eat_keyword(keywords::Mut) {
4445 // Parse mut ident @ pat / mut ref ident @ pat
4446 let mutref_span = self.prev_span.to(self.span);
4447 let binding_mode = if self.eat_keyword(keywords::Ref) {
4449 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4450 .span_suggestion_with_applicability(
4452 "try switching the order",
4454 Applicability::MachineApplicable
4456 BindingMode::ByRef(Mutability::Mutable)
4458 BindingMode::ByValue(Mutability::Mutable)
4460 pat = self.parse_pat_ident(binding_mode)?;
4461 } else if self.eat_keyword(keywords::Ref) {
4462 // Parse ref ident @ pat / ref mut ident @ pat
4463 let mutbl = self.parse_mutability();
4464 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4465 } else if self.eat_keyword(keywords::Box) {
4467 let subpat = self.parse_pat_with_range_pat(false, None)?;
4468 pat = PatKind::Box(subpat);
4469 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4470 self.parse_as_ident() {
4471 // Parse ident @ pat
4472 // This can give false positives and parse nullary enums,
4473 // they are dealt with later in resolve
4474 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4475 pat = self.parse_pat_ident(binding_mode)?;
4476 } else if self.token.is_path_start() {
4477 // Parse pattern starting with a path
4478 let (qself, path) = if self.eat_lt() {
4479 // Parse a qualified path
4480 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4483 // Parse an unqualified path
4484 (None, self.parse_path(PathStyle::Expr)?)
4487 token::Not if qself.is_none() => {
4488 // Parse macro invocation
4490 let (delim, tts) = self.expect_delimited_token_tree()?;
4491 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4492 pat = PatKind::Mac(mac);
4494 token::DotDotDot | token::DotDotEq | token::DotDot => {
4495 let end_kind = match self.token {
4496 token::DotDot => RangeEnd::Excluded,
4497 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4498 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4499 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4502 let op_span = self.span;
4504 let span = lo.to(self.prev_span);
4505 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4507 let end = self.parse_pat_range_end()?;
4508 let op = Spanned { span: op_span, node: end_kind };
4509 pat = PatKind::Range(begin, end, op);
4511 token::OpenDelim(token::Brace) => {
4512 if qself.is_some() {
4513 let msg = "unexpected `{` after qualified path";
4514 let mut err = self.fatal(msg);
4515 err.span_label(self.span, msg);
4518 // Parse struct pattern
4520 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4522 self.recover_stmt();
4526 pat = PatKind::Struct(path, fields, etc);
4528 token::OpenDelim(token::Paren) => {
4529 if qself.is_some() {
4530 let msg = "unexpected `(` after qualified path";
4531 let mut err = self.fatal(msg);
4532 err.span_label(self.span, msg);
4535 // Parse tuple struct or enum pattern
4536 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4537 pat = PatKind::TupleStruct(path, fields, ddpos)
4539 _ => pat = PatKind::Path(qself, path),
4542 // Try to parse everything else as literal with optional minus
4543 match self.parse_literal_maybe_minus() {
4545 let op_span = self.span;
4546 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4547 self.check(&token::DotDotDot) {
4548 let end_kind = if self.eat(&token::DotDotDot) {
4549 RangeEnd::Included(RangeSyntax::DotDotDot)
4550 } else if self.eat(&token::DotDotEq) {
4551 RangeEnd::Included(RangeSyntax::DotDotEq)
4552 } else if self.eat(&token::DotDot) {
4555 panic!("impossible case: we already matched \
4556 on a range-operator token")
4558 let end = self.parse_pat_range_end()?;
4559 let op = Spanned { span: op_span, node: end_kind };
4560 pat = PatKind::Range(begin, end, op);
4562 pat = PatKind::Lit(begin);
4566 self.cancel(&mut err);
4567 let expected = expected.unwrap_or("pattern");
4569 "expected {}, found {}",
4571 self.this_token_descr(),
4573 let mut err = self.fatal(&msg);
4574 err.span_label(self.span, format!("expected {}", expected));
4581 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4582 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4584 if !allow_range_pat {
4587 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4589 PatKind::Range(..) => {
4590 let mut err = self.struct_span_err(
4592 "the range pattern here has ambiguous interpretation",
4594 err.span_suggestion_with_applicability(
4596 "add parentheses to clarify the precedence",
4597 format!("({})", pprust::pat_to_string(&pat)),
4598 // "ambiguous interpretation" implies that we have to be guessing
4599 Applicability::MaybeIncorrect
4610 /// Parse ident or ident @ pat
4611 /// used by the copy foo and ref foo patterns to give a good
4612 /// error message when parsing mistakes like ref foo(a,b)
4613 fn parse_pat_ident(&mut self,
4614 binding_mode: ast::BindingMode)
4615 -> PResult<'a, PatKind> {
4616 let ident = self.parse_ident()?;
4617 let sub = if self.eat(&token::At) {
4618 Some(self.parse_pat(Some("binding pattern"))?)
4623 // just to be friendly, if they write something like
4625 // we end up here with ( as the current token. This shortly
4626 // leads to a parse error. Note that if there is no explicit
4627 // binding mode then we do not end up here, because the lookahead
4628 // will direct us over to parse_enum_variant()
4629 if self.token == token::OpenDelim(token::Paren) {
4630 return Err(self.span_fatal(
4632 "expected identifier, found enum pattern"))
4635 Ok(PatKind::Ident(binding_mode, ident, sub))
4638 /// Parse a local variable declaration
4639 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4640 let lo = self.prev_span;
4641 let pat = self.parse_top_level_pat()?;
4643 let (err, ty) = if self.eat(&token::Colon) {
4644 // Save the state of the parser before parsing type normally, in case there is a `:`
4645 // instead of an `=` typo.
4646 let parser_snapshot_before_type = self.clone();
4647 let colon_sp = self.prev_span;
4648 match self.parse_ty() {
4649 Ok(ty) => (None, Some(ty)),
4651 // Rewind to before attempting to parse the type and continue parsing
4652 let parser_snapshot_after_type = self.clone();
4653 mem::replace(self, parser_snapshot_before_type);
4655 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4656 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4657 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4663 let init = match (self.parse_initializer(err.is_some()), err) {
4664 (Ok(init), None) => { // init parsed, ty parsed
4667 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4668 // Could parse the type as if it were the initializer, it is likely there was a
4669 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4670 err.span_suggestion_short_with_applicability(
4672 "use `=` if you meant to assign",
4674 Applicability::MachineApplicable
4677 // As this was parsed successfully, continue as if the code has been fixed for the
4678 // rest of the file. It will still fail due to the emitted error, but we avoid
4682 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4684 // Couldn't parse the type nor the initializer, only raise the type error and
4685 // return to the parser state before parsing the type as the initializer.
4686 // let x: <parse_error>;
4687 mem::replace(self, snapshot);
4690 (Err(err), None) => { // init error, ty parsed
4691 // Couldn't parse the initializer and we're not attempting to recover a failed
4692 // parse of the type, return the error.
4696 let hi = if self.token == token::Semi {
4705 id: ast::DUMMY_NODE_ID,
4711 /// Parse a structure field
4712 fn parse_name_and_ty(&mut self,
4715 attrs: Vec<Attribute>)
4716 -> PResult<'a, StructField> {
4717 let name = self.parse_ident()?;
4718 self.expect(&token::Colon)?;
4719 let ty = self.parse_ty()?;
4721 span: lo.to(self.prev_span),
4724 id: ast::DUMMY_NODE_ID,
4730 /// Emit an expected item after attributes error.
4731 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
4732 let message = match attrs.last() {
4733 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4734 _ => "expected item after attributes",
4737 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
4738 if attrs.last().unwrap().is_sugared_doc {
4739 err.span_label(self.prev_span, "this doc comment doesn't document anything");
4744 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4745 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4746 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4747 Ok(self.parse_stmt_(true))
4750 // Eat tokens until we can be relatively sure we reached the end of the
4751 // statement. This is something of a best-effort heuristic.
4753 // We terminate when we find an unmatched `}` (without consuming it).
4754 fn recover_stmt(&mut self) {
4755 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4758 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4759 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4760 // approximate - it can mean we break too early due to macros, but that
4761 // should only lead to sub-optimal recovery, not inaccurate parsing).
4763 // If `break_on_block` is `Break`, then we will stop consuming tokens
4764 // after finding (and consuming) a brace-delimited block.
4765 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4766 let mut brace_depth = 0;
4767 let mut bracket_depth = 0;
4768 let mut in_block = false;
4769 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4770 break_on_semi, break_on_block);
4772 debug!("recover_stmt_ loop {:?}", self.token);
4774 token::OpenDelim(token::DelimToken::Brace) => {
4777 if break_on_block == BlockMode::Break &&
4779 bracket_depth == 0 {
4783 token::OpenDelim(token::DelimToken::Bracket) => {
4787 token::CloseDelim(token::DelimToken::Brace) => {
4788 if brace_depth == 0 {
4789 debug!("recover_stmt_ return - close delim {:?}", self.token);
4794 if in_block && bracket_depth == 0 && brace_depth == 0 {
4795 debug!("recover_stmt_ return - block end {:?}", self.token);
4799 token::CloseDelim(token::DelimToken::Bracket) => {
4801 if bracket_depth < 0 {
4807 debug!("recover_stmt_ return - Eof");
4812 if break_on_semi == SemiColonMode::Break &&
4814 bracket_depth == 0 {
4815 debug!("recover_stmt_ return - Semi");
4820 if break_on_semi == SemiColonMode::Comma &&
4822 bracket_depth == 0 {
4823 debug!("recover_stmt_ return - Semi");
4836 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4837 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4839 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4844 fn is_async_block(&mut self) -> bool {
4845 self.token.is_keyword(keywords::Async) &&
4848 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
4849 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4851 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4856 fn is_do_catch_block(&mut self) -> bool {
4857 self.token.is_keyword(keywords::Do) &&
4858 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4859 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4860 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4863 fn is_try_block(&mut self) -> bool {
4864 self.token.is_keyword(keywords::Try) &&
4865 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
4866 self.span.rust_2018() &&
4867 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
4868 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4871 fn is_union_item(&self) -> bool {
4872 self.token.is_keyword(keywords::Union) &&
4873 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4876 fn is_crate_vis(&self) -> bool {
4877 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4880 fn is_existential_type_decl(&self) -> bool {
4881 self.token.is_keyword(keywords::Existential) &&
4882 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
4885 fn is_auto_trait_item(&mut self) -> bool {
4887 (self.token.is_keyword(keywords::Auto)
4888 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4889 || // unsafe auto trait
4890 (self.token.is_keyword(keywords::Unsafe) &&
4891 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4892 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4895 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4896 -> PResult<'a, Option<P<Item>>> {
4897 let token_lo = self.span;
4898 let (ident, def) = match self.token {
4899 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4901 let ident = self.parse_ident()?;
4902 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4903 match self.parse_token_tree() {
4904 TokenTree::Delimited(_, _, tts) => tts,
4905 _ => unreachable!(),
4907 } else if self.check(&token::OpenDelim(token::Paren)) {
4908 let args = self.parse_token_tree();
4909 let body = if self.check(&token::OpenDelim(token::Brace)) {
4910 self.parse_token_tree()
4915 TokenStream::new(vec![
4917 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4925 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4927 token::Ident(ident, _) if ident.name == "macro_rules" &&
4928 self.look_ahead(1, |t| *t == token::Not) => {
4929 let prev_span = self.prev_span;
4930 self.complain_if_pub_macro(&vis.node, prev_span);
4934 let ident = self.parse_ident()?;
4935 let (delim, tokens) = self.expect_delimited_token_tree()?;
4936 if delim != MacDelimiter::Brace {
4937 if !self.eat(&token::Semi) {
4938 let msg = "macros that expand to items must either \
4939 be surrounded with braces or followed by a semicolon";
4940 self.span_err(self.prev_span, msg);
4944 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4946 _ => return Ok(None),
4949 let span = lo.to(self.prev_span);
4950 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4953 fn parse_stmt_without_recovery(&mut self,
4954 macro_legacy_warnings: bool)
4955 -> PResult<'a, Option<Stmt>> {
4956 maybe_whole!(self, NtStmt, |x| Some(x));
4958 let attrs = self.parse_outer_attributes()?;
4961 Ok(Some(if self.eat_keyword(keywords::Let) {
4963 id: ast::DUMMY_NODE_ID,
4964 node: StmtKind::Local(self.parse_local(attrs.into())?),
4965 span: lo.to(self.prev_span),
4967 } else if let Some(macro_def) = self.eat_macro_def(
4969 &source_map::respan(lo, VisibilityKind::Inherited),
4973 id: ast::DUMMY_NODE_ID,
4974 node: StmtKind::Item(macro_def),
4975 span: lo.to(self.prev_span),
4977 // Starts like a simple path, being careful to avoid contextual keywords
4978 // such as a union items, item with `crate` visibility or auto trait items.
4979 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4980 // like a path (1 token), but it fact not a path.
4981 // `union::b::c` - path, `union U { ... }` - not a path.
4982 // `crate::b::c` - path, `crate struct S;` - not a path.
4983 } else if self.token.is_path_start() &&
4984 !self.token.is_qpath_start() &&
4985 !self.is_union_item() &&
4986 !self.is_crate_vis() &&
4987 !self.is_existential_type_decl() &&
4988 !self.is_auto_trait_item() {
4989 let pth = self.parse_path(PathStyle::Expr)?;
4991 if !self.eat(&token::Not) {
4992 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4993 self.parse_struct_expr(lo, pth, ThinVec::new())?
4995 let hi = self.prev_span;
4996 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4999 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
5000 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
5001 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
5004 return Ok(Some(Stmt {
5005 id: ast::DUMMY_NODE_ID,
5006 node: StmtKind::Expr(expr),
5007 span: lo.to(self.prev_span),
5011 // it's a macro invocation
5012 let id = match self.token {
5013 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
5014 _ => self.parse_ident()?,
5017 // check that we're pointing at delimiters (need to check
5018 // again after the `if`, because of `parse_ident`
5019 // consuming more tokens).
5021 token::OpenDelim(_) => {}
5023 // we only expect an ident if we didn't parse one
5025 let ident_str = if id.name == keywords::Invalid.name() {
5030 let tok_str = self.this_token_descr();
5031 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
5034 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
5039 let (delim, tts) = self.expect_delimited_token_tree()?;
5040 let hi = self.prev_span;
5042 let style = if delim == MacDelimiter::Brace {
5043 MacStmtStyle::Braces
5045 MacStmtStyle::NoBraces
5048 if id.name == keywords::Invalid.name() {
5049 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
5050 let node = if delim == MacDelimiter::Brace ||
5051 self.token == token::Semi || self.token == token::Eof {
5052 StmtKind::Mac(P((mac, style, attrs.into())))
5054 // We used to incorrectly stop parsing macro-expanded statements here.
5055 // If the next token will be an error anyway but could have parsed with the
5056 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
5057 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
5058 // These can continue an expression, so we can't stop parsing and warn.
5059 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
5060 token::BinOp(token::Minus) | token::BinOp(token::Star) |
5061 token::BinOp(token::And) | token::BinOp(token::Or) |
5062 token::AndAnd | token::OrOr |
5063 token::DotDot | token::DotDotDot | token::DotDotEq => false,
5066 self.warn_missing_semicolon();
5067 StmtKind::Mac(P((mac, style, attrs.into())))
5069 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
5070 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
5071 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
5075 id: ast::DUMMY_NODE_ID,
5080 // if it has a special ident, it's definitely an item
5082 // Require a semicolon or braces.
5083 if style != MacStmtStyle::Braces {
5084 if !self.eat(&token::Semi) {
5085 self.span_err(self.prev_span,
5086 "macros that expand to items must \
5087 either be surrounded with braces or \
5088 followed by a semicolon");
5091 let span = lo.to(hi);
5093 id: ast::DUMMY_NODE_ID,
5095 node: StmtKind::Item({
5097 span, id /*id is good here*/,
5098 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
5099 respan(lo, VisibilityKind::Inherited),
5105 // FIXME: Bad copy of attrs
5106 let old_directory_ownership =
5107 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
5108 let item = self.parse_item_(attrs.clone(), false, true)?;
5109 self.directory.ownership = old_directory_ownership;
5113 id: ast::DUMMY_NODE_ID,
5114 span: lo.to(i.span),
5115 node: StmtKind::Item(i),
5118 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
5119 if !attrs.is_empty() {
5120 if s.prev_token_kind == PrevTokenKind::DocComment {
5121 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
5122 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
5123 s.span_err(s.span, "expected statement after outer attribute");
5128 // Do not attempt to parse an expression if we're done here.
5129 if self.token == token::Semi {
5130 unused_attrs(&attrs, self);
5135 if self.token == token::CloseDelim(token::Brace) {
5136 unused_attrs(&attrs, self);
5140 // Remainder are line-expr stmts.
5141 let e = self.parse_expr_res(
5142 Restrictions::STMT_EXPR, Some(attrs.into()))?;
5144 id: ast::DUMMY_NODE_ID,
5145 span: lo.to(e.span),
5146 node: StmtKind::Expr(e),
5153 /// Is this expression a successfully-parsed statement?
5154 fn expr_is_complete(&mut self, e: &Expr) -> bool {
5155 self.restrictions.contains(Restrictions::STMT_EXPR) &&
5156 !classify::expr_requires_semi_to_be_stmt(e)
5159 /// Parse a block. No inner attrs are allowed.
5160 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
5161 maybe_whole!(self, NtBlock, |x| x);
5165 if !self.eat(&token::OpenDelim(token::Brace)) {
5167 let tok = self.this_token_descr();
5168 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
5169 let do_not_suggest_help =
5170 self.token.is_keyword(keywords::In) || self.token == token::Colon;
5172 if self.token.is_ident_named("and") {
5173 e.span_suggestion_short_with_applicability(
5175 "use `&&` instead of `and` for the boolean operator",
5177 Applicability::MaybeIncorrect,
5180 if self.token.is_ident_named("or") {
5181 e.span_suggestion_short_with_applicability(
5183 "use `||` instead of `or` for the boolean operator",
5185 Applicability::MaybeIncorrect,
5189 // Check to see if the user has written something like
5194 // Which is valid in other languages, but not Rust.
5195 match self.parse_stmt_without_recovery(false) {
5197 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
5198 || do_not_suggest_help {
5199 // if the next token is an open brace (e.g., `if a b {`), the place-
5200 // inside-a-block suggestion would be more likely wrong than right
5201 e.span_label(sp, "expected `{`");
5204 let mut stmt_span = stmt.span;
5205 // expand the span to include the semicolon, if it exists
5206 if self.eat(&token::Semi) {
5207 stmt_span = stmt_span.with_hi(self.prev_span.hi());
5209 let sugg = pprust::to_string(|s| {
5210 use print::pprust::{PrintState, INDENT_UNIT};
5211 s.ibox(INDENT_UNIT)?;
5213 s.print_stmt(&stmt)?;
5214 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
5216 e.span_suggestion_with_applicability(
5218 "try placing this code inside a block",
5220 // speculative, has been misleading in the past (closed Issue #46836)
5221 Applicability::MaybeIncorrect
5225 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5226 self.cancel(&mut e);
5230 e.span_label(sp, "expected `{`");
5234 self.parse_block_tail(lo, BlockCheckMode::Default)
5237 /// Parse a block. Inner attrs are allowed.
5238 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
5239 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
5242 self.expect(&token::OpenDelim(token::Brace))?;
5243 Ok((self.parse_inner_attributes()?,
5244 self.parse_block_tail(lo, BlockCheckMode::Default)?))
5247 /// Parse the rest of a block expression or function body
5248 /// Precondition: already parsed the '{'.
5249 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
5250 let mut stmts = vec![];
5251 while !self.eat(&token::CloseDelim(token::Brace)) {
5252 let stmt = match self.parse_full_stmt(false) {
5255 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
5257 id: ast::DUMMY_NODE_ID,
5258 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
5264 if let Some(stmt) = stmt {
5266 } else if self.token == token::Eof {
5269 // Found only `;` or `}`.
5275 id: ast::DUMMY_NODE_ID,
5277 span: lo.to(self.prev_span),
5281 /// Parse a statement, including the trailing semicolon.
5282 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5283 // skip looking for a trailing semicolon when we have an interpolated statement
5284 maybe_whole!(self, NtStmt, |x| Some(x));
5286 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5288 None => return Ok(None),
5292 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5293 // expression without semicolon
5294 if classify::expr_requires_semi_to_be_stmt(expr) {
5295 // Just check for errors and recover; do not eat semicolon yet.
5297 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5300 self.recover_stmt();
5304 StmtKind::Local(..) => {
5305 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5306 if macro_legacy_warnings && self.token != token::Semi {
5307 self.warn_missing_semicolon();
5309 self.expect_one_of(&[], &[token::Semi])?;
5315 if self.eat(&token::Semi) {
5316 stmt = stmt.add_trailing_semicolon();
5319 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5323 fn warn_missing_semicolon(&self) {
5324 self.diagnostic().struct_span_warn(self.span, {
5325 &format!("expected `;`, found {}", self.this_token_descr())
5327 "This was erroneously allowed and will become a hard error in a future release"
5331 fn err_dotdotdot_syntax(&self, span: Span) {
5332 self.diagnostic().struct_span_err(span, {
5333 "unexpected token: `...`"
5334 }).span_suggestion_with_applicability(
5335 span, "use `..` for an exclusive range", "..".to_owned(),
5336 Applicability::MaybeIncorrect
5337 ).span_suggestion_with_applicability(
5338 span, "or `..=` for an inclusive range", "..=".to_owned(),
5339 Applicability::MaybeIncorrect
5343 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5344 // BOUND = TY_BOUND | LT_BOUND
5345 // LT_BOUND = LIFETIME (e.g., `'a`)
5346 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5347 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5348 fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
5349 let mut bounds = Vec::new();
5351 // This needs to be synchronized with `Token::can_begin_bound`.
5352 let is_bound_start = self.check_path() || self.check_lifetime() ||
5353 self.check(&token::Question) ||
5354 self.check_keyword(keywords::For) ||
5355 self.check(&token::OpenDelim(token::Paren));
5358 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5359 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5360 if self.token.is_lifetime() {
5361 if let Some(question_span) = question {
5362 self.span_err(question_span,
5363 "`?` may only modify trait bounds, not lifetime bounds");
5365 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5367 self.expect(&token::CloseDelim(token::Paren))?;
5368 self.span_err(self.prev_span,
5369 "parenthesized lifetime bounds are not supported");
5372 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5373 let path = self.parse_path(PathStyle::Type)?;
5375 self.expect(&token::CloseDelim(token::Paren))?;
5377 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
5378 let modifier = if question.is_some() {
5379 TraitBoundModifier::Maybe
5381 TraitBoundModifier::None
5383 bounds.push(GenericBound::Trait(poly_trait, modifier));
5389 if !allow_plus || !self.eat_plus() {
5397 fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
5398 self.parse_generic_bounds_common(true)
5401 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5402 // BOUND = LT_BOUND (e.g., `'a`)
5403 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5404 let mut lifetimes = Vec::new();
5405 while self.check_lifetime() {
5406 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5408 if !self.eat_plus() {
5415 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
5416 fn parse_ty_param(&mut self,
5417 preceding_attrs: Vec<Attribute>)
5418 -> PResult<'a, GenericParam> {
5419 let ident = self.parse_ident()?;
5421 // Parse optional colon and param bounds.
5422 let bounds = if self.eat(&token::Colon) {
5423 self.parse_generic_bounds()?
5428 let default = if self.eat(&token::Eq) {
5429 Some(self.parse_ty()?)
5436 id: ast::DUMMY_NODE_ID,
5437 attrs: preceding_attrs.into(),
5439 kind: GenericParamKind::Type {
5445 /// Parses the following grammar:
5446 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5447 fn parse_trait_item_assoc_ty(&mut self)
5448 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5449 let ident = self.parse_ident()?;
5450 let mut generics = self.parse_generics()?;
5452 // Parse optional colon and param bounds.
5453 let bounds = if self.eat(&token::Colon) {
5454 self.parse_generic_bounds()?
5458 generics.where_clause = self.parse_where_clause()?;
5460 let default = if self.eat(&token::Eq) {
5461 Some(self.parse_ty()?)
5465 self.expect(&token::Semi)?;
5467 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5470 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
5471 /// trailing comma and erroneous trailing attributes.
5472 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5473 let mut lifetimes = Vec::new();
5474 let mut params = Vec::new();
5475 let mut seen_ty_param: Option<Span> = None;
5476 let mut last_comma_span = None;
5477 let mut bad_lifetime_pos = vec![];
5478 let mut suggestions = vec![];
5480 let attrs = self.parse_outer_attributes()?;
5481 if self.check_lifetime() {
5482 let lifetime = self.expect_lifetime();
5483 // Parse lifetime parameter.
5484 let bounds = if self.eat(&token::Colon) {
5485 self.parse_lt_param_bounds()
5489 lifetimes.push(ast::GenericParam {
5490 ident: lifetime.ident,
5492 attrs: attrs.into(),
5494 kind: ast::GenericParamKind::Lifetime,
5496 if let Some(sp) = seen_ty_param {
5497 let remove_sp = last_comma_span.unwrap_or(self.prev_span).to(self.prev_span);
5498 bad_lifetime_pos.push(self.prev_span);
5499 if let Ok(snippet) = self.sess.source_map().span_to_snippet(self.prev_span) {
5500 suggestions.push((remove_sp, String::new()));
5503 format!("{}, ", snippet)));
5506 } else if self.check_ident() {
5507 // Parse type parameter.
5508 params.push(self.parse_ty_param(attrs)?);
5509 if seen_ty_param.is_none() {
5510 seen_ty_param = Some(self.prev_span);
5513 // Check for trailing attributes and stop parsing.
5514 if !attrs.is_empty() {
5515 let param_kind = if seen_ty_param.is_some() { "type" } else { "lifetime" };
5516 self.struct_span_err(
5518 &format!("trailing attribute after {} parameters", param_kind),
5520 .span_label(attrs[0].span, "attributes must go before parameters")
5526 if !self.eat(&token::Comma) {
5529 last_comma_span = Some(self.prev_span);
5531 if !bad_lifetime_pos.is_empty() {
5532 let mut err = self.struct_span_err(
5534 "lifetime parameters must be declared prior to type parameters",
5536 if !suggestions.is_empty() {
5537 err.multipart_suggestion_with_applicability(
5538 "move the lifetime parameter prior to the first type parameter",
5540 Applicability::MachineApplicable,
5545 lifetimes.extend(params); // ensure the correct order of lifetimes and type params
5549 /// Parse a set of optional generic type parameter declarations. Where
5550 /// clauses are not parsed here, and must be added later via
5551 /// `parse_where_clause()`.
5553 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5554 /// | ( < lifetimes , typaramseq ( , )? > )
5555 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5556 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5557 maybe_whole!(self, NtGenerics, |x| x);
5559 let span_lo = self.span;
5561 let params = self.parse_generic_params()?;
5565 where_clause: WhereClause {
5566 id: ast::DUMMY_NODE_ID,
5567 predicates: Vec::new(),
5568 span: syntax_pos::DUMMY_SP,
5570 span: span_lo.to(self.prev_span),
5573 Ok(ast::Generics::default())
5577 /// Parse generic args (within a path segment) with recovery for extra leading angle brackets.
5578 /// For the purposes of understanding the parsing logic of generic arguments, this function
5579 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5580 /// had the correct amount of leading angle brackets.
5582 /// ```ignore (diagnostics)
5583 /// bar::<<<<T as Foo>::Output>();
5584 /// ^^ help: remove extra angle brackets
5586 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5590 ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5591 // We need to detect whether there are extra leading left angle brackets and produce an
5592 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5593 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5594 // then there won't be matching `>` tokens to find.
5596 // To explain how this detection works, consider the following example:
5598 // ```ignore (diagnostics)
5599 // bar::<<<<T as Foo>::Output>();
5600 // ^^ help: remove extra angle brackets
5603 // Parsing of the left angle brackets starts in this function. We start by parsing the
5604 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5607 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5608 // *Unmatched count:* 1
5609 // *`parse_path_segment` calls deep:* 0
5611 // This has the effect of recursing as this function is called if a `<` character
5612 // is found within the expected generic arguments:
5614 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5615 // *Unmatched count:* 2
5616 // *`parse_path_segment` calls deep:* 1
5618 // Eventually we will have recursed until having consumed all of the `<` tokens and
5619 // this will be reflected in the count:
5621 // *Upcoming tokens:* `T as Foo>::Output>;`
5622 // *Unmatched count:* 4
5623 // `parse_path_segment` calls deep:* 3
5625 // The parser will continue until reaching the first `>` - this will decrement the
5626 // unmatched angle bracket count and return to the parent invocation of this function
5627 // having succeeded in parsing:
5629 // *Upcoming tokens:* `::Output>;`
5630 // *Unmatched count:* 3
5631 // *`parse_path_segment` calls deep:* 2
5633 // This will continue until the next `>` character which will also return successfully
5634 // to the parent invocation of this function and decrement the count:
5636 // *Upcoming tokens:* `;`
5637 // *Unmatched count:* 2
5638 // *`parse_path_segment` calls deep:* 1
5640 // At this point, this function will expect to find another matching `>` character but
5641 // won't be able to and will return an error. This will continue all the way up the
5642 // call stack until the first invocation:
5644 // *Upcoming tokens:* `;`
5645 // *Unmatched count:* 2
5646 // *`parse_path_segment` calls deep:* 0
5648 // In doing this, we have managed to work out how many unmatched leading left angle
5649 // brackets there are, but we cannot recover as the unmatched angle brackets have
5650 // already been consumed. To remedy this, we keep a snapshot of the parser state
5651 // before we do the above. We can then inspect whether we ended up with a parsing error
5652 // and unmatched left angle brackets and if so, restore the parser state before we
5653 // consumed any `<` characters to emit an error and consume the erroneous tokens to
5654 // recover by attempting to parse again.
5656 // In practice, the recursion of this function is indirect and there will be other
5657 // locations that consume some `<` characters - as long as we update the count when
5658 // this happens, it isn't an issue.
5660 let is_first_invocation = style == PathStyle::Expr;
5661 // Take a snapshot before attempting to parse - we can restore this later.
5662 let snapshot = if is_first_invocation {
5668 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
5669 match self.parse_generic_args() {
5670 Ok(value) => Ok(value),
5671 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
5672 // Cancel error from being unable to find `>`. We know the error
5673 // must have been this due to a non-zero unmatched angle bracket
5677 // Swap `self` with our backup of the parser state before attempting to parse
5678 // generic arguments.
5679 let snapshot = mem::replace(self, snapshot.unwrap());
5682 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
5683 snapshot.count={:?}",
5684 snapshot.unmatched_angle_bracket_count,
5687 // Eat the unmatched angle brackets.
5688 for _ in 0..snapshot.unmatched_angle_bracket_count {
5692 // Make a span over ${unmatched angle bracket count} characters.
5693 let span = lo.with_hi(
5694 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
5696 let plural = snapshot.unmatched_angle_bracket_count > 1;
5701 "unmatched angle bracket{}",
5702 if plural { "s" } else { "" }
5705 .span_suggestion_with_applicability(
5708 "remove extra angle bracket{}",
5709 if plural { "s" } else { "" }
5712 Applicability::MachineApplicable,
5716 // Try again without unmatched angle bracket characters.
5717 self.parse_generic_args()
5723 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5724 /// possibly including trailing comma.
5725 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5726 let mut args = Vec::new();
5727 let mut bindings = Vec::new();
5729 let mut seen_type = false;
5730 let mut seen_binding = false;
5732 let mut last_comma_span = None;
5733 let mut first_type_or_binding_span: Option<Span> = None;
5734 let mut first_binding_span: Option<Span> = None;
5736 let mut bad_lifetime_pos = vec![];
5737 let mut bad_type_pos = vec![];
5739 let mut lifetime_suggestions = vec![];
5740 let mut type_suggestions = vec![];
5742 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5743 // Parse lifetime argument.
5744 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5746 if seen_type || seen_binding {
5747 let remove_sp = last_comma_span.unwrap_or(self.prev_span).to(self.prev_span);
5748 bad_lifetime_pos.push(self.prev_span);
5750 if let Ok(snippet) = self.sess.source_map().span_to_snippet(self.prev_span) {
5751 lifetime_suggestions.push((remove_sp, String::new()));
5752 lifetime_suggestions.push((
5753 first_type_or_binding_span.unwrap().shrink_to_lo(),
5754 format!("{}, ", snippet)));
5757 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5758 // Parse associated type binding.
5760 let ident = self.parse_ident()?;
5762 let ty = self.parse_ty()?;
5763 let span = lo.to(self.prev_span);
5764 bindings.push(TypeBinding {
5765 id: ast::DUMMY_NODE_ID,
5771 seen_binding = true;
5772 if first_type_or_binding_span.is_none() {
5773 first_type_or_binding_span = Some(span);
5775 if first_binding_span.is_none() {
5776 first_binding_span = Some(span);
5778 } else if self.check_type() {
5779 // Parse type argument.
5780 let ty_param = self.parse_ty()?;
5782 let remove_sp = last_comma_span.unwrap_or(self.prev_span).to(self.prev_span);
5783 bad_type_pos.push(self.prev_span);
5785 if let Ok(snippet) = self.sess.source_map().span_to_snippet(self.prev_span) {
5786 type_suggestions.push((remove_sp, String::new()));
5787 type_suggestions.push((
5788 first_binding_span.unwrap().shrink_to_lo(),
5789 format!("{}, ", snippet)));
5793 if first_type_or_binding_span.is_none() {
5794 first_type_or_binding_span = Some(ty_param.span);
5796 args.push(GenericArg::Type(ty_param));
5802 if !self.eat(&token::Comma) {
5805 last_comma_span = Some(self.prev_span);
5809 self.maybe_report_incorrect_generic_argument_order(
5810 bad_lifetime_pos, bad_type_pos, lifetime_suggestions, type_suggestions
5813 Ok((args, bindings))
5816 /// Maybe report an error about incorrect generic argument order - "lifetime parameters
5817 /// must be declared before type parameters", "type parameters must be declared before
5818 /// associated type bindings" or both.
5819 fn maybe_report_incorrect_generic_argument_order(
5821 bad_lifetime_pos: Vec<Span>,
5822 bad_type_pos: Vec<Span>,
5823 lifetime_suggestions: Vec<(Span, String)>,
5824 type_suggestions: Vec<(Span, String)>,
5826 let mut err = if !bad_lifetime_pos.is_empty() && !bad_type_pos.is_empty() {
5827 let mut positions = bad_lifetime_pos.clone();
5828 positions.extend_from_slice(&bad_type_pos);
5830 self.struct_span_err(
5832 "generic arguments must declare lifetimes, types and associated type bindings in \
5835 } else if !bad_lifetime_pos.is_empty() {
5836 self.struct_span_err(
5837 bad_lifetime_pos.clone(),
5838 "lifetime parameters must be declared prior to type parameters"
5840 } else if !bad_type_pos.is_empty() {
5841 self.struct_span_err(
5842 bad_type_pos.clone(),
5843 "type parameters must be declared prior to associated type bindings"
5849 if !bad_lifetime_pos.is_empty() {
5850 for sp in &bad_lifetime_pos {
5851 err.span_label(*sp, "must be declared prior to type parameters");
5855 if !bad_type_pos.is_empty() {
5856 for sp in &bad_type_pos {
5857 err.span_label(*sp, "must be declared prior to associated type bindings");
5861 if !lifetime_suggestions.is_empty() && !type_suggestions.is_empty() {
5862 let mut suggestions = lifetime_suggestions;
5863 suggestions.extend_from_slice(&type_suggestions);
5865 let plural = bad_lifetime_pos.len() + bad_type_pos.len() > 1;
5866 err.multipart_suggestion_with_applicability(
5868 "move the parameter{}",
5869 if plural { "s" } else { "" },
5872 Applicability::MachineApplicable,
5874 } else if !lifetime_suggestions.is_empty() {
5875 err.multipart_suggestion_with_applicability(
5877 "move the lifetime parameter{} prior to the first type parameter",
5878 if bad_lifetime_pos.len() > 1 { "s" } else { "" },
5880 lifetime_suggestions,
5881 Applicability::MachineApplicable,
5883 } else if !type_suggestions.is_empty() {
5884 err.multipart_suggestion_with_applicability(
5886 "move the type parameter{} prior to the first associated type binding",
5887 if bad_type_pos.len() > 1 { "s" } else { "" },
5890 Applicability::MachineApplicable,
5897 /// Parses an optional `where` clause and places it in `generics`.
5899 /// ```ignore (only-for-syntax-highlight)
5900 /// where T : Trait<U, V> + 'b, 'a : 'b
5902 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5903 maybe_whole!(self, NtWhereClause, |x| x);
5905 let mut where_clause = WhereClause {
5906 id: ast::DUMMY_NODE_ID,
5907 predicates: Vec::new(),
5908 span: syntax_pos::DUMMY_SP,
5911 if !self.eat_keyword(keywords::Where) {
5912 return Ok(where_clause);
5914 let lo = self.prev_span;
5916 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5917 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5918 // change we parse those generics now, but report an error.
5919 if self.choose_generics_over_qpath() {
5920 let generics = self.parse_generics()?;
5921 self.struct_span_err(
5923 "generic parameters on `where` clauses are reserved for future use",
5925 .span_label(generics.span, "currently unsupported")
5931 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5932 let lifetime = self.expect_lifetime();
5933 // Bounds starting with a colon are mandatory, but possibly empty.
5934 self.expect(&token::Colon)?;
5935 let bounds = self.parse_lt_param_bounds();
5936 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5937 ast::WhereRegionPredicate {
5938 span: lo.to(self.prev_span),
5943 } else if self.check_type() {
5944 // Parse optional `for<'a, 'b>`.
5945 // This `for` is parsed greedily and applies to the whole predicate,
5946 // the bounded type can have its own `for` applying only to it.
5947 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5948 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5949 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5950 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5952 // Parse type with mandatory colon and (possibly empty) bounds,
5953 // or with mandatory equality sign and the second type.
5954 let ty = self.parse_ty()?;
5955 if self.eat(&token::Colon) {
5956 let bounds = self.parse_generic_bounds()?;
5957 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5958 ast::WhereBoundPredicate {
5959 span: lo.to(self.prev_span),
5960 bound_generic_params: lifetime_defs,
5965 // FIXME: Decide what should be used here, `=` or `==`.
5966 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5967 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5968 let rhs_ty = self.parse_ty()?;
5969 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5970 ast::WhereEqPredicate {
5971 span: lo.to(self.prev_span),
5974 id: ast::DUMMY_NODE_ID,
5978 return self.unexpected();
5984 if !self.eat(&token::Comma) {
5989 where_clause.span = lo.to(self.prev_span);
5993 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5994 -> PResult<'a, (Vec<Arg> , bool)> {
5995 self.expect(&token::OpenDelim(token::Paren))?;
5998 let mut variadic = false;
5999 let args: Vec<Option<Arg>> =
6000 self.parse_seq_to_before_end(
6001 &token::CloseDelim(token::Paren),
6002 SeqSep::trailing_allowed(token::Comma),
6004 if p.token == token::DotDotDot {
6008 if p.token != token::CloseDelim(token::Paren) {
6011 "`...` must be last in argument list for variadic function");
6015 let span = p.prev_span;
6016 if p.token == token::CloseDelim(token::Paren) {
6017 // continue parsing to present any further errors
6020 "only foreign functions are allowed to be variadic"
6022 Ok(Some(dummy_arg(span)))
6024 // this function definition looks beyond recovery, stop parsing
6026 "only foreign functions are allowed to be variadic");
6031 match p.parse_arg_general(named_args, false) {
6032 Ok(arg) => Ok(Some(arg)),
6035 let lo = p.prev_span;
6036 // Skip every token until next possible arg or end.
6037 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
6038 // Create a placeholder argument for proper arg count (#34264).
6039 let span = lo.to(p.prev_span);
6040 Ok(Some(dummy_arg(span)))
6047 self.eat(&token::CloseDelim(token::Paren));
6049 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
6051 if variadic && args.is_empty() {
6053 "variadic function must be declared with at least one named argument");
6056 Ok((args, variadic))
6059 /// Parse the argument list and result type of a function declaration
6060 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
6062 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
6063 let ret_ty = self.parse_ret_ty(true)?;
6072 /// Returns the parsed optional self argument and whether a self shortcut was used.
6073 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
6074 let expect_ident = |this: &mut Self| match this.token {
6075 // Preserve hygienic context.
6076 token::Ident(ident, _) =>
6077 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
6080 let isolated_self = |this: &mut Self, n| {
6081 this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) &&
6082 this.look_ahead(n + 1, |t| t != &token::ModSep)
6085 // Parse optional self parameter of a method.
6086 // Only a limited set of initial token sequences is considered self parameters, anything
6087 // else is parsed as a normal function parameter list, so some lookahead is required.
6088 let eself_lo = self.span;
6089 let (eself, eself_ident, eself_hi) = match self.token {
6090 token::BinOp(token::And) => {
6096 (if isolated_self(self, 1) {
6098 SelfKind::Region(None, Mutability::Immutable)
6099 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
6100 isolated_self(self, 2) {
6103 SelfKind::Region(None, Mutability::Mutable)
6104 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6105 isolated_self(self, 2) {
6107 let lt = self.expect_lifetime();
6108 SelfKind::Region(Some(lt), Mutability::Immutable)
6109 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6110 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
6111 isolated_self(self, 3) {
6113 let lt = self.expect_lifetime();
6115 SelfKind::Region(Some(lt), Mutability::Mutable)
6118 }, expect_ident(self), self.prev_span)
6120 token::BinOp(token::Star) => {
6125 // Emit special error for `self` cases.
6126 let msg = "cannot pass `self` by raw pointer";
6127 (if isolated_self(self, 1) {
6129 self.struct_span_err(self.span, msg)
6130 .span_label(self.span, msg)
6132 SelfKind::Value(Mutability::Immutable)
6133 } else if self.look_ahead(1, |t| t.is_mutability()) &&
6134 isolated_self(self, 2) {
6137 self.struct_span_err(self.span, msg)
6138 .span_label(self.span, msg)
6140 SelfKind::Value(Mutability::Immutable)
6143 }, expect_ident(self), self.prev_span)
6145 token::Ident(..) => {
6146 if isolated_self(self, 0) {
6149 let eself_ident = expect_ident(self);
6150 let eself_hi = self.prev_span;
6151 (if self.eat(&token::Colon) {
6152 let ty = self.parse_ty()?;
6153 SelfKind::Explicit(ty, Mutability::Immutable)
6155 SelfKind::Value(Mutability::Immutable)
6156 }, eself_ident, eself_hi)
6157 } else if self.token.is_keyword(keywords::Mut) &&
6158 isolated_self(self, 1) {
6162 let eself_ident = expect_ident(self);
6163 let eself_hi = self.prev_span;
6164 (if self.eat(&token::Colon) {
6165 let ty = self.parse_ty()?;
6166 SelfKind::Explicit(ty, Mutability::Mutable)
6168 SelfKind::Value(Mutability::Mutable)
6169 }, eself_ident, eself_hi)
6174 _ => return Ok(None),
6177 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
6178 Ok(Some(Arg::from_self(eself, eself_ident)))
6181 /// Parse the parameter list and result type of a function that may have a `self` parameter.
6182 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
6183 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
6185 self.expect(&token::OpenDelim(token::Paren))?;
6187 // Parse optional self argument
6188 let self_arg = self.parse_self_arg()?;
6190 // Parse the rest of the function parameter list.
6191 let sep = SeqSep::trailing_allowed(token::Comma);
6192 let fn_inputs = if let Some(self_arg) = self_arg {
6193 if self.check(&token::CloseDelim(token::Paren)) {
6195 } else if self.eat(&token::Comma) {
6196 let mut fn_inputs = vec![self_arg];
6197 fn_inputs.append(&mut self.parse_seq_to_before_end(
6198 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
6202 return self.unexpected();
6205 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
6208 // Parse closing paren and return type.
6209 self.expect(&token::CloseDelim(token::Paren))?;
6212 output: self.parse_ret_ty(true)?,
6217 // parse the |arg, arg| header on a lambda
6218 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
6219 let inputs_captures = {
6220 if self.eat(&token::OrOr) {
6223 self.expect(&token::BinOp(token::Or))?;
6224 let args = self.parse_seq_to_before_tokens(
6225 &[&token::BinOp(token::Or), &token::OrOr],
6226 SeqSep::trailing_allowed(token::Comma),
6227 TokenExpectType::NoExpect,
6228 |p| p.parse_fn_block_arg()
6234 let output = self.parse_ret_ty(true)?;
6237 inputs: inputs_captures,
6243 /// Parse the name and optional generic types of a function header.
6244 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
6245 let id = self.parse_ident()?;
6246 let generics = self.parse_generics()?;
6250 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
6251 attrs: Vec<Attribute>) -> P<Item> {
6255 id: ast::DUMMY_NODE_ID,
6263 /// Parse an item-position function declaration.
6264 fn parse_item_fn(&mut self,
6267 constness: Spanned<Constness>,
6269 -> PResult<'a, ItemInfo> {
6270 let (ident, mut generics) = self.parse_fn_header()?;
6271 let decl = self.parse_fn_decl(false)?;
6272 generics.where_clause = self.parse_where_clause()?;
6273 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6274 let header = FnHeader { unsafety, asyncness, constness, abi };
6275 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
6278 /// true if we are looking at `const ID`, false for things like `const fn` etc
6279 fn is_const_item(&mut self) -> bool {
6280 self.token.is_keyword(keywords::Const) &&
6281 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
6282 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
6285 /// parses all the "front matter" for a `fn` declaration, up to
6286 /// and including the `fn` keyword:
6290 /// - `const unsafe fn`
6293 fn parse_fn_front_matter(&mut self)
6301 let is_const_fn = self.eat_keyword(keywords::Const);
6302 let const_span = self.prev_span;
6303 let unsafety = self.parse_unsafety();
6304 let asyncness = self.parse_asyncness();
6305 let (constness, unsafety, abi) = if is_const_fn {
6306 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
6308 let abi = if self.eat_keyword(keywords::Extern) {
6309 self.parse_opt_abi()?.unwrap_or(Abi::C)
6313 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
6315 self.expect_keyword(keywords::Fn)?;
6316 Ok((constness, unsafety, asyncness, abi))
6319 /// Parse an impl item.
6320 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
6321 maybe_whole!(self, NtImplItem, |x| x);
6322 let attrs = self.parse_outer_attributes()?;
6323 let (mut item, tokens) = self.collect_tokens(|this| {
6324 this.parse_impl_item_(at_end, attrs)
6327 // See `parse_item` for why this clause is here.
6328 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6329 item.tokens = Some(tokens);
6334 fn parse_impl_item_(&mut self,
6336 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
6338 let vis = self.parse_visibility(false)?;
6339 let defaultness = self.parse_defaultness();
6340 let (name, node, generics) = if let Some(type_) = self.eat_type() {
6341 let (name, alias, generics) = type_?;
6342 let kind = match alias {
6343 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
6344 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
6346 (name, kind, generics)
6347 } else if self.is_const_item() {
6348 // This parses the grammar:
6349 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
6350 self.expect_keyword(keywords::Const)?;
6351 let name = self.parse_ident()?;
6352 self.expect(&token::Colon)?;
6353 let typ = self.parse_ty()?;
6354 self.expect(&token::Eq)?;
6355 let expr = self.parse_expr()?;
6356 self.expect(&token::Semi)?;
6357 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
6359 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
6360 attrs.extend(inner_attrs);
6361 (name, node, generics)
6365 id: ast::DUMMY_NODE_ID,
6366 span: lo.to(self.prev_span),
6377 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
6379 VisibilityKind::Inherited => {}
6381 let is_macro_rules: bool = match self.token {
6382 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
6385 let mut err = if is_macro_rules {
6386 let mut err = self.diagnostic()
6387 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
6388 err.span_suggestion_with_applicability(
6390 "try exporting the macro",
6391 "#[macro_export]".to_owned(),
6392 Applicability::MaybeIncorrect // speculative
6396 let mut err = self.diagnostic()
6397 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
6398 err.help("try adjusting the macro to put `pub` inside the invocation");
6406 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
6407 -> DiagnosticBuilder<'a>
6409 let expected_kinds = if item_type == "extern" {
6410 "missing `fn`, `type`, or `static`"
6412 "missing `fn`, `type`, or `const`"
6415 // Given this code `path(`, it seems like this is not
6416 // setting the visibility of a macro invocation, but rather
6417 // a mistyped method declaration.
6418 // Create a diagnostic pointing out that `fn` is missing.
6420 // x | pub path(&self) {
6421 // | ^ missing `fn`, `type`, or `const`
6423 // ^^ `sp` below will point to this
6424 let sp = prev_span.between(self.prev_span);
6425 let mut err = self.diagnostic().struct_span_err(
6427 &format!("{} for {}-item declaration",
6428 expected_kinds, item_type));
6429 err.span_label(sp, expected_kinds);
6433 /// Parse a method or a macro invocation in a trait impl.
6434 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
6435 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
6436 ast::ImplItemKind)> {
6437 // code copied from parse_macro_use_or_failure... abstraction!
6438 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
6440 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
6441 ast::ImplItemKind::Macro(mac)))
6443 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
6444 let ident = self.parse_ident()?;
6445 let mut generics = self.parse_generics()?;
6446 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
6447 generics.where_clause = self.parse_where_clause()?;
6449 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6450 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
6451 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
6452 ast::MethodSig { header, decl },
6458 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
6459 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
6460 let ident = self.parse_ident()?;
6461 let mut tps = self.parse_generics()?;
6463 // Parse optional colon and supertrait bounds.
6464 let bounds = if self.eat(&token::Colon) {
6465 self.parse_generic_bounds()?
6470 if self.eat(&token::Eq) {
6471 // it's a trait alias
6472 let bounds = self.parse_generic_bounds()?;
6473 tps.where_clause = self.parse_where_clause()?;
6474 self.expect(&token::Semi)?;
6475 if unsafety != Unsafety::Normal {
6476 let msg = "trait aliases cannot be unsafe";
6477 self.struct_span_err(self.prev_span, msg)
6478 .span_label(self.prev_span, msg)
6481 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
6483 // it's a normal trait
6484 tps.where_clause = self.parse_where_clause()?;
6485 self.expect(&token::OpenDelim(token::Brace))?;
6486 let mut trait_items = vec![];
6487 while !self.eat(&token::CloseDelim(token::Brace)) {
6488 let mut at_end = false;
6489 match self.parse_trait_item(&mut at_end) {
6490 Ok(item) => trait_items.push(item),
6494 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6499 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
6503 fn choose_generics_over_qpath(&self) -> bool {
6504 // There's an ambiguity between generic parameters and qualified paths in impls.
6505 // If we see `<` it may start both, so we have to inspect some following tokens.
6506 // The following combinations can only start generics,
6507 // but not qualified paths (with one exception):
6508 // `<` `>` - empty generic parameters
6509 // `<` `#` - generic parameters with attributes
6510 // `<` (LIFETIME|IDENT) `>` - single generic parameter
6511 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
6512 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
6513 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
6514 // The only truly ambiguous case is
6515 // `<` IDENT `>` `::` IDENT ...
6516 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
6517 // because this is what almost always expected in practice, qualified paths in impls
6518 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
6519 self.token == token::Lt &&
6520 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
6521 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
6522 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
6523 t == &token::Colon || t == &token::Eq))
6526 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6527 self.expect(&token::OpenDelim(token::Brace))?;
6528 let attrs = self.parse_inner_attributes()?;
6530 let mut impl_items = Vec::new();
6531 while !self.eat(&token::CloseDelim(token::Brace)) {
6532 let mut at_end = false;
6533 match self.parse_impl_item(&mut at_end) {
6534 Ok(impl_item) => impl_items.push(impl_item),
6538 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6543 Ok((impl_items, attrs))
6546 /// Parses an implementation item, `impl` keyword is already parsed.
6547 /// impl<'a, T> TYPE { /* impl items */ }
6548 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6549 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6550 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6551 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6552 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6553 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6554 -> PResult<'a, ItemInfo> {
6555 // First, parse generic parameters if necessary.
6556 let mut generics = if self.choose_generics_over_qpath() {
6557 self.parse_generics()?
6559 ast::Generics::default()
6562 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6563 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6565 ast::ImplPolarity::Negative
6567 ast::ImplPolarity::Positive
6570 // Parse both types and traits as a type, then reinterpret if necessary.
6571 let ty_first = self.parse_ty()?;
6573 // If `for` is missing we try to recover.
6574 let has_for = self.eat_keyword(keywords::For);
6575 let missing_for_span = self.prev_span.between(self.span);
6577 let ty_second = if self.token == token::DotDot {
6578 // We need to report this error after `cfg` expansion for compatibility reasons
6579 self.bump(); // `..`, do not add it to expected tokens
6580 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
6581 } else if has_for || self.token.can_begin_type() {
6582 Some(self.parse_ty()?)
6587 generics.where_clause = self.parse_where_clause()?;
6589 let (impl_items, attrs) = self.parse_impl_body()?;
6591 let item_kind = match ty_second {
6592 Some(ty_second) => {
6593 // impl Trait for Type
6595 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6596 .span_suggestion_short_with_applicability(
6599 " for ".to_string(),
6600 Applicability::MachineApplicable,
6604 let ty_first = ty_first.into_inner();
6605 let path = match ty_first.node {
6606 // This notably includes paths passed through `ty` macro fragments (#46438).
6607 TyKind::Path(None, path) => path,
6609 self.span_err(ty_first.span, "expected a trait, found type");
6610 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
6613 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6615 ItemKind::Impl(unsafety, polarity, defaultness,
6616 generics, Some(trait_ref), ty_second, impl_items)
6620 ItemKind::Impl(unsafety, polarity, defaultness,
6621 generics, None, ty_first, impl_items)
6625 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
6628 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6629 if self.eat_keyword(keywords::For) {
6631 let params = self.parse_generic_params()?;
6633 // We rely on AST validation to rule out invalid cases: There must not be type
6634 // parameters, and the lifetime parameters must not have bounds.
6641 /// Parse struct Foo { ... }
6642 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6643 let class_name = self.parse_ident()?;
6645 let mut generics = self.parse_generics()?;
6647 // There is a special case worth noting here, as reported in issue #17904.
6648 // If we are parsing a tuple struct it is the case that the where clause
6649 // should follow the field list. Like so:
6651 // struct Foo<T>(T) where T: Copy;
6653 // If we are parsing a normal record-style struct it is the case
6654 // that the where clause comes before the body, and after the generics.
6655 // So if we look ahead and see a brace or a where-clause we begin
6656 // parsing a record style struct.
6658 // Otherwise if we look ahead and see a paren we parse a tuple-style
6661 let vdata = if self.token.is_keyword(keywords::Where) {
6662 generics.where_clause = self.parse_where_clause()?;
6663 if self.eat(&token::Semi) {
6664 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6665 VariantData::Unit(ast::DUMMY_NODE_ID)
6667 // If we see: `struct Foo<T> where T: Copy { ... }`
6668 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6670 // No `where` so: `struct Foo<T>;`
6671 } else if self.eat(&token::Semi) {
6672 VariantData::Unit(ast::DUMMY_NODE_ID)
6673 // Record-style struct definition
6674 } else if self.token == token::OpenDelim(token::Brace) {
6675 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6676 // Tuple-style struct definition with optional where-clause.
6677 } else if self.token == token::OpenDelim(token::Paren) {
6678 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6679 generics.where_clause = self.parse_where_clause()?;
6680 self.expect(&token::Semi)?;
6683 let token_str = self.this_token_descr();
6684 let mut err = self.fatal(&format!(
6685 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6688 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6692 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6695 /// Parse union Foo { ... }
6696 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6697 let class_name = self.parse_ident()?;
6699 let mut generics = self.parse_generics()?;
6701 let vdata = if self.token.is_keyword(keywords::Where) {
6702 generics.where_clause = self.parse_where_clause()?;
6703 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6704 } else if self.token == token::OpenDelim(token::Brace) {
6705 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6707 let token_str = self.this_token_descr();
6708 let mut err = self.fatal(&format!(
6709 "expected `where` or `{{` after union name, found {}", token_str));
6710 err.span_label(self.span, "expected `where` or `{` after union name");
6714 Ok((class_name, ItemKind::Union(vdata, generics), None))
6717 fn consume_block(&mut self, delim: token::DelimToken) {
6718 let mut brace_depth = 0;
6720 if self.eat(&token::OpenDelim(delim)) {
6722 } else if self.eat(&token::CloseDelim(delim)) {
6723 if brace_depth == 0 {
6729 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
6737 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6738 let mut fields = Vec::new();
6739 if self.eat(&token::OpenDelim(token::Brace)) {
6740 while self.token != token::CloseDelim(token::Brace) {
6741 let field = self.parse_struct_decl_field().map_err(|e| {
6742 self.recover_stmt();
6746 Ok(field) => fields.push(field),
6752 self.eat(&token::CloseDelim(token::Brace));
6754 let token_str = self.this_token_descr();
6755 let mut err = self.fatal(&format!(
6756 "expected `where`, or `{{` after struct name, found {}", token_str));
6757 err.span_label(self.span, "expected `where`, or `{` after struct name");
6764 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6765 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6766 // Unit like structs are handled in parse_item_struct function
6767 let fields = self.parse_unspanned_seq(
6768 &token::OpenDelim(token::Paren),
6769 &token::CloseDelim(token::Paren),
6770 SeqSep::trailing_allowed(token::Comma),
6772 let attrs = p.parse_outer_attributes()?;
6774 let vis = p.parse_visibility(true)?;
6775 let ty = p.parse_ty()?;
6777 span: lo.to(ty.span),
6780 id: ast::DUMMY_NODE_ID,
6789 /// Parse a structure field declaration
6790 fn parse_single_struct_field(&mut self,
6793 attrs: Vec<Attribute> )
6794 -> PResult<'a, StructField> {
6795 let mut seen_comma: bool = false;
6796 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6797 if self.token == token::Comma {
6804 token::CloseDelim(token::Brace) => {}
6805 token::DocComment(_) => {
6806 let previous_span = self.prev_span;
6807 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6808 self.bump(); // consume the doc comment
6809 let comma_after_doc_seen = self.eat(&token::Comma);
6810 // `seen_comma` is always false, because we are inside doc block
6811 // condition is here to make code more readable
6812 if seen_comma == false && comma_after_doc_seen == true {
6815 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6818 if seen_comma == false {
6819 let sp = self.sess.source_map().next_point(previous_span);
6820 err.span_suggestion_with_applicability(
6822 "missing comma here",
6824 Applicability::MachineApplicable
6831 let sp = self.sess.source_map().next_point(self.prev_span);
6832 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
6833 self.this_token_descr()));
6834 if self.token.is_ident() {
6835 // This is likely another field; emit the diagnostic and keep going
6836 err.span_suggestion_with_applicability(
6838 "try adding a comma",
6840 Applicability::MachineApplicable,
6851 /// Parse an element of a struct definition
6852 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6853 let attrs = self.parse_outer_attributes()?;
6855 let vis = self.parse_visibility(false)?;
6856 self.parse_single_struct_field(lo, vis, attrs)
6859 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
6860 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
6861 /// If the following element can't be a tuple (i.e., it's a function definition,
6862 /// it's not a tuple struct field) and the contents within the parens
6863 /// isn't valid, emit a proper diagnostic.
6864 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6865 maybe_whole!(self, NtVis, |x| x);
6867 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
6868 if self.is_crate_vis() {
6869 self.bump(); // `crate`
6870 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6873 if !self.eat_keyword(keywords::Pub) {
6874 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6875 // keyword to grab a span from for inherited visibility; an empty span at the
6876 // beginning of the current token would seem to be the "Schelling span".
6877 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6879 let lo = self.prev_span;
6881 if self.check(&token::OpenDelim(token::Paren)) {
6882 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6883 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6884 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6885 // by the following tokens.
6886 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
6889 self.bump(); // `crate`
6890 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6892 lo.to(self.prev_span),
6893 VisibilityKind::Crate(CrateSugar::PubCrate),
6896 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
6899 self.bump(); // `in`
6900 let path = self.parse_path(PathStyle::Mod)?; // `path`
6901 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6902 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6904 id: ast::DUMMY_NODE_ID,
6907 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6908 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
6909 t.is_keyword(keywords::SelfLower))
6911 // `pub(self)` or `pub(super)`
6913 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6914 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6915 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6917 id: ast::DUMMY_NODE_ID,
6920 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6921 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6923 let msg = "incorrect visibility restriction";
6924 let suggestion = r##"some possible visibility restrictions are:
6925 `pub(crate)`: visible only on the current crate
6926 `pub(super)`: visible only in the current module's parent
6927 `pub(in path::to::module)`: visible only on the specified path"##;
6928 let path = self.parse_path(PathStyle::Mod)?;
6929 let sp = self.prev_span;
6930 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6931 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6932 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6933 err.help(suggestion);
6934 err.span_suggestion_with_applicability(
6935 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6937 err.emit(); // emit diagnostic, but continue with public visibility
6941 Ok(respan(lo, VisibilityKind::Public))
6944 /// Parse defaultness: `default` or nothing.
6945 fn parse_defaultness(&mut self) -> Defaultness {
6946 // `pub` is included for better error messages
6947 if self.check_keyword(keywords::Default) &&
6948 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6949 t.is_keyword(keywords::Const) ||
6950 t.is_keyword(keywords::Fn) ||
6951 t.is_keyword(keywords::Unsafe) ||
6952 t.is_keyword(keywords::Extern) ||
6953 t.is_keyword(keywords::Type) ||
6954 t.is_keyword(keywords::Pub)) {
6955 self.bump(); // `default`
6956 Defaultness::Default
6962 fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
6963 if self.eat(&token::Semi) {
6964 let mut err = self.struct_span_err(self.prev_span, "expected item, found `;`");
6965 err.span_suggestion_short_with_applicability(
6967 "remove this semicolon",
6969 Applicability::MachineApplicable,
6971 if !items.is_empty() {
6972 let previous_item = &items[items.len()-1];
6973 let previous_item_kind_name = match previous_item.node {
6974 // say "braced struct" because tuple-structs and
6975 // braceless-empty-struct declarations do take a semicolon
6976 ItemKind::Struct(..) => Some("braced struct"),
6977 ItemKind::Enum(..) => Some("enum"),
6978 ItemKind::Trait(..) => Some("trait"),
6979 ItemKind::Union(..) => Some("union"),
6982 if let Some(name) = previous_item_kind_name {
6983 err.help(&format!("{} declarations are not followed by a semicolon", name));
6993 /// Given a termination token, parse all of the items in a module
6994 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6995 let mut items = vec![];
6996 while let Some(item) = self.parse_item()? {
6998 self.maybe_consume_incorrect_semicolon(&items);
7001 if !self.eat(term) {
7002 let token_str = self.this_token_descr();
7003 if !self.maybe_consume_incorrect_semicolon(&items) {
7004 let mut err = self.fatal(&format!("expected item, found {}", token_str));
7005 err.span_label(self.span, "expected item");
7010 let hi = if self.span.is_dummy() {
7017 inner: inner_lo.to(hi),
7023 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
7024 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
7025 self.expect(&token::Colon)?;
7026 let ty = self.parse_ty()?;
7027 self.expect(&token::Eq)?;
7028 let e = self.parse_expr()?;
7029 self.expect(&token::Semi)?;
7030 let item = match m {
7031 Some(m) => ItemKind::Static(ty, m, e),
7032 None => ItemKind::Const(ty, e),
7034 Ok((id, item, None))
7037 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
7038 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
7039 let (in_cfg, outer_attrs) = {
7040 let mut strip_unconfigured = ::config::StripUnconfigured {
7042 features: None, // don't perform gated feature checking
7044 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
7045 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
7048 let id_span = self.span;
7049 let id = self.parse_ident()?;
7050 if self.eat(&token::Semi) {
7051 if in_cfg && self.recurse_into_file_modules {
7052 // This mod is in an external file. Let's go get it!
7053 let ModulePathSuccess { path, directory_ownership, warn } =
7054 self.submod_path(id, &outer_attrs, id_span)?;
7055 let (module, mut attrs) =
7056 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
7057 // Record that we fetched the mod from an external file
7059 let attr = Attribute {
7060 id: attr::mk_attr_id(),
7061 style: ast::AttrStyle::Outer,
7062 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
7063 tokens: TokenStream::empty(),
7064 is_sugared_doc: false,
7065 span: syntax_pos::DUMMY_SP,
7067 attr::mark_known(&attr);
7070 Ok((id, ItemKind::Mod(module), Some(attrs)))
7072 let placeholder = ast::Mod {
7073 inner: syntax_pos::DUMMY_SP,
7077 Ok((id, ItemKind::Mod(placeholder), None))
7080 let old_directory = self.directory.clone();
7081 self.push_directory(id, &outer_attrs);
7083 self.expect(&token::OpenDelim(token::Brace))?;
7084 let mod_inner_lo = self.span;
7085 let attrs = self.parse_inner_attributes()?;
7086 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
7088 self.directory = old_directory;
7089 Ok((id, ItemKind::Mod(module), Some(attrs)))
7093 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
7094 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
7095 self.directory.path.to_mut().push(&path.as_str());
7096 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
7098 // We have to push on the current module name in the case of relative
7099 // paths in order to ensure that any additional module paths from inline
7100 // `mod x { ... }` come after the relative extension.
7102 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
7103 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
7104 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
7105 if let Some(ident) = relative.take() { // remove the relative offset
7106 self.directory.path.to_mut().push(ident.as_str());
7109 self.directory.path.to_mut().push(&id.as_str());
7113 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
7114 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
7117 // On windows, the base path might have the form
7118 // `\\?\foo\bar` in which case it does not tolerate
7119 // mixed `/` and `\` separators, so canonicalize
7122 let s = s.replace("/", "\\");
7123 Some(dir_path.join(s))
7129 /// Returns either a path to a module, or .
7130 pub fn default_submod_path(
7132 relative: Option<ast::Ident>,
7134 source_map: &SourceMap) -> ModulePath
7136 // If we're in a foo.rs file instead of a mod.rs file,
7137 // we need to look for submodules in
7138 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
7139 // `./<id>.rs` and `./<id>/mod.rs`.
7140 let relative_prefix_string;
7141 let relative_prefix = if let Some(ident) = relative {
7142 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
7143 &relative_prefix_string
7148 let mod_name = id.to_string();
7149 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
7150 let secondary_path_str = format!("{}{}{}mod.rs",
7151 relative_prefix, mod_name, path::MAIN_SEPARATOR);
7152 let default_path = dir_path.join(&default_path_str);
7153 let secondary_path = dir_path.join(&secondary_path_str);
7154 let default_exists = source_map.file_exists(&default_path);
7155 let secondary_exists = source_map.file_exists(&secondary_path);
7157 let result = match (default_exists, secondary_exists) {
7158 (true, false) => Ok(ModulePathSuccess {
7160 directory_ownership: DirectoryOwnership::Owned {
7165 (false, true) => Ok(ModulePathSuccess {
7166 path: secondary_path,
7167 directory_ownership: DirectoryOwnership::Owned {
7172 (false, false) => Err(Error::FileNotFoundForModule {
7173 mod_name: mod_name.clone(),
7174 default_path: default_path_str,
7175 secondary_path: secondary_path_str,
7176 dir_path: dir_path.display().to_string(),
7178 (true, true) => Err(Error::DuplicatePaths {
7179 mod_name: mod_name.clone(),
7180 default_path: default_path_str,
7181 secondary_path: secondary_path_str,
7187 path_exists: default_exists || secondary_exists,
7192 fn submod_path(&mut self,
7194 outer_attrs: &[Attribute],
7196 -> PResult<'a, ModulePathSuccess> {
7197 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
7198 return Ok(ModulePathSuccess {
7199 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
7200 // All `#[path]` files are treated as though they are a `mod.rs` file.
7201 // This means that `mod foo;` declarations inside `#[path]`-included
7202 // files are siblings,
7204 // Note that this will produce weirdness when a file named `foo.rs` is
7205 // `#[path]` included and contains a `mod foo;` declaration.
7206 // If you encounter this, it's your own darn fault :P
7207 Some(_) => DirectoryOwnership::Owned { relative: None },
7208 _ => DirectoryOwnership::UnownedViaMod(true),
7215 let relative = match self.directory.ownership {
7216 DirectoryOwnership::Owned { relative } => relative,
7217 DirectoryOwnership::UnownedViaBlock |
7218 DirectoryOwnership::UnownedViaMod(_) => None,
7220 let paths = Parser::default_submod_path(
7221 id, relative, &self.directory.path, self.sess.source_map());
7223 match self.directory.ownership {
7224 DirectoryOwnership::Owned { .. } => {
7225 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
7227 DirectoryOwnership::UnownedViaBlock => {
7229 "Cannot declare a non-inline module inside a block \
7230 unless it has a path attribute";
7231 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
7232 if paths.path_exists {
7233 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
7235 err.span_note(id_sp, &msg);
7239 DirectoryOwnership::UnownedViaMod(warn) => {
7241 if let Ok(result) = paths.result {
7242 return Ok(ModulePathSuccess { warn: true, ..result });
7245 let mut err = self.diagnostic().struct_span_err(id_sp,
7246 "cannot declare a new module at this location");
7247 if !id_sp.is_dummy() {
7248 let src_path = self.sess.source_map().span_to_filename(id_sp);
7249 if let FileName::Real(src_path) = src_path {
7250 if let Some(stem) = src_path.file_stem() {
7251 let mut dest_path = src_path.clone();
7252 dest_path.set_file_name(stem);
7253 dest_path.push("mod.rs");
7254 err.span_note(id_sp,
7255 &format!("maybe move this module `{}` to its own \
7256 directory via `{}`", src_path.display(),
7257 dest_path.display()));
7261 if paths.path_exists {
7262 err.span_note(id_sp,
7263 &format!("... or maybe `use` the module `{}` instead \
7264 of possibly redeclaring it",
7272 /// Read a module from a source file.
7273 fn eval_src_mod(&mut self,
7275 directory_ownership: DirectoryOwnership,
7278 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
7279 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
7280 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
7281 let mut err = String::from("circular modules: ");
7282 let len = included_mod_stack.len();
7283 for p in &included_mod_stack[i.. len] {
7284 err.push_str(&p.to_string_lossy());
7285 err.push_str(" -> ");
7287 err.push_str(&path.to_string_lossy());
7288 return Err(self.span_fatal(id_sp, &err[..]));
7290 included_mod_stack.push(path.clone());
7291 drop(included_mod_stack);
7294 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
7295 p0.cfg_mods = self.cfg_mods;
7296 let mod_inner_lo = p0.span;
7297 let mod_attrs = p0.parse_inner_attributes()?;
7298 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
7300 self.sess.included_mod_stack.borrow_mut().pop();
7304 /// Parse a function declaration from a foreign module
7305 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7306 -> PResult<'a, ForeignItem> {
7307 self.expect_keyword(keywords::Fn)?;
7309 let (ident, mut generics) = self.parse_fn_header()?;
7310 let decl = self.parse_fn_decl(true)?;
7311 generics.where_clause = self.parse_where_clause()?;
7313 self.expect(&token::Semi)?;
7314 Ok(ast::ForeignItem {
7317 node: ForeignItemKind::Fn(decl, generics),
7318 id: ast::DUMMY_NODE_ID,
7324 /// Parse a static item from a foreign module.
7325 /// Assumes that the `static` keyword is already parsed.
7326 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7327 -> PResult<'a, ForeignItem> {
7328 let mutbl = self.eat_keyword(keywords::Mut);
7329 let ident = self.parse_ident()?;
7330 self.expect(&token::Colon)?;
7331 let ty = self.parse_ty()?;
7333 self.expect(&token::Semi)?;
7337 node: ForeignItemKind::Static(ty, mutbl),
7338 id: ast::DUMMY_NODE_ID,
7344 /// Parse a type from a foreign module
7345 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7346 -> PResult<'a, ForeignItem> {
7347 self.expect_keyword(keywords::Type)?;
7349 let ident = self.parse_ident()?;
7351 self.expect(&token::Semi)?;
7352 Ok(ast::ForeignItem {
7355 node: ForeignItemKind::Ty,
7356 id: ast::DUMMY_NODE_ID,
7362 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
7363 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
7364 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
7366 let mut ident = if self.token.is_keyword(keywords::SelfLower) {
7367 self.parse_path_segment_ident()
7371 let mut idents = vec![];
7372 let mut replacement = vec![];
7373 let mut fixed_crate_name = false;
7374 // Accept `extern crate name-like-this` for better diagnostics
7375 let dash = token::Token::BinOp(token::BinOpToken::Minus);
7376 if self.token == dash { // Do not include `-` as part of the expected tokens list
7377 while self.eat(&dash) {
7378 fixed_crate_name = true;
7379 replacement.push((self.prev_span, "_".to_string()));
7380 idents.push(self.parse_ident()?);
7383 if fixed_crate_name {
7384 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
7385 let mut fixed_name = format!("{}", ident.name);
7386 for part in idents {
7387 fixed_name.push_str(&format!("_{}", part.name));
7389 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
7391 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
7392 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
7393 err.multipart_suggestion_with_applicability(
7396 Applicability::MachineApplicable,
7403 /// Parse extern crate links
7407 /// extern crate foo;
7408 /// extern crate bar as foo;
7409 fn parse_item_extern_crate(&mut self,
7411 visibility: Visibility,
7412 attrs: Vec<Attribute>)
7413 -> PResult<'a, P<Item>> {
7414 // Accept `extern crate name-like-this` for better diagnostics
7415 let orig_name = self.parse_crate_name_with_dashes()?;
7416 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
7417 (rename, Some(orig_name.name))
7421 self.expect(&token::Semi)?;
7423 let span = lo.to(self.prev_span);
7424 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
7427 /// Parse `extern` for foreign ABIs
7430 /// `extern` is expected to have been
7431 /// consumed before calling this method
7437 fn parse_item_foreign_mod(&mut self,
7439 opt_abi: Option<Abi>,
7440 visibility: Visibility,
7441 mut attrs: Vec<Attribute>)
7442 -> PResult<'a, P<Item>> {
7443 self.expect(&token::OpenDelim(token::Brace))?;
7445 let abi = opt_abi.unwrap_or(Abi::C);
7447 attrs.extend(self.parse_inner_attributes()?);
7449 let mut foreign_items = vec![];
7450 while !self.eat(&token::CloseDelim(token::Brace)) {
7451 foreign_items.push(self.parse_foreign_item()?);
7454 let prev_span = self.prev_span;
7455 let m = ast::ForeignMod {
7457 items: foreign_items
7459 let invalid = keywords::Invalid.ident();
7460 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
7463 /// Parse `type Foo = Bar;`
7465 /// `existential type Foo: Bar;`
7467 /// `return None` without modifying the parser state
7468 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
7469 // This parses the grammar:
7470 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
7471 if self.check_keyword(keywords::Type) ||
7472 self.check_keyword(keywords::Existential) &&
7473 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
7474 let existential = self.eat_keyword(keywords::Existential);
7475 assert!(self.eat_keyword(keywords::Type));
7476 Some(self.parse_existential_or_alias(existential))
7482 /// Parse type alias or existential type
7483 fn parse_existential_or_alias(
7486 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
7487 let ident = self.parse_ident()?;
7488 let mut tps = self.parse_generics()?;
7489 tps.where_clause = self.parse_where_clause()?;
7490 let alias = if existential {
7491 self.expect(&token::Colon)?;
7492 let bounds = self.parse_generic_bounds()?;
7493 AliasKind::Existential(bounds)
7495 self.expect(&token::Eq)?;
7496 let ty = self.parse_ty()?;
7499 self.expect(&token::Semi)?;
7500 Ok((ident, alias, tps))
7503 /// Parse the part of an "enum" decl following the '{'
7504 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
7505 let mut variants = Vec::new();
7506 let mut all_nullary = true;
7507 let mut any_disr = vec![];
7508 while self.token != token::CloseDelim(token::Brace) {
7509 let variant_attrs = self.parse_outer_attributes()?;
7510 let vlo = self.span;
7513 let mut disr_expr = None;
7514 let ident = self.parse_ident()?;
7515 if self.check(&token::OpenDelim(token::Brace)) {
7516 // Parse a struct variant.
7517 all_nullary = false;
7518 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
7519 ast::DUMMY_NODE_ID);
7520 } else if self.check(&token::OpenDelim(token::Paren)) {
7521 all_nullary = false;
7522 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
7523 ast::DUMMY_NODE_ID);
7524 } else if self.eat(&token::Eq) {
7525 disr_expr = Some(AnonConst {
7526 id: ast::DUMMY_NODE_ID,
7527 value: self.parse_expr()?,
7529 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
7532 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7534 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7537 let vr = ast::Variant_ {
7539 attrs: variant_attrs,
7543 variants.push(respan(vlo.to(self.prev_span), vr));
7545 if !self.eat(&token::Comma) { break; }
7547 self.expect(&token::CloseDelim(token::Brace))?;
7548 if !any_disr.is_empty() && !all_nullary {
7549 let mut err =self.struct_span_err(
7551 "discriminator values can only be used with a field-less enum",
7553 for sp in any_disr {
7554 err.span_label(sp, "only valid in field-less enums");
7559 Ok(ast::EnumDef { variants })
7562 /// Parse an "enum" declaration
7563 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7564 let id = self.parse_ident()?;
7565 let mut generics = self.parse_generics()?;
7566 generics.where_clause = self.parse_where_clause()?;
7567 self.expect(&token::OpenDelim(token::Brace))?;
7569 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7570 self.recover_stmt();
7571 self.eat(&token::CloseDelim(token::Brace));
7574 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7577 /// Parses a string as an ABI spec on an extern type or module. Consumes
7578 /// the `extern` keyword, if one is found.
7579 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7581 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
7583 self.expect_no_suffix(sp, "ABI spec", suf);
7585 match abi::lookup(&s.as_str()) {
7586 Some(abi) => Ok(Some(abi)),
7588 let prev_span = self.prev_span;
7589 let mut err = struct_span_err!(
7590 self.sess.span_diagnostic,
7593 "invalid ABI: found `{}`",
7595 err.span_label(prev_span, "invalid ABI");
7596 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7607 fn is_static_global(&mut self) -> bool {
7608 if self.check_keyword(keywords::Static) {
7609 // Check if this could be a closure
7610 !self.look_ahead(1, |token| {
7611 if token.is_keyword(keywords::Move) {
7615 token::BinOp(token::Or) | token::OrOr => true,
7626 attrs: Vec<Attribute>,
7627 macros_allowed: bool,
7628 attributes_allowed: bool,
7629 ) -> PResult<'a, Option<P<Item>>> {
7630 let (ret, tokens) = self.collect_tokens(|this| {
7631 this.parse_item_implementation(attrs, macros_allowed, attributes_allowed)
7634 // Once we've parsed an item and recorded the tokens we got while
7635 // parsing we may want to store `tokens` into the item we're about to
7636 // return. Note, though, that we specifically didn't capture tokens
7637 // related to outer attributes. The `tokens` field here may later be
7638 // used with procedural macros to convert this item back into a token
7639 // stream, but during expansion we may be removing attributes as we go
7642 // If we've got inner attributes then the `tokens` we've got above holds
7643 // these inner attributes. If an inner attribute is expanded we won't
7644 // actually remove it from the token stream, so we'll just keep yielding
7645 // it (bad!). To work around this case for now we just avoid recording
7646 // `tokens` if we detect any inner attributes. This should help keep
7647 // expansion correct, but we should fix this bug one day!
7650 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7651 i.tokens = Some(tokens);
7658 /// Parse one of the items allowed by the flags.
7659 fn parse_item_implementation(
7661 attrs: Vec<Attribute>,
7662 macros_allowed: bool,
7663 attributes_allowed: bool,
7664 ) -> PResult<'a, Option<P<Item>>> {
7665 maybe_whole!(self, NtItem, |item| {
7666 let mut item = item.into_inner();
7667 let mut attrs = attrs;
7668 mem::swap(&mut item.attrs, &mut attrs);
7669 item.attrs.extend(attrs);
7675 let visibility = self.parse_visibility(false)?;
7677 if self.eat_keyword(keywords::Use) {
7679 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7680 self.expect(&token::Semi)?;
7682 let span = lo.to(self.prev_span);
7683 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
7684 return Ok(Some(item));
7687 if self.eat_keyword(keywords::Extern) {
7688 if self.eat_keyword(keywords::Crate) {
7689 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7692 let opt_abi = self.parse_opt_abi()?;
7694 if self.eat_keyword(keywords::Fn) {
7695 // EXTERN FUNCTION ITEM
7696 let fn_span = self.prev_span;
7697 let abi = opt_abi.unwrap_or(Abi::C);
7698 let (ident, item_, extra_attrs) =
7699 self.parse_item_fn(Unsafety::Normal,
7701 respan(fn_span, Constness::NotConst),
7703 let prev_span = self.prev_span;
7704 let item = self.mk_item(lo.to(prev_span),
7708 maybe_append(attrs, extra_attrs));
7709 return Ok(Some(item));
7710 } else if self.check(&token::OpenDelim(token::Brace)) {
7711 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7717 if self.is_static_global() {
7720 let m = if self.eat_keyword(keywords::Mut) {
7723 Mutability::Immutable
7725 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7726 let prev_span = self.prev_span;
7727 let item = self.mk_item(lo.to(prev_span),
7731 maybe_append(attrs, extra_attrs));
7732 return Ok(Some(item));
7734 if self.eat_keyword(keywords::Const) {
7735 let const_span = self.prev_span;
7736 if self.check_keyword(keywords::Fn)
7737 || (self.check_keyword(keywords::Unsafe)
7738 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
7739 // CONST FUNCTION ITEM
7740 let unsafety = self.parse_unsafety();
7742 let (ident, item_, extra_attrs) =
7743 self.parse_item_fn(unsafety,
7745 respan(const_span, Constness::Const),
7747 let prev_span = self.prev_span;
7748 let item = self.mk_item(lo.to(prev_span),
7752 maybe_append(attrs, extra_attrs));
7753 return Ok(Some(item));
7757 if self.eat_keyword(keywords::Mut) {
7758 let prev_span = self.prev_span;
7759 let mut err = self.diagnostic()
7760 .struct_span_err(prev_span, "const globals cannot be mutable");
7761 err.span_label(prev_span, "cannot be mutable");
7762 err.span_suggestion_with_applicability(
7764 "you might want to declare a static instead",
7765 "static".to_owned(),
7766 Applicability::MaybeIncorrect,
7770 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7771 let prev_span = self.prev_span;
7772 let item = self.mk_item(lo.to(prev_span),
7776 maybe_append(attrs, extra_attrs));
7777 return Ok(Some(item));
7780 // `unsafe async fn` or `async fn`
7782 self.check_keyword(keywords::Unsafe) &&
7783 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
7785 self.check_keyword(keywords::Async) &&
7786 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
7789 // ASYNC FUNCTION ITEM
7790 let unsafety = self.parse_unsafety();
7791 self.expect_keyword(keywords::Async)?;
7792 self.expect_keyword(keywords::Fn)?;
7793 let fn_span = self.prev_span;
7794 let (ident, item_, extra_attrs) =
7795 self.parse_item_fn(unsafety,
7797 closure_id: ast::DUMMY_NODE_ID,
7798 return_impl_trait_id: ast::DUMMY_NODE_ID,
7800 respan(fn_span, Constness::NotConst),
7802 let prev_span = self.prev_span;
7803 let item = self.mk_item(lo.to(prev_span),
7807 maybe_append(attrs, extra_attrs));
7808 return Ok(Some(item));
7810 if self.check_keyword(keywords::Unsafe) &&
7811 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
7812 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
7814 // UNSAFE TRAIT ITEM
7815 self.bump(); // `unsafe`
7816 let is_auto = if self.eat_keyword(keywords::Trait) {
7819 self.expect_keyword(keywords::Auto)?;
7820 self.expect_keyword(keywords::Trait)?;
7823 let (ident, item_, extra_attrs) =
7824 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7825 let prev_span = self.prev_span;
7826 let item = self.mk_item(lo.to(prev_span),
7830 maybe_append(attrs, extra_attrs));
7831 return Ok(Some(item));
7833 if self.check_keyword(keywords::Impl) ||
7834 self.check_keyword(keywords::Unsafe) &&
7835 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7836 self.check_keyword(keywords::Default) &&
7837 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7838 self.check_keyword(keywords::Default) &&
7839 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
7841 let defaultness = self.parse_defaultness();
7842 let unsafety = self.parse_unsafety();
7843 self.expect_keyword(keywords::Impl)?;
7844 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7845 let span = lo.to(self.prev_span);
7846 return Ok(Some(self.mk_item(span, ident, item, visibility,
7847 maybe_append(attrs, extra_attrs))));
7849 if self.check_keyword(keywords::Fn) {
7852 let fn_span = self.prev_span;
7853 let (ident, item_, extra_attrs) =
7854 self.parse_item_fn(Unsafety::Normal,
7856 respan(fn_span, Constness::NotConst),
7858 let prev_span = self.prev_span;
7859 let item = self.mk_item(lo.to(prev_span),
7863 maybe_append(attrs, extra_attrs));
7864 return Ok(Some(item));
7866 if self.check_keyword(keywords::Unsafe)
7867 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7868 // UNSAFE FUNCTION ITEM
7869 self.bump(); // `unsafe`
7870 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7871 self.check(&token::OpenDelim(token::Brace));
7872 let abi = if self.eat_keyword(keywords::Extern) {
7873 self.parse_opt_abi()?.unwrap_or(Abi::C)
7877 self.expect_keyword(keywords::Fn)?;
7878 let fn_span = self.prev_span;
7879 let (ident, item_, extra_attrs) =
7880 self.parse_item_fn(Unsafety::Unsafe,
7882 respan(fn_span, Constness::NotConst),
7884 let prev_span = self.prev_span;
7885 let item = self.mk_item(lo.to(prev_span),
7889 maybe_append(attrs, extra_attrs));
7890 return Ok(Some(item));
7892 if self.eat_keyword(keywords::Mod) {
7894 let (ident, item_, extra_attrs) =
7895 self.parse_item_mod(&attrs[..])?;
7896 let prev_span = self.prev_span;
7897 let item = self.mk_item(lo.to(prev_span),
7901 maybe_append(attrs, extra_attrs));
7902 return Ok(Some(item));
7904 if let Some(type_) = self.eat_type() {
7905 let (ident, alias, generics) = type_?;
7907 let item_ = match alias {
7908 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7909 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7911 let prev_span = self.prev_span;
7912 let item = self.mk_item(lo.to(prev_span),
7917 return Ok(Some(item));
7919 if self.eat_keyword(keywords::Enum) {
7921 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7922 let prev_span = self.prev_span;
7923 let item = self.mk_item(lo.to(prev_span),
7927 maybe_append(attrs, extra_attrs));
7928 return Ok(Some(item));
7930 if self.check_keyword(keywords::Trait)
7931 || (self.check_keyword(keywords::Auto)
7932 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
7934 let is_auto = if self.eat_keyword(keywords::Trait) {
7937 self.expect_keyword(keywords::Auto)?;
7938 self.expect_keyword(keywords::Trait)?;
7942 let (ident, item_, extra_attrs) =
7943 self.parse_item_trait(is_auto, Unsafety::Normal)?;
7944 let prev_span = self.prev_span;
7945 let item = self.mk_item(lo.to(prev_span),
7949 maybe_append(attrs, extra_attrs));
7950 return Ok(Some(item));
7952 if self.eat_keyword(keywords::Struct) {
7954 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
7955 let prev_span = self.prev_span;
7956 let item = self.mk_item(lo.to(prev_span),
7960 maybe_append(attrs, extra_attrs));
7961 return Ok(Some(item));
7963 if self.is_union_item() {
7966 let (ident, item_, extra_attrs) = self.parse_item_union()?;
7967 let prev_span = self.prev_span;
7968 let item = self.mk_item(lo.to(prev_span),
7972 maybe_append(attrs, extra_attrs));
7973 return Ok(Some(item));
7975 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
7976 return Ok(Some(macro_def));
7979 // Verify whether we have encountered a struct or method definition where the user forgot to
7980 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
7981 if visibility.node.is_pub() &&
7982 self.check_ident() &&
7983 self.look_ahead(1, |t| *t != token::Not)
7985 // Space between `pub` keyword and the identifier
7988 // ^^^ `sp` points here
7989 let sp = self.prev_span.between(self.span);
7990 let full_sp = self.prev_span.to(self.span);
7991 let ident_sp = self.span;
7992 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
7993 // possible public struct definition where `struct` was forgotten
7994 let ident = self.parse_ident().unwrap();
7995 let msg = format!("add `struct` here to parse `{}` as a public struct",
7997 let mut err = self.diagnostic()
7998 .struct_span_err(sp, "missing `struct` for struct definition");
7999 err.span_suggestion_short_with_applicability(
8000 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
8003 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
8004 let ident = self.parse_ident().unwrap();
8006 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
8011 self.consume_block(token::Paren);
8012 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
8013 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
8015 ("fn", kw_name, false)
8016 } else if self.check(&token::OpenDelim(token::Brace)) {
8018 ("fn", kw_name, false)
8019 } else if self.check(&token::Colon) {
8023 ("fn` or `struct", "function or struct", true)
8025 self.consume_block(token::Brace);
8027 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8028 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8030 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
8034 err.span_suggestion_short_with_applicability(
8035 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
8038 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
8039 err.span_suggestion_with_applicability(
8041 "if you meant to call a macro, try",
8042 format!("{}!", snippet),
8043 // this is the `ambiguous` conditional branch
8044 Applicability::MaybeIncorrect
8047 err.help("if you meant to call a macro, remove the `pub` \
8048 and add a trailing `!` after the identifier");
8052 } else if self.look_ahead(1, |t| *t == token::Lt) {
8053 let ident = self.parse_ident().unwrap();
8054 self.eat_to_tokens(&[&token::Gt]);
8056 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
8057 if let Ok(Some(_)) = self.parse_self_arg() {
8058 ("fn", "method", false)
8060 ("fn", "function", false)
8062 } else if self.check(&token::OpenDelim(token::Brace)) {
8063 ("struct", "struct", false)
8065 ("fn` or `struct", "function or struct", true)
8067 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8068 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8070 err.span_suggestion_short_with_applicability(
8072 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
8073 format!(" {} ", kw),
8074 Applicability::MachineApplicable,
8080 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
8083 /// Parse a foreign item.
8084 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
8085 maybe_whole!(self, NtForeignItem, |ni| ni);
8087 let attrs = self.parse_outer_attributes()?;
8089 let visibility = self.parse_visibility(false)?;
8091 // FOREIGN STATIC ITEM
8092 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
8093 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
8094 if self.token.is_keyword(keywords::Const) {
8096 .struct_span_err(self.span, "extern items cannot be `const`")
8097 .span_suggestion_with_applicability(
8099 "try using a static value",
8100 "static".to_owned(),
8101 Applicability::MachineApplicable
8104 self.bump(); // `static` or `const`
8105 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
8107 // FOREIGN FUNCTION ITEM
8108 if self.check_keyword(keywords::Fn) {
8109 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
8111 // FOREIGN TYPE ITEM
8112 if self.check_keyword(keywords::Type) {
8113 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
8116 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
8120 ident: keywords::Invalid.ident(),
8121 span: lo.to(self.prev_span),
8122 id: ast::DUMMY_NODE_ID,
8125 node: ForeignItemKind::Macro(mac),
8130 if !attrs.is_empty() {
8131 self.expected_item_err(&attrs)?;
8139 /// This is the fall-through for parsing items.
8140 fn parse_macro_use_or_failure(
8142 attrs: Vec<Attribute> ,
8143 macros_allowed: bool,
8144 attributes_allowed: bool,
8146 visibility: Visibility
8147 ) -> PResult<'a, Option<P<Item>>> {
8148 if macros_allowed && self.token.is_path_start() {
8149 // MACRO INVOCATION ITEM
8151 let prev_span = self.prev_span;
8152 self.complain_if_pub_macro(&visibility.node, prev_span);
8154 let mac_lo = self.span;
8157 let pth = self.parse_path(PathStyle::Mod)?;
8158 self.expect(&token::Not)?;
8160 // a 'special' identifier (like what `macro_rules!` uses)
8161 // is optional. We should eventually unify invoc syntax
8163 let id = if self.token.is_ident() {
8166 keywords::Invalid.ident() // no special identifier
8168 // eat a matched-delimiter token tree:
8169 let (delim, tts) = self.expect_delimited_token_tree()?;
8170 if delim != MacDelimiter::Brace {
8171 if !self.eat(&token::Semi) {
8172 self.span_err(self.prev_span,
8173 "macros that expand to items must either \
8174 be surrounded with braces or followed by \
8179 let hi = self.prev_span;
8180 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
8181 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
8182 return Ok(Some(item));
8185 // FAILURE TO PARSE ITEM
8186 match visibility.node {
8187 VisibilityKind::Inherited => {}
8189 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
8193 if !attributes_allowed && !attrs.is_empty() {
8194 self.expected_item_err(&attrs)?;
8199 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
8200 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
8201 at_end: &mut bool) -> PResult<'a, Option<Mac>>
8203 if self.token.is_path_start() {
8204 let prev_span = self.prev_span;
8206 let pth = self.parse_path(PathStyle::Mod)?;
8208 if pth.segments.len() == 1 {
8209 if !self.eat(&token::Not) {
8210 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
8213 self.expect(&token::Not)?;
8216 if let Some(vis) = vis {
8217 self.complain_if_pub_macro(&vis.node, prev_span);
8222 // eat a matched-delimiter token tree:
8223 let (delim, tts) = self.expect_delimited_token_tree()?;
8224 if delim != MacDelimiter::Brace {
8225 self.expect(&token::Semi)?
8228 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
8234 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
8235 where F: FnOnce(&mut Self) -> PResult<'a, R>
8237 // Record all tokens we parse when parsing this item.
8238 let mut tokens = Vec::new();
8239 let prev_collecting = match self.token_cursor.frame.last_token {
8240 LastToken::Collecting(ref mut list) => {
8241 Some(mem::replace(list, Vec::new()))
8243 LastToken::Was(ref mut last) => {
8244 tokens.extend(last.take());
8248 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
8249 let prev = self.token_cursor.stack.len();
8251 let last_token = if self.token_cursor.stack.len() == prev {
8252 &mut self.token_cursor.frame.last_token
8254 &mut self.token_cursor.stack[prev].last_token
8257 // Pull out the tokens that we've collected from the call to `f` above.
8258 let mut collected_tokens = match *last_token {
8259 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
8260 LastToken::Was(_) => panic!("our vector went away?"),
8263 // If we're not at EOF our current token wasn't actually consumed by
8264 // `f`, but it'll still be in our list that we pulled out. In that case
8266 let extra_token = if self.token != token::Eof {
8267 collected_tokens.pop()
8272 // If we were previously collecting tokens, then this was a recursive
8273 // call. In that case we need to record all the tokens we collected in
8274 // our parent list as well. To do that we push a clone of our stream
8275 // onto the previous list.
8276 match prev_collecting {
8278 list.extend(collected_tokens.iter().cloned());
8279 list.extend(extra_token);
8280 *last_token = LastToken::Collecting(list);
8283 *last_token = LastToken::Was(extra_token);
8287 Ok((ret?, TokenStream::new(collected_tokens)))
8290 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
8291 let attrs = self.parse_outer_attributes()?;
8292 self.parse_item_(attrs, true, false)
8296 fn is_import_coupler(&mut self) -> bool {
8297 self.check(&token::ModSep) &&
8298 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
8299 *t == token::BinOp(token::Star))
8304 /// USE_TREE = [`::`] `*` |
8305 /// [`::`] `{` USE_TREE_LIST `}` |
8307 /// PATH `::` `{` USE_TREE_LIST `}` |
8308 /// PATH [`as` IDENT]
8309 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
8312 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
8313 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
8314 self.check(&token::BinOp(token::Star)) ||
8315 self.is_import_coupler() {
8316 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
8317 let mod_sep_ctxt = self.span.ctxt();
8318 if self.eat(&token::ModSep) {
8319 prefix.segments.push(
8320 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
8324 if self.eat(&token::BinOp(token::Star)) {
8327 UseTreeKind::Nested(self.parse_use_tree_list()?)
8330 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
8331 prefix = self.parse_path(PathStyle::Mod)?;
8333 if self.eat(&token::ModSep) {
8334 if self.eat(&token::BinOp(token::Star)) {
8337 UseTreeKind::Nested(self.parse_use_tree_list()?)
8340 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
8344 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
8347 /// Parse UseTreeKind::Nested(list)
8349 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
8350 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
8351 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
8352 &token::CloseDelim(token::Brace),
8353 SeqSep::trailing_allowed(token::Comma), |this| {
8354 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
8358 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
8359 if self.eat_keyword(keywords::As) {
8360 self.parse_ident_or_underscore().map(Some)
8366 /// Parses a source module as a crate. This is the main
8367 /// entry point for the parser.
8368 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
8371 attrs: self.parse_inner_attributes()?,
8372 module: self.parse_mod_items(&token::Eof, lo)?,
8373 span: lo.to(self.span),
8377 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
8378 let ret = match self.token {
8379 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
8380 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
8387 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
8388 match self.parse_optional_str() {
8389 Some((s, style, suf)) => {
8390 let sp = self.prev_span;
8391 self.expect_no_suffix(sp, "string literal", suf);
8395 let msg = "expected string literal";
8396 let mut err = self.fatal(msg);
8397 err.span_label(self.span, msg);