1 // ignore-tidy-filelength
3 use crate::ast::{AngleBracketedArgs, AsyncArgument, ParenthesizedArgs, AttrStyle, BareFnTy};
4 use crate::ast::{GenericBound, TraitBoundModifier};
5 use crate::ast::Unsafety;
6 use crate::ast::{Mod, AnonConst, Arg, ArgSource, Arm, Guard, Attribute, BindingMode, TraitItemKind};
8 use crate::ast::{BlockCheckMode, CaptureBy, Movability};
9 use crate::ast::{Constness, Crate};
10 use crate::ast::Defaultness;
11 use crate::ast::EnumDef;
12 use crate::ast::{Expr, ExprKind, RangeLimits};
13 use crate::ast::{Field, FnDecl, FnHeader};
14 use crate::ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
15 use crate::ast::{GenericParam, GenericParamKind};
16 use crate::ast::GenericArg;
17 use crate::ast::{Ident, ImplItem, IsAsync, IsAuto, Item, ItemKind};
18 use crate::ast::{Label, Lifetime, Lit, LitKind};
19 use crate::ast::{Local, LocalSource};
20 use crate::ast::MacStmtStyle;
21 use crate::ast::{Mac, Mac_, MacDelimiter};
22 use crate::ast::{MutTy, Mutability};
23 use crate::ast::{Pat, PatKind, PathSegment};
24 use crate::ast::{PolyTraitRef, QSelf};
25 use crate::ast::{Stmt, StmtKind};
26 use crate::ast::{VariantData, StructField};
27 use crate::ast::StrStyle;
28 use crate::ast::SelfKind;
29 use crate::ast::{TraitItem, TraitRef, TraitObjectSyntax};
30 use crate::ast::{Ty, TyKind, TypeBinding, GenericBounds};
31 use crate::ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
32 use crate::ast::{UseTree, UseTreeKind};
33 use crate::ast::{BinOpKind, UnOp};
34 use crate::ast::{RangeEnd, RangeSyntax};
35 use crate::{ast, attr};
36 use crate::ext::base::DummyResult;
37 use crate::source_map::{self, SourceMap, Spanned, respan};
38 use crate::parse::{self, SeqSep, classify, token};
39 use crate::parse::lexer::{TokenAndSpan, UnmatchedBrace};
40 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
41 use crate::parse::token::DelimToken;
42 use crate::parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
43 use crate::util::parser::{AssocOp, Fixity};
44 use crate::print::pprust;
46 use crate::parse::PResult;
48 use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
49 use crate::symbol::{Symbol, keywords};
51 use errors::{Applicability, DiagnosticBuilder, DiagnosticId, FatalError};
52 use rustc_target::spec::abi::{self, Abi};
53 use syntax_pos::{Span, MultiSpan, BytePos, FileName};
54 use log::{debug, trace};
59 use std::path::{self, Path, PathBuf};
63 /// Whether the type alias or associated type is a concrete type or an existential type
65 /// Just a new name for the same type
67 /// Only trait impls of the type will be usable, not the actual type itself
68 Existential(GenericBounds),
72 struct Restrictions: u8 {
73 const STMT_EXPR = 1 << 0;
74 const NO_STRUCT_LITERAL = 1 << 1;
78 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
80 /// Specifies how to parse a path.
81 #[derive(Copy, Clone, PartialEq)]
83 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
84 /// with something else. For example, in expressions `segment < ....` can be interpreted
85 /// as a comparison and `segment ( ....` can be interpreted as a function call.
86 /// In all such contexts the non-path interpretation is preferred by default for practical
87 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
88 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
90 /// In other contexts, notably in types, no ambiguity exists and paths can be written
91 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
92 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
94 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
95 /// visibilities or attributes.
96 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
97 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
98 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
99 /// tokens when something goes wrong.
103 #[derive(Clone, Copy, PartialEq, Debug)]
110 #[derive(Clone, Copy, PartialEq, Debug)]
116 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
117 /// dropped into the token stream, which happens while parsing the result of
118 /// macro expansion). Placement of these is not as complex as I feared it would
119 /// be. The important thing is to make sure that lookahead doesn't balk at
120 /// `token::Interpolated` tokens.
121 macro_rules! maybe_whole_expr {
123 if let token::Interpolated(nt) = &$p.token {
125 token::NtExpr(e) | token::NtLiteral(e) => {
130 token::NtPath(path) => {
131 let path = path.clone();
133 return Ok($p.mk_expr($p.span, ExprKind::Path(None, path), ThinVec::new()));
135 token::NtBlock(block) => {
136 let block = block.clone();
138 return Ok($p.mk_expr($p.span, ExprKind::Block(block, None), ThinVec::new()));
146 /// As maybe_whole_expr, but for things other than expressions
147 macro_rules! maybe_whole {
148 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
149 if let token::Interpolated(nt) = &$p.token {
150 if let token::$constructor(x) = &**nt {
159 /// If the next tokens are ill-formed `$ty::` recover them as `<$ty>::`.
160 macro_rules! maybe_recover_from_interpolated_ty_qpath {
161 ($self: expr, $allow_qpath_recovery: expr) => {
162 if $allow_qpath_recovery && $self.look_ahead(1, |t| t == &token::ModSep) {
163 if let token::Interpolated(nt) = &$self.token {
164 if let token::NtTy(ty) = &**nt {
167 return $self.maybe_recover_from_bad_qpath_stage_2($self.prev_span, ty);
174 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
175 if let Some(ref mut rhs) = rhs {
181 #[derive(Debug, Clone, Copy, PartialEq)]
192 trait RecoverQPath: Sized + 'static {
193 const PATH_STYLE: PathStyle = PathStyle::Expr;
194 fn to_ty(&self) -> Option<P<Ty>>;
195 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self;
198 impl RecoverQPath for Ty {
199 const PATH_STYLE: PathStyle = PathStyle::Type;
200 fn to_ty(&self) -> Option<P<Ty>> {
201 Some(P(self.clone()))
203 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
204 Self { span: path.span, node: TyKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
208 impl RecoverQPath for Pat {
209 fn to_ty(&self) -> Option<P<Ty>> {
212 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
213 Self { span: path.span, node: PatKind::Path(qself, path), id: ast::DUMMY_NODE_ID }
217 impl RecoverQPath for Expr {
218 fn to_ty(&self) -> Option<P<Ty>> {
221 fn recovered(qself: Option<QSelf>, path: ast::Path) -> Self {
222 Self { span: path.span, node: ExprKind::Path(qself, path),
223 attrs: ThinVec::new(), id: ast::DUMMY_NODE_ID }
227 /* ident is handled by common.rs */
230 pub struct Parser<'a> {
231 pub sess: &'a ParseSess,
232 /// the current token:
233 pub token: token::Token,
234 /// the span of the current token:
236 /// the span of the previous token:
237 meta_var_span: Option<Span>,
239 /// the previous token kind
240 prev_token_kind: PrevTokenKind,
241 restrictions: Restrictions,
242 /// Used to determine the path to externally loaded source files
243 crate directory: Directory<'a>,
244 /// Whether to parse sub-modules in other files.
245 pub recurse_into_file_modules: bool,
246 /// Name of the root module this parser originated from. If `None`, then the
247 /// name is not known. This does not change while the parser is descending
248 /// into modules, and sub-parsers have new values for this name.
249 pub root_module_name: Option<String>,
250 crate expected_tokens: Vec<TokenType>,
251 token_cursor: TokenCursor,
252 desugar_doc_comments: bool,
253 /// Whether we should configure out of line modules as we parse.
255 /// This field is used to keep track of how many left angle brackets we have seen. This is
256 /// required in order to detect extra leading left angle brackets (`<` characters) and error
259 /// See the comments in the `parse_path_segment` function for more details.
260 crate unmatched_angle_bracket_count: u32,
261 crate max_angle_bracket_count: u32,
262 /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
263 /// it gets removed from here. Every entry left at the end gets emitted as an independent
265 crate unclosed_delims: Vec<UnmatchedBrace>,
266 last_unexpected_token_span: Option<Span>,
269 impl<'a> Drop for Parser<'a> {
271 let diag = self.diagnostic();
272 emit_unclosed_delims(&mut self.unclosed_delims, diag);
278 frame: TokenCursorFrame,
279 stack: Vec<TokenCursorFrame>,
283 struct TokenCursorFrame {
284 delim: token::DelimToken,
287 tree_cursor: tokenstream::Cursor,
289 last_token: LastToken,
292 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
293 /// by the parser, and then that's transitively used to record the tokens that
294 /// each parse AST item is created with.
296 /// Right now this has two states, either collecting tokens or not collecting
297 /// tokens. If we're collecting tokens we just save everything off into a local
298 /// `Vec`. This should eventually though likely save tokens from the original
299 /// token stream and just use slicing of token streams to avoid creation of a
300 /// whole new vector.
302 /// The second state is where we're passively not recording tokens, but the last
303 /// token is still tracked for when we want to start recording tokens. This
304 /// "last token" means that when we start recording tokens we'll want to ensure
305 /// that this, the first token, is included in the output.
307 /// You can find some more example usage of this in the `collect_tokens` method
311 Collecting(Vec<TreeAndJoint>),
312 Was(Option<TreeAndJoint>),
315 impl TokenCursorFrame {
316 fn new(sp: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
320 open_delim: delim == token::NoDelim,
321 tree_cursor: tts.clone().into_trees(),
322 close_delim: delim == token::NoDelim,
323 last_token: LastToken::Was(None),
329 fn next(&mut self) -> TokenAndSpan {
331 let tree = if !self.frame.open_delim {
332 self.frame.open_delim = true;
333 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
334 } else if let Some(tree) = self.frame.tree_cursor.next() {
336 } else if !self.frame.close_delim {
337 self.frame.close_delim = true;
338 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
339 } else if let Some(frame) = self.stack.pop() {
343 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
346 match self.frame.last_token {
347 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
348 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
352 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
353 TokenTree::Delimited(sp, delim, tts) => {
354 let frame = TokenCursorFrame::new(sp, delim, &tts);
355 self.stack.push(mem::replace(&mut self.frame, frame));
361 fn next_desugared(&mut self) -> TokenAndSpan {
362 let (sp, name) = match self.next() {
363 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
367 let stripped = strip_doc_comment_decoration(&name.as_str());
369 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
370 // required to wrap the text.
371 let mut num_of_hashes = 0;
373 for ch in stripped.chars() {
376 '#' if count > 0 => count + 1,
379 num_of_hashes = cmp::max(num_of_hashes, count);
382 let delim_span = DelimSpan::from_single(sp);
383 let body = TokenTree::Delimited(
386 [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
387 TokenTree::Token(sp, token::Eq),
388 TokenTree::Token(sp, token::Literal(
389 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))
391 .iter().cloned().collect::<TokenStream>().into(),
394 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
397 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
398 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
399 .iter().cloned().collect::<TokenStream>().into()
401 [TokenTree::Token(sp, token::Pound), body]
402 .iter().cloned().collect::<TokenStream>().into()
410 #[derive(Clone, PartialEq)]
411 crate enum TokenType {
413 Keyword(keywords::Keyword),
423 fn to_string(&self) -> String {
425 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
426 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
427 TokenType::Operator => "an operator".to_string(),
428 TokenType::Lifetime => "lifetime".to_string(),
429 TokenType::Ident => "identifier".to_string(),
430 TokenType::Path => "path".to_string(),
431 TokenType::Type => "type".to_string(),
432 TokenType::Const => "const".to_string(),
437 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
438 /// `IDENT<<u8 as Trait>::AssocTy>`.
440 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
441 /// that `IDENT` is not the ident of a fn trait.
442 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
443 t == &token::ModSep || t == &token::Lt ||
444 t == &token::BinOp(token::Shl)
447 /// Information about the path to a module.
448 pub struct ModulePath {
451 pub result: Result<ModulePathSuccess, Error>,
454 pub struct ModulePathSuccess {
456 pub directory_ownership: DirectoryOwnership,
461 FileNotFoundForModule {
463 default_path: String,
464 secondary_path: String,
469 default_path: String,
470 secondary_path: String,
473 InclusiveRangeWithNoEnd,
477 fn span_err<S: Into<MultiSpan>>(self,
479 handler: &errors::Handler) -> DiagnosticBuilder<'_> {
481 Error::FileNotFoundForModule { ref mod_name,
485 let mut err = struct_span_err!(handler, sp, E0583,
486 "file not found for module `{}`", mod_name);
487 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
493 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
494 let mut err = struct_span_err!(handler, sp, E0584,
495 "file for module `{}` found at both {} and {}",
499 err.help("delete or rename one of them to remove the ambiguity");
502 Error::UselessDocComment => {
503 let mut err = struct_span_err!(handler, sp, E0585,
504 "found a documentation comment that doesn't document anything");
505 err.help("doc comments must come before what they document, maybe a comment was \
506 intended with `//`?");
509 Error::InclusiveRangeWithNoEnd => {
510 let mut err = struct_span_err!(handler, sp, E0586,
511 "inclusive range with no end");
512 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
522 AttributesParsed(ThinVec<Attribute>),
523 AlreadyParsed(P<Expr>),
526 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
527 fn from(o: Option<ThinVec<Attribute>>) -> Self {
528 if let Some(attrs) = o {
529 LhsExpr::AttributesParsed(attrs)
531 LhsExpr::NotYetParsed
536 impl From<P<Expr>> for LhsExpr {
537 fn from(expr: P<Expr>) -> Self {
538 LhsExpr::AlreadyParsed(expr)
542 /// Creates a placeholder argument.
543 fn dummy_arg(span: Span) -> Arg {
544 let ident = Ident::new(keywords::Invalid.name(), span);
546 id: ast::DUMMY_NODE_ID,
547 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
553 id: ast::DUMMY_NODE_ID
555 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal }
558 #[derive(Copy, Clone, Debug)]
559 enum TokenExpectType {
564 impl<'a> Parser<'a> {
565 pub fn new(sess: &'a ParseSess,
567 directory: Option<Directory<'a>>,
568 recurse_into_file_modules: bool,
569 desugar_doc_comments: bool)
571 let mut parser = Parser {
573 token: token::Whitespace,
574 span: syntax_pos::DUMMY_SP,
575 prev_span: syntax_pos::DUMMY_SP,
577 prev_token_kind: PrevTokenKind::Other,
578 restrictions: Restrictions::empty(),
579 recurse_into_file_modules,
580 directory: Directory {
581 path: Cow::from(PathBuf::new()),
582 ownership: DirectoryOwnership::Owned { relative: None }
584 root_module_name: None,
585 expected_tokens: Vec::new(),
586 token_cursor: TokenCursor {
587 frame: TokenCursorFrame::new(
594 desugar_doc_comments,
596 unmatched_angle_bracket_count: 0,
597 max_angle_bracket_count: 0,
598 unclosed_delims: Vec::new(),
599 last_unexpected_token_span: None,
602 let tok = parser.next_tok();
603 parser.token = tok.tok;
604 parser.span = tok.sp;
606 if let Some(directory) = directory {
607 parser.directory = directory;
608 } else if !parser.span.is_dummy() {
609 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
611 parser.directory.path = Cow::from(path);
615 parser.process_potential_macro_variable();
619 fn next_tok(&mut self) -> TokenAndSpan {
620 let mut next = if self.desugar_doc_comments {
621 self.token_cursor.next_desugared()
623 self.token_cursor.next()
625 if next.sp.is_dummy() {
626 // Tweak the location for better diagnostics, but keep syntactic context intact.
627 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
632 /// Converts the current token to a string using `self`'s reader.
633 pub fn this_token_to_string(&self) -> String {
634 pprust::token_to_string(&self.token)
637 fn token_descr(&self) -> Option<&'static str> {
638 Some(match &self.token {
639 t if t.is_special_ident() => "reserved identifier",
640 t if t.is_used_keyword() => "keyword",
641 t if t.is_unused_keyword() => "reserved keyword",
642 token::DocComment(..) => "doc comment",
647 fn this_token_descr(&self) -> String {
648 if let Some(prefix) = self.token_descr() {
649 format!("{} `{}`", prefix, self.this_token_to_string())
651 format!("`{}`", self.this_token_to_string())
655 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
656 let token_str = pprust::token_to_string(t);
657 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
660 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
661 match self.expect_one_of(&[], &[]) {
663 Ok(_) => unreachable!(),
667 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
668 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, bool /* recovered */> {
669 if self.expected_tokens.is_empty() {
670 if self.token == *t {
674 let token_str = pprust::token_to_string(t);
675 let this_token_str = self.this_token_descr();
676 let mut err = self.fatal(&format!("expected `{}`, found {}",
680 let sp = if self.token == token::Token::Eof {
681 // EOF, don't want to point at the following char, but rather the last token
684 self.sess.source_map().next_point(self.prev_span)
686 let label_exp = format!("expected `{}`", token_str);
687 match self.recover_closing_delimiter(&[t.clone()], err) {
690 return Ok(recovered);
693 let cm = self.sess.source_map();
694 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
695 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
696 // When the spans are in the same line, it means that the only content
697 // between them is whitespace, point only at the found token.
698 err.span_label(self.span, label_exp);
701 err.span_label(sp, label_exp);
702 err.span_label(self.span, "unexpected token");
708 self.expect_one_of(slice::from_ref(t), &[])
712 fn recover_closing_delimiter(
714 tokens: &[token::Token],
715 mut err: DiagnosticBuilder<'a>,
716 ) -> PResult<'a, bool> {
718 // we want to use the last closing delim that would apply
719 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
720 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
721 && Some(self.span) > unmatched.unclosed_span
728 // Recover and assume that the detected unclosed delimiter was meant for
729 // this location. Emit the diagnostic and act as if the delimiter was
730 // present for the parser's sake.
732 // Don't attempt to recover from this unclosed delimiter more than once.
733 let unmatched = self.unclosed_delims.remove(pos);
734 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
736 // We want to suggest the inclusion of the closing delimiter where it makes
737 // the most sense, which is immediately after the last token:
742 // | help: `)` may belong here (FIXME: #58270)
744 // unclosed delimiter
745 if let Some(sp) = unmatched.unclosed_span {
746 err.span_label(sp, "unclosed delimiter");
748 err.span_suggestion_short(
749 self.sess.source_map().next_point(self.prev_span),
750 &format!("{} may belong here", delim.to_string()),
752 Applicability::MaybeIncorrect,
755 self.expected_tokens.clear(); // reduce errors
762 /// Expect next token to be edible or inedible token. If edible,
763 /// then consume it; if inedible, then return without consuming
764 /// anything. Signal a fatal error if next token is unexpected.
765 pub fn expect_one_of(
767 edible: &[token::Token],
768 inedible: &[token::Token],
769 ) -> PResult<'a, bool /* recovered */> {
770 fn tokens_to_string(tokens: &[TokenType]) -> String {
771 let mut i = tokens.iter();
772 // This might be a sign we need a connect method on Iterator.
774 .map_or(String::new(), |t| t.to_string());
775 i.enumerate().fold(b, |mut b, (i, a)| {
776 if tokens.len() > 2 && i == tokens.len() - 2 {
778 } else if tokens.len() == 2 && i == tokens.len() - 2 {
783 b.push_str(&a.to_string());
787 if edible.contains(&self.token) {
790 } else if inedible.contains(&self.token) {
791 // leave it in the input
793 } else if self.last_unexpected_token_span == Some(self.span) {
796 let mut expected = edible.iter()
797 .map(|x| TokenType::Token(x.clone()))
798 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
799 .chain(self.expected_tokens.iter().cloned())
800 .collect::<Vec<_>>();
801 expected.sort_by_cached_key(|x| x.to_string());
803 let expect = tokens_to_string(&expected[..]);
804 let actual = self.this_token_to_string();
805 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
806 let short_expect = if expected.len() > 6 {
807 format!("{} possible tokens", expected.len())
811 (format!("expected one of {}, found `{}`", expect, actual),
812 (self.sess.source_map().next_point(self.prev_span),
813 format!("expected one of {} here", short_expect)))
814 } else if expected.is_empty() {
815 (format!("unexpected token: `{}`", actual),
816 (self.prev_span, "unexpected token after this".to_string()))
818 (format!("expected {}, found `{}`", expect, actual),
819 (self.sess.source_map().next_point(self.prev_span),
820 format!("expected {} here", expect)))
822 self.last_unexpected_token_span = Some(self.span);
823 let mut err = self.fatal(&msg_exp);
824 if self.token.is_ident_named("and") {
825 err.span_suggestion_short(
827 "use `&&` instead of `and` for the boolean operator",
829 Applicability::MaybeIncorrect,
832 if self.token.is_ident_named("or") {
833 err.span_suggestion_short(
835 "use `||` instead of `or` for the boolean operator",
837 Applicability::MaybeIncorrect,
840 let sp = if self.token == token::Token::Eof {
841 // This is EOF, don't want to point at the following char, but rather the last token
846 match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt {
847 TokenType::Token(t) => Some(t.clone()),
849 }).collect::<Vec<_>>(), err) {
852 return Ok(recovered);
856 let is_semi_suggestable = expected.iter().any(|t| match t {
857 TokenType::Token(token::Semi) => true, // we expect a `;` here
859 }) && ( // a `;` would be expected before the current keyword
860 self.token.is_keyword(keywords::Break) ||
861 self.token.is_keyword(keywords::Continue) ||
862 self.token.is_keyword(keywords::For) ||
863 self.token.is_keyword(keywords::If) ||
864 self.token.is_keyword(keywords::Let) ||
865 self.token.is_keyword(keywords::Loop) ||
866 self.token.is_keyword(keywords::Match) ||
867 self.token.is_keyword(keywords::Return) ||
868 self.token.is_keyword(keywords::While)
870 let cm = self.sess.source_map();
871 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
872 (Ok(ref a), Ok(ref b)) if a.line != b.line && is_semi_suggestable => {
873 // The spans are in different lines, expected `;` and found `let` or `return`.
874 // High likelihood that it is only a missing `;`.
875 err.span_suggestion_short(
877 "a semicolon may be missing here",
879 Applicability::MaybeIncorrect,
884 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
885 // When the spans are in the same line, it means that the only content between
886 // them is whitespace, point at the found token in that case:
888 // X | () => { syntax error };
889 // | ^^^^^ expected one of 8 possible tokens here
891 // instead of having:
893 // X | () => { syntax error };
894 // | -^^^^^ unexpected token
896 // | expected one of 8 possible tokens here
897 err.span_label(self.span, label_exp);
899 _ if self.prev_span == syntax_pos::DUMMY_SP => {
900 // Account for macro context where the previous span might not be
901 // available to avoid incorrect output (#54841).
902 err.span_label(self.span, "unexpected token");
905 err.span_label(sp, label_exp);
906 err.span_label(self.span, "unexpected token");
913 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
914 fn interpolated_or_expr_span(&self,
915 expr: PResult<'a, P<Expr>>)
916 -> PResult<'a, (Span, P<Expr>)> {
918 if self.prev_token_kind == PrevTokenKind::Interpolated {
926 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
927 let mut err = self.struct_span_err(self.span,
928 &format!("expected identifier, found {}",
929 self.this_token_descr()));
930 if let token::Ident(ident, false) = &self.token {
931 if ident.is_raw_guess() {
934 "you can escape reserved keywords to use them as identifiers",
935 format!("r#{}", ident),
936 Applicability::MaybeIncorrect,
940 if let Some(token_descr) = self.token_descr() {
941 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
943 err.span_label(self.span, "expected identifier");
944 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
949 Applicability::MachineApplicable,
956 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
957 self.parse_ident_common(true)
960 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
962 token::Ident(ident, _) => {
963 if self.token.is_reserved_ident() {
964 let mut err = self.expected_ident_found();
971 let span = self.span;
973 Ok(Ident::new(ident.name, span))
976 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
977 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
979 self.expected_ident_found()
985 /// Checks if the next token is `tok`, and returns `true` if so.
987 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
989 crate fn check(&mut self, tok: &token::Token) -> bool {
990 let is_present = self.token == *tok;
991 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
995 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
996 pub fn eat(&mut self, tok: &token::Token) -> bool {
997 let is_present = self.check(tok);
998 if is_present { self.bump() }
1002 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
1003 self.expected_tokens.push(TokenType::Keyword(kw));
1004 self.token.is_keyword(kw)
1007 /// If the next token is the given keyword, eats it and returns
1008 /// `true`. Otherwise, returns `false`.
1009 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
1010 if self.check_keyword(kw) {
1018 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
1019 if self.token.is_keyword(kw) {
1027 /// If the given word is not a keyword, signals an error.
1028 /// If the next token is not the given word, signals an error.
1029 /// Otherwise, eats it.
1030 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
1031 if !self.eat_keyword(kw) {
1038 fn check_ident(&mut self) -> bool {
1039 if self.token.is_ident() {
1042 self.expected_tokens.push(TokenType::Ident);
1047 fn check_path(&mut self) -> bool {
1048 if self.token.is_path_start() {
1051 self.expected_tokens.push(TokenType::Path);
1056 fn check_type(&mut self) -> bool {
1057 if self.token.can_begin_type() {
1060 self.expected_tokens.push(TokenType::Type);
1065 fn check_const_arg(&mut self) -> bool {
1066 if self.token.can_begin_const_arg() {
1069 self.expected_tokens.push(TokenType::Const);
1074 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
1075 /// and continues. If a `+` is not seen, returns `false`.
1077 /// This is used when token-splitting `+=` into `+`.
1078 /// See issue #47856 for an example of when this may occur.
1079 fn eat_plus(&mut self) -> bool {
1080 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1082 token::BinOp(token::Plus) => {
1086 token::BinOpEq(token::Plus) => {
1087 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1088 self.bump_with(token::Eq, span);
1096 /// Checks to see if the next token is either `+` or `+=`.
1097 /// Otherwise returns `false`.
1098 fn check_plus(&mut self) -> bool {
1099 if self.token.is_like_plus() {
1103 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1108 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
1109 /// `&` and continues. If an `&` is not seen, signals an error.
1110 fn expect_and(&mut self) -> PResult<'a, ()> {
1111 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
1113 token::BinOp(token::And) => {
1118 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1119 Ok(self.bump_with(token::BinOp(token::And), span))
1121 _ => self.unexpected()
1125 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
1126 /// `|` and continues. If an `|` is not seen, signals an error.
1127 fn expect_or(&mut self) -> PResult<'a, ()> {
1128 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
1130 token::BinOp(token::Or) => {
1135 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1136 Ok(self.bump_with(token::BinOp(token::Or), span))
1138 _ => self.unexpected()
1142 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
1144 None => {/* everything ok */}
1146 let text = suf.as_str();
1147 if text.is_empty() {
1148 self.span_bug(sp, "found empty literal suffix in Some")
1150 let mut err = if kind == "a tuple index" &&
1151 ["i32", "u32", "isize", "usize"].contains(&text.to_string().as_str())
1153 // #59553: warn instead of reject out of hand to allow the fix to percolate
1154 // through the ecosystem when people fix their macros
1155 let mut err = self.struct_span_warn(
1157 &format!("suffixes on {} are invalid", kind),
1160 "`{}` is *temporarily* accepted on tuple index fields as it was \
1161 incorrectly accepted on stable for a few releases",
1165 "on proc macros, you'll want to use `syn::Index::from` or \
1166 `proc_macro::Literal::*_unsuffixed` for code that will desugar \
1167 to tuple field access",
1170 "for more context, see https://github.com/rust-lang/rust/issues/60210",
1174 self.struct_span_err(sp, &format!("suffixes on {} are invalid", kind))
1176 err.span_label(sp, format!("invalid suffix `{}`", text));
1182 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
1183 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
1184 /// and continue. If a `<` is not seen, returns false.
1186 /// This is meant to be used when parsing generics on a path to get the
1188 fn eat_lt(&mut self) -> bool {
1189 self.expected_tokens.push(TokenType::Token(token::Lt));
1190 let ate = match self.token {
1195 token::BinOp(token::Shl) => {
1196 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1197 self.bump_with(token::Lt, span);
1201 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1202 self.bump_with(token::BinOp(token::Minus), span);
1209 // See doc comment for `unmatched_angle_bracket_count`.
1210 self.unmatched_angle_bracket_count += 1;
1211 self.max_angle_bracket_count += 1;
1212 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
1218 fn expect_lt(&mut self) -> PResult<'a, ()> {
1226 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
1227 /// with a single `>` and continues. If a `>` is not seen, signals an error.
1228 fn expect_gt(&mut self) -> PResult<'a, ()> {
1229 self.expected_tokens.push(TokenType::Token(token::Gt));
1230 let ate = match self.token {
1235 token::BinOp(token::Shr) => {
1236 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1237 Some(self.bump_with(token::Gt, span))
1239 token::BinOpEq(token::Shr) => {
1240 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1241 Some(self.bump_with(token::Ge, span))
1244 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1245 Some(self.bump_with(token::Eq, span))
1252 // See doc comment for `unmatched_angle_bracket_count`.
1253 if self.unmatched_angle_bracket_count > 0 {
1254 self.unmatched_angle_bracket_count -= 1;
1255 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1260 None => self.unexpected(),
1264 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
1265 /// passes through any errors encountered. Used for error recovery.
1266 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1267 let handler = self.diagnostic();
1269 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1271 TokenExpectType::Expect,
1272 |p| Ok(p.parse_token_tree())) {
1273 handler.cancel(err);
1277 /// Parses a sequence, including the closing delimiter. The function
1278 /// `f` must consume tokens until reaching the next separator or
1279 /// closing bracket.
1280 pub fn parse_seq_to_end<T, F>(&mut self,
1284 -> PResult<'a, Vec<T>> where
1285 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1287 let (val, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1294 /// Parses a sequence, not including the closing delimiter. The function
1295 /// `f` must consume tokens until reaching the next separator or
1296 /// closing bracket.
1297 pub fn parse_seq_to_before_end<T, F>(
1302 ) -> PResult<'a, (Vec<T>, bool)>
1303 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1305 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1308 fn parse_seq_to_before_tokens<T, F>(
1310 kets: &[&token::Token],
1312 expect: TokenExpectType,
1314 ) -> PResult<'a, (Vec<T>, bool /* recovered */)>
1315 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1317 let mut first = true;
1318 let mut recovered = false;
1320 while !kets.iter().any(|k| {
1322 TokenExpectType::Expect => self.check(k),
1323 TokenExpectType::NoExpect => self.token == **k,
1327 token::CloseDelim(..) | token::Eof => break,
1330 if let Some(ref t) = sep.sep {
1334 match self.expect(t) {
1341 // Attempt to keep parsing if it was a similar separator
1342 if let Some(ref tokens) = t.similar_tokens() {
1343 if tokens.contains(&self.token) {
1348 // Attempt to keep parsing if it was an omitted separator
1363 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1365 TokenExpectType::Expect => self.check(k),
1366 TokenExpectType::NoExpect => self.token == **k,
1379 /// Parses a sequence, including the closing delimiter. The function
1380 /// `f` must consume tokens until reaching the next separator or
1381 /// closing bracket.
1382 fn parse_unspanned_seq<T, F>(
1388 ) -> PResult<'a, Vec<T>> where
1389 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1392 let (result, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1399 /// Advance the parser by one token
1400 pub fn bump(&mut self) {
1401 if self.prev_token_kind == PrevTokenKind::Eof {
1402 // Bumping after EOF is a bad sign, usually an infinite loop.
1403 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1406 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1408 // Record last token kind for possible error recovery.
1409 self.prev_token_kind = match self.token {
1410 token::DocComment(..) => PrevTokenKind::DocComment,
1411 token::Comma => PrevTokenKind::Comma,
1412 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1413 token::Interpolated(..) => PrevTokenKind::Interpolated,
1414 token::Eof => PrevTokenKind::Eof,
1415 token::Ident(..) => PrevTokenKind::Ident,
1416 _ => PrevTokenKind::Other,
1419 let next = self.next_tok();
1420 self.span = next.sp;
1421 self.token = next.tok;
1422 self.expected_tokens.clear();
1423 // check after each token
1424 self.process_potential_macro_variable();
1427 /// Advance the parser using provided token as a next one. Use this when
1428 /// consuming a part of a token. For example a single `<` from `<<`.
1429 fn bump_with(&mut self, next: token::Token, span: Span) {
1430 self.prev_span = self.span.with_hi(span.lo());
1431 // It would be incorrect to record the kind of the current token, but
1432 // fortunately for tokens currently using `bump_with`, the
1433 // prev_token_kind will be of no use anyway.
1434 self.prev_token_kind = PrevTokenKind::Other;
1437 self.expected_tokens.clear();
1440 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1441 F: FnOnce(&token::Token) -> R,
1444 return f(&self.token)
1447 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1448 Some(tree) => match tree {
1449 TokenTree::Token(_, tok) => tok,
1450 TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim),
1452 None => token::CloseDelim(self.token_cursor.frame.delim),
1456 fn look_ahead_span(&self, dist: usize) -> Span {
1461 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1462 Some(TokenTree::Token(span, _)) => span,
1463 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1464 None => self.look_ahead_span(dist - 1),
1467 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1468 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1470 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1471 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1473 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1474 err.span_err(sp, self.diagnostic())
1476 fn bug(&self, m: &str) -> ! {
1477 self.sess.span_diagnostic.span_bug(self.span, m)
1479 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1480 self.sess.span_diagnostic.span_err(sp, m)
1482 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1483 self.sess.span_diagnostic.struct_span_err(sp, m)
1485 fn struct_span_warn<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1486 self.sess.span_diagnostic.struct_span_warn(sp, m)
1488 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1489 self.sess.span_diagnostic.span_bug(sp, m)
1492 fn cancel(&self, err: &mut DiagnosticBuilder<'_>) {
1493 self.sess.span_diagnostic.cancel(err)
1496 crate fn diagnostic(&self) -> &'a errors::Handler {
1497 &self.sess.span_diagnostic
1500 /// Is the current token one of the keywords that signals a bare function type?
1501 fn token_is_bare_fn_keyword(&mut self) -> bool {
1502 self.check_keyword(keywords::Fn) ||
1503 self.check_keyword(keywords::Unsafe) ||
1504 self.check_keyword(keywords::Extern)
1507 /// Parses a `TyKind::BareFn` type.
1508 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1511 [unsafe] [extern "ABI"] fn (S) -> T
1521 let unsafety = self.parse_unsafety();
1522 let abi = if self.eat_keyword(keywords::Extern) {
1523 self.parse_opt_abi()?.unwrap_or(Abi::C)
1528 self.expect_keyword(keywords::Fn)?;
1529 let (inputs, c_variadic) = self.parse_fn_args(false, true)?;
1530 let ret_ty = self.parse_ret_ty(false)?;
1531 let decl = P(FnDecl {
1536 Ok(TyKind::BareFn(P(BareFnTy {
1544 /// Parses asyncness: `async` or nothing.
1545 fn parse_asyncness(&mut self) -> IsAsync {
1546 if self.eat_keyword(keywords::Async) {
1548 closure_id: ast::DUMMY_NODE_ID,
1549 return_impl_trait_id: ast::DUMMY_NODE_ID,
1550 arguments: Vec::new(),
1557 /// Parses unsafety: `unsafe` or nothing.
1558 fn parse_unsafety(&mut self) -> Unsafety {
1559 if self.eat_keyword(keywords::Unsafe) {
1566 /// Parses the items in a trait declaration.
1567 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1568 maybe_whole!(self, NtTraitItem, |x| x);
1569 let attrs = self.parse_outer_attributes()?;
1570 let mut unclosed_delims = vec![];
1571 let (mut item, tokens) = self.collect_tokens(|this| {
1572 let item = this.parse_trait_item_(at_end, attrs);
1573 unclosed_delims.append(&mut this.unclosed_delims);
1576 self.unclosed_delims.append(&mut unclosed_delims);
1577 // See `parse_item` for why this clause is here.
1578 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1579 item.tokens = Some(tokens);
1584 fn parse_trait_item_(&mut self,
1586 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1589 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1590 self.parse_trait_item_assoc_ty()?
1591 } else if self.is_const_item() {
1592 self.expect_keyword(keywords::Const)?;
1593 let ident = self.parse_ident()?;
1594 self.expect(&token::Colon)?;
1595 let ty = self.parse_ty()?;
1596 let default = if self.eat(&token::Eq) {
1597 let expr = self.parse_expr()?;
1598 self.expect(&token::Semi)?;
1601 self.expect(&token::Semi)?;
1604 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1605 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1606 // trait item macro.
1607 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1609 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
1611 let ident = self.parse_ident()?;
1612 let mut generics = self.parse_generics()?;
1614 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1615 // This is somewhat dubious; We don't want to allow
1616 // argument names to be left off if there is a
1619 // We don't allow argument names to be left off in edition 2018.
1620 p.parse_arg_general(p.span.rust_2018(), true, false)
1622 generics.where_clause = self.parse_where_clause()?;
1623 self.construct_async_arguments(&mut asyncness, &d);
1625 let sig = ast::MethodSig {
1635 let body = match self.token {
1639 debug!("parse_trait_methods(): parsing required method");
1642 token::OpenDelim(token::Brace) => {
1643 debug!("parse_trait_methods(): parsing provided method");
1645 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1646 attrs.extend(inner_attrs.iter().cloned());
1649 token::Interpolated(ref nt) => {
1651 token::NtBlock(..) => {
1653 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1654 attrs.extend(inner_attrs.iter().cloned());
1658 let token_str = self.this_token_descr();
1659 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1661 err.span_label(self.span, "expected `;` or `{`");
1667 let token_str = self.this_token_descr();
1668 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1670 err.span_label(self.span, "expected `;` or `{`");
1674 (ident, ast::TraitItemKind::Method(sig, body), generics)
1678 id: ast::DUMMY_NODE_ID,
1683 span: lo.to(self.prev_span),
1688 /// Parses an optional return type `[ -> TY ]` in a function declaration.
1689 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1690 if self.eat(&token::RArrow) {
1691 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true, false)?))
1693 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1698 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1699 self.parse_ty_common(true, true, false)
1702 /// Parses a type in restricted contexts where `+` is not permitted.
1704 /// Example 1: `&'a TYPE`
1705 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1706 /// Example 2: `value1 as TYPE + value2`
1707 /// `+` is prohibited to avoid interactions with expression grammar.
1708 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1709 self.parse_ty_common(false, true, false)
1712 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool,
1713 allow_c_variadic: bool) -> PResult<'a, P<Ty>> {
1714 maybe_recover_from_interpolated_ty_qpath!(self, allow_qpath_recovery);
1715 maybe_whole!(self, NtTy, |x| x);
1718 let mut impl_dyn_multi = false;
1719 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1720 // `(TYPE)` is a parenthesized type.
1721 // `(TYPE,)` is a tuple with a single field of type TYPE.
1722 let mut ts = vec![];
1723 let mut last_comma = false;
1724 while self.token != token::CloseDelim(token::Paren) {
1725 ts.push(self.parse_ty()?);
1726 if self.eat(&token::Comma) {
1733 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1734 self.expect(&token::CloseDelim(token::Paren))?;
1736 if ts.len() == 1 && !last_comma {
1737 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1738 let maybe_bounds = allow_plus && self.token.is_like_plus();
1740 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1741 TyKind::Path(None, ref path) if maybe_bounds => {
1742 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1744 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1745 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1746 let path = match bounds[0] {
1747 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1748 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1750 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1753 _ => TyKind::Paren(P(ty))
1758 } else if self.eat(&token::Not) {
1761 } else if self.eat(&token::BinOp(token::Star)) {
1763 TyKind::Ptr(self.parse_ptr()?)
1764 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1766 let t = self.parse_ty()?;
1767 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1768 let t = match self.maybe_parse_fixed_length_of_vec()? {
1769 None => TyKind::Slice(t),
1770 Some(length) => TyKind::Array(t, AnonConst {
1771 id: ast::DUMMY_NODE_ID,
1775 self.expect(&token::CloseDelim(token::Bracket))?;
1777 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1780 self.parse_borrowed_pointee()?
1781 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1783 // In order to not be ambiguous, the type must be surrounded by parens.
1784 self.expect(&token::OpenDelim(token::Paren))?;
1786 id: ast::DUMMY_NODE_ID,
1787 value: self.parse_expr()?,
1789 self.expect(&token::CloseDelim(token::Paren))?;
1791 } else if self.eat_keyword(keywords::Underscore) {
1792 // A type to be inferred `_`
1794 } else if self.token_is_bare_fn_keyword() {
1795 // Function pointer type
1796 self.parse_ty_bare_fn(Vec::new())?
1797 } else if self.check_keyword(keywords::For) {
1798 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1799 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1800 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1802 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1803 if self.token_is_bare_fn_keyword() {
1804 self.parse_ty_bare_fn(lifetime_defs)?
1806 let path = self.parse_path(PathStyle::Type)?;
1807 let parse_plus = allow_plus && self.check_plus();
1808 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1810 } else if self.eat_keyword(keywords::Impl) {
1811 // Always parse bounds greedily for better error recovery.
1812 let bounds = self.parse_generic_bounds(None)?;
1813 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1814 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1815 } else if self.check_keyword(keywords::Dyn) &&
1816 (self.span.rust_2018() ||
1817 self.look_ahead(1, |t| t.can_begin_bound() &&
1818 !can_continue_type_after_non_fn_ident(t))) {
1819 self.bump(); // `dyn`
1820 // Always parse bounds greedily for better error recovery.
1821 let bounds = self.parse_generic_bounds(None)?;
1822 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1823 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1824 } else if self.check(&token::Question) ||
1825 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1826 // Bound list (trait object type)
1827 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus, None)?,
1828 TraitObjectSyntax::None)
1829 } else if self.eat_lt() {
1831 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1832 TyKind::Path(Some(qself), path)
1833 } else if self.token.is_path_start() {
1835 let path = self.parse_path(PathStyle::Type)?;
1836 if self.eat(&token::Not) {
1837 // Macro invocation in type position
1838 let (delim, tts) = self.expect_delimited_token_tree()?;
1839 let node = Mac_ { path, tts, delim };
1840 TyKind::Mac(respan(lo.to(self.prev_span), node))
1842 // Just a type path or bound list (trait object type) starting with a trait.
1844 // `Trait1 + Trait2 + 'a`
1845 if allow_plus && self.check_plus() {
1846 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1848 TyKind::Path(None, path)
1851 } else if self.check(&token::DotDotDot) {
1852 if allow_c_variadic {
1853 self.eat(&token::DotDotDot);
1856 return Err(self.fatal(
1857 "only foreign functions are allowed to be C-variadic"
1861 let msg = format!("expected type, found {}", self.this_token_descr());
1862 return Err(self.fatal(&msg));
1865 let span = lo.to(self.prev_span);
1866 let ty = P(Ty { node, span, id: ast::DUMMY_NODE_ID });
1868 // Try to recover from use of `+` with incorrect priority.
1869 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1870 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1871 self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)
1874 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1875 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1876 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1877 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1879 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1880 bounds.append(&mut self.parse_generic_bounds(Some(self.prev_span))?);
1882 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1885 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1886 if !allow_plus && impl_dyn_multi {
1887 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1888 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1891 "use parentheses to disambiguate",
1893 Applicability::MachineApplicable
1898 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1899 // Do not add `+` to expected tokens.
1900 if !allow_plus || !self.token.is_like_plus() {
1905 let bounds = self.parse_generic_bounds(None)?;
1906 let sum_span = ty.span.to(self.prev_span);
1908 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1909 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1912 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1913 let sum_with_parens = pprust::to_string(|s| {
1914 use crate::print::pprust::PrintState;
1917 s.print_opt_lifetime(lifetime)?;
1918 s.print_mutability(mut_ty.mutbl)?;
1920 s.print_type(&mut_ty.ty)?;
1921 s.print_type_bounds(" +", &bounds)?;
1924 err.span_suggestion(
1926 "try adding parentheses",
1928 Applicability::MachineApplicable
1931 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1932 err.span_label(sum_span, "perhaps you forgot parentheses?");
1935 err.span_label(sum_span, "expected a path");
1942 /// Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1943 /// Attempt to convert the base expression/pattern/type into a type, parse the `::AssocItem`
1944 /// tail, and combine them into a `<Ty>::AssocItem` expression/pattern/type.
1945 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: P<T>, allow_recovery: bool)
1946 -> PResult<'a, P<T>> {
1947 // Do not add `::` to expected tokens.
1948 if allow_recovery && self.token == token::ModSep {
1949 if let Some(ty) = base.to_ty() {
1950 return self.maybe_recover_from_bad_qpath_stage_2(ty.span, ty);
1956 /// Given an already parsed `Ty` parse the `::AssocItem` tail and
1957 /// combine them into a `<Ty>::AssocItem` expression/pattern/type.
1958 fn maybe_recover_from_bad_qpath_stage_2<T: RecoverQPath>(&mut self, ty_span: Span, ty: P<Ty>)
1959 -> PResult<'a, P<T>> {
1960 self.expect(&token::ModSep)?;
1962 let mut path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
1963 self.parse_path_segments(&mut path.segments, T::PATH_STYLE)?;
1964 path.span = ty_span.to(self.prev_span);
1966 let ty_str = self.sess.source_map().span_to_snippet(ty_span)
1967 .unwrap_or_else(|_| pprust::ty_to_string(&ty));
1969 .struct_span_err(path.span, "missing angle brackets in associated item path")
1970 .span_suggestion( // this is a best-effort recovery
1971 path.span, "try", format!("<{}>::{}", ty_str, path), Applicability::MaybeIncorrect
1974 let path_span = ty_span.shrink_to_hi(); // use an empty path since `position` == 0
1975 Ok(P(T::recovered(Some(QSelf { ty, path_span, position: 0 }), path)))
1978 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1979 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1980 let mutbl = self.parse_mutability();
1981 let ty = self.parse_ty_no_plus()?;
1982 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1985 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1986 let mutbl = if self.eat_keyword(keywords::Mut) {
1988 } else if self.eat_keyword(keywords::Const) {
1989 Mutability::Immutable
1991 let span = self.prev_span;
1992 let msg = "expected mut or const in raw pointer type";
1993 self.struct_span_err(span, msg)
1994 .span_label(span, msg)
1995 .help("use `*mut T` or `*const T` as appropriate")
1997 Mutability::Immutable
1999 let t = self.parse_ty_no_plus()?;
2000 Ok(MutTy { ty: t, mutbl: mutbl })
2003 fn is_named_argument(&mut self) -> bool {
2004 let offset = match self.token {
2005 token::Interpolated(ref nt) => match **nt {
2006 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
2009 token::BinOp(token::And) | token::AndAnd => 1,
2010 _ if self.token.is_keyword(keywords::Mut) => 1,
2014 self.look_ahead(offset, |t| t.is_ident()) &&
2015 self.look_ahead(offset + 1, |t| t == &token::Colon)
2018 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
2020 fn eat_incorrect_doc_comment(&mut self, applied_to: &str) {
2021 if let token::DocComment(_) = self.token {
2022 let mut err = self.diagnostic().struct_span_err(
2024 &format!("documentation comments cannot be applied to {}", applied_to),
2026 err.span_label(self.span, "doc comments are not allowed here");
2029 } else if self.token == token::Pound && self.look_ahead(1, |t| {
2030 *t == token::OpenDelim(token::Bracket)
2033 // Skip every token until next possible arg.
2034 while self.token != token::CloseDelim(token::Bracket) {
2037 let sp = lo.to(self.span);
2039 let mut err = self.diagnostic().struct_span_err(
2041 &format!("attributes cannot be applied to {}", applied_to),
2043 err.span_label(sp, "attributes are not allowed here");
2048 /// This version of parse arg doesn't necessarily require identifier names.
2049 fn parse_arg_general(&mut self, require_name: bool, is_trait_item: bool,
2050 allow_c_variadic: bool) -> PResult<'a, Arg> {
2051 maybe_whole!(self, NtArg, |x| x);
2053 if let Ok(Some(_)) = self.parse_self_arg() {
2054 let mut err = self.struct_span_err(self.prev_span,
2055 "unexpected `self` argument in function");
2056 err.span_label(self.prev_span,
2057 "`self` is only valid as the first argument of an associated function");
2061 let (pat, ty) = if require_name || self.is_named_argument() {
2062 debug!("parse_arg_general parse_pat (require_name:{})",
2064 self.eat_incorrect_doc_comment("method arguments");
2065 let pat = self.parse_pat(Some("argument name"))?;
2067 if let Err(mut err) = self.expect(&token::Colon) {
2068 // If we find a pattern followed by an identifier, it could be an (incorrect)
2069 // C-style parameter declaration.
2070 if self.check_ident() && self.look_ahead(1, |t| {
2071 *t == token::Comma || *t == token::CloseDelim(token::Paren)
2073 let ident = self.parse_ident().unwrap();
2074 let span = pat.span.with_hi(ident.span.hi());
2076 err.span_suggestion(
2078 "declare the type after the parameter binding",
2079 String::from("<identifier>: <type>"),
2080 Applicability::HasPlaceholders,
2082 } else if require_name && is_trait_item {
2083 if let PatKind::Ident(_, ident, _) = pat.node {
2084 err.span_suggestion(
2086 "explicitly ignore parameter",
2087 format!("_: {}", ident),
2088 Applicability::MachineApplicable,
2092 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
2098 self.eat_incorrect_doc_comment("a method argument's type");
2099 (pat, self.parse_ty_common(true, true, allow_c_variadic)?)
2101 debug!("parse_arg_general ident_to_pat");
2102 let parser_snapshot_before_ty = self.clone();
2103 self.eat_incorrect_doc_comment("a method argument's type");
2104 let mut ty = self.parse_ty_common(true, true, allow_c_variadic);
2105 if ty.is_ok() && self.token != token::Comma &&
2106 self.token != token::CloseDelim(token::Paren) {
2107 // This wasn't actually a type, but a pattern looking like a type,
2108 // so we are going to rollback and re-parse for recovery.
2109 ty = self.unexpected();
2113 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
2115 id: ast::DUMMY_NODE_ID,
2116 node: PatKind::Ident(
2117 BindingMode::ByValue(Mutability::Immutable), ident, None),
2123 // If this is a C-variadic argument and we hit an error, return the
2125 if self.token == token::DotDotDot {
2128 // Recover from attempting to parse the argument as a type without pattern.
2130 mem::replace(self, parser_snapshot_before_ty);
2131 let pat = self.parse_pat(Some("argument name"))?;
2132 self.expect(&token::Colon)?;
2133 let ty = self.parse_ty()?;
2135 let mut err = self.diagnostic().struct_span_err_with_code(
2137 "patterns aren't allowed in methods without bodies",
2138 DiagnosticId::Error("E0642".into()),
2140 err.span_suggestion_short(
2142 "give this argument a name or use an underscore to ignore it",
2144 Applicability::MachineApplicable,
2148 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2150 node: PatKind::Wild,
2152 id: ast::DUMMY_NODE_ID
2159 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID, source: ast::ArgSource::Normal })
2162 /// Parses a single function argument.
2163 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
2164 self.parse_arg_general(true, false, false)
2167 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
2168 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
2169 let pat = self.parse_pat(Some("argument name"))?;
2170 let t = if self.eat(&token::Colon) {
2174 id: ast::DUMMY_NODE_ID,
2175 node: TyKind::Infer,
2176 span: self.prev_span,
2182 id: ast::DUMMY_NODE_ID,
2183 source: ast::ArgSource::Normal,
2187 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
2188 if self.eat(&token::Semi) {
2189 Ok(Some(self.parse_expr()?))
2195 /// Matches `token_lit = LIT_INTEGER | ...`.
2196 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
2197 let out = match self.token {
2198 token::Interpolated(ref nt) => match **nt {
2199 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
2200 ExprKind::Lit(ref lit) => { lit.node.clone() }
2201 _ => { return self.unexpected_last(&self.token); }
2203 _ => { return self.unexpected_last(&self.token); }
2205 token::Literal(lit, suf) => {
2206 let diag = Some((self.span, &self.sess.span_diagnostic));
2207 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
2211 self.expect_no_suffix(sp, &format!("a {}", lit.literal_name()), suf)
2216 token::Dot if self.look_ahead(1, |t| match t {
2217 token::Literal(parse::token::Lit::Integer(_) , _) => true,
2219 }) => { // recover from `let x = .4;`
2222 if let token::Literal(
2223 parse::token::Lit::Integer(val),
2226 let suffix = suffix.and_then(|s| {
2230 } else if s == "f64" {
2237 let sp = lo.to(self.prev_span);
2238 let mut err = self.diagnostic()
2239 .struct_span_err(sp, "float literals must have an integer part");
2240 err.span_suggestion(
2242 "must have an integer part",
2243 format!("0.{}{}", val, suffix),
2244 Applicability::MachineApplicable,
2247 return Ok(match suffix {
2248 "f32" => ast::LitKind::Float(val, ast::FloatTy::F32),
2249 "f64" => ast::LitKind::Float(val, ast::FloatTy::F64),
2250 _ => ast::LitKind::FloatUnsuffixed(val),
2256 _ => { return self.unexpected_last(&self.token); }
2263 /// Matches `lit = true | false | token_lit`.
2264 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
2266 let lit = if self.eat_keyword(keywords::True) {
2268 } else if self.eat_keyword(keywords::False) {
2269 LitKind::Bool(false)
2271 let lit = self.parse_lit_token()?;
2274 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
2277 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
2278 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
2279 maybe_whole_expr!(self);
2281 let minus_lo = self.span;
2282 let minus_present = self.eat(&token::BinOp(token::Minus));
2284 let literal = self.parse_lit()?;
2285 let hi = self.prev_span;
2286 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
2289 let minus_hi = self.prev_span;
2290 let unary = self.mk_unary(UnOp::Neg, expr);
2291 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
2297 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2299 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2300 let span = self.span;
2302 Ok(Ident::new(ident.name, span))
2304 _ => self.parse_ident(),
2308 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
2310 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
2311 let span = self.span;
2313 Ok(Ident::new(ident.name, span))
2315 _ => self.parse_ident(),
2319 /// Parses a qualified path.
2320 /// Assumes that the leading `<` has been parsed already.
2322 /// `qualified_path = <type [as trait_ref]>::path`
2327 /// `<T as U>::F::a<S>` (without disambiguator)
2328 /// `<T as U>::F::a::<S>` (with disambiguator)
2329 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2330 let lo = self.prev_span;
2331 let ty = self.parse_ty()?;
2333 // `path` will contain the prefix of the path up to the `>`,
2334 // if any (e.g., `U` in the `<T as U>::*` examples
2335 // above). `path_span` has the span of that path, or an empty
2336 // span in the case of something like `<T>::Bar`.
2337 let (mut path, path_span);
2338 if self.eat_keyword(keywords::As) {
2339 let path_lo = self.span;
2340 path = self.parse_path(PathStyle::Type)?;
2341 path_span = path_lo.to(self.prev_span);
2343 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2344 path_span = self.span.to(self.span);
2347 // See doc comment for `unmatched_angle_bracket_count`.
2348 self.expect(&token::Gt)?;
2349 if self.unmatched_angle_bracket_count > 0 {
2350 self.unmatched_angle_bracket_count -= 1;
2351 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
2354 self.expect(&token::ModSep)?;
2356 let qself = QSelf { ty, path_span, position: path.segments.len() };
2357 self.parse_path_segments(&mut path.segments, style)?;
2359 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2362 /// Parses simple paths.
2364 /// `path = [::] segment+`
2365 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2368 /// `a::b::C<D>` (without disambiguator)
2369 /// `a::b::C::<D>` (with disambiguator)
2370 /// `Fn(Args)` (without disambiguator)
2371 /// `Fn::(Args)` (with disambiguator)
2372 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2373 maybe_whole!(self, NtPath, |path| {
2374 if style == PathStyle::Mod &&
2375 path.segments.iter().any(|segment| segment.args.is_some()) {
2376 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2381 let lo = self.meta_var_span.unwrap_or(self.span);
2382 let mut segments = Vec::new();
2383 let mod_sep_ctxt = self.span.ctxt();
2384 if self.eat(&token::ModSep) {
2385 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2387 self.parse_path_segments(&mut segments, style)?;
2389 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2392 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
2393 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
2395 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2396 let meta_ident = match self.token {
2397 token::Interpolated(ref nt) => match **nt {
2398 token::NtMeta(ref meta) => match meta.node {
2399 ast::MetaItemKind::Word => Some(meta.path.clone()),
2406 if let Some(path) = meta_ident {
2410 self.parse_path(style)
2413 fn parse_path_segments(&mut self,
2414 segments: &mut Vec<PathSegment>,
2416 -> PResult<'a, ()> {
2418 let segment = self.parse_path_segment(style)?;
2419 if style == PathStyle::Expr {
2420 // In order to check for trailing angle brackets, we must have finished
2421 // recursing (`parse_path_segment` can indirectly call this function),
2422 // that is, the next token must be the highlighted part of the below example:
2424 // `Foo::<Bar as Baz<T>>::Qux`
2427 // As opposed to the below highlight (if we had only finished the first
2430 // `Foo::<Bar as Baz<T>>::Qux`
2433 // `PathStyle::Expr` is only provided at the root invocation and never in
2434 // `parse_path_segment` to recurse and therefore can be checked to maintain
2436 self.check_trailing_angle_brackets(&segment, token::ModSep);
2438 segments.push(segment);
2440 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2446 fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
2447 let ident = self.parse_path_segment_ident()?;
2449 let is_args_start = |token: &token::Token| match *token {
2450 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2453 let check_args_start = |this: &mut Self| {
2454 this.expected_tokens.extend_from_slice(
2455 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2457 is_args_start(&this.token)
2460 Ok(if style == PathStyle::Type && check_args_start(self) ||
2461 style != PathStyle::Mod && self.check(&token::ModSep)
2462 && self.look_ahead(1, |t| is_args_start(t)) {
2463 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
2464 // it isn't, then we reset the unmatched angle bracket count as we're about to start
2465 // parsing a new path.
2466 if style == PathStyle::Expr {
2467 self.unmatched_angle_bracket_count = 0;
2468 self.max_angle_bracket_count = 0;
2471 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2472 self.eat(&token::ModSep);
2474 let args = if self.eat_lt() {
2476 let (args, bindings) =
2477 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
2479 let span = lo.to(self.prev_span);
2480 AngleBracketedArgs { args, bindings, span }.into()
2484 let (inputs, recovered) = self.parse_seq_to_before_tokens(
2485 &[&token::CloseDelim(token::Paren)],
2486 SeqSep::trailing_allowed(token::Comma),
2487 TokenExpectType::Expect,
2492 let span = lo.to(self.prev_span);
2493 let output = if self.eat(&token::RArrow) {
2494 Some(self.parse_ty_common(false, false, false)?)
2498 ParenthesizedArgs { inputs, output, span }.into()
2501 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2503 // Generic arguments are not found.
2504 PathSegment::from_ident(ident)
2508 crate fn check_lifetime(&mut self) -> bool {
2509 self.expected_tokens.push(TokenType::Lifetime);
2510 self.token.is_lifetime()
2513 /// Parses a single lifetime `'a` or panics.
2514 crate fn expect_lifetime(&mut self) -> Lifetime {
2515 if let Some(ident) = self.token.lifetime() {
2516 let span = self.span;
2518 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2520 self.span_bug(self.span, "not a lifetime")
2524 fn eat_label(&mut self) -> Option<Label> {
2525 if let Some(ident) = self.token.lifetime() {
2526 let span = self.span;
2528 Some(Label { ident: Ident::new(ident.name, span) })
2534 /// Parses mutability (`mut` or nothing).
2535 fn parse_mutability(&mut self) -> Mutability {
2536 if self.eat_keyword(keywords::Mut) {
2539 Mutability::Immutable
2543 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2544 if let token::Literal(token::Integer(name), suffix) = self.token {
2545 self.expect_no_suffix(self.span, "a tuple index", suffix);
2547 Ok(Ident::new(name, self.prev_span))
2549 self.parse_ident_common(false)
2553 /// Parse ident (COLON expr)?
2554 fn parse_field(&mut self) -> PResult<'a, Field> {
2555 let attrs = self.parse_outer_attributes()?;
2558 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2559 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
2560 t == &token::Colon || t == &token::Eq
2562 let fieldname = self.parse_field_name()?;
2564 // Check for an equals token. This means the source incorrectly attempts to
2565 // initialize a field with an eq rather than a colon.
2566 if self.token == token::Eq {
2568 .struct_span_err(self.span, "expected `:`, found `=`")
2570 fieldname.span.shrink_to_hi().to(self.span),
2571 "replace equals symbol with a colon",
2573 Applicability::MachineApplicable,
2578 (fieldname, self.parse_expr()?, false)
2580 let fieldname = self.parse_ident_common(false)?;
2582 // Mimic `x: x` for the `x` field shorthand.
2583 let path = ast::Path::from_ident(fieldname);
2584 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2585 (fieldname, expr, true)
2589 span: lo.to(expr.span),
2592 attrs: attrs.into(),
2596 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2597 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2600 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2601 ExprKind::Unary(unop, expr)
2604 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2605 ExprKind::Binary(binop, lhs, rhs)
2608 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2609 ExprKind::Call(f, args)
2612 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2613 ExprKind::Index(expr, idx)
2616 fn mk_range(&mut self,
2617 start: Option<P<Expr>>,
2618 end: Option<P<Expr>>,
2619 limits: RangeLimits)
2620 -> PResult<'a, ast::ExprKind> {
2621 if end.is_none() && limits == RangeLimits::Closed {
2622 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2624 Ok(ExprKind::Range(start, end, limits))
2628 fn mk_assign_op(&mut self, binop: ast::BinOp,
2629 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2630 ExprKind::AssignOp(binop, lhs, rhs)
2633 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
2634 let delim = match self.token {
2635 token::OpenDelim(delim) => delim,
2637 let msg = "expected open delimiter";
2638 let mut err = self.fatal(msg);
2639 err.span_label(self.span, msg);
2643 let tts = match self.parse_token_tree() {
2644 TokenTree::Delimited(_, _, tts) => tts,
2645 _ => unreachable!(),
2647 let delim = match delim {
2648 token::Paren => MacDelimiter::Parenthesis,
2649 token::Bracket => MacDelimiter::Bracket,
2650 token::Brace => MacDelimiter::Brace,
2651 token::NoDelim => self.bug("unexpected no delimiter"),
2653 Ok((delim, tts.into()))
2656 /// At the bottom (top?) of the precedence hierarchy,
2657 /// Parses things like parenthesized exprs, macros, `return`, etc.
2659 /// N.B., this does not parse outer attributes, and is private because it only works
2660 /// correctly if called from `parse_dot_or_call_expr()`.
2661 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2662 maybe_recover_from_interpolated_ty_qpath!(self, true);
2663 maybe_whole_expr!(self);
2665 // Outer attributes are already parsed and will be
2666 // added to the return value after the fact.
2668 // Therefore, prevent sub-parser from parsing
2669 // attributes by giving them a empty "already parsed" list.
2670 let mut attrs = ThinVec::new();
2673 let mut hi = self.span;
2677 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2679 token::OpenDelim(token::Paren) => {
2682 attrs.extend(self.parse_inner_attributes()?);
2684 // (e) is parenthesized e
2685 // (e,) is a tuple with only one field, e
2686 let mut es = vec![];
2687 let mut trailing_comma = false;
2688 let mut recovered = false;
2689 while self.token != token::CloseDelim(token::Paren) {
2690 es.push(match self.parse_expr() {
2693 // recover from parse error in tuple list
2694 return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2697 recovered = self.expect_one_of(
2699 &[token::Comma, token::CloseDelim(token::Paren)],
2701 if self.eat(&token::Comma) {
2702 trailing_comma = true;
2704 trailing_comma = false;
2712 hi = self.prev_span;
2713 ex = if es.len() == 1 && !trailing_comma {
2714 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2719 token::OpenDelim(token::Brace) => {
2720 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2722 token::BinOp(token::Or) | token::OrOr => {
2723 return self.parse_lambda_expr(attrs);
2725 token::OpenDelim(token::Bracket) => {
2728 attrs.extend(self.parse_inner_attributes()?);
2730 if self.eat(&token::CloseDelim(token::Bracket)) {
2732 ex = ExprKind::Array(Vec::new());
2735 let first_expr = self.parse_expr()?;
2736 if self.eat(&token::Semi) {
2737 // Repeating array syntax: [ 0; 512 ]
2738 let count = AnonConst {
2739 id: ast::DUMMY_NODE_ID,
2740 value: self.parse_expr()?,
2742 self.expect(&token::CloseDelim(token::Bracket))?;
2743 ex = ExprKind::Repeat(first_expr, count);
2744 } else if self.eat(&token::Comma) {
2745 // Vector with two or more elements.
2746 let remaining_exprs = self.parse_seq_to_end(
2747 &token::CloseDelim(token::Bracket),
2748 SeqSep::trailing_allowed(token::Comma),
2749 |p| Ok(p.parse_expr()?)
2751 let mut exprs = vec![first_expr];
2752 exprs.extend(remaining_exprs);
2753 ex = ExprKind::Array(exprs);
2755 // Vector with one element.
2756 self.expect(&token::CloseDelim(token::Bracket))?;
2757 ex = ExprKind::Array(vec![first_expr]);
2760 hi = self.prev_span;
2764 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2766 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2768 if self.span.rust_2018() && self.check_keyword(keywords::Async)
2770 if self.is_async_block() { // check for `async {` and `async move {`
2771 return self.parse_async_block(attrs);
2773 return self.parse_lambda_expr(attrs);
2776 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2777 return self.parse_lambda_expr(attrs);
2779 if self.eat_keyword(keywords::If) {
2780 return self.parse_if_expr(attrs);
2782 if self.eat_keyword(keywords::For) {
2783 let lo = self.prev_span;
2784 return self.parse_for_expr(None, lo, attrs);
2786 if self.eat_keyword(keywords::While) {
2787 let lo = self.prev_span;
2788 return self.parse_while_expr(None, lo, attrs);
2790 if let Some(label) = self.eat_label() {
2791 let lo = label.ident.span;
2792 self.expect(&token::Colon)?;
2793 if self.eat_keyword(keywords::While) {
2794 return self.parse_while_expr(Some(label), lo, attrs)
2796 if self.eat_keyword(keywords::For) {
2797 return self.parse_for_expr(Some(label), lo, attrs)
2799 if self.eat_keyword(keywords::Loop) {
2800 return self.parse_loop_expr(Some(label), lo, attrs)
2802 if self.token == token::OpenDelim(token::Brace) {
2803 return self.parse_block_expr(Some(label),
2805 BlockCheckMode::Default,
2808 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2809 let mut err = self.fatal(msg);
2810 err.span_label(self.span, msg);
2813 if self.eat_keyword(keywords::Loop) {
2814 let lo = self.prev_span;
2815 return self.parse_loop_expr(None, lo, attrs);
2817 if self.eat_keyword(keywords::Continue) {
2818 let label = self.eat_label();
2819 let ex = ExprKind::Continue(label);
2820 let hi = self.prev_span;
2821 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2823 if self.eat_keyword(keywords::Match) {
2824 let match_sp = self.prev_span;
2825 return self.parse_match_expr(attrs).map_err(|mut err| {
2826 err.span_label(match_sp, "while parsing this match expression");
2830 if self.eat_keyword(keywords::Unsafe) {
2831 return self.parse_block_expr(
2834 BlockCheckMode::Unsafe(ast::UserProvided),
2837 if self.is_do_catch_block() {
2838 let mut db = self.fatal("found removed `do catch` syntax");
2839 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2842 if self.is_try_block() {
2844 assert!(self.eat_keyword(keywords::Try));
2845 return self.parse_try_block(lo, attrs);
2847 if self.eat_keyword(keywords::Return) {
2848 if self.token.can_begin_expr() {
2849 let e = self.parse_expr()?;
2851 ex = ExprKind::Ret(Some(e));
2853 ex = ExprKind::Ret(None);
2855 } else if self.eat_keyword(keywords::Break) {
2856 let label = self.eat_label();
2857 let e = if self.token.can_begin_expr()
2858 && !(self.token == token::OpenDelim(token::Brace)
2859 && self.restrictions.contains(
2860 Restrictions::NO_STRUCT_LITERAL)) {
2861 Some(self.parse_expr()?)
2865 ex = ExprKind::Break(label, e);
2866 hi = self.prev_span;
2867 } else if self.eat_keyword(keywords::Yield) {
2868 if self.token.can_begin_expr() {
2869 let e = self.parse_expr()?;
2871 ex = ExprKind::Yield(Some(e));
2873 ex = ExprKind::Yield(None);
2875 } else if self.token.is_keyword(keywords::Let) {
2876 // Catch this syntax error here, instead of in `parse_ident`, so
2877 // that we can explicitly mention that let is not to be used as an expression
2878 let mut db = self.fatal("expected expression, found statement (`let`)");
2879 db.span_label(self.span, "expected expression");
2880 db.note("variable declaration using `let` is a statement");
2882 } else if self.token.is_path_start() {
2883 let path = self.parse_path(PathStyle::Expr)?;
2885 // `!`, as an operator, is prefix, so we know this isn't that
2886 if self.eat(&token::Not) {
2887 // MACRO INVOCATION expression
2888 let (delim, tts) = self.expect_delimited_token_tree()?;
2889 hi = self.prev_span;
2890 ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2891 } else if self.check(&token::OpenDelim(token::Brace)) {
2892 if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2896 ex = ExprKind::Path(None, path);
2900 ex = ExprKind::Path(None, path);
2903 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2904 // Don't complain about bare semicolons after unclosed braces
2905 // recovery in order to keep the error count down. Fixing the
2906 // delimiters will possibly also fix the bare semicolon found in
2907 // expression context. For example, silence the following error:
2909 // error: expected expression, found `;`
2913 // | ^ expected expression
2916 return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
2918 match self.parse_literal_maybe_minus() {
2921 ex = expr.node.clone();
2924 self.cancel(&mut err);
2925 let msg = format!("expected expression, found {}",
2926 self.this_token_descr());
2927 let mut err = self.fatal(&msg);
2928 err.span_label(self.span, "expected expression");
2936 let expr = self.mk_expr(lo.to(hi), ex, attrs);
2937 self.maybe_recover_from_bad_qpath(expr, true)
2940 fn maybe_parse_struct_expr(
2944 attrs: &ThinVec<Attribute>,
2945 ) -> Option<PResult<'a, P<Expr>>> {
2946 let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2947 let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2948 // `{ ident, ` cannot start a block
2949 self.look_ahead(2, |t| t == &token::Comma) ||
2950 self.look_ahead(2, |t| t == &token::Colon) && (
2951 // `{ ident: token, ` cannot start a block
2952 self.look_ahead(4, |t| t == &token::Comma) ||
2953 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2954 self.look_ahead(3, |t| !t.can_begin_type())
2958 if struct_allowed || certainly_not_a_block() {
2959 // This is a struct literal, but we don't can't accept them here
2960 let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2961 if let (Ok(expr), false) = (&expr, struct_allowed) {
2962 let mut err = self.diagnostic().struct_span_err(
2964 "struct literals are not allowed here",
2966 err.multipart_suggestion(
2967 "surround the struct literal with parenthesis",
2969 (lo.shrink_to_lo(), "(".to_string()),
2970 (expr.span.shrink_to_hi(), ")".to_string()),
2972 Applicability::MachineApplicable,
2981 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2982 -> PResult<'a, P<Expr>> {
2983 let struct_sp = lo.to(self.prev_span);
2985 let mut fields = Vec::new();
2986 let mut base = None;
2988 attrs.extend(self.parse_inner_attributes()?);
2990 while self.token != token::CloseDelim(token::Brace) {
2991 if self.eat(&token::DotDot) {
2992 let exp_span = self.prev_span;
2993 match self.parse_expr() {
2999 self.recover_stmt();
3002 if self.token == token::Comma {
3003 let mut err = self.sess.span_diagnostic.mut_span_err(
3004 exp_span.to(self.prev_span),
3005 "cannot use a comma after the base struct",
3007 err.span_suggestion_short(
3009 "remove this comma",
3011 Applicability::MachineApplicable
3013 err.note("the base struct must always be the last field");
3015 self.recover_stmt();
3020 let mut recovery_field = None;
3021 if let token::Ident(ident, _) = self.token {
3022 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
3023 // Use in case of error after field-looking code: `S { foo: () with a }`
3024 let mut ident = ident.clone();
3025 ident.span = self.span;
3026 recovery_field = Some(ast::Field {
3029 expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
3030 is_shorthand: false,
3031 attrs: ThinVec::new(),
3035 let mut parsed_field = None;
3036 match self.parse_field() {
3037 Ok(f) => parsed_field = Some(f),
3039 e.span_label(struct_sp, "while parsing this struct");
3042 // If the next token is a comma, then try to parse
3043 // what comes next as additional fields, rather than
3044 // bailing out until next `}`.
3045 if self.token != token::Comma {
3046 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
3047 if self.token != token::Comma {
3054 match self.expect_one_of(&[token::Comma],
3055 &[token::CloseDelim(token::Brace)]) {
3056 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
3057 // only include the field if there's no parse error for the field name
3061 if let Some(f) = recovery_field {
3064 e.span_label(struct_sp, "while parsing this struct");
3066 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
3067 self.eat(&token::Comma);
3072 let span = lo.to(self.span);
3073 self.expect(&token::CloseDelim(token::Brace))?;
3074 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
3077 fn parse_or_use_outer_attributes(&mut self,
3078 already_parsed_attrs: Option<ThinVec<Attribute>>)
3079 -> PResult<'a, ThinVec<Attribute>> {
3080 if let Some(attrs) = already_parsed_attrs {
3083 self.parse_outer_attributes().map(|a| a.into())
3087 /// Parses a block or unsafe block.
3088 fn parse_block_expr(&mut self, opt_label: Option<Label>,
3089 lo: Span, blk_mode: BlockCheckMode,
3090 outer_attrs: ThinVec<Attribute>)
3091 -> PResult<'a, P<Expr>> {
3092 self.expect(&token::OpenDelim(token::Brace))?;
3094 let mut attrs = outer_attrs;
3095 attrs.extend(self.parse_inner_attributes()?);
3097 let blk = self.parse_block_tail(lo, blk_mode)?;
3098 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
3101 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
3102 fn parse_dot_or_call_expr(&mut self,
3103 already_parsed_attrs: Option<ThinVec<Attribute>>)
3104 -> PResult<'a, P<Expr>> {
3105 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3107 let b = self.parse_bottom_expr();
3108 let (span, b) = self.interpolated_or_expr_span(b)?;
3109 self.parse_dot_or_call_expr_with(b, span, attrs)
3112 fn parse_dot_or_call_expr_with(&mut self,
3115 mut attrs: ThinVec<Attribute>)
3116 -> PResult<'a, P<Expr>> {
3117 // Stitch the list of outer attributes onto the return value.
3118 // A little bit ugly, but the best way given the current code
3120 self.parse_dot_or_call_expr_with_(e0, lo)
3122 expr.map(|mut expr| {
3123 attrs.extend::<Vec<_>>(expr.attrs.into());
3126 ExprKind::If(..) | ExprKind::IfLet(..) => {
3127 if !expr.attrs.is_empty() {
3128 // Just point to the first attribute in there...
3129 let span = expr.attrs[0].span;
3132 "attributes are not yet allowed on `if` \
3143 // Assuming we have just parsed `.`, continue parsing into an expression.
3144 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3145 let segment = self.parse_path_segment(PathStyle::Expr)?;
3146 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
3148 Ok(match self.token {
3149 token::OpenDelim(token::Paren) => {
3150 // Method call `expr.f()`
3151 let mut args = self.parse_unspanned_seq(
3152 &token::OpenDelim(token::Paren),
3153 &token::CloseDelim(token::Paren),
3154 SeqSep::trailing_allowed(token::Comma),
3155 |p| Ok(p.parse_expr()?)
3157 args.insert(0, self_arg);
3159 let span = lo.to(self.prev_span);
3160 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
3163 // Field access `expr.f`
3164 if let Some(args) = segment.args {
3165 self.span_err(args.span(),
3166 "field expressions may not have generic arguments");
3169 let span = lo.to(self.prev_span);
3170 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
3175 /// This function checks if there are trailing angle brackets and produces
3176 /// a diagnostic to suggest removing them.
3178 /// ```ignore (diagnostic)
3179 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
3180 /// ^^ help: remove extra angle brackets
3182 fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) {
3183 // This function is intended to be invoked after parsing a path segment where there are two
3186 // 1. A specific token is expected after the path segment.
3187 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
3188 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
3189 // 2. No specific token is expected after the path segment.
3190 // eg. `x.foo` (field access)
3192 // This function is called after parsing `.foo` and before parsing the token `end` (if
3193 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
3196 // We only care about trailing angle brackets if we previously parsed angle bracket
3197 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
3198 // removed in this case:
3200 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
3202 // This case is particularly tricky as we won't notice it just looking at the tokens -
3203 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
3204 // have already been parsed):
3206 // `x.foo::<u32>>>(3)`
3207 let parsed_angle_bracket_args = segment.args
3209 .map(|args| args.is_angle_bracketed())
3213 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
3214 parsed_angle_bracket_args,
3216 if !parsed_angle_bracket_args {
3220 // Keep the span at the start so we can highlight the sequence of `>` characters to be
3224 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
3225 // (since we might have the field access case and the characters we're eating are
3226 // actual operators and not trailing characters - ie `x.foo >> 3`).
3227 let mut position = 0;
3229 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
3230 // many of each (so we can correctly pluralize our error messages) and continue to
3232 let mut number_of_shr = 0;
3233 let mut number_of_gt = 0;
3234 while self.look_ahead(position, |t| {
3235 trace!("check_trailing_angle_brackets: t={:?}", t);
3236 if *t == token::BinOp(token::BinOpToken::Shr) {
3239 } else if *t == token::Gt {
3249 // If we didn't find any trailing `>` characters, then we have nothing to error about.
3251 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
3252 number_of_gt, number_of_shr,
3254 if number_of_gt < 1 && number_of_shr < 1 {
3258 // Finally, double check that we have our end token as otherwise this is the
3260 if self.look_ahead(position, |t| {
3261 trace!("check_trailing_angle_brackets: t={:?}", t);
3264 // Eat from where we started until the end token so that parsing can continue
3265 // as if we didn't have those extra angle brackets.
3266 self.eat_to_tokens(&[&end]);
3267 let span = lo.until(self.span);
3269 let plural = number_of_gt > 1 || number_of_shr >= 1;
3273 &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
3277 &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
3279 Applicability::MachineApplicable,
3285 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3290 while self.eat(&token::Question) {
3291 let hi = self.prev_span;
3292 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
3296 if self.eat(&token::Dot) {
3298 token::Ident(..) => {
3299 e = self.parse_dot_suffix(e, lo)?;
3301 token::Literal(token::Integer(name), suffix) => {
3302 let span = self.span;
3304 let field = ExprKind::Field(e, Ident::new(name, span));
3305 e = self.mk_expr(lo.to(span), field, ThinVec::new());
3307 self.expect_no_suffix(span, "a tuple index", suffix);
3309 token::Literal(token::Float(n), _suf) => {
3311 let fstr = n.as_str();
3312 let mut err = self.diagnostic()
3313 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
3314 err.span_label(self.prev_span, "unexpected token");
3315 if fstr.chars().all(|x| "0123456789.".contains(x)) {
3316 let float = match fstr.parse::<f64>().ok() {
3320 let sugg = pprust::to_string(|s| {
3321 use crate::print::pprust::PrintState;
3325 s.print_usize(float.trunc() as usize)?;
3328 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
3330 err.span_suggestion(
3331 lo.to(self.prev_span),
3332 "try parenthesizing the first index",
3334 Applicability::MachineApplicable
3341 // FIXME Could factor this out into non_fatal_unexpected or something.
3342 let actual = self.this_token_to_string();
3343 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
3348 if self.expr_is_complete(&e) { break; }
3351 token::OpenDelim(token::Paren) => {
3352 let seq = self.parse_unspanned_seq(
3353 &token::OpenDelim(token::Paren),
3354 &token::CloseDelim(token::Paren),
3355 SeqSep::trailing_allowed(token::Comma),
3356 |p| Ok(p.parse_expr()?)
3358 let nd = self.mk_call(e, es);
3359 let hi = self.prev_span;
3360 self.mk_expr(lo.to(hi), nd, ThinVec::new())
3362 e = self.recover_seq_parse_error(token::Paren, lo, seq);
3366 // Could be either an index expression or a slicing expression.
3367 token::OpenDelim(token::Bracket) => {
3369 let ix = self.parse_expr()?;
3371 self.expect(&token::CloseDelim(token::Bracket))?;
3372 let index = self.mk_index(e, ix);
3373 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
3381 fn recover_seq_parse_error(
3383 delim: token::DelimToken,
3385 result: PResult<'a, P<Expr>>,
3391 // recover from parse error
3392 self.consume_block(delim);
3393 self.mk_expr(lo.to(self.prev_span), ExprKind::Err, ThinVec::new())
3398 crate fn process_potential_macro_variable(&mut self) {
3399 let (token, span) = match self.token {
3400 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
3401 self.look_ahead(1, |t| t.is_ident()) => {
3403 let name = match self.token {
3404 token::Ident(ident, _) => ident,
3407 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
3408 err.span_label(self.span, "unknown macro variable");
3413 token::Interpolated(ref nt) => {
3414 self.meta_var_span = Some(self.span);
3415 // Interpolated identifier and lifetime tokens are replaced with usual identifier
3416 // and lifetime tokens, so the former are never encountered during normal parsing.
3418 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
3419 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
3429 /// Parses a single token tree from the input.
3430 crate fn parse_token_tree(&mut self) -> TokenTree {
3432 token::OpenDelim(..) => {
3433 let frame = mem::replace(&mut self.token_cursor.frame,
3434 self.token_cursor.stack.pop().unwrap());
3435 self.span = frame.span.entire();
3437 TokenTree::Delimited(
3440 frame.tree_cursor.stream.into(),
3443 token::CloseDelim(_) | token::Eof => unreachable!(),
3445 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
3447 TokenTree::Token(span, token)
3452 // parse a stream of tokens into a list of TokenTree's,
3454 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
3455 let mut tts = Vec::new();
3456 while self.token != token::Eof {
3457 tts.push(self.parse_token_tree());
3462 pub fn parse_tokens(&mut self) -> TokenStream {
3463 let mut result = Vec::new();
3466 token::Eof | token::CloseDelim(..) => break,
3467 _ => result.push(self.parse_token_tree().into()),
3470 TokenStream::new(result)
3473 /// Parse a prefix-unary-operator expr
3474 fn parse_prefix_expr(&mut self,
3475 already_parsed_attrs: Option<ThinVec<Attribute>>)
3476 -> PResult<'a, P<Expr>> {
3477 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3479 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
3480 let (hi, ex) = match self.token {
3483 let e = self.parse_prefix_expr(None);
3484 let (span, e) = self.interpolated_or_expr_span(e)?;
3485 (lo.to(span), self.mk_unary(UnOp::Not, e))
3487 // Suggest `!` for bitwise negation when encountering a `~`
3490 let e = self.parse_prefix_expr(None);
3491 let (span, e) = self.interpolated_or_expr_span(e)?;
3492 let span_of_tilde = lo;
3493 let mut err = self.diagnostic()
3494 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
3495 err.span_suggestion_short(
3497 "use `!` to perform bitwise negation",
3499 Applicability::MachineApplicable
3502 (lo.to(span), self.mk_unary(UnOp::Not, e))
3504 token::BinOp(token::Minus) => {
3506 let e = self.parse_prefix_expr(None);
3507 let (span, e) = self.interpolated_or_expr_span(e)?;
3508 (lo.to(span), self.mk_unary(UnOp::Neg, e))
3510 token::BinOp(token::Star) => {
3512 let e = self.parse_prefix_expr(None);
3513 let (span, e) = self.interpolated_or_expr_span(e)?;
3514 (lo.to(span), self.mk_unary(UnOp::Deref, e))
3516 token::BinOp(token::And) | token::AndAnd => {
3518 let m = self.parse_mutability();
3519 let e = self.parse_prefix_expr(None);
3520 let (span, e) = self.interpolated_or_expr_span(e)?;
3521 (lo.to(span), ExprKind::AddrOf(m, e))
3523 token::Ident(..) if self.token.is_keyword(keywords::In) => {
3525 let place = self.parse_expr_res(
3526 Restrictions::NO_STRUCT_LITERAL,
3529 let blk = self.parse_block()?;
3530 let span = blk.span;
3531 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
3532 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
3534 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
3536 let e = self.parse_prefix_expr(None);
3537 let (span, e) = self.interpolated_or_expr_span(e)?;
3538 (lo.to(span), ExprKind::Box(e))
3540 token::Ident(..) if self.token.is_ident_named("not") => {
3541 // `not` is just an ordinary identifier in Rust-the-language,
3542 // but as `rustc`-the-compiler, we can issue clever diagnostics
3543 // for confused users who really want to say `!`
3544 let token_cannot_continue_expr = |t: &token::Token| match *t {
3545 // These tokens can start an expression after `!`, but
3546 // can't continue an expression after an ident
3547 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3548 token::Literal(..) | token::Pound => true,
3549 token::Interpolated(ref nt) => match **nt {
3550 token::NtIdent(..) | token::NtExpr(..) |
3551 token::NtBlock(..) | token::NtPath(..) => true,
3556 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3557 if cannot_continue_expr {
3559 // Emit the error ...
3560 let mut err = self.diagnostic()
3561 .struct_span_err(self.span,
3562 &format!("unexpected {} after identifier",
3563 self.this_token_descr()));
3564 // span the `not` plus trailing whitespace to avoid
3565 // trailing whitespace after the `!` in our suggestion
3566 let to_replace = self.sess.source_map()
3567 .span_until_non_whitespace(lo.to(self.span));
3568 err.span_suggestion_short(
3570 "use `!` to perform logical negation",
3572 Applicability::MachineApplicable
3575 // —and recover! (just as if we were in the block
3576 // for the `token::Not` arm)
3577 let e = self.parse_prefix_expr(None);
3578 let (span, e) = self.interpolated_or_expr_span(e)?;
3579 (lo.to(span), self.mk_unary(UnOp::Not, e))
3581 return self.parse_dot_or_call_expr(Some(attrs));
3584 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3586 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3589 /// Parses an associative expression.
3591 /// This parses an expression accounting for associativity and precedence of the operators in
3594 fn parse_assoc_expr(&mut self,
3595 already_parsed_attrs: Option<ThinVec<Attribute>>)
3596 -> PResult<'a, P<Expr>> {
3597 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3600 /// Parses an associative expression with operators of at least `min_prec` precedence.
3601 fn parse_assoc_expr_with(&mut self,
3604 -> PResult<'a, P<Expr>> {
3605 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3608 let attrs = match lhs {
3609 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3612 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3613 return self.parse_prefix_range_expr(attrs);
3615 self.parse_prefix_expr(attrs)?
3619 if self.expr_is_complete(&lhs) {
3620 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3623 self.expected_tokens.push(TokenType::Operator);
3624 while let Some(op) = AssocOp::from_token(&self.token) {
3626 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3627 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3628 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3629 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3630 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3631 (PrevTokenKind::Interpolated, _) => self.prev_span,
3632 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3633 if path.segments.len() == 1 => self.prev_span,
3637 let cur_op_span = self.span;
3638 let restrictions = if op.is_assign_like() {
3639 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3643 if op.precedence() < min_prec {
3646 // Check for deprecated `...` syntax
3647 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3648 self.err_dotdotdot_syntax(self.span);
3652 if op.is_comparison() {
3653 self.check_no_chained_comparison(&lhs, &op);
3656 if op == AssocOp::As {
3657 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3659 } else if op == AssocOp::Colon {
3660 let maybe_path = self.could_ascription_be_path(&lhs.node);
3661 let next_sp = self.span;
3663 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3666 self.bad_type_ascription(
3677 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3678 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3679 // generalise it to the Fixity::None code.
3681 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3682 // two variants are handled with `parse_prefix_range_expr` call above.
3683 let rhs = if self.is_at_start_of_range_notation_rhs() {
3684 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3685 LhsExpr::NotYetParsed)?)
3689 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3694 let limits = if op == AssocOp::DotDot {
3695 RangeLimits::HalfOpen
3700 let r = self.mk_range(Some(lhs), rhs, limits)?;
3701 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3705 let rhs = match op.fixity() {
3706 Fixity::Right => self.with_res(
3707 restrictions - Restrictions::STMT_EXPR,
3709 this.parse_assoc_expr_with(op.precedence(),
3710 LhsExpr::NotYetParsed)
3712 Fixity::Left => self.with_res(
3713 restrictions - Restrictions::STMT_EXPR,
3715 this.parse_assoc_expr_with(op.precedence() + 1,
3716 LhsExpr::NotYetParsed)
3718 // We currently have no non-associative operators that are not handled above by
3719 // the special cases. The code is here only for future convenience.
3720 Fixity::None => self.with_res(
3721 restrictions - Restrictions::STMT_EXPR,
3723 this.parse_assoc_expr_with(op.precedence() + 1,
3724 LhsExpr::NotYetParsed)
3728 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
3729 // including the attributes.
3733 .filter(|a| a.style == AttrStyle::Outer)
3735 .map_or(lhs_span, |a| a.span);
3736 let span = lhs_span.to(rhs.span);
3738 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3739 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3740 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3741 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3742 AssocOp::Greater | AssocOp::GreaterEqual => {
3743 let ast_op = op.to_ast_binop().unwrap();
3744 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3745 self.mk_expr(span, binary, ThinVec::new())
3748 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3749 AssocOp::ObsoleteInPlace =>
3750 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3751 AssocOp::AssignOp(k) => {
3753 token::Plus => BinOpKind::Add,
3754 token::Minus => BinOpKind::Sub,
3755 token::Star => BinOpKind::Mul,
3756 token::Slash => BinOpKind::Div,
3757 token::Percent => BinOpKind::Rem,
3758 token::Caret => BinOpKind::BitXor,
3759 token::And => BinOpKind::BitAnd,
3760 token::Or => BinOpKind::BitOr,
3761 token::Shl => BinOpKind::Shl,
3762 token::Shr => BinOpKind::Shr,
3764 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3765 self.mk_expr(span, aopexpr, ThinVec::new())
3767 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3768 self.bug("AssocOp should have been handled by special case")
3772 if op.fixity() == Fixity::None { break }
3777 fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
3778 self.token.is_ident() &&
3779 if let ast::ExprKind::Path(..) = node { true } else { false } &&
3780 !self.token.is_reserved_ident() && // v `foo:bar(baz)`
3781 self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren)) ||
3782 self.look_ahead(1, |t| t == &token::Lt) && // `foo:bar<baz`
3783 self.look_ahead(2, |t| t.is_ident()) ||
3784 self.look_ahead(1, |t| t == &token::Colon) && // `foo:bar:baz`
3785 self.look_ahead(2, |t| t.is_ident()) ||
3786 self.look_ahead(1, |t| t == &token::ModSep) && // `foo:bar::baz`
3787 self.look_ahead(2, |t| t.is_ident())
3790 fn bad_type_ascription(
3792 err: &mut DiagnosticBuilder<'a>,
3798 err.span_label(self.span, "expecting a type here because of type ascription");
3799 let cm = self.sess.source_map();
3800 let next_pos = cm.lookup_char_pos(next_sp.lo());
3801 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3802 if op_pos.line != next_pos.line {
3803 err.span_suggestion(
3805 "try using a semicolon",
3807 Applicability::MaybeIncorrect,
3811 err.span_suggestion(
3813 "maybe you meant to write a path separator here",
3815 Applicability::MaybeIncorrect,
3818 err.note("type ascription is a nightly-only feature that lets \
3819 you annotate an expression with a type: `<expr>: <type>`");
3822 "this expression expects an ascribed type after the colon",
3824 err.help("this might be indicative of a syntax error elsewhere");
3829 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3830 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3831 -> PResult<'a, P<Expr>> {
3832 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3833 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3836 // Save the state of the parser before parsing type normally, in case there is a
3837 // LessThan comparison after this cast.
3838 let parser_snapshot_before_type = self.clone();
3839 match self.parse_ty_no_plus() {
3841 Ok(mk_expr(self, rhs))
3843 Err(mut type_err) => {
3844 // Rewind to before attempting to parse the type with generics, to recover
3845 // from situations like `x as usize < y` in which we first tried to parse
3846 // `usize < y` as a type with generic arguments.
3847 let parser_snapshot_after_type = self.clone();
3848 mem::replace(self, parser_snapshot_before_type);
3850 match self.parse_path(PathStyle::Expr) {
3852 let (op_noun, op_verb) = match self.token {
3853 token::Lt => ("comparison", "comparing"),
3854 token::BinOp(token::Shl) => ("shift", "shifting"),
3856 // We can end up here even without `<` being the next token, for
3857 // example because `parse_ty_no_plus` returns `Err` on keywords,
3858 // but `parse_path` returns `Ok` on them due to error recovery.
3859 // Return original error and parser state.
3860 mem::replace(self, parser_snapshot_after_type);
3861 return Err(type_err);
3865 // Successfully parsed the type path leaving a `<` yet to parse.
3868 // Report non-fatal diagnostics, keep `x as usize` as an expression
3869 // in AST and continue parsing.
3870 let msg = format!("`<` is interpreted as a start of generic \
3871 arguments for `{}`, not a {}", path, op_noun);
3872 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3873 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3874 "interpreted as generic arguments");
3875 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3877 let expr = mk_expr(self, P(Ty {
3879 node: TyKind::Path(None, path),
3880 id: ast::DUMMY_NODE_ID
3883 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3884 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3885 err.span_suggestion(
3887 &format!("try {} the cast value", op_verb),
3888 format!("({})", expr_str),
3889 Applicability::MachineApplicable
3895 Err(mut path_err) => {
3896 // Couldn't parse as a path, return original error and parser state.
3898 mem::replace(self, parser_snapshot_after_type);
3906 /// Produce an error if comparison operators are chained (RFC #558).
3907 /// We only need to check lhs, not rhs, because all comparison ops
3908 /// have same precedence and are left-associative
3909 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3910 debug_assert!(outer_op.is_comparison(),
3911 "check_no_chained_comparison: {:?} is not comparison",
3914 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3915 // respan to include both operators
3916 let op_span = op.span.to(self.span);
3917 let mut err = self.diagnostic().struct_span_err(op_span,
3918 "chained comparison operators require parentheses");
3919 if op.node == BinOpKind::Lt &&
3920 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3921 *outer_op == AssocOp::Greater // even in a case like the following:
3922 { // Foo<Bar<Baz<Qux, ()>>>
3924 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3925 err.help("or use `(...)` if you meant to specify fn arguments");
3933 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3934 fn parse_prefix_range_expr(&mut self,
3935 already_parsed_attrs: Option<ThinVec<Attribute>>)
3936 -> PResult<'a, P<Expr>> {
3937 // Check for deprecated `...` syntax
3938 if self.token == token::DotDotDot {
3939 self.err_dotdotdot_syntax(self.span);
3942 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3943 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3945 let tok = self.token.clone();
3946 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3948 let mut hi = self.span;
3950 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3951 // RHS must be parsed with more associativity than the dots.
3952 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3953 Some(self.parse_assoc_expr_with(next_prec,
3954 LhsExpr::NotYetParsed)
3962 let limits = if tok == token::DotDot {
3963 RangeLimits::HalfOpen
3968 let r = self.mk_range(None, opt_end, limits)?;
3969 Ok(self.mk_expr(lo.to(hi), r, attrs))
3972 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3973 if self.token.can_begin_expr() {
3974 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3975 if self.token == token::OpenDelim(token::Brace) {
3976 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3984 /// Parses an `if` or `if let` expression (`if` token already eaten).
3985 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3986 if self.check_keyword(keywords::Let) {
3987 return self.parse_if_let_expr(attrs);
3989 let lo = self.prev_span;
3990 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3992 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3993 // verify that the last statement is either an implicit return (no `;`) or an explicit
3994 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3995 // the dead code lint.
3996 if self.eat_keyword(keywords::Else) || !cond.returns() {
3997 let sp = self.sess.source_map().next_point(lo);
3998 let mut err = self.diagnostic()
3999 .struct_span_err(sp, "missing condition for `if` statemement");
4000 err.span_label(sp, "expected if condition here");
4003 let not_block = self.token != token::OpenDelim(token::Brace);
4004 let thn = self.parse_block().map_err(|mut err| {
4006 err.span_label(lo, "this `if` statement has a condition, but no block");
4010 let mut els: Option<P<Expr>> = None;
4011 let mut hi = thn.span;
4012 if self.eat_keyword(keywords::Else) {
4013 let elexpr = self.parse_else_expr()?;
4017 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
4020 /// Parses an `if let` expression (`if` token already eaten).
4021 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
4022 -> PResult<'a, P<Expr>> {
4023 let lo = self.prev_span;
4024 self.expect_keyword(keywords::Let)?;
4025 let pats = self.parse_pats()?;
4026 self.expect(&token::Eq)?;
4027 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4028 let thn = self.parse_block()?;
4029 let (hi, els) = if self.eat_keyword(keywords::Else) {
4030 let expr = self.parse_else_expr()?;
4031 (expr.span, Some(expr))
4035 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
4038 /// Parses `move |args| expr`.
4039 fn parse_lambda_expr(&mut self,
4040 attrs: ThinVec<Attribute>)
4041 -> PResult<'a, P<Expr>>
4044 let movability = if self.eat_keyword(keywords::Static) {
4049 let asyncness = if self.span.rust_2018() {
4050 self.parse_asyncness()
4054 let capture_clause = if self.eat_keyword(keywords::Move) {
4059 let decl = self.parse_fn_block_decl()?;
4060 let decl_hi = self.prev_span;
4061 let body = match decl.output {
4062 FunctionRetTy::Default(_) => {
4063 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
4064 self.parse_expr_res(restrictions, None)?
4067 // If an explicit return type is given, require a
4068 // block to appear (RFC 968).
4069 let body_lo = self.span;
4070 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
4076 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
4080 // `else` token already eaten
4081 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
4082 if self.eat_keyword(keywords::If) {
4083 return self.parse_if_expr(ThinVec::new());
4085 let blk = self.parse_block()?;
4086 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
4090 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
4091 fn parse_for_expr(&mut self, opt_label: Option<Label>,
4093 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4094 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
4096 let pat = self.parse_top_level_pat()?;
4097 if !self.eat_keyword(keywords::In) {
4098 let in_span = self.prev_span.between(self.span);
4099 let mut err = self.sess.span_diagnostic
4100 .struct_span_err(in_span, "missing `in` in `for` loop");
4101 err.span_suggestion_short(
4102 in_span, "try adding `in` here", " in ".into(),
4103 // has been misleading, at least in the past (closed Issue #48492)
4104 Applicability::MaybeIncorrect
4108 let in_span = self.prev_span;
4109 if self.eat_keyword(keywords::In) {
4110 // a common typo: `for _ in in bar {}`
4111 let mut err = self.sess.span_diagnostic.struct_span_err(
4113 "expected iterable, found keyword `in`",
4115 err.span_suggestion_short(
4116 in_span.until(self.prev_span),
4117 "remove the duplicated `in`",
4119 Applicability::MachineApplicable,
4121 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
4122 err.note("for more information on the status of emplacement syntax, see <\
4123 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
4126 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4127 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
4128 attrs.extend(iattrs);
4130 let hi = self.prev_span;
4131 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
4134 /// Parses a `while` or `while let` expression (`while` token already eaten).
4135 fn parse_while_expr(&mut self, opt_label: Option<Label>,
4137 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4138 if self.token.is_keyword(keywords::Let) {
4139 return self.parse_while_let_expr(opt_label, span_lo, attrs);
4141 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4142 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4143 attrs.extend(iattrs);
4144 let span = span_lo.to(body.span);
4145 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
4148 /// Parses a `while let` expression (`while` token already eaten).
4149 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
4151 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4152 self.expect_keyword(keywords::Let)?;
4153 let pats = self.parse_pats()?;
4154 self.expect(&token::Eq)?;
4155 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4156 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4157 attrs.extend(iattrs);
4158 let span = span_lo.to(body.span);
4159 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
4162 // parse `loop {...}`, `loop` token already eaten
4163 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
4165 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4166 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4167 attrs.extend(iattrs);
4168 let span = span_lo.to(body.span);
4169 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
4172 /// Parses an `async move {...}` expression.
4173 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
4174 -> PResult<'a, P<Expr>>
4176 let span_lo = self.span;
4177 self.expect_keyword(keywords::Async)?;
4178 let capture_clause = if self.eat_keyword(keywords::Move) {
4183 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4184 attrs.extend(iattrs);
4186 span_lo.to(body.span),
4187 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
4190 /// Parses a `try {...}` expression (`try` token already eaten).
4191 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
4192 -> PResult<'a, P<Expr>>
4194 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4195 attrs.extend(iattrs);
4196 if self.eat_keyword(keywords::Catch) {
4197 let mut error = self.struct_span_err(self.prev_span,
4198 "keyword `catch` cannot follow a `try` block");
4199 error.help("try using `match` on the result of the `try` block instead");
4203 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
4207 // `match` token already eaten
4208 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4209 let match_span = self.prev_span;
4210 let lo = self.prev_span;
4211 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
4213 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
4214 if self.token == token::Token::Semi {
4215 e.span_suggestion_short(
4217 "try removing this `match`",
4219 Applicability::MaybeIncorrect // speculative
4224 attrs.extend(self.parse_inner_attributes()?);
4226 let mut arms: Vec<Arm> = Vec::new();
4227 while self.token != token::CloseDelim(token::Brace) {
4228 match self.parse_arm() {
4229 Ok(arm) => arms.push(arm),
4231 // Recover by skipping to the end of the block.
4233 self.recover_stmt();
4234 let span = lo.to(self.span);
4235 if self.token == token::CloseDelim(token::Brace) {
4238 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
4244 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
4247 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
4248 maybe_whole!(self, NtArm, |x| x);
4250 let attrs = self.parse_outer_attributes()?;
4251 let pats = self.parse_pats()?;
4252 let guard = if self.eat_keyword(keywords::If) {
4253 Some(Guard::If(self.parse_expr()?))
4257 let arrow_span = self.span;
4258 self.expect(&token::FatArrow)?;
4259 let arm_start_span = self.span;
4261 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
4262 .map_err(|mut err| {
4263 err.span_label(arrow_span, "while parsing the `match` arm starting here");
4267 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
4268 && self.token != token::CloseDelim(token::Brace);
4271 let cm = self.sess.source_map();
4272 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
4273 .map_err(|mut err| {
4274 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
4275 (Ok(ref expr_lines), Ok(ref arm_start_lines))
4276 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
4277 && expr_lines.lines.len() == 2
4278 && self.token == token::FatArrow => {
4279 // We check whether there's any trailing code in the parse span,
4280 // if there isn't, we very likely have the following:
4283 // | -- - missing comma
4289 // | parsed until here as `"y" & X`
4290 err.span_suggestion_short(
4291 cm.next_point(arm_start_span),
4292 "missing a comma here to end this `match` arm",
4294 Applicability::MachineApplicable
4298 err.span_label(arrow_span,
4299 "while parsing the `match` arm starting here");
4305 self.eat(&token::Comma);
4316 /// Parses an expression.
4318 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
4319 self.parse_expr_res(Restrictions::empty(), None)
4322 /// Evaluates the closure with restrictions in place.
4324 /// Afters the closure is evaluated, restrictions are reset.
4325 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
4326 where F: FnOnce(&mut Self) -> T
4328 let old = self.restrictions;
4329 self.restrictions = r;
4331 self.restrictions = old;
4336 /// Parses an expression, subject to the given restrictions.
4338 fn parse_expr_res(&mut self, r: Restrictions,
4339 already_parsed_attrs: Option<ThinVec<Attribute>>)
4340 -> PResult<'a, P<Expr>> {
4341 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
4344 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
4345 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
4346 if self.eat(&token::Eq) {
4347 Ok(Some(self.parse_expr()?))
4349 Ok(Some(self.parse_expr()?))
4355 /// Parses patterns, separated by '|' s.
4356 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
4357 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
4358 self.eat(&token::BinOp(token::Or));
4360 let mut pats = Vec::new();
4362 pats.push(self.parse_top_level_pat()?);
4364 if self.token == token::OrOr {
4365 let mut err = self.struct_span_err(self.span,
4366 "unexpected token `||` after pattern");
4367 err.span_suggestion(
4369 "use a single `|` to specify multiple patterns",
4371 Applicability::MachineApplicable
4375 } else if self.eat(&token::BinOp(token::Or)) {
4376 // This is a No-op. Continue the loop to parse the next
4384 // Parses a parenthesized list of patterns like
4385 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
4386 // - a vector of the patterns that were parsed
4387 // - an option indicating the index of the `..` element
4388 // - a boolean indicating whether a trailing comma was present.
4389 // Trailing commas are significant because (p) and (p,) are different patterns.
4390 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4391 self.expect(&token::OpenDelim(token::Paren))?;
4392 let result = match self.parse_pat_list() {
4393 Ok(result) => result,
4394 Err(mut err) => { // recover from parse error in tuple pattern list
4396 self.consume_block(token::Paren);
4397 return Ok((vec![], Some(0), false));
4400 self.expect(&token::CloseDelim(token::Paren))?;
4404 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4405 let mut fields = Vec::new();
4406 let mut ddpos = None;
4407 let mut prev_dd_sp = None;
4408 let mut trailing_comma = false;
4410 if self.eat(&token::DotDot) {
4411 if ddpos.is_none() {
4412 ddpos = Some(fields.len());
4413 prev_dd_sp = Some(self.prev_span);
4415 // Emit a friendly error, ignore `..` and continue parsing
4416 let mut err = self.struct_span_err(
4418 "`..` can only be used once per tuple or tuple struct pattern",
4420 err.span_label(self.prev_span, "can only be used once per pattern");
4421 if let Some(sp) = prev_dd_sp {
4422 err.span_label(sp, "previously present here");
4426 } else if !self.check(&token::CloseDelim(token::Paren)) {
4427 fields.push(self.parse_pat(None)?);
4432 trailing_comma = self.eat(&token::Comma);
4433 if !trailing_comma {
4438 if ddpos == Some(fields.len()) && trailing_comma {
4439 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
4440 let msg = "trailing comma is not permitted after `..`";
4441 self.struct_span_err(self.prev_span, msg)
4442 .span_label(self.prev_span, msg)
4446 Ok((fields, ddpos, trailing_comma))
4449 fn parse_pat_vec_elements(
4451 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
4452 let mut before = Vec::new();
4453 let mut slice = None;
4454 let mut after = Vec::new();
4455 let mut first = true;
4456 let mut before_slice = true;
4458 while self.token != token::CloseDelim(token::Bracket) {
4462 self.expect(&token::Comma)?;
4464 if self.token == token::CloseDelim(token::Bracket)
4465 && (before_slice || !after.is_empty()) {
4471 if self.eat(&token::DotDot) {
4473 if self.check(&token::Comma) ||
4474 self.check(&token::CloseDelim(token::Bracket)) {
4475 slice = Some(P(Pat {
4476 id: ast::DUMMY_NODE_ID,
4477 node: PatKind::Wild,
4478 span: self.prev_span,
4480 before_slice = false;
4486 let subpat = self.parse_pat(None)?;
4487 if before_slice && self.eat(&token::DotDot) {
4488 slice = Some(subpat);
4489 before_slice = false;
4490 } else if before_slice {
4491 before.push(subpat);
4497 Ok((before, slice, after))
4503 attrs: Vec<Attribute>
4504 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
4505 // Check if a colon exists one ahead. This means we're parsing a fieldname.
4507 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
4508 // Parsing a pattern of the form "fieldname: pat"
4509 let fieldname = self.parse_field_name()?;
4511 let pat = self.parse_pat(None)?;
4513 (pat, fieldname, false)
4515 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
4516 let is_box = self.eat_keyword(keywords::Box);
4517 let boxed_span = self.span;
4518 let is_ref = self.eat_keyword(keywords::Ref);
4519 let is_mut = self.eat_keyword(keywords::Mut);
4520 let fieldname = self.parse_ident()?;
4521 hi = self.prev_span;
4523 let bind_type = match (is_ref, is_mut) {
4524 (true, true) => BindingMode::ByRef(Mutability::Mutable),
4525 (true, false) => BindingMode::ByRef(Mutability::Immutable),
4526 (false, true) => BindingMode::ByValue(Mutability::Mutable),
4527 (false, false) => BindingMode::ByValue(Mutability::Immutable),
4529 let fieldpat = P(Pat {
4530 id: ast::DUMMY_NODE_ID,
4531 node: PatKind::Ident(bind_type, fieldname, None),
4532 span: boxed_span.to(hi),
4535 let subpat = if is_box {
4537 id: ast::DUMMY_NODE_ID,
4538 node: PatKind::Box(fieldpat),
4544 (subpat, fieldname, true)
4547 Ok(source_map::Spanned {
4549 node: ast::FieldPat {
4553 attrs: attrs.into(),
4558 /// Parses the fields of a struct-like pattern.
4559 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
4560 let mut fields = Vec::new();
4561 let mut etc = false;
4562 let mut ate_comma = true;
4563 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
4564 let mut etc_span = None;
4566 while self.token != token::CloseDelim(token::Brace) {
4567 let attrs = self.parse_outer_attributes()?;
4570 // check that a comma comes after every field
4572 let err = self.struct_span_err(self.prev_span, "expected `,`");
4573 if let Some(mut delayed) = delayed_err {
4580 if self.check(&token::DotDot) || self.token == token::DotDotDot {
4582 let mut etc_sp = self.span;
4584 if self.token == token::DotDotDot { // Issue #46718
4585 // Accept `...` as if it were `..` to avoid further errors
4586 let mut err = self.struct_span_err(self.span,
4587 "expected field pattern, found `...`");
4588 err.span_suggestion(
4590 "to omit remaining fields, use one fewer `.`",
4592 Applicability::MachineApplicable
4596 self.bump(); // `..` || `...`
4598 if self.token == token::CloseDelim(token::Brace) {
4599 etc_span = Some(etc_sp);
4602 let token_str = self.this_token_descr();
4603 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
4605 err.span_label(self.span, "expected `}`");
4606 let mut comma_sp = None;
4607 if self.token == token::Comma { // Issue #49257
4608 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
4609 err.span_label(etc_sp,
4610 "`..` must be at the end and cannot have a trailing comma");
4611 comma_sp = Some(self.span);
4616 etc_span = Some(etc_sp.until(self.span));
4617 if self.token == token::CloseDelim(token::Brace) {
4618 // If the struct looks otherwise well formed, recover and continue.
4619 if let Some(sp) = comma_sp {
4620 err.span_suggestion_short(
4622 "remove this comma",
4624 Applicability::MachineApplicable,
4629 } else if self.token.is_ident() && ate_comma {
4630 // Accept fields coming after `..,`.
4631 // This way we avoid "pattern missing fields" errors afterwards.
4632 // We delay this error until the end in order to have a span for a
4634 if let Some(mut delayed_err) = delayed_err {
4638 delayed_err = Some(err);
4641 if let Some(mut err) = delayed_err {
4648 fields.push(match self.parse_pat_field(lo, attrs) {
4651 if let Some(mut delayed_err) = delayed_err {
4657 ate_comma = self.eat(&token::Comma);
4660 if let Some(mut err) = delayed_err {
4661 if let Some(etc_span) = etc_span {
4662 err.multipart_suggestion(
4663 "move the `..` to the end of the field list",
4665 (etc_span, String::new()),
4666 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4668 Applicability::MachineApplicable,
4673 return Ok((fields, etc));
4676 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4677 if self.token.is_path_start() {
4679 let (qself, path) = if self.eat_lt() {
4680 // Parse a qualified path
4681 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4684 // Parse an unqualified path
4685 (None, self.parse_path(PathStyle::Expr)?)
4687 let hi = self.prev_span;
4688 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4690 self.parse_literal_maybe_minus()
4694 // helper function to decide whether to parse as ident binding or to try to do
4695 // something more complex like range patterns
4696 fn parse_as_ident(&mut self) -> bool {
4697 self.look_ahead(1, |t| match *t {
4698 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4699 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4700 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4701 // range pattern branch
4702 token::DotDot => None,
4704 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4705 token::Comma | token::CloseDelim(token::Bracket) => true,
4710 /// A wrapper around `parse_pat` with some special error handling for the
4711 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4712 /// to subpatterns within such).
4713 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4714 let pat = self.parse_pat(None)?;
4715 if self.token == token::Comma {
4716 // An unexpected comma after a top-level pattern is a clue that the
4717 // user (perhaps more accustomed to some other language) forgot the
4718 // parentheses in what should have been a tuple pattern; return a
4719 // suggestion-enhanced error here rather than choking on the comma
4721 let comma_span = self.span;
4723 if let Err(mut err) = self.parse_pat_list() {
4724 // We didn't expect this to work anyway; we just wanted
4725 // to advance to the end of the comma-sequence so we know
4726 // the span to suggest parenthesizing
4729 let seq_span = pat.span.to(self.prev_span);
4730 let mut err = self.struct_span_err(comma_span,
4731 "unexpected `,` in pattern");
4732 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4733 err.span_suggestion(
4735 "try adding parentheses to match on a tuple..",
4736 format!("({})", seq_snippet),
4737 Applicability::MachineApplicable
4740 "..or a vertical bar to match on multiple alternatives",
4741 format!("{}", seq_snippet.replace(",", " |")),
4742 Applicability::MachineApplicable
4750 /// Parses a pattern.
4751 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4752 self.parse_pat_with_range_pat(true, expected)
4755 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
4757 fn parse_pat_with_range_pat(
4759 allow_range_pat: bool,
4760 expected: Option<&'static str>,
4761 ) -> PResult<'a, P<Pat>> {
4762 maybe_recover_from_interpolated_ty_qpath!(self, true);
4763 maybe_whole!(self, NtPat, |x| x);
4768 token::BinOp(token::And) | token::AndAnd => {
4769 // Parse &pat / &mut pat
4771 let mutbl = self.parse_mutability();
4772 if let token::Lifetime(ident) = self.token {
4773 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4775 err.span_label(self.span, "unexpected lifetime");
4778 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4779 pat = PatKind::Ref(subpat, mutbl);
4781 token::OpenDelim(token::Paren) => {
4782 // Parse (pat,pat,pat,...) as tuple pattern
4783 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4784 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4785 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4787 PatKind::Tuple(fields, ddpos)
4790 token::OpenDelim(token::Bracket) => {
4791 // Parse [pat,pat,...] as slice pattern
4793 let (before, slice, after) = self.parse_pat_vec_elements()?;
4794 self.expect(&token::CloseDelim(token::Bracket))?;
4795 pat = PatKind::Slice(before, slice, after);
4797 // At this point, token != &, &&, (, [
4798 _ => if self.eat_keyword(keywords::Underscore) {
4800 pat = PatKind::Wild;
4801 } else if self.eat_keyword(keywords::Mut) {
4802 // Parse mut ident @ pat / mut ref ident @ pat
4803 let mutref_span = self.prev_span.to(self.span);
4804 let binding_mode = if self.eat_keyword(keywords::Ref) {
4806 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4809 "try switching the order",
4811 Applicability::MachineApplicable
4813 BindingMode::ByRef(Mutability::Mutable)
4815 BindingMode::ByValue(Mutability::Mutable)
4817 pat = self.parse_pat_ident(binding_mode)?;
4818 } else if self.eat_keyword(keywords::Ref) {
4819 // Parse ref ident @ pat / ref mut ident @ pat
4820 let mutbl = self.parse_mutability();
4821 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4822 } else if self.eat_keyword(keywords::Box) {
4824 let subpat = self.parse_pat_with_range_pat(false, None)?;
4825 pat = PatKind::Box(subpat);
4826 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4827 self.parse_as_ident() {
4828 // Parse ident @ pat
4829 // This can give false positives and parse nullary enums,
4830 // they are dealt with later in resolve
4831 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4832 pat = self.parse_pat_ident(binding_mode)?;
4833 } else if self.token.is_path_start() {
4834 // Parse pattern starting with a path
4835 let (qself, path) = if self.eat_lt() {
4836 // Parse a qualified path
4837 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4840 // Parse an unqualified path
4841 (None, self.parse_path(PathStyle::Expr)?)
4844 token::Not if qself.is_none() => {
4845 // Parse macro invocation
4847 let (delim, tts) = self.expect_delimited_token_tree()?;
4848 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4849 pat = PatKind::Mac(mac);
4851 token::DotDotDot | token::DotDotEq | token::DotDot => {
4852 let end_kind = match self.token {
4853 token::DotDot => RangeEnd::Excluded,
4854 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4855 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4856 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4859 let op_span = self.span;
4861 let span = lo.to(self.prev_span);
4862 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4864 let end = self.parse_pat_range_end()?;
4865 let op = Spanned { span: op_span, node: end_kind };
4866 pat = PatKind::Range(begin, end, op);
4868 token::OpenDelim(token::Brace) => {
4869 if qself.is_some() {
4870 let msg = "unexpected `{` after qualified path";
4871 let mut err = self.fatal(msg);
4872 err.span_label(self.span, msg);
4875 // Parse struct pattern
4877 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4879 self.recover_stmt();
4883 pat = PatKind::Struct(path, fields, etc);
4885 token::OpenDelim(token::Paren) => {
4886 if qself.is_some() {
4887 let msg = "unexpected `(` after qualified path";
4888 let mut err = self.fatal(msg);
4889 err.span_label(self.span, msg);
4892 // Parse tuple struct or enum pattern
4893 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4894 pat = PatKind::TupleStruct(path, fields, ddpos)
4896 _ => pat = PatKind::Path(qself, path),
4899 // Try to parse everything else as literal with optional minus
4900 match self.parse_literal_maybe_minus() {
4902 let op_span = self.span;
4903 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4904 self.check(&token::DotDotDot) {
4905 let end_kind = if self.eat(&token::DotDotDot) {
4906 RangeEnd::Included(RangeSyntax::DotDotDot)
4907 } else if self.eat(&token::DotDotEq) {
4908 RangeEnd::Included(RangeSyntax::DotDotEq)
4909 } else if self.eat(&token::DotDot) {
4912 panic!("impossible case: we already matched \
4913 on a range-operator token")
4915 let end = self.parse_pat_range_end()?;
4916 let op = Spanned { span: op_span, node: end_kind };
4917 pat = PatKind::Range(begin, end, op);
4919 pat = PatKind::Lit(begin);
4923 self.cancel(&mut err);
4924 let expected = expected.unwrap_or("pattern");
4926 "expected {}, found {}",
4928 self.this_token_descr(),
4930 let mut err = self.fatal(&msg);
4931 err.span_label(self.span, format!("expected {}", expected));
4938 let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4939 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4941 if !allow_range_pat {
4944 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4946 PatKind::Range(..) => {
4947 let mut err = self.struct_span_err(
4949 "the range pattern here has ambiguous interpretation",
4951 err.span_suggestion(
4953 "add parentheses to clarify the precedence",
4954 format!("({})", pprust::pat_to_string(&pat)),
4955 // "ambiguous interpretation" implies that we have to be guessing
4956 Applicability::MaybeIncorrect
4967 /// Parses `ident` or `ident @ pat`.
4968 /// used by the copy foo and ref foo patterns to give a good
4969 /// error message when parsing mistakes like `ref foo(a, b)`.
4970 fn parse_pat_ident(&mut self,
4971 binding_mode: ast::BindingMode)
4972 -> PResult<'a, PatKind> {
4973 let ident = self.parse_ident()?;
4974 let sub = if self.eat(&token::At) {
4975 Some(self.parse_pat(Some("binding pattern"))?)
4980 // just to be friendly, if they write something like
4982 // we end up here with ( as the current token. This shortly
4983 // leads to a parse error. Note that if there is no explicit
4984 // binding mode then we do not end up here, because the lookahead
4985 // will direct us over to parse_enum_variant()
4986 if self.token == token::OpenDelim(token::Paren) {
4987 return Err(self.span_fatal(
4989 "expected identifier, found enum pattern"))
4992 Ok(PatKind::Ident(binding_mode, ident, sub))
4995 /// Parses a local variable declaration.
4996 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4997 let lo = self.prev_span;
4998 let pat = self.parse_top_level_pat()?;
5000 let (err, ty) = if self.eat(&token::Colon) {
5001 // Save the state of the parser before parsing type normally, in case there is a `:`
5002 // instead of an `=` typo.
5003 let parser_snapshot_before_type = self.clone();
5004 let colon_sp = self.prev_span;
5005 match self.parse_ty() {
5006 Ok(ty) => (None, Some(ty)),
5008 // Rewind to before attempting to parse the type and continue parsing
5009 let parser_snapshot_after_type = self.clone();
5010 mem::replace(self, parser_snapshot_before_type);
5012 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
5013 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
5014 (Some((parser_snapshot_after_type, colon_sp, err)), None)
5020 let init = match (self.parse_initializer(err.is_some()), err) {
5021 (Ok(init), None) => { // init parsed, ty parsed
5024 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
5025 // Could parse the type as if it were the initializer, it is likely there was a
5026 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
5027 err.span_suggestion_short(
5029 "use `=` if you meant to assign",
5031 Applicability::MachineApplicable
5034 // As this was parsed successfully, continue as if the code has been fixed for the
5035 // rest of the file. It will still fail due to the emitted error, but we avoid
5039 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
5041 // Couldn't parse the type nor the initializer, only raise the type error and
5042 // return to the parser state before parsing the type as the initializer.
5043 // let x: <parse_error>;
5044 mem::replace(self, snapshot);
5047 (Err(err), None) => { // init error, ty parsed
5048 // Couldn't parse the initializer and we're not attempting to recover a failed
5049 // parse of the type, return the error.
5053 let hi = if self.token == token::Semi {
5062 id: ast::DUMMY_NODE_ID,
5065 source: LocalSource::Normal,
5069 /// Parses a structure field.
5070 fn parse_name_and_ty(&mut self,
5073 attrs: Vec<Attribute>)
5074 -> PResult<'a, StructField> {
5075 let name = self.parse_ident()?;
5076 self.expect(&token::Colon)?;
5077 let ty = self.parse_ty()?;
5079 span: lo.to(self.prev_span),
5082 id: ast::DUMMY_NODE_ID,
5088 /// Emits an expected-item-after-attributes error.
5089 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
5090 let message = match attrs.last() {
5091 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
5092 _ => "expected item after attributes",
5095 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
5096 if attrs.last().unwrap().is_sugared_doc {
5097 err.span_label(self.prev_span, "this doc comment doesn't document anything");
5102 /// Parse a statement. This stops just before trailing semicolons on everything but items.
5103 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
5104 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
5105 Ok(self.parse_stmt_(true))
5108 // Eat tokens until we can be relatively sure we reached the end of the
5109 // statement. This is something of a best-effort heuristic.
5111 // We terminate when we find an unmatched `}` (without consuming it).
5112 fn recover_stmt(&mut self) {
5113 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
5116 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
5117 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
5118 // approximate - it can mean we break too early due to macros, but that
5119 // should only lead to sub-optimal recovery, not inaccurate parsing).
5121 // If `break_on_block` is `Break`, then we will stop consuming tokens
5122 // after finding (and consuming) a brace-delimited block.
5123 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
5124 let mut brace_depth = 0;
5125 let mut bracket_depth = 0;
5126 let mut in_block = false;
5127 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
5128 break_on_semi, break_on_block);
5130 debug!("recover_stmt_ loop {:?}", self.token);
5132 token::OpenDelim(token::DelimToken::Brace) => {
5135 if break_on_block == BlockMode::Break &&
5137 bracket_depth == 0 {
5141 token::OpenDelim(token::DelimToken::Bracket) => {
5145 token::CloseDelim(token::DelimToken::Brace) => {
5146 if brace_depth == 0 {
5147 debug!("recover_stmt_ return - close delim {:?}", self.token);
5152 if in_block && bracket_depth == 0 && brace_depth == 0 {
5153 debug!("recover_stmt_ return - block end {:?}", self.token);
5157 token::CloseDelim(token::DelimToken::Bracket) => {
5159 if bracket_depth < 0 {
5165 debug!("recover_stmt_ return - Eof");
5170 if break_on_semi == SemiColonMode::Break &&
5172 bracket_depth == 0 {
5173 debug!("recover_stmt_ return - Semi");
5178 if break_on_semi == SemiColonMode::Comma &&
5180 bracket_depth == 0 {
5181 debug!("recover_stmt_ return - Semi");
5194 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
5195 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
5197 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5202 fn is_async_block(&mut self) -> bool {
5203 self.token.is_keyword(keywords::Async) &&
5206 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
5207 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
5209 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
5214 fn is_async_fn(&mut self) -> bool {
5215 self.token.is_keyword(keywords::Async) &&
5216 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
5219 fn is_do_catch_block(&mut self) -> bool {
5220 self.token.is_keyword(keywords::Do) &&
5221 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
5222 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
5223 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5226 fn is_try_block(&mut self) -> bool {
5227 self.token.is_keyword(keywords::Try) &&
5228 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
5229 self.span.rust_2018() &&
5230 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
5231 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5234 fn is_union_item(&self) -> bool {
5235 self.token.is_keyword(keywords::Union) &&
5236 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
5239 fn is_crate_vis(&self) -> bool {
5240 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
5243 fn is_existential_type_decl(&self) -> bool {
5244 self.token.is_keyword(keywords::Existential) &&
5245 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
5248 fn is_auto_trait_item(&mut self) -> bool {
5250 (self.token.is_keyword(keywords::Auto)
5251 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
5252 || // unsafe auto trait
5253 (self.token.is_keyword(keywords::Unsafe) &&
5254 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
5255 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
5258 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
5259 -> PResult<'a, Option<P<Item>>> {
5260 let token_lo = self.span;
5261 let (ident, def) = match self.token {
5262 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
5264 let ident = self.parse_ident()?;
5265 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
5266 match self.parse_token_tree() {
5267 TokenTree::Delimited(_, _, tts) => tts,
5268 _ => unreachable!(),
5270 } else if self.check(&token::OpenDelim(token::Paren)) {
5271 let args = self.parse_token_tree();
5272 let body = if self.check(&token::OpenDelim(token::Brace)) {
5273 self.parse_token_tree()
5278 TokenStream::new(vec![
5280 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
5288 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
5290 token::Ident(ident, _) if ident.name == "macro_rules" &&
5291 self.look_ahead(1, |t| *t == token::Not) => {
5292 let prev_span = self.prev_span;
5293 self.complain_if_pub_macro(&vis.node, prev_span);
5297 let ident = self.parse_ident()?;
5298 let (delim, tokens) = self.expect_delimited_token_tree()?;
5299 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
5300 self.report_invalid_macro_expansion_item();
5303 (ident, ast::MacroDef { tokens: tokens, legacy: true })
5305 _ => return Ok(None),
5308 let span = lo.to(self.prev_span);
5309 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
5312 fn parse_stmt_without_recovery(&mut self,
5313 macro_legacy_warnings: bool)
5314 -> PResult<'a, Option<Stmt>> {
5315 maybe_whole!(self, NtStmt, |x| Some(x));
5317 let attrs = self.parse_outer_attributes()?;
5320 Ok(Some(if self.eat_keyword(keywords::Let) {
5322 id: ast::DUMMY_NODE_ID,
5323 node: StmtKind::Local(self.parse_local(attrs.into())?),
5324 span: lo.to(self.prev_span),
5326 } else if let Some(macro_def) = self.eat_macro_def(
5328 &source_map::respan(lo, VisibilityKind::Inherited),
5332 id: ast::DUMMY_NODE_ID,
5333 node: StmtKind::Item(macro_def),
5334 span: lo.to(self.prev_span),
5336 // Starts like a simple path, being careful to avoid contextual keywords
5337 // such as a union items, item with `crate` visibility or auto trait items.
5338 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
5339 // like a path (1 token), but it fact not a path.
5340 // `union::b::c` - path, `union U { ... }` - not a path.
5341 // `crate::b::c` - path, `crate struct S;` - not a path.
5342 } else if self.token.is_path_start() &&
5343 !self.token.is_qpath_start() &&
5344 !self.is_union_item() &&
5345 !self.is_crate_vis() &&
5346 !self.is_existential_type_decl() &&
5347 !self.is_auto_trait_item() &&
5348 !self.is_async_fn() {
5349 let pth = self.parse_path(PathStyle::Expr)?;
5351 if !self.eat(&token::Not) {
5352 let expr = if self.check(&token::OpenDelim(token::Brace)) {
5353 self.parse_struct_expr(lo, pth, ThinVec::new())?
5355 let hi = self.prev_span;
5356 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
5359 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
5360 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
5361 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
5364 return Ok(Some(Stmt {
5365 id: ast::DUMMY_NODE_ID,
5366 node: StmtKind::Expr(expr),
5367 span: lo.to(self.prev_span),
5371 // it's a macro invocation
5372 let id = match self.token {
5373 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
5374 _ => self.parse_ident()?,
5377 // check that we're pointing at delimiters (need to check
5378 // again after the `if`, because of `parse_ident`
5379 // consuming more tokens).
5381 token::OpenDelim(_) => {}
5383 // we only expect an ident if we didn't parse one
5385 let ident_str = if id.name == keywords::Invalid.name() {
5390 let tok_str = self.this_token_descr();
5391 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
5394 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
5399 let (delim, tts) = self.expect_delimited_token_tree()?;
5400 let hi = self.prev_span;
5402 let style = if delim == MacDelimiter::Brace {
5403 MacStmtStyle::Braces
5405 MacStmtStyle::NoBraces
5408 if id.name == keywords::Invalid.name() {
5409 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
5410 let node = if delim == MacDelimiter::Brace ||
5411 self.token == token::Semi || self.token == token::Eof {
5412 StmtKind::Mac(P((mac, style, attrs.into())))
5414 // We used to incorrectly stop parsing macro-expanded statements here.
5415 // If the next token will be an error anyway but could have parsed with the
5416 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
5417 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
5418 // These can continue an expression, so we can't stop parsing and warn.
5419 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
5420 token::BinOp(token::Minus) | token::BinOp(token::Star) |
5421 token::BinOp(token::And) | token::BinOp(token::Or) |
5422 token::AndAnd | token::OrOr |
5423 token::DotDot | token::DotDotDot | token::DotDotEq => false,
5426 self.warn_missing_semicolon();
5427 StmtKind::Mac(P((mac, style, attrs.into())))
5429 let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
5430 let e = self.maybe_recover_from_bad_qpath(e, true)?;
5431 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
5432 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
5436 id: ast::DUMMY_NODE_ID,
5441 // if it has a special ident, it's definitely an item
5443 // Require a semicolon or braces.
5444 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
5445 self.report_invalid_macro_expansion_item();
5447 let span = lo.to(hi);
5449 id: ast::DUMMY_NODE_ID,
5451 node: StmtKind::Item({
5453 span, id /*id is good here*/,
5454 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
5455 respan(lo, VisibilityKind::Inherited),
5461 // FIXME: Bad copy of attrs
5462 let old_directory_ownership =
5463 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
5464 let item = self.parse_item_(attrs.clone(), false, true)?;
5465 self.directory.ownership = old_directory_ownership;
5469 id: ast::DUMMY_NODE_ID,
5470 span: lo.to(i.span),
5471 node: StmtKind::Item(i),
5474 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
5475 if !attrs.is_empty() {
5476 if s.prev_token_kind == PrevTokenKind::DocComment {
5477 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
5478 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
5479 s.span_err(s.span, "expected statement after outer attribute");
5484 // Do not attempt to parse an expression if we're done here.
5485 if self.token == token::Semi {
5486 unused_attrs(&attrs, self);
5491 if self.token == token::CloseDelim(token::Brace) {
5492 unused_attrs(&attrs, self);
5496 // Remainder are line-expr stmts.
5497 let e = self.parse_expr_res(
5498 Restrictions::STMT_EXPR, Some(attrs.into()))?;
5500 id: ast::DUMMY_NODE_ID,
5501 span: lo.to(e.span),
5502 node: StmtKind::Expr(e),
5509 /// Checks if this expression is a successfully parsed statement.
5510 fn expr_is_complete(&mut self, e: &Expr) -> bool {
5511 self.restrictions.contains(Restrictions::STMT_EXPR) &&
5512 !classify::expr_requires_semi_to_be_stmt(e)
5515 /// Parses a block. No inner attributes are allowed.
5516 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
5517 maybe_whole!(self, NtBlock, |x| x);
5521 if !self.eat(&token::OpenDelim(token::Brace)) {
5523 let tok = self.this_token_descr();
5524 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
5525 let do_not_suggest_help =
5526 self.token.is_keyword(keywords::In) || self.token == token::Colon;
5528 if self.token.is_ident_named("and") {
5529 e.span_suggestion_short(
5531 "use `&&` instead of `and` for the boolean operator",
5533 Applicability::MaybeIncorrect,
5536 if self.token.is_ident_named("or") {
5537 e.span_suggestion_short(
5539 "use `||` instead of `or` for the boolean operator",
5541 Applicability::MaybeIncorrect,
5545 // Check to see if the user has written something like
5550 // Which is valid in other languages, but not Rust.
5551 match self.parse_stmt_without_recovery(false) {
5553 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
5554 || do_not_suggest_help {
5555 // if the next token is an open brace (e.g., `if a b {`), the place-
5556 // inside-a-block suggestion would be more likely wrong than right
5557 e.span_label(sp, "expected `{`");
5560 let mut stmt_span = stmt.span;
5561 // expand the span to include the semicolon, if it exists
5562 if self.eat(&token::Semi) {
5563 stmt_span = stmt_span.with_hi(self.prev_span.hi());
5565 let sugg = pprust::to_string(|s| {
5566 use crate::print::pprust::{PrintState, INDENT_UNIT};
5567 s.ibox(INDENT_UNIT)?;
5569 s.print_stmt(&stmt)?;
5570 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
5574 "try placing this code inside a block",
5576 // speculative, has been misleading in the past (closed Issue #46836)
5577 Applicability::MaybeIncorrect
5581 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5582 self.cancel(&mut e);
5586 e.span_label(sp, "expected `{`");
5590 self.parse_block_tail(lo, BlockCheckMode::Default)
5593 /// Parses a block. Inner attributes are allowed.
5594 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
5595 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
5598 self.expect(&token::OpenDelim(token::Brace))?;
5599 Ok((self.parse_inner_attributes()?,
5600 self.parse_block_tail(lo, BlockCheckMode::Default)?))
5603 /// Parses the rest of a block expression or function body.
5604 /// Precondition: already parsed the '{'.
5605 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
5606 let mut stmts = vec![];
5607 while !self.eat(&token::CloseDelim(token::Brace)) {
5608 let stmt = match self.parse_full_stmt(false) {
5611 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
5613 id: ast::DUMMY_NODE_ID,
5614 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
5620 if let Some(stmt) = stmt {
5622 } else if self.token == token::Eof {
5625 // Found only `;` or `}`.
5631 id: ast::DUMMY_NODE_ID,
5633 span: lo.to(self.prev_span),
5637 /// Parses a statement, including the trailing semicolon.
5638 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5639 // skip looking for a trailing semicolon when we have an interpolated statement
5640 maybe_whole!(self, NtStmt, |x| Some(x));
5642 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5644 None => return Ok(None),
5648 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5649 // expression without semicolon
5650 if classify::expr_requires_semi_to_be_stmt(expr) {
5651 // Just check for errors and recover; do not eat semicolon yet.
5653 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5656 self.recover_stmt();
5660 StmtKind::Local(..) => {
5661 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5662 if macro_legacy_warnings && self.token != token::Semi {
5663 self.warn_missing_semicolon();
5665 self.expect_one_of(&[], &[token::Semi])?;
5671 if self.eat(&token::Semi) {
5672 stmt = stmt.add_trailing_semicolon();
5675 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5679 fn warn_missing_semicolon(&self) {
5680 self.diagnostic().struct_span_warn(self.span, {
5681 &format!("expected `;`, found {}", self.this_token_descr())
5683 "This was erroneously allowed and will become a hard error in a future release"
5687 fn err_dotdotdot_syntax(&self, span: Span) {
5688 self.diagnostic().struct_span_err(span, {
5689 "unexpected token: `...`"
5691 span, "use `..` for an exclusive range", "..".to_owned(),
5692 Applicability::MaybeIncorrect
5694 span, "or `..=` for an inclusive range", "..=".to_owned(),
5695 Applicability::MaybeIncorrect
5699 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
5702 /// BOUND = TY_BOUND | LT_BOUND
5703 /// LT_BOUND = LIFETIME (e.g., `'a`)
5704 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5705 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5707 fn parse_generic_bounds_common(&mut self,
5709 colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5710 let mut bounds = Vec::new();
5711 let mut negative_bounds = Vec::new();
5712 let mut last_plus_span = None;
5713 let mut was_negative = false;
5715 // This needs to be synchronized with `Token::can_begin_bound`.
5716 let is_bound_start = self.check_path() || self.check_lifetime() ||
5717 self.check(&token::Not) || // used for error reporting only
5718 self.check(&token::Question) ||
5719 self.check_keyword(keywords::For) ||
5720 self.check(&token::OpenDelim(token::Paren));
5723 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5724 let inner_lo = self.span;
5725 let is_negative = self.eat(&token::Not);
5726 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5727 if self.token.is_lifetime() {
5728 if let Some(question_span) = question {
5729 self.span_err(question_span,
5730 "`?` may only modify trait bounds, not lifetime bounds");
5732 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5734 let inner_span = inner_lo.to(self.prev_span);
5735 self.expect(&token::CloseDelim(token::Paren))?;
5736 let mut err = self.struct_span_err(
5737 lo.to(self.prev_span),
5738 "parenthesized lifetime bounds are not supported"
5740 if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
5741 err.span_suggestion_short(
5742 lo.to(self.prev_span),
5743 "remove the parentheses",
5745 Applicability::MachineApplicable
5751 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5752 let path = self.parse_path(PathStyle::Type)?;
5754 self.expect(&token::CloseDelim(token::Paren))?;
5756 let poly_span = lo.to(self.prev_span);
5758 was_negative = true;
5759 if let Some(sp) = last_plus_span.or(colon_span) {
5760 negative_bounds.push(sp.to(poly_span));
5763 let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
5764 let modifier = if question.is_some() {
5765 TraitBoundModifier::Maybe
5767 TraitBoundModifier::None
5769 bounds.push(GenericBound::Trait(poly_trait, modifier));
5776 if !allow_plus || !self.eat_plus() {
5779 last_plus_span = Some(self.prev_span);
5783 if !negative_bounds.is_empty() || was_negative {
5784 let plural = negative_bounds.len() > 1;
5785 let last_span = negative_bounds.last().map(|sp| *sp);
5786 let mut err = self.struct_span_err(
5788 "negative trait bounds are not supported",
5790 if let Some(sp) = last_span {
5791 err.span_label(sp, "negative trait bounds are not supported");
5793 if let Some(bound_list) = colon_span {
5794 let bound_list = bound_list.to(self.prev_span);
5795 let mut new_bound_list = String::new();
5796 if !bounds.is_empty() {
5797 let mut snippets = bounds.iter().map(|bound| bound.span())
5798 .map(|span| self.sess.source_map().span_to_snippet(span));
5799 while let Some(Ok(snippet)) = snippets.next() {
5800 new_bound_list.push_str(" + ");
5801 new_bound_list.push_str(&snippet);
5803 new_bound_list = new_bound_list.replacen(" +", ":", 1);
5805 err.span_suggestion_hidden(
5807 &format!("remove the trait bound{}", if plural { "s" } else { "" }),
5809 Applicability::MachineApplicable,
5818 fn parse_generic_bounds(&mut self, colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5819 self.parse_generic_bounds_common(true, colon_span)
5822 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5825 /// BOUND = LT_BOUND (e.g., `'a`)
5827 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5828 let mut lifetimes = Vec::new();
5829 while self.check_lifetime() {
5830 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5832 if !self.eat_plus() {
5839 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
5840 fn parse_ty_param(&mut self,
5841 preceding_attrs: Vec<Attribute>)
5842 -> PResult<'a, GenericParam> {
5843 let ident = self.parse_ident()?;
5845 // Parse optional colon and param bounds.
5846 let bounds = if self.eat(&token::Colon) {
5847 self.parse_generic_bounds(Some(self.prev_span))?
5852 let default = if self.eat(&token::Eq) {
5853 Some(self.parse_ty()?)
5860 id: ast::DUMMY_NODE_ID,
5861 attrs: preceding_attrs.into(),
5863 kind: GenericParamKind::Type {
5869 /// Parses the following grammar:
5871 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5872 fn parse_trait_item_assoc_ty(&mut self)
5873 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5874 let ident = self.parse_ident()?;
5875 let mut generics = self.parse_generics()?;
5877 // Parse optional colon and param bounds.
5878 let bounds = if self.eat(&token::Colon) {
5879 self.parse_generic_bounds(None)?
5883 generics.where_clause = self.parse_where_clause()?;
5885 let default = if self.eat(&token::Eq) {
5886 Some(self.parse_ty()?)
5890 self.expect(&token::Semi)?;
5892 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5895 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
5896 self.expect_keyword(keywords::Const)?;
5897 let ident = self.parse_ident()?;
5898 self.expect(&token::Colon)?;
5899 let ty = self.parse_ty()?;
5903 id: ast::DUMMY_NODE_ID,
5904 attrs: preceding_attrs.into(),
5906 kind: GenericParamKind::Const {
5912 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
5913 /// a trailing comma and erroneous trailing attributes.
5914 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5915 let mut params = Vec::new();
5917 let attrs = self.parse_outer_attributes()?;
5918 if self.check_lifetime() {
5919 let lifetime = self.expect_lifetime();
5920 // Parse lifetime parameter.
5921 let bounds = if self.eat(&token::Colon) {
5922 self.parse_lt_param_bounds()
5926 params.push(ast::GenericParam {
5927 ident: lifetime.ident,
5929 attrs: attrs.into(),
5931 kind: ast::GenericParamKind::Lifetime,
5933 } else if self.check_keyword(keywords::Const) {
5934 // Parse const parameter.
5935 params.push(self.parse_const_param(attrs)?);
5936 } else if self.check_ident() {
5937 // Parse type parameter.
5938 params.push(self.parse_ty_param(attrs)?);
5940 // Check for trailing attributes and stop parsing.
5941 if !attrs.is_empty() {
5942 if !params.is_empty() {
5943 self.struct_span_err(
5945 &format!("trailing attribute after generic parameter"),
5947 .span_label(attrs[0].span, "attributes must go before parameters")
5950 self.struct_span_err(
5952 &format!("attribute without generic parameters"),
5956 "attributes are only permitted when preceding parameters",
5964 if !self.eat(&token::Comma) {
5971 /// Parses a set of optional generic type parameter declarations. Where
5972 /// clauses are not parsed here, and must be added later via
5973 /// `parse_where_clause()`.
5975 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5976 /// | ( < lifetimes , typaramseq ( , )? > )
5977 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5978 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5979 maybe_whole!(self, NtGenerics, |x| x);
5981 let span_lo = self.span;
5983 let params = self.parse_generic_params()?;
5987 where_clause: WhereClause {
5988 id: ast::DUMMY_NODE_ID,
5989 predicates: Vec::new(),
5990 span: syntax_pos::DUMMY_SP,
5992 span: span_lo.to(self.prev_span),
5995 Ok(ast::Generics::default())
5999 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
6000 /// For the purposes of understanding the parsing logic of generic arguments, this function
6001 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
6002 /// had the correct amount of leading angle brackets.
6004 /// ```ignore (diagnostics)
6005 /// bar::<<<<T as Foo>::Output>();
6006 /// ^^ help: remove extra angle brackets
6008 fn parse_generic_args_with_leaning_angle_bracket_recovery(
6012 ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
6013 // We need to detect whether there are extra leading left angle brackets and produce an
6014 // appropriate error and suggestion. This cannot be implemented by looking ahead at
6015 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
6016 // then there won't be matching `>` tokens to find.
6018 // To explain how this detection works, consider the following example:
6020 // ```ignore (diagnostics)
6021 // bar::<<<<T as Foo>::Output>();
6022 // ^^ help: remove extra angle brackets
6025 // Parsing of the left angle brackets starts in this function. We start by parsing the
6026 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
6029 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
6030 // *Unmatched count:* 1
6031 // *`parse_path_segment` calls deep:* 0
6033 // This has the effect of recursing as this function is called if a `<` character
6034 // is found within the expected generic arguments:
6036 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
6037 // *Unmatched count:* 2
6038 // *`parse_path_segment` calls deep:* 1
6040 // Eventually we will have recursed until having consumed all of the `<` tokens and
6041 // this will be reflected in the count:
6043 // *Upcoming tokens:* `T as Foo>::Output>;`
6044 // *Unmatched count:* 4
6045 // `parse_path_segment` calls deep:* 3
6047 // The parser will continue until reaching the first `>` - this will decrement the
6048 // unmatched angle bracket count and return to the parent invocation of this function
6049 // having succeeded in parsing:
6051 // *Upcoming tokens:* `::Output>;`
6052 // *Unmatched count:* 3
6053 // *`parse_path_segment` calls deep:* 2
6055 // This will continue until the next `>` character which will also return successfully
6056 // to the parent invocation of this function and decrement the count:
6058 // *Upcoming tokens:* `;`
6059 // *Unmatched count:* 2
6060 // *`parse_path_segment` calls deep:* 1
6062 // At this point, this function will expect to find another matching `>` character but
6063 // won't be able to and will return an error. This will continue all the way up the
6064 // call stack until the first invocation:
6066 // *Upcoming tokens:* `;`
6067 // *Unmatched count:* 2
6068 // *`parse_path_segment` calls deep:* 0
6070 // In doing this, we have managed to work out how many unmatched leading left angle
6071 // brackets there are, but we cannot recover as the unmatched angle brackets have
6072 // already been consumed. To remedy this, we keep a snapshot of the parser state
6073 // before we do the above. We can then inspect whether we ended up with a parsing error
6074 // and unmatched left angle brackets and if so, restore the parser state before we
6075 // consumed any `<` characters to emit an error and consume the erroneous tokens to
6076 // recover by attempting to parse again.
6078 // In practice, the recursion of this function is indirect and there will be other
6079 // locations that consume some `<` characters - as long as we update the count when
6080 // this happens, it isn't an issue.
6082 let is_first_invocation = style == PathStyle::Expr;
6083 // Take a snapshot before attempting to parse - we can restore this later.
6084 let snapshot = if is_first_invocation {
6090 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
6091 match self.parse_generic_args() {
6092 Ok(value) => Ok(value),
6093 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
6094 // Cancel error from being unable to find `>`. We know the error
6095 // must have been this due to a non-zero unmatched angle bracket
6099 // Swap `self` with our backup of the parser state before attempting to parse
6100 // generic arguments.
6101 let snapshot = mem::replace(self, snapshot.unwrap());
6104 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
6105 snapshot.count={:?}",
6106 snapshot.unmatched_angle_bracket_count,
6109 // Eat the unmatched angle brackets.
6110 for _ in 0..snapshot.unmatched_angle_bracket_count {
6114 // Make a span over ${unmatched angle bracket count} characters.
6115 let span = lo.with_hi(
6116 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
6118 let plural = snapshot.unmatched_angle_bracket_count > 1;
6123 "unmatched angle bracket{}",
6124 if plural { "s" } else { "" }
6130 "remove extra angle bracket{}",
6131 if plural { "s" } else { "" }
6134 Applicability::MachineApplicable,
6138 // Try again without unmatched angle bracket characters.
6139 self.parse_generic_args()
6145 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
6146 /// possibly including trailing comma.
6147 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
6148 let mut args = Vec::new();
6149 let mut bindings = Vec::new();
6150 let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new();
6151 let mut assoc_ty_bindings: Vec<Span> = Vec::new();
6153 let args_lo = self.span;
6156 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6157 // Parse lifetime argument.
6158 args.push(GenericArg::Lifetime(self.expect_lifetime()));
6159 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6160 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
6161 // Parse associated type binding.
6163 let ident = self.parse_ident()?;
6165 let ty = self.parse_ty()?;
6166 let span = lo.to(self.prev_span);
6167 bindings.push(TypeBinding {
6168 id: ast::DUMMY_NODE_ID,
6173 assoc_ty_bindings.push(span);
6174 } else if self.check_const_arg() {
6175 // FIXME(const_generics): to distinguish between idents for types and consts,
6176 // we should introduce a GenericArg::Ident in the AST and distinguish when
6177 // lowering to the HIR. For now, idents for const args are not permitted.
6179 // Parse const argument.
6180 let expr = if let token::OpenDelim(token::Brace) = self.token {
6181 self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
6182 } else if self.token.is_ident() {
6183 // FIXME(const_generics): to distinguish between idents for types and consts,
6184 // we should introduce a GenericArg::Ident in the AST and distinguish when
6185 // lowering to the HIR. For now, idents for const args are not permitted.
6187 self.fatal("identifiers may currently not be used for const generics")
6190 // FIXME(const_generics): this currently conflicts with emplacement syntax
6191 // with negative integer literals.
6192 self.parse_literal_maybe_minus()?
6194 let value = AnonConst {
6195 id: ast::DUMMY_NODE_ID,
6198 args.push(GenericArg::Const(value));
6199 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6200 } else if self.check_type() {
6201 // Parse type argument.
6202 args.push(GenericArg::Type(self.parse_ty()?));
6203 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6208 if !self.eat(&token::Comma) {
6213 // FIXME: we would like to report this in ast_validation instead, but we currently do not
6214 // preserve ordering of generic parameters with respect to associated type binding, so we
6215 // lose that information after parsing.
6216 if misplaced_assoc_ty_bindings.len() > 0 {
6217 let mut err = self.struct_span_err(
6218 args_lo.to(self.prev_span),
6219 "associated type bindings must be declared after generic parameters",
6221 for span in misplaced_assoc_ty_bindings {
6224 "this associated type binding should be moved after the generic parameters",
6230 Ok((args, bindings))
6233 /// Parses an optional where-clause and places it in `generics`.
6235 /// ```ignore (only-for-syntax-highlight)
6236 /// where T : Trait<U, V> + 'b, 'a : 'b
6238 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
6239 maybe_whole!(self, NtWhereClause, |x| x);
6241 let mut where_clause = WhereClause {
6242 id: ast::DUMMY_NODE_ID,
6243 predicates: Vec::new(),
6244 span: syntax_pos::DUMMY_SP,
6247 if !self.eat_keyword(keywords::Where) {
6248 return Ok(where_clause);
6250 let lo = self.prev_span;
6252 // We are considering adding generics to the `where` keyword as an alternative higher-rank
6253 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
6254 // change we parse those generics now, but report an error.
6255 if self.choose_generics_over_qpath() {
6256 let generics = self.parse_generics()?;
6257 self.struct_span_err(
6259 "generic parameters on `where` clauses are reserved for future use",
6261 .span_label(generics.span, "currently unsupported")
6267 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6268 let lifetime = self.expect_lifetime();
6269 // Bounds starting with a colon are mandatory, but possibly empty.
6270 self.expect(&token::Colon)?;
6271 let bounds = self.parse_lt_param_bounds();
6272 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
6273 ast::WhereRegionPredicate {
6274 span: lo.to(self.prev_span),
6279 } else if self.check_type() {
6280 // Parse optional `for<'a, 'b>`.
6281 // This `for` is parsed greedily and applies to the whole predicate,
6282 // the bounded type can have its own `for` applying only to it.
6283 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
6284 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
6285 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
6286 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
6288 // Parse type with mandatory colon and (possibly empty) bounds,
6289 // or with mandatory equality sign and the second type.
6290 let ty = self.parse_ty()?;
6291 if self.eat(&token::Colon) {
6292 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6293 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
6294 ast::WhereBoundPredicate {
6295 span: lo.to(self.prev_span),
6296 bound_generic_params: lifetime_defs,
6301 // FIXME: Decide what should be used here, `=` or `==`.
6302 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
6303 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
6304 let rhs_ty = self.parse_ty()?;
6305 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
6306 ast::WhereEqPredicate {
6307 span: lo.to(self.prev_span),
6310 id: ast::DUMMY_NODE_ID,
6314 return self.unexpected();
6320 if !self.eat(&token::Comma) {
6325 where_clause.span = lo.to(self.prev_span);
6329 fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
6330 -> PResult<'a, (Vec<Arg> , bool)> {
6331 self.expect(&token::OpenDelim(token::Paren))?;
6334 let mut c_variadic = false;
6335 let (args, recovered): (Vec<Option<Arg>>, bool) =
6336 self.parse_seq_to_before_end(
6337 &token::CloseDelim(token::Paren),
6338 SeqSep::trailing_allowed(token::Comma),
6340 // If the argument is a C-variadic argument we should not
6341 // enforce named arguments.
6342 let enforce_named_args = if p.token == token::DotDotDot {
6347 match p.parse_arg_general(enforce_named_args, false,
6350 if let TyKind::CVarArgs = arg.ty.node {
6352 if p.token != token::CloseDelim(token::Paren) {
6355 "`...` must be the last argument of a C-variadic function");
6366 let lo = p.prev_span;
6367 // Skip every token until next possible arg or end.
6368 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
6369 // Create a placeholder argument for proper arg count (issue #34264).
6370 let span = lo.to(p.prev_span);
6371 Ok(Some(dummy_arg(span)))
6378 self.eat(&token::CloseDelim(token::Paren));
6381 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
6383 if c_variadic && args.is_empty() {
6385 "C-variadic function must be declared with at least one named argument");
6388 Ok((args, c_variadic))
6391 /// Parses the argument list and result type of a function declaration.
6392 fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
6394 let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
6395 let ret_ty = self.parse_ret_ty(true)?;
6404 /// Returns the parsed optional self argument and whether a self shortcut was used.
6405 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
6406 let expect_ident = |this: &mut Self| match this.token {
6407 // Preserve hygienic context.
6408 token::Ident(ident, _) =>
6409 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
6412 let isolated_self = |this: &mut Self, n| {
6413 this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) &&
6414 this.look_ahead(n + 1, |t| t != &token::ModSep)
6417 // Parse optional self parameter of a method.
6418 // Only a limited set of initial token sequences is considered self parameters, anything
6419 // else is parsed as a normal function parameter list, so some lookahead is required.
6420 let eself_lo = self.span;
6421 let (eself, eself_ident, eself_hi) = match self.token {
6422 token::BinOp(token::And) => {
6428 (if isolated_self(self, 1) {
6430 SelfKind::Region(None, Mutability::Immutable)
6431 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
6432 isolated_self(self, 2) {
6435 SelfKind::Region(None, Mutability::Mutable)
6436 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6437 isolated_self(self, 2) {
6439 let lt = self.expect_lifetime();
6440 SelfKind::Region(Some(lt), Mutability::Immutable)
6441 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6442 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
6443 isolated_self(self, 3) {
6445 let lt = self.expect_lifetime();
6447 SelfKind::Region(Some(lt), Mutability::Mutable)
6450 }, expect_ident(self), self.prev_span)
6452 token::BinOp(token::Star) => {
6457 // Emit special error for `self` cases.
6458 let msg = "cannot pass `self` by raw pointer";
6459 (if isolated_self(self, 1) {
6461 self.struct_span_err(self.span, msg)
6462 .span_label(self.span, msg)
6464 SelfKind::Value(Mutability::Immutable)
6465 } else if self.look_ahead(1, |t| t.is_mutability()) &&
6466 isolated_self(self, 2) {
6469 self.struct_span_err(self.span, msg)
6470 .span_label(self.span, msg)
6472 SelfKind::Value(Mutability::Immutable)
6475 }, expect_ident(self), self.prev_span)
6477 token::Ident(..) => {
6478 if isolated_self(self, 0) {
6481 let eself_ident = expect_ident(self);
6482 let eself_hi = self.prev_span;
6483 (if self.eat(&token::Colon) {
6484 let ty = self.parse_ty()?;
6485 SelfKind::Explicit(ty, Mutability::Immutable)
6487 SelfKind::Value(Mutability::Immutable)
6488 }, eself_ident, eself_hi)
6489 } else if self.token.is_keyword(keywords::Mut) &&
6490 isolated_self(self, 1) {
6494 let eself_ident = expect_ident(self);
6495 let eself_hi = self.prev_span;
6496 (if self.eat(&token::Colon) {
6497 let ty = self.parse_ty()?;
6498 SelfKind::Explicit(ty, Mutability::Mutable)
6500 SelfKind::Value(Mutability::Mutable)
6501 }, eself_ident, eself_hi)
6506 _ => return Ok(None),
6509 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
6510 Ok(Some(Arg::from_self(eself, eself_ident)))
6513 /// Parses the parameter list and result type of a function that may have a `self` parameter.
6514 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
6515 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
6517 self.expect(&token::OpenDelim(token::Paren))?;
6519 // Parse optional self argument
6520 let self_arg = self.parse_self_arg()?;
6522 // Parse the rest of the function parameter list.
6523 let sep = SeqSep::trailing_allowed(token::Comma);
6524 let (fn_inputs, recovered) = if let Some(self_arg) = self_arg {
6525 if self.check(&token::CloseDelim(token::Paren)) {
6526 (vec![self_arg], false)
6527 } else if self.eat(&token::Comma) {
6528 let mut fn_inputs = vec![self_arg];
6529 let (mut input, recovered) = self.parse_seq_to_before_end(
6530 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
6531 fn_inputs.append(&mut input);
6532 (fn_inputs, recovered)
6534 match self.expect_one_of(&[], &[]) {
6535 Err(err) => return Err(err),
6536 Ok(recovered) => (vec![self_arg], recovered),
6540 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
6544 // Parse closing paren and return type.
6545 self.expect(&token::CloseDelim(token::Paren))?;
6549 output: self.parse_ret_ty(true)?,
6554 /// Parses the `|arg, arg|` header of a closure.
6555 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
6556 let inputs_captures = {
6557 if self.eat(&token::OrOr) {
6560 self.expect(&token::BinOp(token::Or))?;
6561 let args = self.parse_seq_to_before_tokens(
6562 &[&token::BinOp(token::Or), &token::OrOr],
6563 SeqSep::trailing_allowed(token::Comma),
6564 TokenExpectType::NoExpect,
6565 |p| p.parse_fn_block_arg()
6571 let output = self.parse_ret_ty(true)?;
6574 inputs: inputs_captures,
6580 /// Parses the name and optional generic types of a function header.
6581 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
6582 let id = self.parse_ident()?;
6583 let generics = self.parse_generics()?;
6587 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
6588 attrs: Vec<Attribute>) -> P<Item> {
6592 id: ast::DUMMY_NODE_ID,
6600 /// Parses an item-position function declaration.
6601 fn parse_item_fn(&mut self,
6603 mut asyncness: Spanned<IsAsync>,
6604 constness: Spanned<Constness>,
6606 -> PResult<'a, ItemInfo> {
6607 let (ident, mut generics) = self.parse_fn_header()?;
6608 let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
6609 let decl = self.parse_fn_decl(allow_c_variadic)?;
6610 generics.where_clause = self.parse_where_clause()?;
6611 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6612 self.construct_async_arguments(&mut asyncness, &decl);
6613 let header = FnHeader { unsafety, asyncness, constness, abi };
6614 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
6617 /// Returns `true` if we are looking at `const ID`
6618 /// (returns `false` for things like `const fn`, etc.).
6619 fn is_const_item(&mut self) -> bool {
6620 self.token.is_keyword(keywords::Const) &&
6621 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
6622 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
6625 /// Parses all the "front matter" for a `fn` declaration, up to
6626 /// and including the `fn` keyword:
6630 /// - `const unsafe fn`
6633 fn parse_fn_front_matter(&mut self)
6641 let is_const_fn = self.eat_keyword(keywords::Const);
6642 let const_span = self.prev_span;
6643 let unsafety = self.parse_unsafety();
6644 let asyncness = self.parse_asyncness();
6645 let asyncness = respan(self.prev_span, asyncness);
6646 let (constness, unsafety, abi) = if is_const_fn {
6647 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
6649 let abi = if self.eat_keyword(keywords::Extern) {
6650 self.parse_opt_abi()?.unwrap_or(Abi::C)
6654 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
6656 if !self.eat_keyword(keywords::Fn) {
6657 // It is possible for `expect_one_of` to recover given the contents of
6658 // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
6659 // account for this.
6660 if !self.expect_one_of(&[], &[])? { unreachable!() }
6662 Ok((constness, unsafety, asyncness, abi))
6665 /// Parses an impl item.
6666 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
6667 maybe_whole!(self, NtImplItem, |x| x);
6668 let attrs = self.parse_outer_attributes()?;
6669 let mut unclosed_delims = vec![];
6670 let (mut item, tokens) = self.collect_tokens(|this| {
6671 let item = this.parse_impl_item_(at_end, attrs);
6672 unclosed_delims.append(&mut this.unclosed_delims);
6675 self.unclosed_delims.append(&mut unclosed_delims);
6677 // See `parse_item` for why this clause is here.
6678 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6679 item.tokens = Some(tokens);
6684 fn parse_impl_item_(&mut self,
6686 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
6688 let vis = self.parse_visibility(false)?;
6689 let defaultness = self.parse_defaultness();
6690 let (name, node, generics) = if let Some(type_) = self.eat_type() {
6691 let (name, alias, generics) = type_?;
6692 let kind = match alias {
6693 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
6694 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
6696 (name, kind, generics)
6697 } else if self.is_const_item() {
6698 // This parses the grammar:
6699 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
6700 self.expect_keyword(keywords::Const)?;
6701 let name = self.parse_ident()?;
6702 self.expect(&token::Colon)?;
6703 let typ = self.parse_ty()?;
6704 self.expect(&token::Eq)?;
6705 let expr = self.parse_expr()?;
6706 self.expect(&token::Semi)?;
6707 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
6709 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
6710 attrs.extend(inner_attrs);
6711 (name, node, generics)
6715 id: ast::DUMMY_NODE_ID,
6716 span: lo.to(self.prev_span),
6727 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
6729 VisibilityKind::Inherited => {}
6731 let is_macro_rules: bool = match self.token {
6732 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
6735 let mut err = if is_macro_rules {
6736 let mut err = self.diagnostic()
6737 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
6738 err.span_suggestion(
6740 "try exporting the macro",
6741 "#[macro_export]".to_owned(),
6742 Applicability::MaybeIncorrect // speculative
6746 let mut err = self.diagnostic()
6747 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
6748 err.help("try adjusting the macro to put `pub` inside the invocation");
6756 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
6757 -> DiagnosticBuilder<'a>
6759 let expected_kinds = if item_type == "extern" {
6760 "missing `fn`, `type`, or `static`"
6762 "missing `fn`, `type`, or `const`"
6765 // Given this code `path(`, it seems like this is not
6766 // setting the visibility of a macro invocation, but rather
6767 // a mistyped method declaration.
6768 // Create a diagnostic pointing out that `fn` is missing.
6770 // x | pub path(&self) {
6771 // | ^ missing `fn`, `type`, or `const`
6773 // ^^ `sp` below will point to this
6774 let sp = prev_span.between(self.prev_span);
6775 let mut err = self.diagnostic().struct_span_err(
6777 &format!("{} for {}-item declaration",
6778 expected_kinds, item_type));
6779 err.span_label(sp, expected_kinds);
6783 /// Parse a method or a macro invocation in a trait impl.
6784 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
6785 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
6786 ast::ImplItemKind)> {
6787 // code copied from parse_macro_use_or_failure... abstraction!
6788 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
6790 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
6791 ast::ImplItemKind::Macro(mac)))
6793 let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
6794 let ident = self.parse_ident()?;
6795 let mut generics = self.parse_generics()?;
6796 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
6797 generics.where_clause = self.parse_where_clause()?;
6798 self.construct_async_arguments(&mut asyncness, &decl);
6800 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6801 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
6802 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
6803 ast::MethodSig { header, decl },
6809 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
6810 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
6811 let ident = self.parse_ident()?;
6812 let mut tps = self.parse_generics()?;
6814 // Parse optional colon and supertrait bounds.
6815 let bounds = if self.eat(&token::Colon) {
6816 self.parse_generic_bounds(Some(self.prev_span))?
6821 if self.eat(&token::Eq) {
6822 // it's a trait alias
6823 let bounds = self.parse_generic_bounds(None)?;
6824 tps.where_clause = self.parse_where_clause()?;
6825 self.expect(&token::Semi)?;
6826 if is_auto == IsAuto::Yes {
6827 let msg = "trait aliases cannot be `auto`";
6828 self.struct_span_err(self.prev_span, msg)
6829 .span_label(self.prev_span, msg)
6832 if unsafety != Unsafety::Normal {
6833 let msg = "trait aliases cannot be `unsafe`";
6834 self.struct_span_err(self.prev_span, msg)
6835 .span_label(self.prev_span, msg)
6838 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
6840 // it's a normal trait
6841 tps.where_clause = self.parse_where_clause()?;
6842 self.expect(&token::OpenDelim(token::Brace))?;
6843 let mut trait_items = vec![];
6844 while !self.eat(&token::CloseDelim(token::Brace)) {
6845 if let token::DocComment(_) = self.token {
6846 if self.look_ahead(1,
6847 |tok| tok == &token::Token::CloseDelim(token::Brace)) {
6848 let mut err = self.diagnostic().struct_span_err_with_code(
6850 "found a documentation comment that doesn't document anything",
6851 DiagnosticId::Error("E0584".into()),
6853 err.help("doc comments must come before what they document, maybe a \
6854 comment was intended with `//`?",
6861 let mut at_end = false;
6862 match self.parse_trait_item(&mut at_end) {
6863 Ok(item) => trait_items.push(item),
6867 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6872 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
6876 fn choose_generics_over_qpath(&self) -> bool {
6877 // There's an ambiguity between generic parameters and qualified paths in impls.
6878 // If we see `<` it may start both, so we have to inspect some following tokens.
6879 // The following combinations can only start generics,
6880 // but not qualified paths (with one exception):
6881 // `<` `>` - empty generic parameters
6882 // `<` `#` - generic parameters with attributes
6883 // `<` (LIFETIME|IDENT) `>` - single generic parameter
6884 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
6885 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
6886 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
6887 // `<` const - generic const parameter
6888 // The only truly ambiguous case is
6889 // `<` IDENT `>` `::` IDENT ...
6890 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
6891 // because this is what almost always expected in practice, qualified paths in impls
6892 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
6893 self.token == token::Lt &&
6894 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
6895 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
6896 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
6897 t == &token::Colon || t == &token::Eq) ||
6898 self.look_ahead(1, |t| t.is_keyword(keywords::Const)))
6901 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6902 self.expect(&token::OpenDelim(token::Brace))?;
6903 let attrs = self.parse_inner_attributes()?;
6905 let mut impl_items = Vec::new();
6906 while !self.eat(&token::CloseDelim(token::Brace)) {
6907 let mut at_end = false;
6908 match self.parse_impl_item(&mut at_end) {
6909 Ok(impl_item) => impl_items.push(impl_item),
6913 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6918 Ok((impl_items, attrs))
6921 /// Parses an implementation item, `impl` keyword is already parsed.
6923 /// impl<'a, T> TYPE { /* impl items */ }
6924 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6925 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6927 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6928 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6929 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6930 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6931 -> PResult<'a, ItemInfo> {
6932 // First, parse generic parameters if necessary.
6933 let mut generics = if self.choose_generics_over_qpath() {
6934 self.parse_generics()?
6936 ast::Generics::default()
6939 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6940 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6942 ast::ImplPolarity::Negative
6944 ast::ImplPolarity::Positive
6947 // Parse both types and traits as a type, then reinterpret if necessary.
6948 let err_path = |span| ast::Path::from_ident(Ident::new(keywords::Invalid.name(), span));
6949 let ty_first = if self.token.is_keyword(keywords::For) &&
6950 self.look_ahead(1, |t| t != &token::Lt) {
6951 let span = self.prev_span.between(self.span);
6952 self.struct_span_err(span, "missing trait in a trait impl").emit();
6953 P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6958 // If `for` is missing we try to recover.
6959 let has_for = self.eat_keyword(keywords::For);
6960 let missing_for_span = self.prev_span.between(self.span);
6962 let ty_second = if self.token == token::DotDot {
6963 // We need to report this error after `cfg` expansion for compatibility reasons
6964 self.bump(); // `..`, do not add it to expected tokens
6965 Some(DummyResult::raw_ty(self.prev_span, true))
6966 } else if has_for || self.token.can_begin_type() {
6967 Some(self.parse_ty()?)
6972 generics.where_clause = self.parse_where_clause()?;
6974 let (impl_items, attrs) = self.parse_impl_body()?;
6976 let item_kind = match ty_second {
6977 Some(ty_second) => {
6978 // impl Trait for Type
6980 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6981 .span_suggestion_short(
6984 " for ".to_string(),
6985 Applicability::MachineApplicable,
6989 let ty_first = ty_first.into_inner();
6990 let path = match ty_first.node {
6991 // This notably includes paths passed through `ty` macro fragments (#46438).
6992 TyKind::Path(None, path) => path,
6994 self.span_err(ty_first.span, "expected a trait, found type");
6995 err_path(ty_first.span)
6998 let trait_ref = TraitRef { path, ref_id: ty_first.id };
7000 ItemKind::Impl(unsafety, polarity, defaultness,
7001 generics, Some(trait_ref), ty_second, impl_items)
7005 ItemKind::Impl(unsafety, polarity, defaultness,
7006 generics, None, ty_first, impl_items)
7010 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
7013 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
7014 if self.eat_keyword(keywords::For) {
7016 let params = self.parse_generic_params()?;
7018 // We rely on AST validation to rule out invalid cases: There must not be type
7019 // parameters, and the lifetime parameters must not have bounds.
7026 /// Parses `struct Foo { ... }`.
7027 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
7028 let class_name = self.parse_ident()?;
7030 let mut generics = self.parse_generics()?;
7032 // There is a special case worth noting here, as reported in issue #17904.
7033 // If we are parsing a tuple struct it is the case that the where clause
7034 // should follow the field list. Like so:
7036 // struct Foo<T>(T) where T: Copy;
7038 // If we are parsing a normal record-style struct it is the case
7039 // that the where clause comes before the body, and after the generics.
7040 // So if we look ahead and see a brace or a where-clause we begin
7041 // parsing a record style struct.
7043 // Otherwise if we look ahead and see a paren we parse a tuple-style
7046 let vdata = if self.token.is_keyword(keywords::Where) {
7047 generics.where_clause = self.parse_where_clause()?;
7048 if self.eat(&token::Semi) {
7049 // If we see a: `struct Foo<T> where T: Copy;` style decl.
7050 VariantData::Unit(ast::DUMMY_NODE_ID)
7052 // If we see: `struct Foo<T> where T: Copy { ... }`
7053 let (fields, recovered) = self.parse_record_struct_body()?;
7054 VariantData::Struct(fields, recovered)
7056 // No `where` so: `struct Foo<T>;`
7057 } else if self.eat(&token::Semi) {
7058 VariantData::Unit(ast::DUMMY_NODE_ID)
7059 // Record-style struct definition
7060 } else if self.token == token::OpenDelim(token::Brace) {
7061 let (fields, recovered) = self.parse_record_struct_body()?;
7062 VariantData::Struct(fields, recovered)
7063 // Tuple-style struct definition with optional where-clause.
7064 } else if self.token == token::OpenDelim(token::Paren) {
7065 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
7066 generics.where_clause = self.parse_where_clause()?;
7067 self.expect(&token::Semi)?;
7070 let token_str = self.this_token_descr();
7071 let mut err = self.fatal(&format!(
7072 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
7075 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
7079 Ok((class_name, ItemKind::Struct(vdata, generics), None))
7082 /// Parses `union Foo { ... }`.
7083 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
7084 let class_name = self.parse_ident()?;
7086 let mut generics = self.parse_generics()?;
7088 let vdata = if self.token.is_keyword(keywords::Where) {
7089 generics.where_clause = self.parse_where_clause()?;
7090 let (fields, recovered) = self.parse_record_struct_body()?;
7091 VariantData::Struct(fields, recovered)
7092 } else if self.token == token::OpenDelim(token::Brace) {
7093 let (fields, recovered) = self.parse_record_struct_body()?;
7094 VariantData::Struct(fields, recovered)
7096 let token_str = self.this_token_descr();
7097 let mut err = self.fatal(&format!(
7098 "expected `where` or `{{` after union name, found {}", token_str));
7099 err.span_label(self.span, "expected `where` or `{` after union name");
7103 Ok((class_name, ItemKind::Union(vdata, generics), None))
7106 fn consume_block(&mut self, delim: token::DelimToken) {
7107 let mut brace_depth = 0;
7109 if self.eat(&token::OpenDelim(delim)) {
7111 } else if self.eat(&token::CloseDelim(delim)) {
7112 if brace_depth == 0 {
7118 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
7126 fn parse_record_struct_body(
7128 ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
7129 let mut fields = Vec::new();
7130 let mut recovered = false;
7131 if self.eat(&token::OpenDelim(token::Brace)) {
7132 while self.token != token::CloseDelim(token::Brace) {
7133 let field = self.parse_struct_decl_field().map_err(|e| {
7134 self.recover_stmt();
7139 Ok(field) => fields.push(field),
7145 self.eat(&token::CloseDelim(token::Brace));
7147 let token_str = self.this_token_descr();
7148 let mut err = self.fatal(&format!(
7149 "expected `where`, or `{{` after struct name, found {}", token_str));
7150 err.span_label(self.span, "expected `where`, or `{` after struct name");
7154 Ok((fields, recovered))
7157 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
7158 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
7159 // Unit like structs are handled in parse_item_struct function
7160 let fields = self.parse_unspanned_seq(
7161 &token::OpenDelim(token::Paren),
7162 &token::CloseDelim(token::Paren),
7163 SeqSep::trailing_allowed(token::Comma),
7165 let attrs = p.parse_outer_attributes()?;
7167 let vis = p.parse_visibility(true)?;
7168 let ty = p.parse_ty()?;
7170 span: lo.to(ty.span),
7173 id: ast::DUMMY_NODE_ID,
7182 /// Parses a structure field declaration.
7183 fn parse_single_struct_field(&mut self,
7186 attrs: Vec<Attribute> )
7187 -> PResult<'a, StructField> {
7188 let mut seen_comma: bool = false;
7189 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
7190 if self.token == token::Comma {
7197 token::CloseDelim(token::Brace) => {}
7198 token::DocComment(_) => {
7199 let previous_span = self.prev_span;
7200 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
7201 self.bump(); // consume the doc comment
7202 let comma_after_doc_seen = self.eat(&token::Comma);
7203 // `seen_comma` is always false, because we are inside doc block
7204 // condition is here to make code more readable
7205 if seen_comma == false && comma_after_doc_seen == true {
7208 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
7211 if seen_comma == false {
7212 let sp = self.sess.source_map().next_point(previous_span);
7213 err.span_suggestion(
7215 "missing comma here",
7217 Applicability::MachineApplicable
7224 let sp = self.sess.source_map().next_point(self.prev_span);
7225 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
7226 self.this_token_descr()));
7227 if self.token.is_ident() {
7228 // This is likely another field; emit the diagnostic and keep going
7229 err.span_suggestion(
7231 "try adding a comma",
7233 Applicability::MachineApplicable,
7244 /// Parses an element of a struct declaration.
7245 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
7246 let attrs = self.parse_outer_attributes()?;
7248 let vis = self.parse_visibility(false)?;
7249 self.parse_single_struct_field(lo, vis, attrs)
7252 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
7253 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
7254 /// If the following element can't be a tuple (i.e., it's a function definition), then
7255 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
7256 /// so emit a proper diagnostic.
7257 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
7258 maybe_whole!(self, NtVis, |x| x);
7260 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
7261 if self.is_crate_vis() {
7262 self.bump(); // `crate`
7263 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
7266 if !self.eat_keyword(keywords::Pub) {
7267 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
7268 // keyword to grab a span from for inherited visibility; an empty span at the
7269 // beginning of the current token would seem to be the "Schelling span".
7270 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
7272 let lo = self.prev_span;
7274 if self.check(&token::OpenDelim(token::Paren)) {
7275 // We don't `self.bump()` the `(` yet because this might be a struct definition where
7276 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
7277 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
7278 // by the following tokens.
7279 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
7282 self.bump(); // `crate`
7283 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7285 lo.to(self.prev_span),
7286 VisibilityKind::Crate(CrateSugar::PubCrate),
7289 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
7292 self.bump(); // `in`
7293 let path = self.parse_path(PathStyle::Mod)?; // `path`
7294 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7295 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7297 id: ast::DUMMY_NODE_ID,
7300 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
7301 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
7302 t.is_keyword(keywords::SelfLower))
7304 // `pub(self)` or `pub(super)`
7306 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
7307 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7308 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7310 id: ast::DUMMY_NODE_ID,
7313 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
7314 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
7316 let msg = "incorrect visibility restriction";
7317 let suggestion = r##"some possible visibility restrictions are:
7318 `pub(crate)`: visible only on the current crate
7319 `pub(super)`: visible only in the current module's parent
7320 `pub(in path::to::module)`: visible only on the specified path"##;
7321 let path = self.parse_path(PathStyle::Mod)?;
7322 let sp = self.prev_span;
7323 let help_msg = format!("make this visible only to module `{}` with `in`", path);
7324 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7325 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
7326 err.help(suggestion);
7327 err.span_suggestion(
7328 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
7330 err.emit(); // emit diagnostic, but continue with public visibility
7334 Ok(respan(lo, VisibilityKind::Public))
7337 /// Parses defaultness (i.e., `default` or nothing).
7338 fn parse_defaultness(&mut self) -> Defaultness {
7339 // `pub` is included for better error messages
7340 if self.check_keyword(keywords::Default) &&
7341 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
7342 t.is_keyword(keywords::Const) ||
7343 t.is_keyword(keywords::Fn) ||
7344 t.is_keyword(keywords::Unsafe) ||
7345 t.is_keyword(keywords::Extern) ||
7346 t.is_keyword(keywords::Type) ||
7347 t.is_keyword(keywords::Pub)) {
7348 self.bump(); // `default`
7349 Defaultness::Default
7355 fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
7356 if self.eat(&token::Semi) {
7357 let mut err = self.struct_span_err(self.prev_span, "expected item, found `;`");
7358 err.span_suggestion_short(
7360 "remove this semicolon",
7362 Applicability::MachineApplicable,
7364 if !items.is_empty() {
7365 let previous_item = &items[items.len()-1];
7366 let previous_item_kind_name = match previous_item.node {
7367 // say "braced struct" because tuple-structs and
7368 // braceless-empty-struct declarations do take a semicolon
7369 ItemKind::Struct(..) => Some("braced struct"),
7370 ItemKind::Enum(..) => Some("enum"),
7371 ItemKind::Trait(..) => Some("trait"),
7372 ItemKind::Union(..) => Some("union"),
7375 if let Some(name) = previous_item_kind_name {
7376 err.help(&format!("{} declarations are not followed by a semicolon", name));
7386 /// Given a termination token, parses all of the items in a module.
7387 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
7388 let mut items = vec![];
7389 while let Some(item) = self.parse_item()? {
7391 self.maybe_consume_incorrect_semicolon(&items);
7394 if !self.eat(term) {
7395 let token_str = self.this_token_descr();
7396 if !self.maybe_consume_incorrect_semicolon(&items) {
7397 let mut err = self.fatal(&format!("expected item, found {}", token_str));
7398 err.span_label(self.span, "expected item");
7403 let hi = if self.span.is_dummy() {
7410 inner: inner_lo.to(hi),
7416 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
7417 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
7418 self.expect(&token::Colon)?;
7419 let ty = self.parse_ty()?;
7420 self.expect(&token::Eq)?;
7421 let e = self.parse_expr()?;
7422 self.expect(&token::Semi)?;
7423 let item = match m {
7424 Some(m) => ItemKind::Static(ty, m, e),
7425 None => ItemKind::Const(ty, e),
7427 Ok((id, item, None))
7430 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
7431 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
7432 let (in_cfg, outer_attrs) = {
7433 let mut strip_unconfigured = crate::config::StripUnconfigured {
7435 features: None, // don't perform gated feature checking
7437 let mut outer_attrs = outer_attrs.to_owned();
7438 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
7439 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
7442 let id_span = self.span;
7443 let id = self.parse_ident()?;
7444 if self.eat(&token::Semi) {
7445 if in_cfg && self.recurse_into_file_modules {
7446 // This mod is in an external file. Let's go get it!
7447 let ModulePathSuccess { path, directory_ownership, warn } =
7448 self.submod_path(id, &outer_attrs, id_span)?;
7449 let (module, mut attrs) =
7450 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
7451 // Record that we fetched the mod from an external file
7453 let attr = Attribute {
7454 id: attr::mk_attr_id(),
7455 style: ast::AttrStyle::Outer,
7456 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
7457 tokens: TokenStream::empty(),
7458 is_sugared_doc: false,
7459 span: syntax_pos::DUMMY_SP,
7461 attr::mark_known(&attr);
7464 Ok((id, ItemKind::Mod(module), Some(attrs)))
7466 let placeholder = ast::Mod {
7467 inner: syntax_pos::DUMMY_SP,
7471 Ok((id, ItemKind::Mod(placeholder), None))
7474 let old_directory = self.directory.clone();
7475 self.push_directory(id, &outer_attrs);
7477 self.expect(&token::OpenDelim(token::Brace))?;
7478 let mod_inner_lo = self.span;
7479 let attrs = self.parse_inner_attributes()?;
7480 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
7482 self.directory = old_directory;
7483 Ok((id, ItemKind::Mod(module), Some(attrs)))
7487 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
7488 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
7489 self.directory.path.to_mut().push(&path.as_str());
7490 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
7492 // We have to push on the current module name in the case of relative
7493 // paths in order to ensure that any additional module paths from inline
7494 // `mod x { ... }` come after the relative extension.
7496 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
7497 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
7498 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
7499 if let Some(ident) = relative.take() { // remove the relative offset
7500 self.directory.path.to_mut().push(ident.as_str());
7503 self.directory.path.to_mut().push(&id.as_str());
7507 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
7508 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
7511 // On windows, the base path might have the form
7512 // `\\?\foo\bar` in which case it does not tolerate
7513 // mixed `/` and `\` separators, so canonicalize
7516 let s = s.replace("/", "\\");
7517 Some(dir_path.join(s))
7523 /// Returns a path to a module.
7524 pub fn default_submod_path(
7526 relative: Option<ast::Ident>,
7528 source_map: &SourceMap) -> ModulePath
7530 // If we're in a foo.rs file instead of a mod.rs file,
7531 // we need to look for submodules in
7532 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
7533 // `./<id>.rs` and `./<id>/mod.rs`.
7534 let relative_prefix_string;
7535 let relative_prefix = if let Some(ident) = relative {
7536 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
7537 &relative_prefix_string
7542 let mod_name = id.to_string();
7543 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
7544 let secondary_path_str = format!("{}{}{}mod.rs",
7545 relative_prefix, mod_name, path::MAIN_SEPARATOR);
7546 let default_path = dir_path.join(&default_path_str);
7547 let secondary_path = dir_path.join(&secondary_path_str);
7548 let default_exists = source_map.file_exists(&default_path);
7549 let secondary_exists = source_map.file_exists(&secondary_path);
7551 let result = match (default_exists, secondary_exists) {
7552 (true, false) => Ok(ModulePathSuccess {
7554 directory_ownership: DirectoryOwnership::Owned {
7559 (false, true) => Ok(ModulePathSuccess {
7560 path: secondary_path,
7561 directory_ownership: DirectoryOwnership::Owned {
7566 (false, false) => Err(Error::FileNotFoundForModule {
7567 mod_name: mod_name.clone(),
7568 default_path: default_path_str,
7569 secondary_path: secondary_path_str,
7570 dir_path: dir_path.display().to_string(),
7572 (true, true) => Err(Error::DuplicatePaths {
7573 mod_name: mod_name.clone(),
7574 default_path: default_path_str,
7575 secondary_path: secondary_path_str,
7581 path_exists: default_exists || secondary_exists,
7586 fn submod_path(&mut self,
7588 outer_attrs: &[Attribute],
7590 -> PResult<'a, ModulePathSuccess> {
7591 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
7592 return Ok(ModulePathSuccess {
7593 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
7594 // All `#[path]` files are treated as though they are a `mod.rs` file.
7595 // This means that `mod foo;` declarations inside `#[path]`-included
7596 // files are siblings,
7598 // Note that this will produce weirdness when a file named `foo.rs` is
7599 // `#[path]` included and contains a `mod foo;` declaration.
7600 // If you encounter this, it's your own darn fault :P
7601 Some(_) => DirectoryOwnership::Owned { relative: None },
7602 _ => DirectoryOwnership::UnownedViaMod(true),
7609 let relative = match self.directory.ownership {
7610 DirectoryOwnership::Owned { relative } => relative,
7611 DirectoryOwnership::UnownedViaBlock |
7612 DirectoryOwnership::UnownedViaMod(_) => None,
7614 let paths = Parser::default_submod_path(
7615 id, relative, &self.directory.path, self.sess.source_map());
7617 match self.directory.ownership {
7618 DirectoryOwnership::Owned { .. } => {
7619 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
7621 DirectoryOwnership::UnownedViaBlock => {
7623 "Cannot declare a non-inline module inside a block \
7624 unless it has a path attribute";
7625 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
7626 if paths.path_exists {
7627 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
7629 err.span_note(id_sp, &msg);
7633 DirectoryOwnership::UnownedViaMod(warn) => {
7635 if let Ok(result) = paths.result {
7636 return Ok(ModulePathSuccess { warn: true, ..result });
7639 let mut err = self.diagnostic().struct_span_err(id_sp,
7640 "cannot declare a new module at this location");
7641 if !id_sp.is_dummy() {
7642 let src_path = self.sess.source_map().span_to_filename(id_sp);
7643 if let FileName::Real(src_path) = src_path {
7644 if let Some(stem) = src_path.file_stem() {
7645 let mut dest_path = src_path.clone();
7646 dest_path.set_file_name(stem);
7647 dest_path.push("mod.rs");
7648 err.span_note(id_sp,
7649 &format!("maybe move this module `{}` to its own \
7650 directory via `{}`", src_path.display(),
7651 dest_path.display()));
7655 if paths.path_exists {
7656 err.span_note(id_sp,
7657 &format!("... or maybe `use` the module `{}` instead \
7658 of possibly redeclaring it",
7666 /// Reads a module from a source file.
7667 fn eval_src_mod(&mut self,
7669 directory_ownership: DirectoryOwnership,
7672 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
7673 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
7674 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
7675 let mut err = String::from("circular modules: ");
7676 let len = included_mod_stack.len();
7677 for p in &included_mod_stack[i.. len] {
7678 err.push_str(&p.to_string_lossy());
7679 err.push_str(" -> ");
7681 err.push_str(&path.to_string_lossy());
7682 return Err(self.span_fatal(id_sp, &err[..]));
7684 included_mod_stack.push(path.clone());
7685 drop(included_mod_stack);
7688 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
7689 p0.cfg_mods = self.cfg_mods;
7690 let mod_inner_lo = p0.span;
7691 let mod_attrs = p0.parse_inner_attributes()?;
7692 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
7694 self.sess.included_mod_stack.borrow_mut().pop();
7698 /// Parses a function declaration from a foreign module.
7699 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7700 -> PResult<'a, ForeignItem> {
7701 self.expect_keyword(keywords::Fn)?;
7703 let (ident, mut generics) = self.parse_fn_header()?;
7704 let decl = self.parse_fn_decl(true)?;
7705 generics.where_clause = self.parse_where_clause()?;
7707 self.expect(&token::Semi)?;
7708 Ok(ast::ForeignItem {
7711 node: ForeignItemKind::Fn(decl, generics),
7712 id: ast::DUMMY_NODE_ID,
7718 /// Parses a static item from a foreign module.
7719 /// Assumes that the `static` keyword is already parsed.
7720 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7721 -> PResult<'a, ForeignItem> {
7722 let mutbl = self.parse_mutability();
7723 let ident = self.parse_ident()?;
7724 self.expect(&token::Colon)?;
7725 let ty = self.parse_ty()?;
7727 self.expect(&token::Semi)?;
7731 node: ForeignItemKind::Static(ty, mutbl),
7732 id: ast::DUMMY_NODE_ID,
7738 /// Parses a type from a foreign module.
7739 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7740 -> PResult<'a, ForeignItem> {
7741 self.expect_keyword(keywords::Type)?;
7743 let ident = self.parse_ident()?;
7745 self.expect(&token::Semi)?;
7746 Ok(ast::ForeignItem {
7749 node: ForeignItemKind::Ty,
7750 id: ast::DUMMY_NODE_ID,
7756 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
7757 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
7758 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
7760 let mut ident = if self.token.is_keyword(keywords::SelfLower) {
7761 self.parse_path_segment_ident()
7765 let mut idents = vec![];
7766 let mut replacement = vec![];
7767 let mut fixed_crate_name = false;
7768 // Accept `extern crate name-like-this` for better diagnostics
7769 let dash = token::Token::BinOp(token::BinOpToken::Minus);
7770 if self.token == dash { // Do not include `-` as part of the expected tokens list
7771 while self.eat(&dash) {
7772 fixed_crate_name = true;
7773 replacement.push((self.prev_span, "_".to_string()));
7774 idents.push(self.parse_ident()?);
7777 if fixed_crate_name {
7778 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
7779 let mut fixed_name = format!("{}", ident.name);
7780 for part in idents {
7781 fixed_name.push_str(&format!("_{}", part.name));
7783 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
7785 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
7786 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
7787 err.multipart_suggestion(
7790 Applicability::MachineApplicable,
7797 /// Parses `extern crate` links.
7802 /// extern crate foo;
7803 /// extern crate bar as foo;
7805 fn parse_item_extern_crate(&mut self,
7807 visibility: Visibility,
7808 attrs: Vec<Attribute>)
7809 -> PResult<'a, P<Item>> {
7810 // Accept `extern crate name-like-this` for better diagnostics
7811 let orig_name = self.parse_crate_name_with_dashes()?;
7812 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
7813 (rename, Some(orig_name.name))
7817 self.expect(&token::Semi)?;
7819 let span = lo.to(self.prev_span);
7820 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
7823 /// Parses `extern` for foreign ABIs modules.
7825 /// `extern` is expected to have been
7826 /// consumed before calling this method.
7830 /// ```ignore (only-for-syntax-highlight)
7834 fn parse_item_foreign_mod(&mut self,
7836 opt_abi: Option<Abi>,
7837 visibility: Visibility,
7838 mut attrs: Vec<Attribute>)
7839 -> PResult<'a, P<Item>> {
7840 self.expect(&token::OpenDelim(token::Brace))?;
7842 let abi = opt_abi.unwrap_or(Abi::C);
7844 attrs.extend(self.parse_inner_attributes()?);
7846 let mut foreign_items = vec![];
7847 while !self.eat(&token::CloseDelim(token::Brace)) {
7848 foreign_items.push(self.parse_foreign_item()?);
7851 let prev_span = self.prev_span;
7852 let m = ast::ForeignMod {
7854 items: foreign_items
7856 let invalid = keywords::Invalid.ident();
7857 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
7860 /// Parses `type Foo = Bar;`
7862 /// `existential type Foo: Bar;`
7865 /// without modifying the parser state.
7866 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
7867 // This parses the grammar:
7868 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
7869 if self.check_keyword(keywords::Type) ||
7870 self.check_keyword(keywords::Existential) &&
7871 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
7872 let existential = self.eat_keyword(keywords::Existential);
7873 assert!(self.eat_keyword(keywords::Type));
7874 Some(self.parse_existential_or_alias(existential))
7880 /// Parses a type alias or existential type.
7881 fn parse_existential_or_alias(
7884 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
7885 let ident = self.parse_ident()?;
7886 let mut tps = self.parse_generics()?;
7887 tps.where_clause = self.parse_where_clause()?;
7888 let alias = if existential {
7889 self.expect(&token::Colon)?;
7890 let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
7891 AliasKind::Existential(bounds)
7893 self.expect(&token::Eq)?;
7894 let ty = self.parse_ty()?;
7897 self.expect(&token::Semi)?;
7898 Ok((ident, alias, tps))
7901 /// Parses the part of an enum declaration following the `{`.
7902 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
7903 let mut variants = Vec::new();
7904 let mut all_nullary = true;
7905 let mut any_disr = vec![];
7906 while self.token != token::CloseDelim(token::Brace) {
7907 let variant_attrs = self.parse_outer_attributes()?;
7908 let vlo = self.span;
7911 let mut disr_expr = None;
7913 let ident = self.parse_ident()?;
7914 if self.check(&token::OpenDelim(token::Brace)) {
7915 // Parse a struct variant.
7916 all_nullary = false;
7917 let (fields, recovered) = self.parse_record_struct_body()?;
7918 struct_def = VariantData::Struct(fields, recovered);
7919 } else if self.check(&token::OpenDelim(token::Paren)) {
7920 all_nullary = false;
7921 struct_def = VariantData::Tuple(
7922 self.parse_tuple_struct_body()?,
7925 } else if self.eat(&token::Eq) {
7926 disr_expr = Some(AnonConst {
7927 id: ast::DUMMY_NODE_ID,
7928 value: self.parse_expr()?,
7930 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
7933 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7935 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7938 let vr = ast::Variant_ {
7940 id: ast::DUMMY_NODE_ID,
7941 attrs: variant_attrs,
7945 variants.push(respan(vlo.to(self.prev_span), vr));
7947 if !self.eat(&token::Comma) {
7948 if self.token.is_ident() && !self.token.is_reserved_ident() {
7949 let sp = self.sess.source_map().next_point(self.prev_span);
7950 let mut err = self.struct_span_err(sp, "missing comma");
7951 err.span_suggestion_short(
7955 Applicability::MaybeIncorrect,
7963 self.expect(&token::CloseDelim(token::Brace))?;
7964 if !any_disr.is_empty() && !all_nullary {
7965 let mut err = self.struct_span_err(
7967 "discriminator values can only be used with a field-less enum",
7969 for sp in any_disr {
7970 err.span_label(sp, "only valid in field-less enums");
7975 Ok(ast::EnumDef { variants })
7978 /// Parses an enum declaration.
7979 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7980 let id = self.parse_ident()?;
7981 let mut generics = self.parse_generics()?;
7982 generics.where_clause = self.parse_where_clause()?;
7983 self.expect(&token::OpenDelim(token::Brace))?;
7985 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7986 self.recover_stmt();
7987 self.eat(&token::CloseDelim(token::Brace));
7990 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7993 /// Parses a string as an ABI spec on an extern type or module. Consumes
7994 /// the `extern` keyword, if one is found.
7995 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7997 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
7999 self.expect_no_suffix(sp, "an ABI spec", suf);
8001 match abi::lookup(&s.as_str()) {
8002 Some(abi) => Ok(Some(abi)),
8004 let prev_span = self.prev_span;
8005 let mut err = struct_span_err!(
8006 self.sess.span_diagnostic,
8009 "invalid ABI: found `{}`",
8011 err.span_label(prev_span, "invalid ABI");
8012 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
8023 fn is_static_global(&mut self) -> bool {
8024 if self.check_keyword(keywords::Static) {
8025 // Check if this could be a closure
8026 !self.look_ahead(1, |token| {
8027 if token.is_keyword(keywords::Move) {
8031 token::BinOp(token::Or) | token::OrOr => true,
8042 attrs: Vec<Attribute>,
8043 macros_allowed: bool,
8044 attributes_allowed: bool,
8045 ) -> PResult<'a, Option<P<Item>>> {
8046 let mut unclosed_delims = vec![];
8047 let (ret, tokens) = self.collect_tokens(|this| {
8048 let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
8049 unclosed_delims.append(&mut this.unclosed_delims);
8052 self.unclosed_delims.append(&mut unclosed_delims);
8054 // Once we've parsed an item and recorded the tokens we got while
8055 // parsing we may want to store `tokens` into the item we're about to
8056 // return. Note, though, that we specifically didn't capture tokens
8057 // related to outer attributes. The `tokens` field here may later be
8058 // used with procedural macros to convert this item back into a token
8059 // stream, but during expansion we may be removing attributes as we go
8062 // If we've got inner attributes then the `tokens` we've got above holds
8063 // these inner attributes. If an inner attribute is expanded we won't
8064 // actually remove it from the token stream, so we'll just keep yielding
8065 // it (bad!). To work around this case for now we just avoid recording
8066 // `tokens` if we detect any inner attributes. This should help keep
8067 // expansion correct, but we should fix this bug one day!
8070 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
8071 i.tokens = Some(tokens);
8078 /// Parses one of the items allowed by the flags.
8079 fn parse_item_implementation(
8081 attrs: Vec<Attribute>,
8082 macros_allowed: bool,
8083 attributes_allowed: bool,
8084 ) -> PResult<'a, Option<P<Item>>> {
8085 maybe_whole!(self, NtItem, |item| {
8086 let mut item = item.into_inner();
8087 let mut attrs = attrs;
8088 mem::swap(&mut item.attrs, &mut attrs);
8089 item.attrs.extend(attrs);
8095 let visibility = self.parse_visibility(false)?;
8097 if self.eat_keyword(keywords::Use) {
8099 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
8100 self.expect(&token::Semi)?;
8102 let span = lo.to(self.prev_span);
8103 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
8104 return Ok(Some(item));
8107 if self.eat_keyword(keywords::Extern) {
8108 if self.eat_keyword(keywords::Crate) {
8109 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
8112 let opt_abi = self.parse_opt_abi()?;
8114 if self.eat_keyword(keywords::Fn) {
8115 // EXTERN FUNCTION ITEM
8116 let fn_span = self.prev_span;
8117 let abi = opt_abi.unwrap_or(Abi::C);
8118 let (ident, item_, extra_attrs) =
8119 self.parse_item_fn(Unsafety::Normal,
8120 respan(fn_span, IsAsync::NotAsync),
8121 respan(fn_span, Constness::NotConst),
8123 let prev_span = self.prev_span;
8124 let item = self.mk_item(lo.to(prev_span),
8128 maybe_append(attrs, extra_attrs));
8129 return Ok(Some(item));
8130 } else if self.check(&token::OpenDelim(token::Brace)) {
8131 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
8137 if self.is_static_global() {
8140 let m = if self.eat_keyword(keywords::Mut) {
8143 Mutability::Immutable
8145 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
8146 let prev_span = self.prev_span;
8147 let item = self.mk_item(lo.to(prev_span),
8151 maybe_append(attrs, extra_attrs));
8152 return Ok(Some(item));
8154 if self.eat_keyword(keywords::Const) {
8155 let const_span = self.prev_span;
8156 if self.check_keyword(keywords::Fn)
8157 || (self.check_keyword(keywords::Unsafe)
8158 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
8159 // CONST FUNCTION ITEM
8160 let unsafety = self.parse_unsafety();
8162 let (ident, item_, extra_attrs) =
8163 self.parse_item_fn(unsafety,
8164 respan(const_span, IsAsync::NotAsync),
8165 respan(const_span, Constness::Const),
8167 let prev_span = self.prev_span;
8168 let item = self.mk_item(lo.to(prev_span),
8172 maybe_append(attrs, extra_attrs));
8173 return Ok(Some(item));
8177 if self.eat_keyword(keywords::Mut) {
8178 let prev_span = self.prev_span;
8179 let mut err = self.diagnostic()
8180 .struct_span_err(prev_span, "const globals cannot be mutable");
8181 err.span_label(prev_span, "cannot be mutable");
8182 err.span_suggestion(
8184 "you might want to declare a static instead",
8185 "static".to_owned(),
8186 Applicability::MaybeIncorrect,
8190 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
8191 let prev_span = self.prev_span;
8192 let item = self.mk_item(lo.to(prev_span),
8196 maybe_append(attrs, extra_attrs));
8197 return Ok(Some(item));
8200 // `unsafe async fn` or `async fn`
8202 self.check_keyword(keywords::Unsafe) &&
8203 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
8205 self.check_keyword(keywords::Async) &&
8206 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
8209 // ASYNC FUNCTION ITEM
8210 let unsafety = self.parse_unsafety();
8211 self.expect_keyword(keywords::Async)?;
8212 let async_span = self.prev_span;
8213 self.expect_keyword(keywords::Fn)?;
8214 let fn_span = self.prev_span;
8215 let (ident, item_, extra_attrs) =
8216 self.parse_item_fn(unsafety,
8217 respan(async_span, IsAsync::Async {
8218 closure_id: ast::DUMMY_NODE_ID,
8219 return_impl_trait_id: ast::DUMMY_NODE_ID,
8220 arguments: Vec::new(),
8222 respan(fn_span, Constness::NotConst),
8224 let prev_span = self.prev_span;
8225 let item = self.mk_item(lo.to(prev_span),
8229 maybe_append(attrs, extra_attrs));
8230 if self.span.rust_2015() {
8231 self.diagnostic().struct_span_err_with_code(
8233 "`async fn` is not permitted in the 2015 edition",
8234 DiagnosticId::Error("E0670".into())
8237 return Ok(Some(item));
8239 if self.check_keyword(keywords::Unsafe) &&
8240 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
8241 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
8243 // UNSAFE TRAIT ITEM
8244 self.bump(); // `unsafe`
8245 let is_auto = if self.eat_keyword(keywords::Trait) {
8248 self.expect_keyword(keywords::Auto)?;
8249 self.expect_keyword(keywords::Trait)?;
8252 let (ident, item_, extra_attrs) =
8253 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
8254 let prev_span = self.prev_span;
8255 let item = self.mk_item(lo.to(prev_span),
8259 maybe_append(attrs, extra_attrs));
8260 return Ok(Some(item));
8262 if self.check_keyword(keywords::Impl) ||
8263 self.check_keyword(keywords::Unsafe) &&
8264 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8265 self.check_keyword(keywords::Default) &&
8266 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8267 self.check_keyword(keywords::Default) &&
8268 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
8270 let defaultness = self.parse_defaultness();
8271 let unsafety = self.parse_unsafety();
8272 self.expect_keyword(keywords::Impl)?;
8273 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
8274 let span = lo.to(self.prev_span);
8275 return Ok(Some(self.mk_item(span, ident, item, visibility,
8276 maybe_append(attrs, extra_attrs))));
8278 if self.check_keyword(keywords::Fn) {
8281 let fn_span = self.prev_span;
8282 let (ident, item_, extra_attrs) =
8283 self.parse_item_fn(Unsafety::Normal,
8284 respan(fn_span, IsAsync::NotAsync),
8285 respan(fn_span, Constness::NotConst),
8287 let prev_span = self.prev_span;
8288 let item = self.mk_item(lo.to(prev_span),
8292 maybe_append(attrs, extra_attrs));
8293 return Ok(Some(item));
8295 if self.check_keyword(keywords::Unsafe)
8296 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
8297 // UNSAFE FUNCTION ITEM
8298 self.bump(); // `unsafe`
8299 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
8300 self.check(&token::OpenDelim(token::Brace));
8301 let abi = if self.eat_keyword(keywords::Extern) {
8302 self.parse_opt_abi()?.unwrap_or(Abi::C)
8306 self.expect_keyword(keywords::Fn)?;
8307 let fn_span = self.prev_span;
8308 let (ident, item_, extra_attrs) =
8309 self.parse_item_fn(Unsafety::Unsafe,
8310 respan(fn_span, IsAsync::NotAsync),
8311 respan(fn_span, Constness::NotConst),
8313 let prev_span = self.prev_span;
8314 let item = self.mk_item(lo.to(prev_span),
8318 maybe_append(attrs, extra_attrs));
8319 return Ok(Some(item));
8321 if self.eat_keyword(keywords::Mod) {
8323 let (ident, item_, extra_attrs) =
8324 self.parse_item_mod(&attrs[..])?;
8325 let prev_span = self.prev_span;
8326 let item = self.mk_item(lo.to(prev_span),
8330 maybe_append(attrs, extra_attrs));
8331 return Ok(Some(item));
8333 if let Some(type_) = self.eat_type() {
8334 let (ident, alias, generics) = type_?;
8336 let item_ = match alias {
8337 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
8338 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
8340 let prev_span = self.prev_span;
8341 let item = self.mk_item(lo.to(prev_span),
8346 return Ok(Some(item));
8348 if self.eat_keyword(keywords::Enum) {
8350 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
8351 let prev_span = self.prev_span;
8352 let item = self.mk_item(lo.to(prev_span),
8356 maybe_append(attrs, extra_attrs));
8357 return Ok(Some(item));
8359 if self.check_keyword(keywords::Trait)
8360 || (self.check_keyword(keywords::Auto)
8361 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
8363 let is_auto = if self.eat_keyword(keywords::Trait) {
8366 self.expect_keyword(keywords::Auto)?;
8367 self.expect_keyword(keywords::Trait)?;
8371 let (ident, item_, extra_attrs) =
8372 self.parse_item_trait(is_auto, Unsafety::Normal)?;
8373 let prev_span = self.prev_span;
8374 let item = self.mk_item(lo.to(prev_span),
8378 maybe_append(attrs, extra_attrs));
8379 return Ok(Some(item));
8381 if self.eat_keyword(keywords::Struct) {
8383 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
8384 let prev_span = self.prev_span;
8385 let item = self.mk_item(lo.to(prev_span),
8389 maybe_append(attrs, extra_attrs));
8390 return Ok(Some(item));
8392 if self.is_union_item() {
8395 let (ident, item_, extra_attrs) = self.parse_item_union()?;
8396 let prev_span = self.prev_span;
8397 let item = self.mk_item(lo.to(prev_span),
8401 maybe_append(attrs, extra_attrs));
8402 return Ok(Some(item));
8404 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
8405 return Ok(Some(macro_def));
8408 // Verify whether we have encountered a struct or method definition where the user forgot to
8409 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
8410 if visibility.node.is_pub() &&
8411 self.check_ident() &&
8412 self.look_ahead(1, |t| *t != token::Not)
8414 // Space between `pub` keyword and the identifier
8417 // ^^^ `sp` points here
8418 let sp = self.prev_span.between(self.span);
8419 let full_sp = self.prev_span.to(self.span);
8420 let ident_sp = self.span;
8421 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
8422 // possible public struct definition where `struct` was forgotten
8423 let ident = self.parse_ident().unwrap();
8424 let msg = format!("add `struct` here to parse `{}` as a public struct",
8426 let mut err = self.diagnostic()
8427 .struct_span_err(sp, "missing `struct` for struct definition");
8428 err.span_suggestion_short(
8429 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
8432 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
8433 let ident = self.parse_ident().unwrap();
8435 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
8440 self.consume_block(token::Paren);
8441 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
8442 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
8444 ("fn", kw_name, false)
8445 } else if self.check(&token::OpenDelim(token::Brace)) {
8447 ("fn", kw_name, false)
8448 } else if self.check(&token::Colon) {
8452 ("fn` or `struct", "function or struct", true)
8455 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8456 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8458 self.consume_block(token::Brace);
8459 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
8463 err.span_suggestion_short(
8464 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
8467 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
8468 err.span_suggestion(
8470 "if you meant to call a macro, try",
8471 format!("{}!", snippet),
8472 // this is the `ambiguous` conditional branch
8473 Applicability::MaybeIncorrect
8476 err.help("if you meant to call a macro, remove the `pub` \
8477 and add a trailing `!` after the identifier");
8481 } else if self.look_ahead(1, |t| *t == token::Lt) {
8482 let ident = self.parse_ident().unwrap();
8483 self.eat_to_tokens(&[&token::Gt]);
8485 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
8486 if let Ok(Some(_)) = self.parse_self_arg() {
8487 ("fn", "method", false)
8489 ("fn", "function", false)
8491 } else if self.check(&token::OpenDelim(token::Brace)) {
8492 ("struct", "struct", false)
8494 ("fn` or `struct", "function or struct", true)
8496 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8497 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8499 err.span_suggestion_short(
8501 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
8502 format!(" {} ", kw),
8503 Applicability::MachineApplicable,
8509 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
8512 /// Parses a foreign item.
8513 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
8514 maybe_whole!(self, NtForeignItem, |ni| ni);
8516 let attrs = self.parse_outer_attributes()?;
8518 let visibility = self.parse_visibility(false)?;
8520 // FOREIGN STATIC ITEM
8521 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
8522 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
8523 if self.token.is_keyword(keywords::Const) {
8525 .struct_span_err(self.span, "extern items cannot be `const`")
8528 "try using a static value",
8529 "static".to_owned(),
8530 Applicability::MachineApplicable
8533 self.bump(); // `static` or `const`
8534 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
8536 // FOREIGN FUNCTION ITEM
8537 if self.check_keyword(keywords::Fn) {
8538 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
8540 // FOREIGN TYPE ITEM
8541 if self.check_keyword(keywords::Type) {
8542 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
8545 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
8549 ident: keywords::Invalid.ident(),
8550 span: lo.to(self.prev_span),
8551 id: ast::DUMMY_NODE_ID,
8554 node: ForeignItemKind::Macro(mac),
8559 if !attrs.is_empty() {
8560 self.expected_item_err(&attrs)?;
8568 /// This is the fall-through for parsing items.
8569 fn parse_macro_use_or_failure(
8571 attrs: Vec<Attribute> ,
8572 macros_allowed: bool,
8573 attributes_allowed: bool,
8575 visibility: Visibility
8576 ) -> PResult<'a, Option<P<Item>>> {
8577 if macros_allowed && self.token.is_path_start() &&
8578 !(self.is_async_fn() && self.span.rust_2015()) {
8579 // MACRO INVOCATION ITEM
8581 let prev_span = self.prev_span;
8582 self.complain_if_pub_macro(&visibility.node, prev_span);
8584 let mac_lo = self.span;
8587 let pth = self.parse_path(PathStyle::Mod)?;
8588 self.expect(&token::Not)?;
8590 // a 'special' identifier (like what `macro_rules!` uses)
8591 // is optional. We should eventually unify invoc syntax
8593 let id = if self.token.is_ident() {
8596 keywords::Invalid.ident() // no special identifier
8598 // eat a matched-delimiter token tree:
8599 let (delim, tts) = self.expect_delimited_token_tree()?;
8600 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
8601 self.report_invalid_macro_expansion_item();
8604 let hi = self.prev_span;
8605 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
8606 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
8607 return Ok(Some(item));
8610 // FAILURE TO PARSE ITEM
8611 match visibility.node {
8612 VisibilityKind::Inherited => {}
8614 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
8618 if !attributes_allowed && !attrs.is_empty() {
8619 self.expected_item_err(&attrs)?;
8624 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
8625 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
8626 at_end: &mut bool) -> PResult<'a, Option<Mac>>
8628 if self.token.is_path_start() &&
8629 !(self.is_async_fn() && self.span.rust_2015()) {
8630 let prev_span = self.prev_span;
8632 let pth = self.parse_path(PathStyle::Mod)?;
8634 if pth.segments.len() == 1 {
8635 if !self.eat(&token::Not) {
8636 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
8639 self.expect(&token::Not)?;
8642 if let Some(vis) = vis {
8643 self.complain_if_pub_macro(&vis.node, prev_span);
8648 // eat a matched-delimiter token tree:
8649 let (delim, tts) = self.expect_delimited_token_tree()?;
8650 if delim != MacDelimiter::Brace {
8651 self.expect(&token::Semi)?;
8654 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
8660 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
8661 where F: FnOnce(&mut Self) -> PResult<'a, R>
8663 // Record all tokens we parse when parsing this item.
8664 let mut tokens = Vec::new();
8665 let prev_collecting = match self.token_cursor.frame.last_token {
8666 LastToken::Collecting(ref mut list) => {
8667 Some(mem::replace(list, Vec::new()))
8669 LastToken::Was(ref mut last) => {
8670 tokens.extend(last.take());
8674 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
8675 let prev = self.token_cursor.stack.len();
8677 let last_token = if self.token_cursor.stack.len() == prev {
8678 &mut self.token_cursor.frame.last_token
8680 &mut self.token_cursor.stack[prev].last_token
8683 // Pull out the tokens that we've collected from the call to `f` above.
8684 let mut collected_tokens = match *last_token {
8685 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
8686 LastToken::Was(_) => panic!("our vector went away?"),
8689 // If we're not at EOF our current token wasn't actually consumed by
8690 // `f`, but it'll still be in our list that we pulled out. In that case
8692 let extra_token = if self.token != token::Eof {
8693 collected_tokens.pop()
8698 // If we were previously collecting tokens, then this was a recursive
8699 // call. In that case we need to record all the tokens we collected in
8700 // our parent list as well. To do that we push a clone of our stream
8701 // onto the previous list.
8702 match prev_collecting {
8704 list.extend(collected_tokens.iter().cloned());
8705 list.extend(extra_token);
8706 *last_token = LastToken::Collecting(list);
8709 *last_token = LastToken::Was(extra_token);
8713 Ok((ret?, TokenStream::new(collected_tokens)))
8716 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
8717 let attrs = self.parse_outer_attributes()?;
8718 self.parse_item_(attrs, true, false)
8722 fn is_import_coupler(&mut self) -> bool {
8723 self.check(&token::ModSep) &&
8724 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
8725 *t == token::BinOp(token::Star))
8728 /// Parses a `UseTree`.
8731 /// USE_TREE = [`::`] `*` |
8732 /// [`::`] `{` USE_TREE_LIST `}` |
8734 /// PATH `::` `{` USE_TREE_LIST `}` |
8735 /// PATH [`as` IDENT]
8737 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
8740 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
8741 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
8742 self.check(&token::BinOp(token::Star)) ||
8743 self.is_import_coupler() {
8744 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
8745 let mod_sep_ctxt = self.span.ctxt();
8746 if self.eat(&token::ModSep) {
8747 prefix.segments.push(
8748 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
8752 if self.eat(&token::BinOp(token::Star)) {
8755 UseTreeKind::Nested(self.parse_use_tree_list()?)
8758 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
8759 prefix = self.parse_path(PathStyle::Mod)?;
8761 if self.eat(&token::ModSep) {
8762 if self.eat(&token::BinOp(token::Star)) {
8765 UseTreeKind::Nested(self.parse_use_tree_list()?)
8768 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
8772 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
8775 /// Parses a `UseTreeKind::Nested(list)`.
8778 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
8780 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
8781 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
8782 &token::CloseDelim(token::Brace),
8783 SeqSep::trailing_allowed(token::Comma), |this| {
8784 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
8788 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
8789 if self.eat_keyword(keywords::As) {
8790 self.parse_ident_or_underscore().map(Some)
8796 /// Parses a source module as a crate. This is the main entry point for the parser.
8797 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
8799 let krate = Ok(ast::Crate {
8800 attrs: self.parse_inner_attributes()?,
8801 module: self.parse_mod_items(&token::Eof, lo)?,
8802 span: lo.to(self.span),
8807 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
8808 let ret = match self.token {
8809 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
8810 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
8817 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
8818 match self.parse_optional_str() {
8819 Some((s, style, suf)) => {
8820 let sp = self.prev_span;
8821 self.expect_no_suffix(sp, "a string literal", suf);
8825 let msg = "expected string literal";
8826 let mut err = self.fatal(msg);
8827 err.span_label(self.span, msg);
8833 fn report_invalid_macro_expansion_item(&self) {
8834 self.struct_span_err(
8836 "macros that expand to items must be delimited with braces or followed by a semicolon",
8837 ).multipart_suggestion(
8838 "change the delimiters to curly braces",
8840 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
8841 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
8843 Applicability::MaybeIncorrect,
8845 self.sess.source_map.next_point(self.prev_span),
8848 Applicability::MaybeIncorrect,
8852 /// Recover from `pub` keyword in places where it seems _reasonable_ but isn't valid.
8853 fn eat_bad_pub(&mut self) {
8854 if self.token.is_keyword(keywords::Pub) {
8855 match self.parse_visibility(false) {
8857 let mut err = self.diagnostic()
8858 .struct_span_err(vis.span, "unnecessary visibility qualifier");
8859 err.span_label(vis.span, "`pub` not permitted here");
8862 Err(mut err) => err.emit(),
8867 /// When lowering a `async fn` to the HIR, we need to move all of the arguments of the function
8868 /// into the generated closure so that they are dropped when the future is polled and not when
8871 /// The arguments of the function are replaced in HIR lowering with the arguments created by
8872 /// this function and the statements created here are inserted at the top of the closure body.
8873 fn construct_async_arguments(&mut self, asyncness: &mut Spanned<IsAsync>, decl: &FnDecl) {
8874 if let IsAsync::Async { ref mut arguments, .. } = asyncness.node {
8875 for (index, input) in decl.inputs.iter().enumerate() {
8876 let id = ast::DUMMY_NODE_ID;
8877 let span = input.pat.span;
8879 // Construct a name for our temporary argument.
8880 let name = format!("__arg{}", index);
8881 let ident = Ident::from_str(&name);
8883 // Construct an argument representing `__argN: <ty>` to replace the argument of the
8886 ty: input.ty.clone(),
8890 node: PatKind::Ident(
8891 BindingMode::ByValue(Mutability::Immutable), ident, None,
8895 source: ArgSource::AsyncFn(input.pat.clone()),
8898 // Construct a `let <pat> = __argN;` statement to insert at the top of the
8900 let local = P(Local {
8901 pat: input.pat.clone(),
8902 // We explicitly do not specify the type for this statement. When the user's
8903 // argument type is `impl Trait` then this would require the
8904 // `impl_trait_in_bindings` feature to also be present for that same type to
8905 // be valid in this binding. At the time of writing (13 Mar 19),
8906 // `impl_trait_in_bindings` is not stable.
8910 node: ExprKind::Path(None, ast::Path {
8912 segments: vec![PathSegment { ident, id, args: None }],
8915 attrs: ThinVec::new(),
8919 attrs: ThinVec::new(),
8920 source: LocalSource::AsyncFn,
8922 let stmt = Stmt { id, node: StmtKind::Local(local), span, };
8924 arguments.push(AsyncArgument { ident, arg, stmt });
8930 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
8931 for unmatched in unclosed_delims.iter() {
8932 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
8933 "incorrect close delimiter: `{}`",
8934 pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
8936 err.span_label(unmatched.found_span, "incorrect close delimiter");
8937 if let Some(sp) = unmatched.candidate_span {
8938 err.span_label(sp, "close delimiter possibly meant for this");
8940 if let Some(sp) = unmatched.unclosed_span {
8941 err.span_label(sp, "un-closed delimiter");
8945 unclosed_delims.clear();