1 use crate::ast::{AngleBracketedArgs, ParenthesizedArgs, AttrStyle, BareFnTy};
2 use crate::ast::{GenericBound, TraitBoundModifier};
3 use crate::ast::Unsafety;
4 use crate::ast::{Mod, AnonConst, Arg, Arm, Guard, Attribute, BindingMode, TraitItemKind};
6 use crate::ast::{BlockCheckMode, CaptureBy, Movability};
7 use crate::ast::{Constness, Crate};
8 use crate::ast::Defaultness;
9 use crate::ast::EnumDef;
10 use crate::ast::{Expr, ExprKind, RangeLimits};
11 use crate::ast::{Field, FnDecl, FnHeader};
12 use crate::ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
13 use crate::ast::{GenericParam, GenericParamKind};
14 use crate::ast::GenericArg;
15 use crate::ast::{Ident, ImplItem, IsAsync, IsAuto, Item, ItemKind};
16 use crate::ast::{Label, Lifetime, Lit, LitKind};
17 use crate::ast::Local;
18 use crate::ast::MacStmtStyle;
19 use crate::ast::{Mac, Mac_, MacDelimiter};
20 use crate::ast::{MutTy, Mutability};
21 use crate::ast::{Pat, PatKind, PathSegment};
22 use crate::ast::{PolyTraitRef, QSelf};
23 use crate::ast::{Stmt, StmtKind};
24 use crate::ast::{VariantData, StructField};
25 use crate::ast::StrStyle;
26 use crate::ast::SelfKind;
27 use crate::ast::{TraitItem, TraitRef, TraitObjectSyntax};
28 use crate::ast::{Ty, TyKind, TypeBinding, GenericBounds};
29 use crate::ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
30 use crate::ast::{UseTree, UseTreeKind};
31 use crate::ast::{BinOpKind, UnOp};
32 use crate::ast::{RangeEnd, RangeSyntax};
33 use crate::{ast, attr};
34 use crate::ext::base::DummyResult;
35 use crate::source_map::{self, SourceMap, Spanned, respan};
36 use crate::parse::{self, SeqSep, classify, token};
37 use crate::parse::lexer::{TokenAndSpan, UnmatchedBrace};
38 use crate::parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
39 use crate::parse::token::DelimToken;
40 use crate::parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
41 use crate::util::parser::{AssocOp, Fixity};
42 use crate::print::pprust;
44 use crate::parse::PResult;
46 use crate::tokenstream::{self, DelimSpan, TokenTree, TokenStream, TreeAndJoint};
47 use crate::symbol::{Symbol, keywords};
49 use errors::{Applicability, DiagnosticBuilder, DiagnosticId};
50 use rustc_target::spec::abi::{self, Abi};
51 use syntax_pos::{Span, MultiSpan, BytePos, FileName};
52 use log::{debug, trace};
57 use std::path::{self, Path, PathBuf};
61 /// Whether the type alias or associated type is a concrete type or an existential type
63 /// Just a new name for the same type
65 /// Only trait impls of the type will be usable, not the actual type itself
66 Existential(GenericBounds),
70 struct Restrictions: u8 {
71 const STMT_EXPR = 1 << 0;
72 const NO_STRUCT_LITERAL = 1 << 1;
76 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
78 /// Specifies how to parse a path.
79 #[derive(Copy, Clone, PartialEq)]
81 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
82 /// with something else. For example, in expressions `segment < ....` can be interpreted
83 /// as a comparison and `segment ( ....` can be interpreted as a function call.
84 /// In all such contexts the non-path interpretation is preferred by default for practical
85 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
86 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
88 /// In other contexts, notably in types, no ambiguity exists and paths can be written
89 /// without the disambiguator, e.g., `x<y>` - unambiguously a path.
90 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
92 /// A path with generic arguments disallowed, e.g., `foo::bar::Baz`, used in imports,
93 /// visibilities or attributes.
94 /// Technically, this variant is unnecessary and e.g., `Expr` can be used instead
95 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
96 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
97 /// tokens when something goes wrong.
101 #[derive(Clone, Copy, PartialEq, Debug)]
108 #[derive(Clone, Copy, PartialEq, Debug)]
114 /// Possibly accepts an `token::Interpolated` expression (a pre-parsed expression
115 /// dropped into the token stream, which happens while parsing the result of
116 /// macro expansion). Placement of these is not as complex as I feared it would
117 /// be. The important thing is to make sure that lookahead doesn't balk at
118 /// `token::Interpolated` tokens.
119 macro_rules! maybe_whole_expr {
121 if let token::Interpolated(nt) = $p.token.clone() {
123 token::NtExpr(ref e) | token::NtLiteral(ref e) => {
125 return Ok((*e).clone());
127 token::NtPath(ref path) => {
130 let kind = ExprKind::Path(None, (*path).clone());
131 return Ok($p.mk_expr(span, kind, ThinVec::new()));
133 token::NtBlock(ref block) => {
136 let kind = ExprKind::Block((*block).clone(), None);
137 return Ok($p.mk_expr(span, kind, ThinVec::new()));
145 /// As maybe_whole_expr, but for things other than expressions
146 macro_rules! maybe_whole {
147 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
148 if let token::Interpolated(nt) = $p.token.clone() {
149 if let token::$constructor($x) = nt.0.clone() {
157 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
158 if let Some(ref mut rhs) = rhs {
164 #[derive(Debug, Clone, Copy, PartialEq)]
175 trait RecoverQPath: Sized {
176 const PATH_STYLE: PathStyle = PathStyle::Expr;
177 fn to_ty(&self) -> Option<P<Ty>>;
178 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self;
179 fn to_string(&self) -> String;
182 impl RecoverQPath for Ty {
183 const PATH_STYLE: PathStyle = PathStyle::Type;
184 fn to_ty(&self) -> Option<P<Ty>> {
185 Some(P(self.clone()))
187 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
188 Self { span: path.span, node: TyKind::Path(qself, path), id: self.id }
190 fn to_string(&self) -> String {
191 pprust::ty_to_string(self)
195 impl RecoverQPath for Pat {
196 fn to_ty(&self) -> Option<P<Ty>> {
199 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
200 Self { span: path.span, node: PatKind::Path(qself, path), id: self.id }
202 fn to_string(&self) -> String {
203 pprust::pat_to_string(self)
207 impl RecoverQPath for Expr {
208 fn to_ty(&self) -> Option<P<Ty>> {
211 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
212 Self { span: path.span, node: ExprKind::Path(qself, path),
213 id: self.id, attrs: self.attrs.clone() }
215 fn to_string(&self) -> String {
216 pprust::expr_to_string(self)
220 /* ident is handled by common.rs */
223 pub struct Parser<'a> {
224 pub sess: &'a ParseSess,
225 /// the current token:
226 pub token: token::Token,
227 /// the span of the current token:
229 /// the span of the previous token:
230 meta_var_span: Option<Span>,
232 /// the previous token kind
233 prev_token_kind: PrevTokenKind,
234 restrictions: Restrictions,
235 /// Used to determine the path to externally loaded source files
236 crate directory: Directory<'a>,
237 /// Whether to parse sub-modules in other files.
238 pub recurse_into_file_modules: bool,
239 /// Name of the root module this parser originated from. If `None`, then the
240 /// name is not known. This does not change while the parser is descending
241 /// into modules, and sub-parsers have new values for this name.
242 pub root_module_name: Option<String>,
243 crate expected_tokens: Vec<TokenType>,
244 token_cursor: TokenCursor,
245 desugar_doc_comments: bool,
246 /// Whether we should configure out of line modules as we parse.
248 /// This field is used to keep track of how many left angle brackets we have seen. This is
249 /// required in order to detect extra leading left angle brackets (`<` characters) and error
252 /// See the comments in the `parse_path_segment` function for more details.
253 crate unmatched_angle_bracket_count: u32,
254 crate max_angle_bracket_count: u32,
255 /// List of all unclosed delimiters found by the lexer. If an entry is used for error recovery
256 /// it gets removed from here. Every entry left at the end gets emitted as an independent
258 crate unclosed_delims: Vec<UnmatchedBrace>,
264 frame: TokenCursorFrame,
265 stack: Vec<TokenCursorFrame>,
269 struct TokenCursorFrame {
270 delim: token::DelimToken,
273 tree_cursor: tokenstream::Cursor,
275 last_token: LastToken,
278 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
279 /// by the parser, and then that's transitively used to record the tokens that
280 /// each parse AST item is created with.
282 /// Right now this has two states, either collecting tokens or not collecting
283 /// tokens. If we're collecting tokens we just save everything off into a local
284 /// `Vec`. This should eventually though likely save tokens from the original
285 /// token stream and just use slicing of token streams to avoid creation of a
286 /// whole new vector.
288 /// The second state is where we're passively not recording tokens, but the last
289 /// token is still tracked for when we want to start recording tokens. This
290 /// "last token" means that when we start recording tokens we'll want to ensure
291 /// that this, the first token, is included in the output.
293 /// You can find some more example usage of this in the `collect_tokens` method
297 Collecting(Vec<TreeAndJoint>),
298 Was(Option<TreeAndJoint>),
301 impl TokenCursorFrame {
302 fn new(sp: DelimSpan, delim: DelimToken, tts: &TokenStream) -> Self {
306 open_delim: delim == token::NoDelim,
307 tree_cursor: tts.clone().into_trees(),
308 close_delim: delim == token::NoDelim,
309 last_token: LastToken::Was(None),
315 fn next(&mut self) -> TokenAndSpan {
317 let tree = if !self.frame.open_delim {
318 self.frame.open_delim = true;
319 TokenTree::open_tt(self.frame.span.open, self.frame.delim)
320 } else if let Some(tree) = self.frame.tree_cursor.next() {
322 } else if !self.frame.close_delim {
323 self.frame.close_delim = true;
324 TokenTree::close_tt(self.frame.span.close, self.frame.delim)
325 } else if let Some(frame) = self.stack.pop() {
329 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
332 match self.frame.last_token {
333 LastToken::Collecting(ref mut v) => v.push(tree.clone().into()),
334 LastToken::Was(ref mut t) => *t = Some(tree.clone().into()),
338 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
339 TokenTree::Delimited(sp, delim, tts) => {
340 let frame = TokenCursorFrame::new(sp, delim, &tts);
341 self.stack.push(mem::replace(&mut self.frame, frame));
347 fn next_desugared(&mut self) -> TokenAndSpan {
348 let (sp, name) = match self.next() {
349 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
353 let stripped = strip_doc_comment_decoration(&name.as_str());
355 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
356 // required to wrap the text.
357 let mut num_of_hashes = 0;
359 for ch in stripped.chars() {
362 '#' if count > 0 => count + 1,
365 num_of_hashes = cmp::max(num_of_hashes, count);
368 let delim_span = DelimSpan::from_single(sp);
369 let body = TokenTree::Delimited(
372 [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
373 TokenTree::Token(sp, token::Eq),
374 TokenTree::Token(sp, token::Literal(
375 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))
377 .iter().cloned().collect::<TokenStream>().into(),
380 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(
383 &if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
384 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
385 .iter().cloned().collect::<TokenStream>().into()
387 [TokenTree::Token(sp, token::Pound), body]
388 .iter().cloned().collect::<TokenStream>().into()
396 #[derive(Clone, PartialEq)]
397 crate enum TokenType {
399 Keyword(keywords::Keyword),
409 fn to_string(&self) -> String {
411 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
412 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
413 TokenType::Operator => "an operator".to_string(),
414 TokenType::Lifetime => "lifetime".to_string(),
415 TokenType::Ident => "identifier".to_string(),
416 TokenType::Path => "path".to_string(),
417 TokenType::Type => "type".to_string(),
418 TokenType::Const => "const".to_string(),
423 /// Returns `true` if `IDENT t` can start a type -- `IDENT::a::b`, `IDENT<u8, u8>`,
424 /// `IDENT<<u8 as Trait>::AssocTy>`.
426 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
427 /// that `IDENT` is not the ident of a fn trait.
428 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
429 t == &token::ModSep || t == &token::Lt ||
430 t == &token::BinOp(token::Shl)
433 /// Information about the path to a module.
434 pub struct ModulePath {
437 pub result: Result<ModulePathSuccess, Error>,
440 pub struct ModulePathSuccess {
442 pub directory_ownership: DirectoryOwnership,
447 FileNotFoundForModule {
449 default_path: String,
450 secondary_path: String,
455 default_path: String,
456 secondary_path: String,
459 InclusiveRangeWithNoEnd,
463 fn span_err<S: Into<MultiSpan>>(self,
465 handler: &errors::Handler) -> DiagnosticBuilder<'_> {
467 Error::FileNotFoundForModule { ref mod_name,
471 let mut err = struct_span_err!(handler, sp, E0583,
472 "file not found for module `{}`", mod_name);
473 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
479 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
480 let mut err = struct_span_err!(handler, sp, E0584,
481 "file for module `{}` found at both {} and {}",
485 err.help("delete or rename one of them to remove the ambiguity");
488 Error::UselessDocComment => {
489 let mut err = struct_span_err!(handler, sp, E0585,
490 "found a documentation comment that doesn't document anything");
491 err.help("doc comments must come before what they document, maybe a comment was \
492 intended with `//`?");
495 Error::InclusiveRangeWithNoEnd => {
496 let mut err = struct_span_err!(handler, sp, E0586,
497 "inclusive range with no end");
498 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
508 AttributesParsed(ThinVec<Attribute>),
509 AlreadyParsed(P<Expr>),
512 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
513 fn from(o: Option<ThinVec<Attribute>>) -> Self {
514 if let Some(attrs) = o {
515 LhsExpr::AttributesParsed(attrs)
517 LhsExpr::NotYetParsed
522 impl From<P<Expr>> for LhsExpr {
523 fn from(expr: P<Expr>) -> Self {
524 LhsExpr::AlreadyParsed(expr)
528 /// Creates a placeholder argument.
529 fn dummy_arg(span: Span) -> Arg {
530 let ident = Ident::new(keywords::Invalid.name(), span);
532 id: ast::DUMMY_NODE_ID,
533 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
539 id: ast::DUMMY_NODE_ID
541 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
544 #[derive(Copy, Clone, Debug)]
545 enum TokenExpectType {
550 impl<'a> Parser<'a> {
551 pub fn new(sess: &'a ParseSess,
553 directory: Option<Directory<'a>>,
554 recurse_into_file_modules: bool,
555 desugar_doc_comments: bool)
557 let mut parser = Parser {
559 token: token::Whitespace,
560 span: syntax_pos::DUMMY_SP,
561 prev_span: syntax_pos::DUMMY_SP,
563 prev_token_kind: PrevTokenKind::Other,
564 restrictions: Restrictions::empty(),
565 recurse_into_file_modules,
566 directory: Directory {
567 path: Cow::from(PathBuf::new()),
568 ownership: DirectoryOwnership::Owned { relative: None }
570 root_module_name: None,
571 expected_tokens: Vec::new(),
572 token_cursor: TokenCursor {
573 frame: TokenCursorFrame::new(
580 desugar_doc_comments,
582 unmatched_angle_bracket_count: 0,
583 max_angle_bracket_count: 0,
584 unclosed_delims: Vec::new(),
587 let tok = parser.next_tok();
588 parser.token = tok.tok;
589 parser.span = tok.sp;
591 if let Some(directory) = directory {
592 parser.directory = directory;
593 } else if !parser.span.is_dummy() {
594 if let FileName::Real(mut path) = sess.source_map().span_to_unmapped_path(parser.span) {
596 parser.directory.path = Cow::from(path);
600 parser.process_potential_macro_variable();
604 fn next_tok(&mut self) -> TokenAndSpan {
605 let mut next = if self.desugar_doc_comments {
606 self.token_cursor.next_desugared()
608 self.token_cursor.next()
610 if next.sp.is_dummy() {
611 // Tweak the location for better diagnostics, but keep syntactic context intact.
612 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
617 /// Converts the current token to a string using `self`'s reader.
618 pub fn this_token_to_string(&self) -> String {
619 pprust::token_to_string(&self.token)
622 fn token_descr(&self) -> Option<&'static str> {
623 Some(match &self.token {
624 t if t.is_special_ident() => "reserved identifier",
625 t if t.is_used_keyword() => "keyword",
626 t if t.is_unused_keyword() => "reserved keyword",
627 token::DocComment(..) => "doc comment",
632 fn this_token_descr(&self) -> String {
633 if let Some(prefix) = self.token_descr() {
634 format!("{} `{}`", prefix, self.this_token_to_string())
636 format!("`{}`", self.this_token_to_string())
640 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
641 let token_str = pprust::token_to_string(t);
642 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
645 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
646 match self.expect_one_of(&[], &[]) {
648 Ok(_) => unreachable!(),
652 /// Expects and consumes the token `t`. Signals an error if the next token is not `t`.
653 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, bool /* recovered */> {
654 if self.expected_tokens.is_empty() {
655 if self.token == *t {
659 let token_str = pprust::token_to_string(t);
660 let this_token_str = self.this_token_descr();
661 let mut err = self.fatal(&format!("expected `{}`, found {}",
665 let sp = if self.token == token::Token::Eof {
666 // EOF, don't want to point at the following char, but rather the last token
669 self.sess.source_map().next_point(self.prev_span)
671 let label_exp = format!("expected `{}`", token_str);
672 match self.recover_closing_delimiter(&[t.clone()], err) {
675 return Ok(recovered);
678 let cm = self.sess.source_map();
679 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
680 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
681 // When the spans are in the same line, it means that the only content
682 // between them is whitespace, point only at the found token.
683 err.span_label(self.span, label_exp);
686 err.span_label(sp, label_exp);
687 err.span_label(self.span, "unexpected token");
693 self.expect_one_of(slice::from_ref(t), &[])
697 fn recover_closing_delimiter(
699 tokens: &[token::Token],
700 mut err: DiagnosticBuilder<'a>,
701 ) -> PResult<'a, bool> {
703 // we want to use the last closing delim that would apply
704 for (i, unmatched) in self.unclosed_delims.iter().enumerate().rev() {
705 if tokens.contains(&token::CloseDelim(unmatched.expected_delim))
706 && Some(self.span) > unmatched.unclosed_span
713 // Recover and assume that the detected unclosed delimiter was meant for
714 // this location. Emit the diagnostic and act as if the delimiter was
715 // present for the parser's sake.
717 // Don't attempt to recover from this unclosed delimiter more than once.
718 let unmatched = self.unclosed_delims.remove(pos);
719 let delim = TokenType::Token(token::CloseDelim(unmatched.expected_delim));
721 // We want to suggest the inclusion of the closing delimiter where it makes
722 // the most sense, which is immediately after the last token:
727 // | help: `)` may belong here (FIXME: #58270)
729 // unclosed delimiter
730 if let Some(sp) = unmatched.unclosed_span {
731 err.span_label(sp, "unclosed delimiter");
733 err.span_suggestion_short(
734 self.sess.source_map().next_point(self.prev_span),
735 &format!("{} may belong here", delim.to_string()),
737 Applicability::MaybeIncorrect,
740 self.expected_tokens.clear(); // reduce errors
747 /// Expect next token to be edible or inedible token. If edible,
748 /// then consume it; if inedible, then return without consuming
749 /// anything. Signal a fatal error if next token is unexpected.
750 pub fn expect_one_of(
752 edible: &[token::Token],
753 inedible: &[token::Token],
754 ) -> PResult<'a, bool /* recovered */> {
755 fn tokens_to_string(tokens: &[TokenType]) -> String {
756 let mut i = tokens.iter();
757 // This might be a sign we need a connect method on Iterator.
759 .map_or(String::new(), |t| t.to_string());
760 i.enumerate().fold(b, |mut b, (i, a)| {
761 if tokens.len() > 2 && i == tokens.len() - 2 {
763 } else if tokens.len() == 2 && i == tokens.len() - 2 {
768 b.push_str(&a.to_string());
772 if edible.contains(&self.token) {
775 } else if inedible.contains(&self.token) {
776 // leave it in the input
779 let mut expected = edible.iter()
780 .map(|x| TokenType::Token(x.clone()))
781 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
782 .chain(self.expected_tokens.iter().cloned())
783 .collect::<Vec<_>>();
784 expected.sort_by_cached_key(|x| x.to_string());
786 let expect = tokens_to_string(&expected[..]);
787 let actual = self.this_token_to_string();
788 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
789 let short_expect = if expected.len() > 6 {
790 format!("{} possible tokens", expected.len())
794 (format!("expected one of {}, found `{}`", expect, actual),
795 (self.sess.source_map().next_point(self.prev_span),
796 format!("expected one of {} here", short_expect)))
797 } else if expected.is_empty() {
798 (format!("unexpected token: `{}`", actual),
799 (self.prev_span, "unexpected token after this".to_string()))
801 (format!("expected {}, found `{}`", expect, actual),
802 (self.sess.source_map().next_point(self.prev_span),
803 format!("expected {} here", expect)))
805 let mut err = self.fatal(&msg_exp);
806 if self.token.is_ident_named("and") {
807 err.span_suggestion_short(
809 "use `&&` instead of `and` for the boolean operator",
811 Applicability::MaybeIncorrect,
814 if self.token.is_ident_named("or") {
815 err.span_suggestion_short(
817 "use `||` instead of `or` for the boolean operator",
819 Applicability::MaybeIncorrect,
822 let sp = if self.token == token::Token::Eof {
823 // This is EOF, don't want to point at the following char, but rather the last token
828 match self.recover_closing_delimiter(&expected.iter().filter_map(|tt| match tt {
829 TokenType::Token(t) => Some(t.clone()),
831 }).collect::<Vec<_>>(), err) {
834 return Ok(recovered);
838 let cm = self.sess.source_map();
839 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
840 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
841 // When the spans are in the same line, it means that the only content between
842 // them is whitespace, point at the found token in that case:
844 // X | () => { syntax error };
845 // | ^^^^^ expected one of 8 possible tokens here
847 // instead of having:
849 // X | () => { syntax error };
850 // | -^^^^^ unexpected token
852 // | expected one of 8 possible tokens here
853 err.span_label(self.span, label_exp);
855 _ if self.prev_span == syntax_pos::DUMMY_SP => {
856 // Account for macro context where the previous span might not be
857 // available to avoid incorrect output (#54841).
858 err.span_label(self.span, "unexpected token");
861 err.span_label(sp, label_exp);
862 err.span_label(self.span, "unexpected token");
869 /// Returns the span of expr, if it was not interpolated or the span of the interpolated token.
870 fn interpolated_or_expr_span(&self,
871 expr: PResult<'a, P<Expr>>)
872 -> PResult<'a, (Span, P<Expr>)> {
874 if self.prev_token_kind == PrevTokenKind::Interpolated {
882 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
883 let mut err = self.struct_span_err(self.span,
884 &format!("expected identifier, found {}",
885 self.this_token_descr()));
886 if let token::Ident(ident, false) = &self.token {
887 if ident.is_reserved() && !ident.is_path_segment_keyword() &&
888 ident.name != keywords::Underscore.name()
892 "you can escape reserved keywords to use them as identifiers",
893 format!("r#{}", ident),
894 Applicability::MaybeIncorrect,
898 if let Some(token_descr) = self.token_descr() {
899 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
901 err.span_label(self.span, "expected identifier");
902 if self.token == token::Comma && self.look_ahead(1, |t| t.is_ident()) {
907 Applicability::MachineApplicable,
914 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
915 self.parse_ident_common(true)
918 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
920 token::Ident(ident, _) => {
921 if self.token.is_reserved_ident() {
922 let mut err = self.expected_ident_found();
929 let span = self.span;
931 Ok(Ident::new(ident.name, span))
934 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
935 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
937 self.expected_ident_found()
943 /// Checks if the next token is `tok`, and returns `true` if so.
945 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
947 crate fn check(&mut self, tok: &token::Token) -> bool {
948 let is_present = self.token == *tok;
949 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
953 /// Consumes a token 'tok' if it exists. Returns whether the given token was present.
954 pub fn eat(&mut self, tok: &token::Token) -> bool {
955 let is_present = self.check(tok);
956 if is_present { self.bump() }
960 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
961 self.expected_tokens.push(TokenType::Keyword(kw));
962 self.token.is_keyword(kw)
965 /// If the next token is the given keyword, eats it and returns
966 /// `true`. Otherwise, returns `false`.
967 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
968 if self.check_keyword(kw) {
976 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
977 if self.token.is_keyword(kw) {
985 /// If the given word is not a keyword, signals an error.
986 /// If the next token is not the given word, signals an error.
987 /// Otherwise, eats it.
988 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
989 if !self.eat_keyword(kw) {
996 fn check_ident(&mut self) -> bool {
997 if self.token.is_ident() {
1000 self.expected_tokens.push(TokenType::Ident);
1005 fn check_path(&mut self) -> bool {
1006 if self.token.is_path_start() {
1009 self.expected_tokens.push(TokenType::Path);
1014 fn check_type(&mut self) -> bool {
1015 if self.token.can_begin_type() {
1018 self.expected_tokens.push(TokenType::Type);
1023 fn check_const_arg(&mut self) -> bool {
1024 if self.token.can_begin_const_arg() {
1027 self.expected_tokens.push(TokenType::Const);
1032 /// Expects and consumes a `+`. if `+=` is seen, replaces it with a `=`
1033 /// and continues. If a `+` is not seen, returns `false`.
1035 /// This is used when token-splitting `+=` into `+`.
1036 /// See issue #47856 for an example of when this may occur.
1037 fn eat_plus(&mut self) -> bool {
1038 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1040 token::BinOp(token::Plus) => {
1044 token::BinOpEq(token::Plus) => {
1045 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1046 self.bump_with(token::Eq, span);
1054 /// Checks to see if the next token is either `+` or `+=`.
1055 /// Otherwise returns `false`.
1056 fn check_plus(&mut self) -> bool {
1057 if self.token.is_like_plus() {
1061 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
1066 /// Expects and consumes an `&`. If `&&` is seen, replaces it with a single
1067 /// `&` and continues. If an `&` is not seen, signals an error.
1068 fn expect_and(&mut self) -> PResult<'a, ()> {
1069 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
1071 token::BinOp(token::And) => {
1076 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1077 Ok(self.bump_with(token::BinOp(token::And), span))
1079 _ => self.unexpected()
1083 /// Expects and consumes an `|`. If `||` is seen, replaces it with a single
1084 /// `|` and continues. If an `|` is not seen, signals an error.
1085 fn expect_or(&mut self) -> PResult<'a, ()> {
1086 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
1088 token::BinOp(token::Or) => {
1093 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1094 Ok(self.bump_with(token::BinOp(token::Or), span))
1096 _ => self.unexpected()
1100 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
1102 None => {/* everything ok */}
1104 let text = suf.as_str();
1105 if text.is_empty() {
1106 self.span_bug(sp, "found empty literal suffix in Some")
1108 let msg = format!("{} with a suffix is invalid", kind);
1109 self.struct_span_err(sp, &msg)
1110 .span_label(sp, msg)
1116 /// Attempts to consume a `<`. If `<<` is seen, replaces it with a single
1117 /// `<` and continue. If `<-` is seen, replaces it with a single `<`
1118 /// and continue. If a `<` is not seen, returns false.
1120 /// This is meant to be used when parsing generics on a path to get the
1122 fn eat_lt(&mut self) -> bool {
1123 self.expected_tokens.push(TokenType::Token(token::Lt));
1124 let ate = match self.token {
1129 token::BinOp(token::Shl) => {
1130 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1131 self.bump_with(token::Lt, span);
1135 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1136 self.bump_with(token::BinOp(token::Minus), span);
1143 // See doc comment for `unmatched_angle_bracket_count`.
1144 self.unmatched_angle_bracket_count += 1;
1145 self.max_angle_bracket_count += 1;
1146 debug!("eat_lt: (increment) count={:?}", self.unmatched_angle_bracket_count);
1152 fn expect_lt(&mut self) -> PResult<'a, ()> {
1160 /// Expects and consumes a single `>` token. if a `>>` is seen, replaces it
1161 /// with a single `>` and continues. If a `>` is not seen, signals an error.
1162 fn expect_gt(&mut self) -> PResult<'a, ()> {
1163 self.expected_tokens.push(TokenType::Token(token::Gt));
1164 let ate = match self.token {
1169 token::BinOp(token::Shr) => {
1170 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1171 Some(self.bump_with(token::Gt, span))
1173 token::BinOpEq(token::Shr) => {
1174 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1175 Some(self.bump_with(token::Ge, span))
1178 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1179 Some(self.bump_with(token::Eq, span))
1186 // See doc comment for `unmatched_angle_bracket_count`.
1187 self.unmatched_angle_bracket_count -= 1;
1188 debug!("expect_gt: (decrement) count={:?}", self.unmatched_angle_bracket_count);
1192 None => self.unexpected(),
1196 /// Eats and discards tokens until one of `kets` is encountered. Respects token trees,
1197 /// passes through any errors encountered. Used for error recovery.
1198 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1199 let handler = self.diagnostic();
1201 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1203 TokenExpectType::Expect,
1204 |p| Ok(p.parse_token_tree())) {
1205 handler.cancel(err);
1209 /// Parses a sequence, including the closing delimiter. The function
1210 /// `f` must consume tokens until reaching the next separator or
1211 /// closing bracket.
1212 pub fn parse_seq_to_end<T, F>(&mut self,
1216 -> PResult<'a, Vec<T>> where
1217 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1219 let (val, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1226 /// Parses a sequence, not including the closing delimiter. The function
1227 /// `f` must consume tokens until reaching the next separator or
1228 /// closing bracket.
1229 pub fn parse_seq_to_before_end<T, F>(
1234 ) -> PResult<'a, (Vec<T>, bool)>
1235 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1237 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1240 fn parse_seq_to_before_tokens<T, F>(
1242 kets: &[&token::Token],
1244 expect: TokenExpectType,
1246 ) -> PResult<'a, (Vec<T>, bool /* recovered */)>
1247 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1249 let mut first = true;
1250 let mut recovered = false;
1252 while !kets.iter().any(|k| {
1254 TokenExpectType::Expect => self.check(k),
1255 TokenExpectType::NoExpect => self.token == **k,
1259 token::CloseDelim(..) | token::Eof => break,
1262 if let Some(ref t) = sep.sep {
1266 match self.expect(t) {
1273 // Attempt to keep parsing if it was a similar separator
1274 if let Some(ref tokens) = t.similar_tokens() {
1275 if tokens.contains(&self.token) {
1280 // Attempt to keep parsing if it was an omitted separator
1295 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1297 TokenExpectType::Expect => self.check(k),
1298 TokenExpectType::NoExpect => self.token == **k,
1311 /// Parses a sequence, including the closing delimiter. The function
1312 /// `f` must consume tokens until reaching the next separator or
1313 /// closing bracket.
1314 fn parse_unspanned_seq<T, F>(
1320 ) -> PResult<'a, Vec<T>> where
1321 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1324 let (result, recovered) = self.parse_seq_to_before_end(ket, sep, f)?;
1331 /// Advance the parser by one token
1332 pub fn bump(&mut self) {
1333 if self.prev_token_kind == PrevTokenKind::Eof {
1334 // Bumping after EOF is a bad sign, usually an infinite loop.
1335 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1338 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1340 // Record last token kind for possible error recovery.
1341 self.prev_token_kind = match self.token {
1342 token::DocComment(..) => PrevTokenKind::DocComment,
1343 token::Comma => PrevTokenKind::Comma,
1344 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1345 token::Interpolated(..) => PrevTokenKind::Interpolated,
1346 token::Eof => PrevTokenKind::Eof,
1347 token::Ident(..) => PrevTokenKind::Ident,
1348 _ => PrevTokenKind::Other,
1351 let next = self.next_tok();
1352 self.span = next.sp;
1353 self.token = next.tok;
1354 self.expected_tokens.clear();
1355 // check after each token
1356 self.process_potential_macro_variable();
1359 /// Advance the parser using provided token as a next one. Use this when
1360 /// consuming a part of a token. For example a single `<` from `<<`.
1361 fn bump_with(&mut self, next: token::Token, span: Span) {
1362 self.prev_span = self.span.with_hi(span.lo());
1363 // It would be incorrect to record the kind of the current token, but
1364 // fortunately for tokens currently using `bump_with`, the
1365 // prev_token_kind will be of no use anyway.
1366 self.prev_token_kind = PrevTokenKind::Other;
1369 self.expected_tokens.clear();
1372 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1373 F: FnOnce(&token::Token) -> R,
1376 return f(&self.token)
1379 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1380 Some(tree) => match tree {
1381 TokenTree::Token(_, tok) => tok,
1382 TokenTree::Delimited(_, delim, _) => token::OpenDelim(delim),
1384 None => token::CloseDelim(self.token_cursor.frame.delim),
1388 fn look_ahead_span(&self, dist: usize) -> Span {
1393 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1394 Some(TokenTree::Token(span, _)) => span,
1395 Some(TokenTree::Delimited(span, ..)) => span.entire(),
1396 None => self.look_ahead_span(dist - 1),
1399 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1400 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1402 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1403 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1405 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1406 err.span_err(sp, self.diagnostic())
1408 fn bug(&self, m: &str) -> ! {
1409 self.sess.span_diagnostic.span_bug(self.span, m)
1411 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1412 self.sess.span_diagnostic.span_err(sp, m)
1414 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1415 self.sess.span_diagnostic.struct_span_err(sp, m)
1417 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1418 self.sess.span_diagnostic.span_bug(sp, m)
1421 fn cancel(&self, err: &mut DiagnosticBuilder<'_>) {
1422 self.sess.span_diagnostic.cancel(err)
1425 crate fn diagnostic(&self) -> &'a errors::Handler {
1426 &self.sess.span_diagnostic
1429 /// Is the current token one of the keywords that signals a bare function type?
1430 fn token_is_bare_fn_keyword(&mut self) -> bool {
1431 self.check_keyword(keywords::Fn) ||
1432 self.check_keyword(keywords::Unsafe) ||
1433 self.check_keyword(keywords::Extern)
1436 /// Parses a `TyKind::BareFn` type.
1437 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>) -> PResult<'a, TyKind> {
1440 [unsafe] [extern "ABI"] fn (S) -> T
1450 let unsafety = self.parse_unsafety();
1451 let abi = if self.eat_keyword(keywords::Extern) {
1452 self.parse_opt_abi()?.unwrap_or(Abi::C)
1457 self.expect_keyword(keywords::Fn)?;
1458 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1459 let ret_ty = self.parse_ret_ty(false)?;
1460 let decl = P(FnDecl {
1465 Ok(TyKind::BareFn(P(BareFnTy {
1473 /// Parses asyncness: `async` or nothing.
1474 fn parse_asyncness(&mut self) -> IsAsync {
1475 if self.eat_keyword(keywords::Async) {
1477 closure_id: ast::DUMMY_NODE_ID,
1478 return_impl_trait_id: ast::DUMMY_NODE_ID,
1485 /// Parses unsafety: `unsafe` or nothing.
1486 fn parse_unsafety(&mut self) -> Unsafety {
1487 if self.eat_keyword(keywords::Unsafe) {
1494 /// Parses the items in a trait declaration.
1495 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1496 maybe_whole!(self, NtTraitItem, |x| x);
1497 let attrs = self.parse_outer_attributes()?;
1498 let (mut item, tokens) = self.collect_tokens(|this| {
1499 this.parse_trait_item_(at_end, attrs)
1501 // See `parse_item` for why this clause is here.
1502 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1503 item.tokens = Some(tokens);
1508 fn parse_trait_item_(&mut self,
1510 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1513 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1514 self.parse_trait_item_assoc_ty()?
1515 } else if self.is_const_item() {
1516 self.expect_keyword(keywords::Const)?;
1517 let ident = self.parse_ident()?;
1518 self.expect(&token::Colon)?;
1519 let ty = self.parse_ty()?;
1520 let default = if self.eat(&token::Eq) {
1521 let expr = self.parse_expr()?;
1522 self.expect(&token::Semi)?;
1525 self.expect(&token::Semi)?;
1528 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1529 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1530 // trait item macro.
1531 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1533 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
1535 let ident = self.parse_ident()?;
1536 let mut generics = self.parse_generics()?;
1538 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>| {
1539 // This is somewhat dubious; We don't want to allow
1540 // argument names to be left off if there is a
1543 // We don't allow argument names to be left off in edition 2018.
1544 p.parse_arg_general(p.span.rust_2018(), true)
1546 generics.where_clause = self.parse_where_clause()?;
1548 let sig = ast::MethodSig {
1558 let body = match self.token {
1562 debug!("parse_trait_methods(): parsing required method");
1565 token::OpenDelim(token::Brace) => {
1566 debug!("parse_trait_methods(): parsing provided method");
1568 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1569 attrs.extend(inner_attrs.iter().cloned());
1572 token::Interpolated(ref nt) => {
1574 token::NtBlock(..) => {
1576 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1577 attrs.extend(inner_attrs.iter().cloned());
1581 let token_str = self.this_token_descr();
1582 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1584 err.span_label(self.span, "expected `;` or `{`");
1590 let token_str = self.this_token_descr();
1591 let mut err = self.fatal(&format!("expected `;` or `{{`, found {}",
1593 err.span_label(self.span, "expected `;` or `{`");
1597 (ident, ast::TraitItemKind::Method(sig, body), generics)
1601 id: ast::DUMMY_NODE_ID,
1606 span: lo.to(self.prev_span),
1611 /// Parses an optional return type `[ -> TY ]` in a function declaration.
1612 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1613 if self.eat(&token::RArrow) {
1614 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1616 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1621 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1622 self.parse_ty_common(true, true)
1625 /// Parses a type in restricted contexts where `+` is not permitted.
1627 /// Example 1: `&'a TYPE`
1628 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1629 /// Example 2: `value1 as TYPE + value2`
1630 /// `+` is prohibited to avoid interactions with expression grammar.
1631 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1632 self.parse_ty_common(false, true)
1635 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1636 -> PResult<'a, P<Ty>> {
1637 maybe_whole!(self, NtTy, |x| x);
1640 let mut impl_dyn_multi = false;
1641 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1642 // `(TYPE)` is a parenthesized type.
1643 // `(TYPE,)` is a tuple with a single field of type TYPE.
1644 let mut ts = vec![];
1645 let mut last_comma = false;
1646 while self.token != token::CloseDelim(token::Paren) {
1647 ts.push(self.parse_ty()?);
1648 if self.eat(&token::Comma) {
1655 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1656 self.expect(&token::CloseDelim(token::Paren))?;
1658 if ts.len() == 1 && !last_comma {
1659 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1660 let maybe_bounds = allow_plus && self.token.is_like_plus();
1662 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1663 TyKind::Path(None, ref path) if maybe_bounds => {
1664 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1666 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1667 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1668 let path = match bounds[0] {
1669 GenericBound::Trait(ref pt, ..) => pt.trait_ref.path.clone(),
1670 GenericBound::Outlives(..) => self.bug("unexpected lifetime bound"),
1672 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1675 _ => TyKind::Paren(P(ty))
1680 } else if self.eat(&token::Not) {
1683 } else if self.eat(&token::BinOp(token::Star)) {
1685 TyKind::Ptr(self.parse_ptr()?)
1686 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1688 let t = self.parse_ty()?;
1689 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1690 let t = match self.maybe_parse_fixed_length_of_vec()? {
1691 None => TyKind::Slice(t),
1692 Some(length) => TyKind::Array(t, AnonConst {
1693 id: ast::DUMMY_NODE_ID,
1697 self.expect(&token::CloseDelim(token::Bracket))?;
1699 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1702 self.parse_borrowed_pointee()?
1703 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1705 // In order to not be ambiguous, the type must be surrounded by parens.
1706 self.expect(&token::OpenDelim(token::Paren))?;
1708 id: ast::DUMMY_NODE_ID,
1709 value: self.parse_expr()?,
1711 self.expect(&token::CloseDelim(token::Paren))?;
1713 } else if self.eat_keyword(keywords::Underscore) {
1714 // A type to be inferred `_`
1716 } else if self.token_is_bare_fn_keyword() {
1717 // Function pointer type
1718 self.parse_ty_bare_fn(Vec::new())?
1719 } else if self.check_keyword(keywords::For) {
1720 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1721 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1722 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1724 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1725 if self.token_is_bare_fn_keyword() {
1726 self.parse_ty_bare_fn(lifetime_defs)?
1728 let path = self.parse_path(PathStyle::Type)?;
1729 let parse_plus = allow_plus && self.check_plus();
1730 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1732 } else if self.eat_keyword(keywords::Impl) {
1733 // Always parse bounds greedily for better error recovery.
1734 let bounds = self.parse_generic_bounds()?;
1735 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1736 TyKind::ImplTrait(ast::DUMMY_NODE_ID, bounds)
1737 } else if self.check_keyword(keywords::Dyn) &&
1738 (self.span.rust_2018() ||
1739 self.look_ahead(1, |t| t.can_begin_bound() &&
1740 !can_continue_type_after_non_fn_ident(t))) {
1741 self.bump(); // `dyn`
1742 // Always parse bounds greedily for better error recovery.
1743 let bounds = self.parse_generic_bounds()?;
1744 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1745 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1746 } else if self.check(&token::Question) ||
1747 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1748 // Bound list (trait object type)
1749 TyKind::TraitObject(self.parse_generic_bounds_common(allow_plus)?,
1750 TraitObjectSyntax::None)
1751 } else if self.eat_lt() {
1753 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1754 TyKind::Path(Some(qself), path)
1755 } else if self.token.is_path_start() {
1757 let path = self.parse_path(PathStyle::Type)?;
1758 if self.eat(&token::Not) {
1759 // Macro invocation in type position
1760 let (delim, tts) = self.expect_delimited_token_tree()?;
1761 let node = Mac_ { path, tts, delim };
1762 TyKind::Mac(respan(lo.to(self.prev_span), node))
1764 // Just a type path or bound list (trait object type) starting with a trait.
1766 // `Trait1 + Trait2 + 'a`
1767 if allow_plus && self.check_plus() {
1768 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1770 TyKind::Path(None, path)
1774 let msg = format!("expected type, found {}", self.this_token_descr());
1775 return Err(self.fatal(&msg));
1778 let span = lo.to(self.prev_span);
1779 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1781 // Try to recover from use of `+` with incorrect priority.
1782 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1783 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1784 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1789 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1790 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1791 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1792 let mut bounds = vec![GenericBound::Trait(poly_trait_ref, TraitBoundModifier::None)];
1794 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1795 bounds.append(&mut self.parse_generic_bounds()?);
1797 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1800 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1801 if !allow_plus && impl_dyn_multi {
1802 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1803 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1806 "use parentheses to disambiguate",
1808 Applicability::MachineApplicable
1813 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1814 // Do not add `+` to expected tokens.
1815 if !allow_plus || !self.token.is_like_plus() {
1820 let bounds = self.parse_generic_bounds()?;
1821 let sum_span = ty.span.to(self.prev_span);
1823 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1824 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1827 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1828 let sum_with_parens = pprust::to_string(|s| {
1829 use crate::print::pprust::PrintState;
1832 s.print_opt_lifetime(lifetime)?;
1833 s.print_mutability(mut_ty.mutbl)?;
1835 s.print_type(&mut_ty.ty)?;
1836 s.print_type_bounds(" +", &bounds)?;
1839 err.span_suggestion(
1841 "try adding parentheses",
1843 Applicability::MachineApplicable
1846 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1847 err.span_label(sum_span, "perhaps you forgot parentheses?");
1850 err.span_label(sum_span, "expected a path");
1857 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1858 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1860 // Do not add `::` to expected tokens.
1861 if !allow_recovery || self.token != token::ModSep {
1864 let ty = match base.to_ty() {
1866 None => return Ok(base),
1869 self.bump(); // `::`
1870 let mut segments = Vec::new();
1871 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1873 let span = ty.span.to(self.prev_span);
1874 let path_span = span.to(span); // use an empty path since `position` == 0
1875 let recovered = base.to_recovered(
1876 Some(QSelf { ty, path_span, position: 0 }),
1877 ast::Path { segments, span },
1881 .struct_span_err(span, "missing angle brackets in associated item path")
1882 .span_suggestion( // this is a best-effort recovery
1883 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1889 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1890 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1891 let mutbl = self.parse_mutability();
1892 let ty = self.parse_ty_no_plus()?;
1893 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1896 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1897 let mutbl = if self.eat_keyword(keywords::Mut) {
1899 } else if self.eat_keyword(keywords::Const) {
1900 Mutability::Immutable
1902 let span = self.prev_span;
1903 let msg = "expected mut or const in raw pointer type";
1904 self.struct_span_err(span, msg)
1905 .span_label(span, msg)
1906 .help("use `*mut T` or `*const T` as appropriate")
1908 Mutability::Immutable
1910 let t = self.parse_ty_no_plus()?;
1911 Ok(MutTy { ty: t, mutbl: mutbl })
1914 fn is_named_argument(&mut self) -> bool {
1915 let offset = match self.token {
1916 token::Interpolated(ref nt) => match nt.0 {
1917 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1920 token::BinOp(token::And) | token::AndAnd => 1,
1921 _ if self.token.is_keyword(keywords::Mut) => 1,
1925 self.look_ahead(offset, |t| t.is_ident()) &&
1926 self.look_ahead(offset + 1, |t| t == &token::Colon)
1929 /// Skips unexpected attributes and doc comments in this position and emits an appropriate
1931 fn eat_incorrect_doc_comment(&mut self, applied_to: &str) {
1932 if let token::DocComment(_) = self.token {
1933 let mut err = self.diagnostic().struct_span_err(
1935 &format!("documentation comments cannot be applied to {}", applied_to),
1937 err.span_label(self.span, "doc comments are not allowed here");
1940 } else if self.token == token::Pound && self.look_ahead(1, |t| {
1941 *t == token::OpenDelim(token::Bracket)
1944 // Skip every token until next possible arg.
1945 while self.token != token::CloseDelim(token::Bracket) {
1948 let sp = lo.to(self.span);
1950 let mut err = self.diagnostic().struct_span_err(
1952 &format!("attributes cannot be applied to {}", applied_to),
1954 err.span_label(sp, "attributes are not allowed here");
1959 /// This version of parse arg doesn't necessarily require identifier names.
1960 fn parse_arg_general(&mut self, require_name: bool, is_trait_item: bool) -> PResult<'a, Arg> {
1961 maybe_whole!(self, NtArg, |x| x);
1963 if let Ok(Some(_)) = self.parse_self_arg() {
1964 let mut err = self.struct_span_err(self.prev_span,
1965 "unexpected `self` argument in function");
1966 err.span_label(self.prev_span,
1967 "`self` is only valid as the first argument of an associated function");
1971 let (pat, ty) = if require_name || self.is_named_argument() {
1972 debug!("parse_arg_general parse_pat (require_name:{})",
1974 self.eat_incorrect_doc_comment("method arguments");
1975 let pat = self.parse_pat(Some("argument name"))?;
1977 if let Err(mut err) = self.expect(&token::Colon) {
1978 // If we find a pattern followed by an identifier, it could be an (incorrect)
1979 // C-style parameter declaration.
1980 if self.check_ident() && self.look_ahead(1, |t| {
1981 *t == token::Comma || *t == token::CloseDelim(token::Paren)
1983 let ident = self.parse_ident().unwrap();
1984 let span = pat.span.with_hi(ident.span.hi());
1986 err.span_suggestion(
1988 "declare the type after the parameter binding",
1989 String::from("<identifier>: <type>"),
1990 Applicability::HasPlaceholders,
1992 } else if require_name && is_trait_item {
1993 if let PatKind::Ident(_, ident, _) = pat.node {
1994 err.span_suggestion(
1996 "explicitly ignore parameter",
1997 format!("_: {}", ident),
1998 Applicability::MachineApplicable,
2002 err.note("anonymous parameters are removed in the 2018 edition (see RFC 1685)");
2008 self.eat_incorrect_doc_comment("a method argument's type");
2009 (pat, self.parse_ty()?)
2011 debug!("parse_arg_general ident_to_pat");
2012 let parser_snapshot_before_ty = self.clone();
2013 self.eat_incorrect_doc_comment("a method argument's type");
2014 let mut ty = self.parse_ty();
2015 if ty.is_ok() && self.token != token::Comma &&
2016 self.token != token::CloseDelim(token::Paren) {
2017 // This wasn't actually a type, but a pattern looking like a type,
2018 // so we are going to rollback and re-parse for recovery.
2019 ty = self.unexpected();
2023 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
2025 id: ast::DUMMY_NODE_ID,
2026 node: PatKind::Ident(
2027 BindingMode::ByValue(Mutability::Immutable), ident, None),
2033 // Recover from attempting to parse the argument as a type without pattern.
2035 mem::replace(self, parser_snapshot_before_ty);
2036 let pat = self.parse_pat(Some("argument name"))?;
2037 self.expect(&token::Colon)?;
2038 let ty = self.parse_ty()?;
2040 let mut err = self.diagnostic().struct_span_err_with_code(
2042 "patterns aren't allowed in methods without bodies",
2043 DiagnosticId::Error("E0642".into()),
2045 err.span_suggestion_short(
2047 "give this argument a name or use an underscore to ignore it",
2049 Applicability::MachineApplicable,
2053 // Pretend the pattern is `_`, to avoid duplicate errors from AST validation.
2055 node: PatKind::Wild,
2057 id: ast::DUMMY_NODE_ID
2064 Ok(Arg { ty, pat, id: ast::DUMMY_NODE_ID })
2067 /// Parses a single function argument.
2068 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
2069 self.parse_arg_general(true, false)
2072 /// Parses an argument in a lambda header (e.g., `|arg, arg|`).
2073 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
2074 let pat = self.parse_pat(Some("argument name"))?;
2075 let t = if self.eat(&token::Colon) {
2079 id: ast::DUMMY_NODE_ID,
2080 node: TyKind::Infer,
2081 span: self.prev_span,
2087 id: ast::DUMMY_NODE_ID
2091 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
2092 if self.eat(&token::Semi) {
2093 Ok(Some(self.parse_expr()?))
2099 /// Matches `token_lit = LIT_INTEGER | ...`.
2100 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
2101 let out = match self.token {
2102 token::Interpolated(ref nt) => match nt.0 {
2103 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
2104 ExprKind::Lit(ref lit) => { lit.node.clone() }
2105 _ => { return self.unexpected_last(&self.token); }
2107 _ => { return self.unexpected_last(&self.token); }
2109 token::Literal(lit, suf) => {
2110 let diag = Some((self.span, &self.sess.span_diagnostic));
2111 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
2115 self.expect_no_suffix(sp, lit.literal_name(), suf)
2120 token::Dot if self.look_ahead(1, |t| match t {
2121 token::Literal(parse::token::Lit::Integer(_) , _) => true,
2123 }) => { // recover from `let x = .4;`
2126 if let token::Literal(
2127 parse::token::Lit::Integer(val),
2130 let suffix = suffix.and_then(|s| {
2131 let s = s.as_str().get();
2132 if ["f32", "f64"].contains(&s) {
2139 let sp = lo.to(self.prev_span);
2140 let mut err = self.diagnostic()
2141 .struct_span_err(sp, "float literals must have an integer part");
2142 err.span_suggestion(
2144 "must have an integer part",
2145 format!("0.{}{}", val, suffix),
2146 Applicability::MachineApplicable,
2149 return Ok(match suffix {
2150 "f32" => ast::LitKind::Float(val, ast::FloatTy::F32),
2151 "f64" => ast::LitKind::Float(val, ast::FloatTy::F64),
2152 _ => ast::LitKind::FloatUnsuffixed(val),
2158 _ => { return self.unexpected_last(&self.token); }
2165 /// Matches `lit = true | false | token_lit`.
2166 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
2168 let lit = if self.eat_keyword(keywords::True) {
2170 } else if self.eat_keyword(keywords::False) {
2171 LitKind::Bool(false)
2173 let lit = self.parse_lit_token()?;
2176 Ok(source_map::Spanned { node: lit, span: lo.to(self.prev_span) })
2179 /// Matches `'-' lit | lit` (cf. `ast_validation::AstValidator::check_expr_within_pat`).
2180 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
2181 maybe_whole_expr!(self);
2183 let minus_lo = self.span;
2184 let minus_present = self.eat(&token::BinOp(token::Minus));
2186 let literal = self.parse_lit()?;
2187 let hi = self.prev_span;
2188 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
2191 let minus_hi = self.prev_span;
2192 let unary = self.mk_unary(UnOp::Neg, expr);
2193 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
2199 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
2201 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
2202 let span = self.span;
2204 Ok(Ident::new(ident.name, span))
2206 _ => self.parse_ident(),
2210 fn parse_ident_or_underscore(&mut self) -> PResult<'a, ast::Ident> {
2212 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
2213 let span = self.span;
2215 Ok(Ident::new(ident.name, span))
2217 _ => self.parse_ident(),
2221 /// Parses a qualified path.
2222 /// Assumes that the leading `<` has been parsed already.
2224 /// `qualified_path = <type [as trait_ref]>::path`
2229 /// `<T as U>::F::a<S>` (without disambiguator)
2230 /// `<T as U>::F::a::<S>` (with disambiguator)
2231 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
2232 let lo = self.prev_span;
2233 let ty = self.parse_ty()?;
2235 // `path` will contain the prefix of the path up to the `>`,
2236 // if any (e.g., `U` in the `<T as U>::*` examples
2237 // above). `path_span` has the span of that path, or an empty
2238 // span in the case of something like `<T>::Bar`.
2239 let (mut path, path_span);
2240 if self.eat_keyword(keywords::As) {
2241 let path_lo = self.span;
2242 path = self.parse_path(PathStyle::Type)?;
2243 path_span = path_lo.to(self.prev_span);
2245 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
2246 path_span = self.span.to(self.span);
2249 // See doc comment for `unmatched_angle_bracket_count`.
2250 self.expect(&token::Gt)?;
2251 self.unmatched_angle_bracket_count -= 1;
2252 debug!("parse_qpath: (decrement) count={:?}", self.unmatched_angle_bracket_count);
2254 self.expect(&token::ModSep)?;
2256 let qself = QSelf { ty, path_span, position: path.segments.len() };
2257 self.parse_path_segments(&mut path.segments, style, true)?;
2259 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
2262 /// Parses simple paths.
2264 /// `path = [::] segment+`
2265 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
2268 /// `a::b::C<D>` (without disambiguator)
2269 /// `a::b::C::<D>` (with disambiguator)
2270 /// `Fn(Args)` (without disambiguator)
2271 /// `Fn::(Args)` (with disambiguator)
2272 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2273 self.parse_path_common(style, true)
2276 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
2277 -> PResult<'a, ast::Path> {
2278 maybe_whole!(self, NtPath, |path| {
2279 if style == PathStyle::Mod &&
2280 path.segments.iter().any(|segment| segment.args.is_some()) {
2281 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
2286 let lo = self.meta_var_span.unwrap_or(self.span);
2287 let mut segments = Vec::new();
2288 let mod_sep_ctxt = self.span.ctxt();
2289 if self.eat(&token::ModSep) {
2290 segments.push(PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt)));
2292 self.parse_path_segments(&mut segments, style, enable_warning)?;
2294 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
2297 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for
2298 /// backwards-compatibility. This is used when parsing derive macro paths in `#[derive]`
2300 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
2301 let meta_ident = match self.token {
2302 token::Interpolated(ref nt) => match nt.0 {
2303 token::NtMeta(ref meta) => match meta.node {
2304 ast::MetaItemKind::Word => Some(meta.ident.clone()),
2311 if let Some(path) = meta_ident {
2315 self.parse_path(style)
2318 fn parse_path_segments(&mut self,
2319 segments: &mut Vec<PathSegment>,
2321 enable_warning: bool)
2322 -> PResult<'a, ()> {
2324 let segment = self.parse_path_segment(style, enable_warning)?;
2325 if style == PathStyle::Expr {
2326 // In order to check for trailing angle brackets, we must have finished
2327 // recursing (`parse_path_segment` can indirectly call this function),
2328 // that is, the next token must be the highlighted part of the below example:
2330 // `Foo::<Bar as Baz<T>>::Qux`
2333 // As opposed to the below highlight (if we had only finished the first
2336 // `Foo::<Bar as Baz<T>>::Qux`
2339 // `PathStyle::Expr` is only provided at the root invocation and never in
2340 // `parse_path_segment` to recurse and therefore can be checked to maintain
2342 self.check_trailing_angle_brackets(&segment, token::ModSep);
2344 segments.push(segment);
2346 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2352 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2353 -> PResult<'a, PathSegment> {
2354 let ident = self.parse_path_segment_ident()?;
2356 let is_args_start = |token: &token::Token| match *token {
2357 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2360 let check_args_start = |this: &mut Self| {
2361 this.expected_tokens.extend_from_slice(
2362 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2364 is_args_start(&this.token)
2367 Ok(if style == PathStyle::Type && check_args_start(self) ||
2368 style != PathStyle::Mod && self.check(&token::ModSep)
2369 && self.look_ahead(1, |t| is_args_start(t)) {
2370 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2371 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2372 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2373 .span_label(self.prev_span, "try removing `::`").emit();
2377 // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
2378 // it isn't, then we reset the unmatched angle bracket count as we're about to start
2379 // parsing a new path.
2380 if style == PathStyle::Expr {
2381 self.unmatched_angle_bracket_count = 0;
2382 self.max_angle_bracket_count = 0;
2385 let args = if self.eat_lt() {
2387 let (args, bindings) =
2388 self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
2390 let span = lo.to(self.prev_span);
2391 AngleBracketedArgs { args, bindings, span }.into()
2395 let (inputs, recovered) = self.parse_seq_to_before_tokens(
2396 &[&token::CloseDelim(token::Paren)],
2397 SeqSep::trailing_allowed(token::Comma),
2398 TokenExpectType::Expect,
2403 let span = lo.to(self.prev_span);
2404 let output = if self.eat(&token::RArrow) {
2405 Some(self.parse_ty_common(false, false)?)
2409 ParenthesizedArgs { inputs, output, span }.into()
2412 PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2414 // Generic arguments are not found.
2415 PathSegment::from_ident(ident)
2419 crate fn check_lifetime(&mut self) -> bool {
2420 self.expected_tokens.push(TokenType::Lifetime);
2421 self.token.is_lifetime()
2424 /// Parses a single lifetime `'a` or panics.
2425 crate fn expect_lifetime(&mut self) -> Lifetime {
2426 if let Some(ident) = self.token.lifetime() {
2427 let span = self.span;
2429 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2431 self.span_bug(self.span, "not a lifetime")
2435 fn eat_label(&mut self) -> Option<Label> {
2436 if let Some(ident) = self.token.lifetime() {
2437 let span = self.span;
2439 Some(Label { ident: Ident::new(ident.name, span) })
2445 /// Parses mutability (`mut` or nothing).
2446 fn parse_mutability(&mut self) -> Mutability {
2447 if self.eat_keyword(keywords::Mut) {
2450 Mutability::Immutable
2454 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2455 if let token::Literal(token::Integer(name), None) = self.token {
2457 Ok(Ident::new(name, self.prev_span))
2459 self.parse_ident_common(false)
2463 /// Parse ident (COLON expr)?
2464 fn parse_field(&mut self) -> PResult<'a, Field> {
2465 let attrs = self.parse_outer_attributes()?;
2468 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2469 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
2470 t == &token::Colon || t == &token::Eq
2472 let fieldname = self.parse_field_name()?;
2474 // Check for an equals token. This means the source incorrectly attempts to
2475 // initialize a field with an eq rather than a colon.
2476 if self.token == token::Eq {
2478 .struct_span_err(self.span, "expected `:`, found `=`")
2480 fieldname.span.shrink_to_hi().to(self.span),
2481 "replace equals symbol with a colon",
2483 Applicability::MachineApplicable,
2488 (fieldname, self.parse_expr()?, false)
2490 let fieldname = self.parse_ident_common(false)?;
2492 // Mimic `x: x` for the `x` field shorthand.
2493 let path = ast::Path::from_ident(fieldname);
2494 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2495 (fieldname, expr, true)
2499 span: lo.to(expr.span),
2502 attrs: attrs.into(),
2506 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2507 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2510 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2511 ExprKind::Unary(unop, expr)
2514 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2515 ExprKind::Binary(binop, lhs, rhs)
2518 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2519 ExprKind::Call(f, args)
2522 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2523 ExprKind::Index(expr, idx)
2526 fn mk_range(&mut self,
2527 start: Option<P<Expr>>,
2528 end: Option<P<Expr>>,
2529 limits: RangeLimits)
2530 -> PResult<'a, ast::ExprKind> {
2531 if end.is_none() && limits == RangeLimits::Closed {
2532 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2534 Ok(ExprKind::Range(start, end, limits))
2538 fn mk_assign_op(&mut self, binop: ast::BinOp,
2539 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2540 ExprKind::AssignOp(binop, lhs, rhs)
2543 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2545 id: ast::DUMMY_NODE_ID,
2546 node: ExprKind::Mac(source_map::Spanned {node: m, span: span}),
2552 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
2553 let delim = match self.token {
2554 token::OpenDelim(delim) => delim,
2556 let msg = "expected open delimiter";
2557 let mut err = self.fatal(msg);
2558 err.span_label(self.span, msg);
2562 let tts = match self.parse_token_tree() {
2563 TokenTree::Delimited(_, _, tts) => tts,
2564 _ => unreachable!(),
2566 let delim = match delim {
2567 token::Paren => MacDelimiter::Parenthesis,
2568 token::Bracket => MacDelimiter::Bracket,
2569 token::Brace => MacDelimiter::Brace,
2570 token::NoDelim => self.bug("unexpected no delimiter"),
2572 Ok((delim, tts.into()))
2575 /// At the bottom (top?) of the precedence hierarchy,
2576 /// Parses things like parenthesized exprs, macros, `return`, etc.
2578 /// N.B., this does not parse outer attributes, and is private because it only works
2579 /// correctly if called from `parse_dot_or_call_expr()`.
2580 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2581 maybe_whole_expr!(self);
2583 // Outer attributes are already parsed and will be
2584 // added to the return value after the fact.
2586 // Therefore, prevent sub-parser from parsing
2587 // attributes by giving them a empty "already parsed" list.
2588 let mut attrs = ThinVec::new();
2591 let mut hi = self.span;
2595 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2597 token::OpenDelim(token::Paren) => {
2600 attrs.extend(self.parse_inner_attributes()?);
2602 // (e) is parenthesized e
2603 // (e,) is a tuple with only one field, e
2604 let mut es = vec![];
2605 let mut trailing_comma = false;
2606 let mut recovered = false;
2607 while self.token != token::CloseDelim(token::Paren) {
2608 es.push(self.parse_expr()?);
2609 recovered = self.expect_one_of(
2611 &[token::Comma, token::CloseDelim(token::Paren)],
2613 if self.eat(&token::Comma) {
2614 trailing_comma = true;
2616 trailing_comma = false;
2624 hi = self.prev_span;
2625 ex = if es.len() == 1 && !trailing_comma {
2626 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2631 token::OpenDelim(token::Brace) => {
2632 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2634 token::BinOp(token::Or) | token::OrOr => {
2635 return self.parse_lambda_expr(attrs);
2637 token::OpenDelim(token::Bracket) => {
2640 attrs.extend(self.parse_inner_attributes()?);
2642 if self.eat(&token::CloseDelim(token::Bracket)) {
2644 ex = ExprKind::Array(Vec::new());
2647 let first_expr = self.parse_expr()?;
2648 if self.eat(&token::Semi) {
2649 // Repeating array syntax: [ 0; 512 ]
2650 let count = AnonConst {
2651 id: ast::DUMMY_NODE_ID,
2652 value: self.parse_expr()?,
2654 self.expect(&token::CloseDelim(token::Bracket))?;
2655 ex = ExprKind::Repeat(first_expr, count);
2656 } else if self.eat(&token::Comma) {
2657 // Vector with two or more elements.
2658 let remaining_exprs = self.parse_seq_to_end(
2659 &token::CloseDelim(token::Bracket),
2660 SeqSep::trailing_allowed(token::Comma),
2661 |p| Ok(p.parse_expr()?)
2663 let mut exprs = vec![first_expr];
2664 exprs.extend(remaining_exprs);
2665 ex = ExprKind::Array(exprs);
2667 // Vector with one element.
2668 self.expect(&token::CloseDelim(token::Bracket))?;
2669 ex = ExprKind::Array(vec![first_expr]);
2672 hi = self.prev_span;
2676 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2678 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2680 if self.span.rust_2018() && self.check_keyword(keywords::Async)
2682 if self.is_async_block() { // check for `async {` and `async move {`
2683 return self.parse_async_block(attrs);
2685 return self.parse_lambda_expr(attrs);
2688 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2689 return self.parse_lambda_expr(attrs);
2691 if self.eat_keyword(keywords::If) {
2692 return self.parse_if_expr(attrs);
2694 if self.eat_keyword(keywords::For) {
2695 let lo = self.prev_span;
2696 return self.parse_for_expr(None, lo, attrs);
2698 if self.eat_keyword(keywords::While) {
2699 let lo = self.prev_span;
2700 return self.parse_while_expr(None, lo, attrs);
2702 if let Some(label) = self.eat_label() {
2703 let lo = label.ident.span;
2704 self.expect(&token::Colon)?;
2705 if self.eat_keyword(keywords::While) {
2706 return self.parse_while_expr(Some(label), lo, attrs)
2708 if self.eat_keyword(keywords::For) {
2709 return self.parse_for_expr(Some(label), lo, attrs)
2711 if self.eat_keyword(keywords::Loop) {
2712 return self.parse_loop_expr(Some(label), lo, attrs)
2714 if self.token == token::OpenDelim(token::Brace) {
2715 return self.parse_block_expr(Some(label),
2717 BlockCheckMode::Default,
2720 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2721 let mut err = self.fatal(msg);
2722 err.span_label(self.span, msg);
2725 if self.eat_keyword(keywords::Loop) {
2726 let lo = self.prev_span;
2727 return self.parse_loop_expr(None, lo, attrs);
2729 if self.eat_keyword(keywords::Continue) {
2730 let label = self.eat_label();
2731 let ex = ExprKind::Continue(label);
2732 let hi = self.prev_span;
2733 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2735 if self.eat_keyword(keywords::Match) {
2736 let match_sp = self.prev_span;
2737 return self.parse_match_expr(attrs).map_err(|mut err| {
2738 err.span_label(match_sp, "while parsing this match expression");
2742 if self.eat_keyword(keywords::Unsafe) {
2743 return self.parse_block_expr(
2746 BlockCheckMode::Unsafe(ast::UserProvided),
2749 if self.is_do_catch_block() {
2750 let mut db = self.fatal("found removed `do catch` syntax");
2751 db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2754 if self.is_try_block() {
2756 assert!(self.eat_keyword(keywords::Try));
2757 return self.parse_try_block(lo, attrs);
2759 if self.eat_keyword(keywords::Return) {
2760 if self.token.can_begin_expr() {
2761 let e = self.parse_expr()?;
2763 ex = ExprKind::Ret(Some(e));
2765 ex = ExprKind::Ret(None);
2767 } else if self.eat_keyword(keywords::Break) {
2768 let label = self.eat_label();
2769 let e = if self.token.can_begin_expr()
2770 && !(self.token == token::OpenDelim(token::Brace)
2771 && self.restrictions.contains(
2772 Restrictions::NO_STRUCT_LITERAL)) {
2773 Some(self.parse_expr()?)
2777 ex = ExprKind::Break(label, e);
2778 hi = self.prev_span;
2779 } else if self.eat_keyword(keywords::Yield) {
2780 if self.token.can_begin_expr() {
2781 let e = self.parse_expr()?;
2783 ex = ExprKind::Yield(Some(e));
2785 ex = ExprKind::Yield(None);
2787 } else if self.token.is_keyword(keywords::Let) {
2788 // Catch this syntax error here, instead of in `parse_ident`, so
2789 // that we can explicitly mention that let is not to be used as an expression
2790 let mut db = self.fatal("expected expression, found statement (`let`)");
2791 db.span_label(self.span, "expected expression");
2792 db.note("variable declaration using `let` is a statement");
2794 } else if self.token.is_path_start() {
2795 let pth = self.parse_path(PathStyle::Expr)?;
2797 // `!`, as an operator, is prefix, so we know this isn't that
2798 if self.eat(&token::Not) {
2799 // MACRO INVOCATION expression
2800 let (delim, tts) = self.expect_delimited_token_tree()?;
2801 let hi = self.prev_span;
2802 let node = Mac_ { path: pth, tts, delim };
2803 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2805 if self.check(&token::OpenDelim(token::Brace)) {
2806 // This is a struct literal, unless we're prohibited
2807 // from parsing struct literals here.
2808 let prohibited = self.restrictions.contains(
2809 Restrictions::NO_STRUCT_LITERAL
2812 return self.parse_struct_expr(lo, pth, attrs);
2817 ex = ExprKind::Path(None, pth);
2819 if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2820 // Don't complain about bare semicolons after unclosed braces
2821 // recovery in order to keep the error count down. Fixing the
2822 // delimiters will possibly also fix the bare semicolon found in
2823 // expression context. For example, silence the following error:
2825 // error: expected expression, found `;`
2829 // | ^ expected expression
2832 return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
2834 match self.parse_literal_maybe_minus() {
2837 ex = expr.node.clone();
2840 self.cancel(&mut err);
2841 let msg = format!("expected expression, found {}",
2842 self.this_token_descr());
2843 let mut err = self.fatal(&msg);
2844 err.span_label(self.span, "expected expression");
2852 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2853 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2858 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2859 -> PResult<'a, P<Expr>> {
2860 let struct_sp = lo.to(self.prev_span);
2862 let mut fields = Vec::new();
2863 let mut base = None;
2865 attrs.extend(self.parse_inner_attributes()?);
2867 while self.token != token::CloseDelim(token::Brace) {
2868 if self.eat(&token::DotDot) {
2869 let exp_span = self.prev_span;
2870 match self.parse_expr() {
2876 self.recover_stmt();
2879 if self.token == token::Comma {
2880 let mut err = self.sess.span_diagnostic.mut_span_err(
2881 exp_span.to(self.prev_span),
2882 "cannot use a comma after the base struct",
2884 err.span_suggestion_short(
2886 "remove this comma",
2888 Applicability::MachineApplicable
2890 err.note("the base struct must always be the last field");
2892 self.recover_stmt();
2897 let mut recovery_field = None;
2898 if let token::Ident(ident, _) = self.token {
2899 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2900 // Use in case of error after field-looking code: `S { foo: () with a }`
2901 let mut ident = ident.clone();
2902 ident.span = self.span;
2903 recovery_field = Some(ast::Field {
2906 expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
2907 is_shorthand: false,
2908 attrs: ThinVec::new(),
2912 let mut parsed_field = None;
2913 match self.parse_field() {
2914 Ok(f) => parsed_field = Some(f),
2916 e.span_label(struct_sp, "while parsing this struct");
2919 // If the next token is a comma, then try to parse
2920 // what comes next as additional fields, rather than
2921 // bailing out until next `}`.
2922 if self.token != token::Comma {
2923 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2924 if self.token != token::Comma {
2931 match self.expect_one_of(&[token::Comma],
2932 &[token::CloseDelim(token::Brace)]) {
2933 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2934 // only include the field if there's no parse error for the field name
2938 if let Some(f) = recovery_field {
2941 e.span_label(struct_sp, "while parsing this struct");
2943 self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2944 self.eat(&token::Comma);
2949 let span = lo.to(self.span);
2950 self.expect(&token::CloseDelim(token::Brace))?;
2951 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2954 fn parse_or_use_outer_attributes(&mut self,
2955 already_parsed_attrs: Option<ThinVec<Attribute>>)
2956 -> PResult<'a, ThinVec<Attribute>> {
2957 if let Some(attrs) = already_parsed_attrs {
2960 self.parse_outer_attributes().map(|a| a.into())
2964 /// Parses a block or unsafe block.
2965 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2966 lo: Span, blk_mode: BlockCheckMode,
2967 outer_attrs: ThinVec<Attribute>)
2968 -> PResult<'a, P<Expr>> {
2969 self.expect(&token::OpenDelim(token::Brace))?;
2971 let mut attrs = outer_attrs;
2972 attrs.extend(self.parse_inner_attributes()?);
2974 let blk = self.parse_block_tail(lo, blk_mode)?;
2975 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2978 /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2979 fn parse_dot_or_call_expr(&mut self,
2980 already_parsed_attrs: Option<ThinVec<Attribute>>)
2981 -> PResult<'a, P<Expr>> {
2982 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2984 let b = self.parse_bottom_expr();
2985 let (span, b) = self.interpolated_or_expr_span(b)?;
2986 self.parse_dot_or_call_expr_with(b, span, attrs)
2989 fn parse_dot_or_call_expr_with(&mut self,
2992 mut attrs: ThinVec<Attribute>)
2993 -> PResult<'a, P<Expr>> {
2994 // Stitch the list of outer attributes onto the return value.
2995 // A little bit ugly, but the best way given the current code
2997 self.parse_dot_or_call_expr_with_(e0, lo)
2999 expr.map(|mut expr| {
3000 attrs.extend::<Vec<_>>(expr.attrs.into());
3003 ExprKind::If(..) | ExprKind::IfLet(..) => {
3004 if !expr.attrs.is_empty() {
3005 // Just point to the first attribute in there...
3006 let span = expr.attrs[0].span;
3009 "attributes are not yet allowed on `if` \
3020 // Assuming we have just parsed `.`, continue parsing into an expression.
3021 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3022 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
3023 self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
3025 Ok(match self.token {
3026 token::OpenDelim(token::Paren) => {
3027 // Method call `expr.f()`
3028 let mut args = self.parse_unspanned_seq(
3029 &token::OpenDelim(token::Paren),
3030 &token::CloseDelim(token::Paren),
3031 SeqSep::trailing_allowed(token::Comma),
3032 |p| Ok(p.parse_expr()?)
3034 args.insert(0, self_arg);
3036 let span = lo.to(self.prev_span);
3037 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
3040 // Field access `expr.f`
3041 if let Some(args) = segment.args {
3042 self.span_err(args.span(),
3043 "field expressions may not have generic arguments");
3046 let span = lo.to(self.prev_span);
3047 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
3052 /// This function checks if there are trailing angle brackets and produces
3053 /// a diagnostic to suggest removing them.
3055 /// ```ignore (diagnostic)
3056 /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
3057 /// ^^ help: remove extra angle brackets
3059 fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) {
3060 // This function is intended to be invoked after parsing a path segment where there are two
3063 // 1. A specific token is expected after the path segment.
3064 // eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
3065 // `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
3066 // 2. No specific token is expected after the path segment.
3067 // eg. `x.foo` (field access)
3069 // This function is called after parsing `.foo` and before parsing the token `end` (if
3070 // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
3073 // We only care about trailing angle brackets if we previously parsed angle bracket
3074 // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
3075 // removed in this case:
3077 // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
3079 // This case is particularly tricky as we won't notice it just looking at the tokens -
3080 // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
3081 // have already been parsed):
3083 // `x.foo::<u32>>>(3)`
3084 let parsed_angle_bracket_args = segment.args
3086 .map(|args| args.is_angle_bracketed())
3090 "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
3091 parsed_angle_bracket_args,
3093 if !parsed_angle_bracket_args {
3097 // Keep the span at the start so we can highlight the sequence of `>` characters to be
3101 // We need to look-ahead to see if we have `>` characters without moving the cursor forward
3102 // (since we might have the field access case and the characters we're eating are
3103 // actual operators and not trailing characters - ie `x.foo >> 3`).
3104 let mut position = 0;
3106 // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
3107 // many of each (so we can correctly pluralize our error messages) and continue to
3109 let mut number_of_shr = 0;
3110 let mut number_of_gt = 0;
3111 while self.look_ahead(position, |t| {
3112 trace!("check_trailing_angle_brackets: t={:?}", t);
3113 if *t == token::BinOp(token::BinOpToken::Shr) {
3116 } else if *t == token::Gt {
3126 // If we didn't find any trailing `>` characters, then we have nothing to error about.
3128 "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
3129 number_of_gt, number_of_shr,
3131 if number_of_gt < 1 && number_of_shr < 1 {
3135 // Finally, double check that we have our end token as otherwise this is the
3137 if self.look_ahead(position, |t| {
3138 trace!("check_trailing_angle_brackets: t={:?}", t);
3141 // Eat from where we started until the end token so that parsing can continue
3142 // as if we didn't have those extra angle brackets.
3143 self.eat_to_tokens(&[&end]);
3144 let span = lo.until(self.span);
3146 let plural = number_of_gt > 1 || number_of_shr >= 1;
3150 &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
3154 &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
3156 Applicability::MachineApplicable,
3162 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3167 while self.eat(&token::Question) {
3168 let hi = self.prev_span;
3169 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
3173 if self.eat(&token::Dot) {
3175 token::Ident(..) => {
3176 e = self.parse_dot_suffix(e, lo)?;
3178 token::Literal(token::Integer(name), _) => {
3179 let span = self.span;
3181 let field = ExprKind::Field(e, Ident::new(name, span));
3182 e = self.mk_expr(lo.to(span), field, ThinVec::new());
3184 token::Literal(token::Float(n), _suf) => {
3186 let fstr = n.as_str();
3187 let mut err = self.diagnostic()
3188 .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
3189 err.span_label(self.prev_span, "unexpected token");
3190 if fstr.chars().all(|x| "0123456789.".contains(x)) {
3191 let float = match fstr.parse::<f64>().ok() {
3195 let sugg = pprust::to_string(|s| {
3196 use crate::print::pprust::PrintState;
3200 s.print_usize(float.trunc() as usize)?;
3203 s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
3205 err.span_suggestion(
3206 lo.to(self.prev_span),
3207 "try parenthesizing the first index",
3209 Applicability::MachineApplicable
3216 // FIXME Could factor this out into non_fatal_unexpected or something.
3217 let actual = self.this_token_to_string();
3218 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
3223 if self.expr_is_complete(&e) { break; }
3226 token::OpenDelim(token::Paren) => {
3227 let es = self.parse_unspanned_seq(
3228 &token::OpenDelim(token::Paren),
3229 &token::CloseDelim(token::Paren),
3230 SeqSep::trailing_allowed(token::Comma),
3231 |p| Ok(p.parse_expr()?)
3233 hi = self.prev_span;
3235 let nd = self.mk_call(e, es);
3236 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
3240 // Could be either an index expression or a slicing expression.
3241 token::OpenDelim(token::Bracket) => {
3243 let ix = self.parse_expr()?;
3245 self.expect(&token::CloseDelim(token::Bracket))?;
3246 let index = self.mk_index(e, ix);
3247 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
3255 crate fn process_potential_macro_variable(&mut self) {
3256 let (token, span) = match self.token {
3257 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
3258 self.look_ahead(1, |t| t.is_ident()) => {
3260 let name = match self.token {
3261 token::Ident(ident, _) => ident,
3264 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
3265 err.span_label(self.span, "unknown macro variable");
3270 token::Interpolated(ref nt) => {
3271 self.meta_var_span = Some(self.span);
3272 // Interpolated identifier and lifetime tokens are replaced with usual identifier
3273 // and lifetime tokens, so the former are never encountered during normal parsing.
3275 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
3276 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
3286 /// Parses a single token tree from the input.
3287 crate fn parse_token_tree(&mut self) -> TokenTree {
3289 token::OpenDelim(..) => {
3290 let frame = mem::replace(&mut self.token_cursor.frame,
3291 self.token_cursor.stack.pop().unwrap());
3292 self.span = frame.span.entire();
3294 TokenTree::Delimited(
3297 frame.tree_cursor.stream.into(),
3300 token::CloseDelim(_) | token::Eof => unreachable!(),
3302 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
3304 TokenTree::Token(span, token)
3309 // parse a stream of tokens into a list of TokenTree's,
3311 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
3312 let mut tts = Vec::new();
3313 while self.token != token::Eof {
3314 tts.push(self.parse_token_tree());
3319 pub fn parse_tokens(&mut self) -> TokenStream {
3320 let mut result = Vec::new();
3323 token::Eof | token::CloseDelim(..) => break,
3324 _ => result.push(self.parse_token_tree().into()),
3327 TokenStream::new(result)
3330 /// Parse a prefix-unary-operator expr
3331 fn parse_prefix_expr(&mut self,
3332 already_parsed_attrs: Option<ThinVec<Attribute>>)
3333 -> PResult<'a, P<Expr>> {
3334 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3336 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
3337 let (hi, ex) = match self.token {
3340 let e = self.parse_prefix_expr(None);
3341 let (span, e) = self.interpolated_or_expr_span(e)?;
3342 (lo.to(span), self.mk_unary(UnOp::Not, e))
3344 // Suggest `!` for bitwise negation when encountering a `~`
3347 let e = self.parse_prefix_expr(None);
3348 let (span, e) = self.interpolated_or_expr_span(e)?;
3349 let span_of_tilde = lo;
3350 let mut err = self.diagnostic()
3351 .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
3352 err.span_suggestion_short(
3354 "use `!` to perform bitwise negation",
3356 Applicability::MachineApplicable
3359 (lo.to(span), self.mk_unary(UnOp::Not, e))
3361 token::BinOp(token::Minus) => {
3363 let e = self.parse_prefix_expr(None);
3364 let (span, e) = self.interpolated_or_expr_span(e)?;
3365 (lo.to(span), self.mk_unary(UnOp::Neg, e))
3367 token::BinOp(token::Star) => {
3369 let e = self.parse_prefix_expr(None);
3370 let (span, e) = self.interpolated_or_expr_span(e)?;
3371 (lo.to(span), self.mk_unary(UnOp::Deref, e))
3373 token::BinOp(token::And) | token::AndAnd => {
3375 let m = self.parse_mutability();
3376 let e = self.parse_prefix_expr(None);
3377 let (span, e) = self.interpolated_or_expr_span(e)?;
3378 (lo.to(span), ExprKind::AddrOf(m, e))
3380 token::Ident(..) if self.token.is_keyword(keywords::In) => {
3382 let place = self.parse_expr_res(
3383 Restrictions::NO_STRUCT_LITERAL,
3386 let blk = self.parse_block()?;
3387 let span = blk.span;
3388 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
3389 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
3391 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
3393 let e = self.parse_prefix_expr(None);
3394 let (span, e) = self.interpolated_or_expr_span(e)?;
3395 (lo.to(span), ExprKind::Box(e))
3397 token::Ident(..) if self.token.is_ident_named("not") => {
3398 // `not` is just an ordinary identifier in Rust-the-language,
3399 // but as `rustc`-the-compiler, we can issue clever diagnostics
3400 // for confused users who really want to say `!`
3401 let token_cannot_continue_expr = |t: &token::Token| match *t {
3402 // These tokens can start an expression after `!`, but
3403 // can't continue an expression after an ident
3404 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3405 token::Literal(..) | token::Pound => true,
3406 token::Interpolated(ref nt) => match nt.0 {
3407 token::NtIdent(..) | token::NtExpr(..) |
3408 token::NtBlock(..) | token::NtPath(..) => true,
3413 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3414 if cannot_continue_expr {
3416 // Emit the error ...
3417 let mut err = self.diagnostic()
3418 .struct_span_err(self.span,
3419 &format!("unexpected {} after identifier",
3420 self.this_token_descr()));
3421 // span the `not` plus trailing whitespace to avoid
3422 // trailing whitespace after the `!` in our suggestion
3423 let to_replace = self.sess.source_map()
3424 .span_until_non_whitespace(lo.to(self.span));
3425 err.span_suggestion_short(
3427 "use `!` to perform logical negation",
3429 Applicability::MachineApplicable
3432 // —and recover! (just as if we were in the block
3433 // for the `token::Not` arm)
3434 let e = self.parse_prefix_expr(None);
3435 let (span, e) = self.interpolated_or_expr_span(e)?;
3436 (lo.to(span), self.mk_unary(UnOp::Not, e))
3438 return self.parse_dot_or_call_expr(Some(attrs));
3441 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3443 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3446 /// Parses an associative expression.
3448 /// This parses an expression accounting for associativity and precedence of the operators in
3451 fn parse_assoc_expr(&mut self,
3452 already_parsed_attrs: Option<ThinVec<Attribute>>)
3453 -> PResult<'a, P<Expr>> {
3454 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3457 /// Parses an associative expression with operators of at least `min_prec` precedence.
3458 fn parse_assoc_expr_with(&mut self,
3461 -> PResult<'a, P<Expr>> {
3462 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3465 let attrs = match lhs {
3466 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3469 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3470 return self.parse_prefix_range_expr(attrs);
3472 self.parse_prefix_expr(attrs)?
3476 if self.expr_is_complete(&lhs) {
3477 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3480 self.expected_tokens.push(TokenType::Operator);
3481 while let Some(op) = AssocOp::from_token(&self.token) {
3483 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3484 // it refers to. Interpolated identifiers are unwrapped early and never show up here
3485 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3486 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3487 let lhs_span = match (self.prev_token_kind, &lhs.node) {
3488 (PrevTokenKind::Interpolated, _) => self.prev_span,
3489 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3490 if path.segments.len() == 1 => self.prev_span,
3494 let cur_op_span = self.span;
3495 let restrictions = if op.is_assign_like() {
3496 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3500 if op.precedence() < min_prec {
3503 // Check for deprecated `...` syntax
3504 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3505 self.err_dotdotdot_syntax(self.span);
3509 if op.is_comparison() {
3510 self.check_no_chained_comparison(&lhs, &op);
3513 if op == AssocOp::As {
3514 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3516 } else if op == AssocOp::Colon {
3517 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3520 err.span_label(self.span,
3521 "expecting a type here because of type ascription");
3522 let cm = self.sess.source_map();
3523 let cur_pos = cm.lookup_char_pos(self.span.lo());
3524 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3525 if cur_pos.line != op_pos.line {
3526 err.span_suggestion(
3528 "try using a semicolon",
3530 Applicability::MaybeIncorrect // speculative
3537 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3538 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3539 // generalise it to the Fixity::None code.
3541 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3542 // two variants are handled with `parse_prefix_range_expr` call above.
3543 let rhs = if self.is_at_start_of_range_notation_rhs() {
3544 Some(self.parse_assoc_expr_with(op.precedence() + 1,
3545 LhsExpr::NotYetParsed)?)
3549 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3554 let limits = if op == AssocOp::DotDot {
3555 RangeLimits::HalfOpen
3560 let r = self.mk_range(Some(lhs), rhs, limits)?;
3561 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3565 let rhs = match op.fixity() {
3566 Fixity::Right => self.with_res(
3567 restrictions - Restrictions::STMT_EXPR,
3569 this.parse_assoc_expr_with(op.precedence(),
3570 LhsExpr::NotYetParsed)
3572 Fixity::Left => self.with_res(
3573 restrictions - Restrictions::STMT_EXPR,
3575 this.parse_assoc_expr_with(op.precedence() + 1,
3576 LhsExpr::NotYetParsed)
3578 // We currently have no non-associative operators that are not handled above by
3579 // the special cases. The code is here only for future convenience.
3580 Fixity::None => self.with_res(
3581 restrictions - Restrictions::STMT_EXPR,
3583 this.parse_assoc_expr_with(op.precedence() + 1,
3584 LhsExpr::NotYetParsed)
3588 // Make sure that the span of the parent node is larger than the span of lhs and rhs,
3589 // including the attributes.
3593 .filter(|a| a.style == AttrStyle::Outer)
3595 .map_or(lhs_span, |a| a.span);
3596 let span = lhs_span.to(rhs.span);
3598 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3599 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3600 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3601 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3602 AssocOp::Greater | AssocOp::GreaterEqual => {
3603 let ast_op = op.to_ast_binop().unwrap();
3604 let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3605 self.mk_expr(span, binary, ThinVec::new())
3608 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3609 AssocOp::ObsoleteInPlace =>
3610 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3611 AssocOp::AssignOp(k) => {
3613 token::Plus => BinOpKind::Add,
3614 token::Minus => BinOpKind::Sub,
3615 token::Star => BinOpKind::Mul,
3616 token::Slash => BinOpKind::Div,
3617 token::Percent => BinOpKind::Rem,
3618 token::Caret => BinOpKind::BitXor,
3619 token::And => BinOpKind::BitAnd,
3620 token::Or => BinOpKind::BitOr,
3621 token::Shl => BinOpKind::Shl,
3622 token::Shr => BinOpKind::Shr,
3624 let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3625 self.mk_expr(span, aopexpr, ThinVec::new())
3627 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3628 self.bug("AssocOp should have been handled by special case")
3632 if op.fixity() == Fixity::None { break }
3637 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3638 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3639 -> PResult<'a, P<Expr>> {
3640 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3641 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3644 // Save the state of the parser before parsing type normally, in case there is a
3645 // LessThan comparison after this cast.
3646 let parser_snapshot_before_type = self.clone();
3647 match self.parse_ty_no_plus() {
3649 Ok(mk_expr(self, rhs))
3651 Err(mut type_err) => {
3652 // Rewind to before attempting to parse the type with generics, to recover
3653 // from situations like `x as usize < y` in which we first tried to parse
3654 // `usize < y` as a type with generic arguments.
3655 let parser_snapshot_after_type = self.clone();
3656 mem::replace(self, parser_snapshot_before_type);
3658 match self.parse_path(PathStyle::Expr) {
3660 let (op_noun, op_verb) = match self.token {
3661 token::Lt => ("comparison", "comparing"),
3662 token::BinOp(token::Shl) => ("shift", "shifting"),
3664 // We can end up here even without `<` being the next token, for
3665 // example because `parse_ty_no_plus` returns `Err` on keywords,
3666 // but `parse_path` returns `Ok` on them due to error recovery.
3667 // Return original error and parser state.
3668 mem::replace(self, parser_snapshot_after_type);
3669 return Err(type_err);
3673 // Successfully parsed the type path leaving a `<` yet to parse.
3676 // Report non-fatal diagnostics, keep `x as usize` as an expression
3677 // in AST and continue parsing.
3678 let msg = format!("`<` is interpreted as a start of generic \
3679 arguments for `{}`, not a {}", path, op_noun);
3680 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3681 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3682 "interpreted as generic arguments");
3683 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3685 let expr = mk_expr(self, P(Ty {
3687 node: TyKind::Path(None, path),
3688 id: ast::DUMMY_NODE_ID
3691 let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3692 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3693 err.span_suggestion(
3695 &format!("try {} the cast value", op_verb),
3696 format!("({})", expr_str),
3697 Applicability::MachineApplicable
3703 Err(mut path_err) => {
3704 // Couldn't parse as a path, return original error and parser state.
3706 mem::replace(self, parser_snapshot_after_type);
3714 /// Produce an error if comparison operators are chained (RFC #558).
3715 /// We only need to check lhs, not rhs, because all comparison ops
3716 /// have same precedence and are left-associative
3717 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3718 debug_assert!(outer_op.is_comparison(),
3719 "check_no_chained_comparison: {:?} is not comparison",
3722 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3723 // respan to include both operators
3724 let op_span = op.span.to(self.span);
3725 let mut err = self.diagnostic().struct_span_err(op_span,
3726 "chained comparison operators require parentheses");
3727 if op.node == BinOpKind::Lt &&
3728 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3729 *outer_op == AssocOp::Greater // even in a case like the following:
3730 { // Foo<Bar<Baz<Qux, ()>>>
3732 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3733 err.help("or use `(...)` if you meant to specify fn arguments");
3741 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3742 fn parse_prefix_range_expr(&mut self,
3743 already_parsed_attrs: Option<ThinVec<Attribute>>)
3744 -> PResult<'a, P<Expr>> {
3745 // Check for deprecated `...` syntax
3746 if self.token == token::DotDotDot {
3747 self.err_dotdotdot_syntax(self.span);
3750 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3751 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3753 let tok = self.token.clone();
3754 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3756 let mut hi = self.span;
3758 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3759 // RHS must be parsed with more associativity than the dots.
3760 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3761 Some(self.parse_assoc_expr_with(next_prec,
3762 LhsExpr::NotYetParsed)
3770 let limits = if tok == token::DotDot {
3771 RangeLimits::HalfOpen
3776 let r = self.mk_range(None, opt_end, limits)?;
3777 Ok(self.mk_expr(lo.to(hi), r, attrs))
3780 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3781 if self.token.can_begin_expr() {
3782 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3783 if self.token == token::OpenDelim(token::Brace) {
3784 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3792 /// Parses an `if` or `if let` expression (`if` token already eaten).
3793 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3794 if self.check_keyword(keywords::Let) {
3795 return self.parse_if_let_expr(attrs);
3797 let lo = self.prev_span;
3798 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3800 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3801 // verify that the last statement is either an implicit return (no `;`) or an explicit
3802 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3803 // the dead code lint.
3804 if self.eat_keyword(keywords::Else) || !cond.returns() {
3805 let sp = self.sess.source_map().next_point(lo);
3806 let mut err = self.diagnostic()
3807 .struct_span_err(sp, "missing condition for `if` statemement");
3808 err.span_label(sp, "expected if condition here");
3811 let not_block = self.token != token::OpenDelim(token::Brace);
3812 let thn = self.parse_block().map_err(|mut err| {
3814 err.span_label(lo, "this `if` statement has a condition, but no block");
3818 let mut els: Option<P<Expr>> = None;
3819 let mut hi = thn.span;
3820 if self.eat_keyword(keywords::Else) {
3821 let elexpr = self.parse_else_expr()?;
3825 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3828 /// Parses an `if let` expression (`if` token already eaten).
3829 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3830 -> PResult<'a, P<Expr>> {
3831 let lo = self.prev_span;
3832 self.expect_keyword(keywords::Let)?;
3833 let pats = self.parse_pats()?;
3834 self.expect(&token::Eq)?;
3835 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3836 let thn = self.parse_block()?;
3837 let (hi, els) = if self.eat_keyword(keywords::Else) {
3838 let expr = self.parse_else_expr()?;
3839 (expr.span, Some(expr))
3843 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3846 /// Parses `move |args| expr`.
3847 fn parse_lambda_expr(&mut self,
3848 attrs: ThinVec<Attribute>)
3849 -> PResult<'a, P<Expr>>
3852 let movability = if self.eat_keyword(keywords::Static) {
3857 let asyncness = if self.span.rust_2018() {
3858 self.parse_asyncness()
3862 let capture_clause = if self.eat_keyword(keywords::Move) {
3867 let decl = self.parse_fn_block_decl()?;
3868 let decl_hi = self.prev_span;
3869 let body = match decl.output {
3870 FunctionRetTy::Default(_) => {
3871 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3872 self.parse_expr_res(restrictions, None)?
3875 // If an explicit return type is given, require a
3876 // block to appear (RFC 968).
3877 let body_lo = self.span;
3878 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3884 ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3888 // `else` token already eaten
3889 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3890 if self.eat_keyword(keywords::If) {
3891 return self.parse_if_expr(ThinVec::new());
3893 let blk = self.parse_block()?;
3894 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3898 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3899 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3901 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3902 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3904 let pat = self.parse_top_level_pat()?;
3905 if !self.eat_keyword(keywords::In) {
3906 let in_span = self.prev_span.between(self.span);
3907 let mut err = self.sess.span_diagnostic
3908 .struct_span_err(in_span, "missing `in` in `for` loop");
3909 err.span_suggestion_short(
3910 in_span, "try adding `in` here", " in ".into(),
3911 // has been misleading, at least in the past (closed Issue #48492)
3912 Applicability::MaybeIncorrect
3916 let in_span = self.prev_span;
3917 if self.eat_keyword(keywords::In) {
3918 // a common typo: `for _ in in bar {}`
3919 let mut err = self.sess.span_diagnostic.struct_span_err(
3921 "expected iterable, found keyword `in`",
3923 err.span_suggestion_short(
3924 in_span.until(self.prev_span),
3925 "remove the duplicated `in`",
3927 Applicability::MachineApplicable,
3929 err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
3930 err.note("for more information on the status of emplacement syntax, see <\
3931 https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
3934 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3935 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3936 attrs.extend(iattrs);
3938 let hi = self.prev_span;
3939 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3942 /// Parses a `while` or `while let` expression (`while` token already eaten).
3943 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3945 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3946 if self.token.is_keyword(keywords::Let) {
3947 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3949 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3950 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3951 attrs.extend(iattrs);
3952 let span = span_lo.to(body.span);
3953 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3956 /// Parses a `while let` expression (`while` token already eaten).
3957 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3959 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3960 self.expect_keyword(keywords::Let)?;
3961 let pats = self.parse_pats()?;
3962 self.expect(&token::Eq)?;
3963 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3964 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3965 attrs.extend(iattrs);
3966 let span = span_lo.to(body.span);
3967 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3970 // parse `loop {...}`, `loop` token already eaten
3971 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3973 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3974 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3975 attrs.extend(iattrs);
3976 let span = span_lo.to(body.span);
3977 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3980 /// Parses an `async move {...}` expression.
3981 pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
3982 -> PResult<'a, P<Expr>>
3984 let span_lo = self.span;
3985 self.expect_keyword(keywords::Async)?;
3986 let capture_clause = if self.eat_keyword(keywords::Move) {
3991 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3992 attrs.extend(iattrs);
3994 span_lo.to(body.span),
3995 ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
3998 /// Parses a `try {...}` expression (`try` token already eaten).
3999 fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
4000 -> PResult<'a, P<Expr>>
4002 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4003 attrs.extend(iattrs);
4004 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
4007 // `match` token already eaten
4008 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4009 let match_span = self.prev_span;
4010 let lo = self.prev_span;
4011 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
4013 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
4014 if self.token == token::Token::Semi {
4015 e.span_suggestion_short(
4017 "try removing this `match`",
4019 Applicability::MaybeIncorrect // speculative
4024 attrs.extend(self.parse_inner_attributes()?);
4026 let mut arms: Vec<Arm> = Vec::new();
4027 while self.token != token::CloseDelim(token::Brace) {
4028 match self.parse_arm() {
4029 Ok(arm) => arms.push(arm),
4031 // Recover by skipping to the end of the block.
4033 self.recover_stmt();
4034 let span = lo.to(self.span);
4035 if self.token == token::CloseDelim(token::Brace) {
4038 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
4044 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
4047 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
4048 maybe_whole!(self, NtArm, |x| x);
4050 let attrs = self.parse_outer_attributes()?;
4051 let pats = self.parse_pats()?;
4052 let guard = if self.eat_keyword(keywords::If) {
4053 Some(Guard::If(self.parse_expr()?))
4057 let arrow_span = self.span;
4058 self.expect(&token::FatArrow)?;
4059 let arm_start_span = self.span;
4061 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
4062 .map_err(|mut err| {
4063 err.span_label(arrow_span, "while parsing the `match` arm starting here");
4067 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
4068 && self.token != token::CloseDelim(token::Brace);
4071 let cm = self.sess.source_map();
4072 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
4073 .map_err(|mut err| {
4074 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
4075 (Ok(ref expr_lines), Ok(ref arm_start_lines))
4076 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
4077 && expr_lines.lines.len() == 2
4078 && self.token == token::FatArrow => {
4079 // We check whether there's any trailing code in the parse span,
4080 // if there isn't, we very likely have the following:
4083 // | -- - missing comma
4089 // | parsed until here as `"y" & X`
4090 err.span_suggestion_short(
4091 cm.next_point(arm_start_span),
4092 "missing a comma here to end this `match` arm",
4094 Applicability::MachineApplicable
4098 err.span_label(arrow_span,
4099 "while parsing the `match` arm starting here");
4105 self.eat(&token::Comma);
4116 /// Parses an expression.
4118 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
4119 self.parse_expr_res(Restrictions::empty(), None)
4122 /// Evaluates the closure with restrictions in place.
4124 /// Afters the closure is evaluated, restrictions are reset.
4125 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
4126 where F: FnOnce(&mut Self) -> T
4128 let old = self.restrictions;
4129 self.restrictions = r;
4131 self.restrictions = old;
4136 /// Parses an expression, subject to the given restrictions.
4138 fn parse_expr_res(&mut self, r: Restrictions,
4139 already_parsed_attrs: Option<ThinVec<Attribute>>)
4140 -> PResult<'a, P<Expr>> {
4141 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
4144 /// Parses the RHS of a local variable declaration (e.g., '= 14;').
4145 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
4146 if self.eat(&token::Eq) {
4147 Ok(Some(self.parse_expr()?))
4149 Ok(Some(self.parse_expr()?))
4155 /// Parses patterns, separated by '|' s.
4156 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
4157 // Allow a '|' before the pats (RFC 1925 + RFC 2530)
4158 self.eat(&token::BinOp(token::Or));
4160 let mut pats = Vec::new();
4162 pats.push(self.parse_top_level_pat()?);
4164 if self.token == token::OrOr {
4165 let mut err = self.struct_span_err(self.span,
4166 "unexpected token `||` after pattern");
4167 err.span_suggestion(
4169 "use a single `|` to specify multiple patterns",
4171 Applicability::MachineApplicable
4175 } else if self.eat(&token::BinOp(token::Or)) {
4183 // Parses a parenthesized list of patterns like
4184 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
4185 // - a vector of the patterns that were parsed
4186 // - an option indicating the index of the `..` element
4187 // - a boolean indicating whether a trailing comma was present.
4188 // Trailing commas are significant because (p) and (p,) are different patterns.
4189 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4190 self.expect(&token::OpenDelim(token::Paren))?;
4191 let result = self.parse_pat_list()?;
4192 self.expect(&token::CloseDelim(token::Paren))?;
4196 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4197 let mut fields = Vec::new();
4198 let mut ddpos = None;
4199 let mut trailing_comma = false;
4201 if self.eat(&token::DotDot) {
4202 if ddpos.is_none() {
4203 ddpos = Some(fields.len());
4205 // Emit a friendly error, ignore `..` and continue parsing
4206 self.struct_span_err(
4208 "`..` can only be used once per tuple or tuple struct pattern",
4210 .span_label(self.prev_span, "can only be used once per pattern")
4213 } else if !self.check(&token::CloseDelim(token::Paren)) {
4214 fields.push(self.parse_pat(None)?);
4219 trailing_comma = self.eat(&token::Comma);
4220 if !trailing_comma {
4225 if ddpos == Some(fields.len()) && trailing_comma {
4226 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
4227 let msg = "trailing comma is not permitted after `..`";
4228 self.struct_span_err(self.prev_span, msg)
4229 .span_label(self.prev_span, msg)
4233 Ok((fields, ddpos, trailing_comma))
4236 fn parse_pat_vec_elements(
4238 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
4239 let mut before = Vec::new();
4240 let mut slice = None;
4241 let mut after = Vec::new();
4242 let mut first = true;
4243 let mut before_slice = true;
4245 while self.token != token::CloseDelim(token::Bracket) {
4249 self.expect(&token::Comma)?;
4251 if self.token == token::CloseDelim(token::Bracket)
4252 && (before_slice || !after.is_empty()) {
4258 if self.eat(&token::DotDot) {
4260 if self.check(&token::Comma) ||
4261 self.check(&token::CloseDelim(token::Bracket)) {
4262 slice = Some(P(Pat {
4263 id: ast::DUMMY_NODE_ID,
4264 node: PatKind::Wild,
4265 span: self.prev_span,
4267 before_slice = false;
4273 let subpat = self.parse_pat(None)?;
4274 if before_slice && self.eat(&token::DotDot) {
4275 slice = Some(subpat);
4276 before_slice = false;
4277 } else if before_slice {
4278 before.push(subpat);
4284 Ok((before, slice, after))
4290 attrs: Vec<Attribute>
4291 ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
4292 // Check if a colon exists one ahead. This means we're parsing a fieldname.
4294 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
4295 // Parsing a pattern of the form "fieldname: pat"
4296 let fieldname = self.parse_field_name()?;
4298 let pat = self.parse_pat(None)?;
4300 (pat, fieldname, false)
4302 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
4303 let is_box = self.eat_keyword(keywords::Box);
4304 let boxed_span = self.span;
4305 let is_ref = self.eat_keyword(keywords::Ref);
4306 let is_mut = self.eat_keyword(keywords::Mut);
4307 let fieldname = self.parse_ident()?;
4308 hi = self.prev_span;
4310 let bind_type = match (is_ref, is_mut) {
4311 (true, true) => BindingMode::ByRef(Mutability::Mutable),
4312 (true, false) => BindingMode::ByRef(Mutability::Immutable),
4313 (false, true) => BindingMode::ByValue(Mutability::Mutable),
4314 (false, false) => BindingMode::ByValue(Mutability::Immutable),
4316 let fieldpat = P(Pat {
4317 id: ast::DUMMY_NODE_ID,
4318 node: PatKind::Ident(bind_type, fieldname, None),
4319 span: boxed_span.to(hi),
4322 let subpat = if is_box {
4324 id: ast::DUMMY_NODE_ID,
4325 node: PatKind::Box(fieldpat),
4331 (subpat, fieldname, true)
4334 Ok(source_map::Spanned {
4336 node: ast::FieldPat {
4340 attrs: attrs.into(),
4345 /// Parses the fields of a struct-like pattern.
4346 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
4347 let mut fields = Vec::new();
4348 let mut etc = false;
4349 let mut ate_comma = true;
4350 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
4351 let mut etc_span = None;
4353 while self.token != token::CloseDelim(token::Brace) {
4354 let attrs = self.parse_outer_attributes()?;
4357 // check that a comma comes after every field
4359 let err = self.struct_span_err(self.prev_span, "expected `,`");
4360 if let Some(mut delayed) = delayed_err {
4367 if self.check(&token::DotDot) || self.token == token::DotDotDot {
4369 let mut etc_sp = self.span;
4371 if self.token == token::DotDotDot { // Issue #46718
4372 // Accept `...` as if it were `..` to avoid further errors
4373 let mut err = self.struct_span_err(self.span,
4374 "expected field pattern, found `...`");
4375 err.span_suggestion(
4377 "to omit remaining fields, use one fewer `.`",
4379 Applicability::MachineApplicable
4383 self.bump(); // `..` || `...`
4385 if self.token == token::CloseDelim(token::Brace) {
4386 etc_span = Some(etc_sp);
4389 let token_str = self.this_token_descr();
4390 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
4392 err.span_label(self.span, "expected `}`");
4393 let mut comma_sp = None;
4394 if self.token == token::Comma { // Issue #49257
4395 etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
4396 err.span_label(etc_sp,
4397 "`..` must be at the end and cannot have a trailing comma");
4398 comma_sp = Some(self.span);
4403 etc_span = Some(etc_sp.until(self.span));
4404 if self.token == token::CloseDelim(token::Brace) {
4405 // If the struct looks otherwise well formed, recover and continue.
4406 if let Some(sp) = comma_sp {
4407 err.span_suggestion_short(
4409 "remove this comma",
4411 Applicability::MachineApplicable,
4416 } else if self.token.is_ident() && ate_comma {
4417 // Accept fields coming after `..,`.
4418 // This way we avoid "pattern missing fields" errors afterwards.
4419 // We delay this error until the end in order to have a span for a
4421 if let Some(mut delayed_err) = delayed_err {
4425 delayed_err = Some(err);
4428 if let Some(mut err) = delayed_err {
4435 fields.push(match self.parse_pat_field(lo, attrs) {
4438 if let Some(mut delayed_err) = delayed_err {
4444 ate_comma = self.eat(&token::Comma);
4447 if let Some(mut err) = delayed_err {
4448 if let Some(etc_span) = etc_span {
4449 err.multipart_suggestion(
4450 "move the `..` to the end of the field list",
4452 (etc_span, String::new()),
4453 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4455 Applicability::MachineApplicable,
4460 return Ok((fields, etc));
4463 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4464 if self.token.is_path_start() {
4466 let (qself, path) = if self.eat_lt() {
4467 // Parse a qualified path
4468 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4471 // Parse an unqualified path
4472 (None, self.parse_path(PathStyle::Expr)?)
4474 let hi = self.prev_span;
4475 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4477 self.parse_literal_maybe_minus()
4481 // helper function to decide whether to parse as ident binding or to try to do
4482 // something more complex like range patterns
4483 fn parse_as_ident(&mut self) -> bool {
4484 self.look_ahead(1, |t| match *t {
4485 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4486 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4487 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4488 // range pattern branch
4489 token::DotDot => None,
4491 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4492 token::Comma | token::CloseDelim(token::Bracket) => true,
4497 /// A wrapper around `parse_pat` with some special error handling for the
4498 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4499 /// to subpatterns within such).
4500 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4501 let pat = self.parse_pat(None)?;
4502 if self.token == token::Comma {
4503 // An unexpected comma after a top-level pattern is a clue that the
4504 // user (perhaps more accustomed to some other language) forgot the
4505 // parentheses in what should have been a tuple pattern; return a
4506 // suggestion-enhanced error here rather than choking on the comma
4508 let comma_span = self.span;
4510 if let Err(mut err) = self.parse_pat_list() {
4511 // We didn't expect this to work anyway; we just wanted
4512 // to advance to the end of the comma-sequence so we know
4513 // the span to suggest parenthesizing
4516 let seq_span = pat.span.to(self.prev_span);
4517 let mut err = self.struct_span_err(comma_span,
4518 "unexpected `,` in pattern");
4519 if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4520 err.span_suggestion(
4522 "try adding parentheses to match on a tuple..",
4523 format!("({})", seq_snippet),
4524 Applicability::MachineApplicable
4527 "..or a vertical bar to match on multiple alternatives",
4528 format!("{}", seq_snippet.replace(",", " |")),
4529 Applicability::MachineApplicable
4537 /// Parses a pattern.
4538 pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4539 self.parse_pat_with_range_pat(true, expected)
4542 /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
4544 fn parse_pat_with_range_pat(
4546 allow_range_pat: bool,
4547 expected: Option<&'static str>,
4548 ) -> PResult<'a, P<Pat>> {
4549 maybe_whole!(self, NtPat, |x| x);
4554 token::BinOp(token::And) | token::AndAnd => {
4555 // Parse &pat / &mut pat
4557 let mutbl = self.parse_mutability();
4558 if let token::Lifetime(ident) = self.token {
4559 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4561 err.span_label(self.span, "unexpected lifetime");
4564 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4565 pat = PatKind::Ref(subpat, mutbl);
4567 token::OpenDelim(token::Paren) => {
4568 // Parse (pat,pat,pat,...) as tuple pattern
4569 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4570 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4571 PatKind::Paren(fields.into_iter().nth(0).unwrap())
4573 PatKind::Tuple(fields, ddpos)
4576 token::OpenDelim(token::Bracket) => {
4577 // Parse [pat,pat,...] as slice pattern
4579 let (before, slice, after) = self.parse_pat_vec_elements()?;
4580 self.expect(&token::CloseDelim(token::Bracket))?;
4581 pat = PatKind::Slice(before, slice, after);
4583 // At this point, token != &, &&, (, [
4584 _ => if self.eat_keyword(keywords::Underscore) {
4586 pat = PatKind::Wild;
4587 } else if self.eat_keyword(keywords::Mut) {
4588 // Parse mut ident @ pat / mut ref ident @ pat
4589 let mutref_span = self.prev_span.to(self.span);
4590 let binding_mode = if self.eat_keyword(keywords::Ref) {
4592 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4595 "try switching the order",
4597 Applicability::MachineApplicable
4599 BindingMode::ByRef(Mutability::Mutable)
4601 BindingMode::ByValue(Mutability::Mutable)
4603 pat = self.parse_pat_ident(binding_mode)?;
4604 } else if self.eat_keyword(keywords::Ref) {
4605 // Parse ref ident @ pat / ref mut ident @ pat
4606 let mutbl = self.parse_mutability();
4607 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4608 } else if self.eat_keyword(keywords::Box) {
4610 let subpat = self.parse_pat_with_range_pat(false, None)?;
4611 pat = PatKind::Box(subpat);
4612 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4613 self.parse_as_ident() {
4614 // Parse ident @ pat
4615 // This can give false positives and parse nullary enums,
4616 // they are dealt with later in resolve
4617 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4618 pat = self.parse_pat_ident(binding_mode)?;
4619 } else if self.token.is_path_start() {
4620 // Parse pattern starting with a path
4621 let (qself, path) = if self.eat_lt() {
4622 // Parse a qualified path
4623 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4626 // Parse an unqualified path
4627 (None, self.parse_path(PathStyle::Expr)?)
4630 token::Not if qself.is_none() => {
4631 // Parse macro invocation
4633 let (delim, tts) = self.expect_delimited_token_tree()?;
4634 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4635 pat = PatKind::Mac(mac);
4637 token::DotDotDot | token::DotDotEq | token::DotDot => {
4638 let end_kind = match self.token {
4639 token::DotDot => RangeEnd::Excluded,
4640 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4641 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4642 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4645 let op_span = self.span;
4647 let span = lo.to(self.prev_span);
4648 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4650 let end = self.parse_pat_range_end()?;
4651 let op = Spanned { span: op_span, node: end_kind };
4652 pat = PatKind::Range(begin, end, op);
4654 token::OpenDelim(token::Brace) => {
4655 if qself.is_some() {
4656 let msg = "unexpected `{` after qualified path";
4657 let mut err = self.fatal(msg);
4658 err.span_label(self.span, msg);
4661 // Parse struct pattern
4663 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4665 self.recover_stmt();
4669 pat = PatKind::Struct(path, fields, etc);
4671 token::OpenDelim(token::Paren) => {
4672 if qself.is_some() {
4673 let msg = "unexpected `(` after qualified path";
4674 let mut err = self.fatal(msg);
4675 err.span_label(self.span, msg);
4678 // Parse tuple struct or enum pattern
4679 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4680 pat = PatKind::TupleStruct(path, fields, ddpos)
4682 _ => pat = PatKind::Path(qself, path),
4685 // Try to parse everything else as literal with optional minus
4686 match self.parse_literal_maybe_minus() {
4688 let op_span = self.span;
4689 if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4690 self.check(&token::DotDotDot) {
4691 let end_kind = if self.eat(&token::DotDotDot) {
4692 RangeEnd::Included(RangeSyntax::DotDotDot)
4693 } else if self.eat(&token::DotDotEq) {
4694 RangeEnd::Included(RangeSyntax::DotDotEq)
4695 } else if self.eat(&token::DotDot) {
4698 panic!("impossible case: we already matched \
4699 on a range-operator token")
4701 let end = self.parse_pat_range_end()?;
4702 let op = Spanned { span: op_span, node: end_kind };
4703 pat = PatKind::Range(begin, end, op);
4705 pat = PatKind::Lit(begin);
4709 self.cancel(&mut err);
4710 let expected = expected.unwrap_or("pattern");
4712 "expected {}, found {}",
4714 self.this_token_descr(),
4716 let mut err = self.fatal(&msg);
4717 err.span_label(self.span, format!("expected {}", expected));
4724 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4725 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4727 if !allow_range_pat {
4730 _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4732 PatKind::Range(..) => {
4733 let mut err = self.struct_span_err(
4735 "the range pattern here has ambiguous interpretation",
4737 err.span_suggestion(
4739 "add parentheses to clarify the precedence",
4740 format!("({})", pprust::pat_to_string(&pat)),
4741 // "ambiguous interpretation" implies that we have to be guessing
4742 Applicability::MaybeIncorrect
4753 /// Parses `ident` or `ident @ pat`.
4754 /// used by the copy foo and ref foo patterns to give a good
4755 /// error message when parsing mistakes like `ref foo(a, b)`.
4756 fn parse_pat_ident(&mut self,
4757 binding_mode: ast::BindingMode)
4758 -> PResult<'a, PatKind> {
4759 let ident = self.parse_ident()?;
4760 let sub = if self.eat(&token::At) {
4761 Some(self.parse_pat(Some("binding pattern"))?)
4766 // just to be friendly, if they write something like
4768 // we end up here with ( as the current token. This shortly
4769 // leads to a parse error. Note that if there is no explicit
4770 // binding mode then we do not end up here, because the lookahead
4771 // will direct us over to parse_enum_variant()
4772 if self.token == token::OpenDelim(token::Paren) {
4773 return Err(self.span_fatal(
4775 "expected identifier, found enum pattern"))
4778 Ok(PatKind::Ident(binding_mode, ident, sub))
4781 /// Parses a local variable declaration.
4782 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4783 let lo = self.prev_span;
4784 let pat = self.parse_top_level_pat()?;
4786 let (err, ty) = if self.eat(&token::Colon) {
4787 // Save the state of the parser before parsing type normally, in case there is a `:`
4788 // instead of an `=` typo.
4789 let parser_snapshot_before_type = self.clone();
4790 let colon_sp = self.prev_span;
4791 match self.parse_ty() {
4792 Ok(ty) => (None, Some(ty)),
4794 // Rewind to before attempting to parse the type and continue parsing
4795 let parser_snapshot_after_type = self.clone();
4796 mem::replace(self, parser_snapshot_before_type);
4798 let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4799 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4800 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4806 let init = match (self.parse_initializer(err.is_some()), err) {
4807 (Ok(init), None) => { // init parsed, ty parsed
4810 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4811 // Could parse the type as if it were the initializer, it is likely there was a
4812 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4813 err.span_suggestion_short(
4815 "use `=` if you meant to assign",
4817 Applicability::MachineApplicable
4820 // As this was parsed successfully, continue as if the code has been fixed for the
4821 // rest of the file. It will still fail due to the emitted error, but we avoid
4825 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4827 // Couldn't parse the type nor the initializer, only raise the type error and
4828 // return to the parser state before parsing the type as the initializer.
4829 // let x: <parse_error>;
4830 mem::replace(self, snapshot);
4833 (Err(err), None) => { // init error, ty parsed
4834 // Couldn't parse the initializer and we're not attempting to recover a failed
4835 // parse of the type, return the error.
4839 let hi = if self.token == token::Semi {
4848 id: ast::DUMMY_NODE_ID,
4854 /// Parses a structure field.
4855 fn parse_name_and_ty(&mut self,
4858 attrs: Vec<Attribute>)
4859 -> PResult<'a, StructField> {
4860 let name = self.parse_ident()?;
4861 self.expect(&token::Colon)?;
4862 let ty = self.parse_ty()?;
4864 span: lo.to(self.prev_span),
4867 id: ast::DUMMY_NODE_ID,
4873 /// Emits an expected-item-after-attributes error.
4874 fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a, ()> {
4875 let message = match attrs.last() {
4876 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4877 _ => "expected item after attributes",
4880 let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
4881 if attrs.last().unwrap().is_sugared_doc {
4882 err.span_label(self.prev_span, "this doc comment doesn't document anything");
4887 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4888 /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4889 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4890 Ok(self.parse_stmt_(true))
4893 // Eat tokens until we can be relatively sure we reached the end of the
4894 // statement. This is something of a best-effort heuristic.
4896 // We terminate when we find an unmatched `}` (without consuming it).
4897 fn recover_stmt(&mut self) {
4898 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4901 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4902 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4903 // approximate - it can mean we break too early due to macros, but that
4904 // should only lead to sub-optimal recovery, not inaccurate parsing).
4906 // If `break_on_block` is `Break`, then we will stop consuming tokens
4907 // after finding (and consuming) a brace-delimited block.
4908 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4909 let mut brace_depth = 0;
4910 let mut bracket_depth = 0;
4911 let mut in_block = false;
4912 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4913 break_on_semi, break_on_block);
4915 debug!("recover_stmt_ loop {:?}", self.token);
4917 token::OpenDelim(token::DelimToken::Brace) => {
4920 if break_on_block == BlockMode::Break &&
4922 bracket_depth == 0 {
4926 token::OpenDelim(token::DelimToken::Bracket) => {
4930 token::CloseDelim(token::DelimToken::Brace) => {
4931 if brace_depth == 0 {
4932 debug!("recover_stmt_ return - close delim {:?}", self.token);
4937 if in_block && bracket_depth == 0 && brace_depth == 0 {
4938 debug!("recover_stmt_ return - block end {:?}", self.token);
4942 token::CloseDelim(token::DelimToken::Bracket) => {
4944 if bracket_depth < 0 {
4950 debug!("recover_stmt_ return - Eof");
4955 if break_on_semi == SemiColonMode::Break &&
4957 bracket_depth == 0 {
4958 debug!("recover_stmt_ return - Semi");
4963 if break_on_semi == SemiColonMode::Comma &&
4965 bracket_depth == 0 {
4966 debug!("recover_stmt_ return - Semi");
4979 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4980 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4982 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4987 fn is_async_block(&mut self) -> bool {
4988 self.token.is_keyword(keywords::Async) &&
4991 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
4992 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4994 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4999 fn is_do_catch_block(&mut self) -> bool {
5000 self.token.is_keyword(keywords::Do) &&
5001 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
5002 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
5003 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5006 fn is_try_block(&mut self) -> bool {
5007 self.token.is_keyword(keywords::Try) &&
5008 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
5009 self.span.rust_2018() &&
5010 // prevent `while try {} {}`, `if try {} {} else {}`, etc.
5011 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5014 fn is_union_item(&self) -> bool {
5015 self.token.is_keyword(keywords::Union) &&
5016 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
5019 fn is_crate_vis(&self) -> bool {
5020 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
5023 fn is_existential_type_decl(&self) -> bool {
5024 self.token.is_keyword(keywords::Existential) &&
5025 self.look_ahead(1, |t| t.is_keyword(keywords::Type))
5028 fn is_auto_trait_item(&mut self) -> bool {
5030 (self.token.is_keyword(keywords::Auto)
5031 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
5032 || // unsafe auto trait
5033 (self.token.is_keyword(keywords::Unsafe) &&
5034 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
5035 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
5038 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
5039 -> PResult<'a, Option<P<Item>>> {
5040 let token_lo = self.span;
5041 let (ident, def) = match self.token {
5042 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
5044 let ident = self.parse_ident()?;
5045 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
5046 match self.parse_token_tree() {
5047 TokenTree::Delimited(_, _, tts) => tts,
5048 _ => unreachable!(),
5050 } else if self.check(&token::OpenDelim(token::Paren)) {
5051 let args = self.parse_token_tree();
5052 let body = if self.check(&token::OpenDelim(token::Brace)) {
5053 self.parse_token_tree()
5058 TokenStream::new(vec![
5060 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
5068 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
5070 token::Ident(ident, _) if ident.name == "macro_rules" &&
5071 self.look_ahead(1, |t| *t == token::Not) => {
5072 let prev_span = self.prev_span;
5073 self.complain_if_pub_macro(&vis.node, prev_span);
5077 let ident = self.parse_ident()?;
5078 let (delim, tokens) = self.expect_delimited_token_tree()?;
5079 if delim != MacDelimiter::Brace {
5080 if !self.eat(&token::Semi) {
5081 let msg = "macros that expand to items must either \
5082 be surrounded with braces or followed by a semicolon";
5083 self.span_err(self.prev_span, msg);
5087 (ident, ast::MacroDef { tokens: tokens, legacy: true })
5089 _ => return Ok(None),
5092 let span = lo.to(self.prev_span);
5093 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
5096 fn parse_stmt_without_recovery(&mut self,
5097 macro_legacy_warnings: bool)
5098 -> PResult<'a, Option<Stmt>> {
5099 maybe_whole!(self, NtStmt, |x| Some(x));
5101 let attrs = self.parse_outer_attributes()?;
5104 Ok(Some(if self.eat_keyword(keywords::Let) {
5106 id: ast::DUMMY_NODE_ID,
5107 node: StmtKind::Local(self.parse_local(attrs.into())?),
5108 span: lo.to(self.prev_span),
5110 } else if let Some(macro_def) = self.eat_macro_def(
5112 &source_map::respan(lo, VisibilityKind::Inherited),
5116 id: ast::DUMMY_NODE_ID,
5117 node: StmtKind::Item(macro_def),
5118 span: lo.to(self.prev_span),
5120 // Starts like a simple path, being careful to avoid contextual keywords
5121 // such as a union items, item with `crate` visibility or auto trait items.
5122 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
5123 // like a path (1 token), but it fact not a path.
5124 // `union::b::c` - path, `union U { ... }` - not a path.
5125 // `crate::b::c` - path, `crate struct S;` - not a path.
5126 } else if self.token.is_path_start() &&
5127 !self.token.is_qpath_start() &&
5128 !self.is_union_item() &&
5129 !self.is_crate_vis() &&
5130 !self.is_existential_type_decl() &&
5131 !self.is_auto_trait_item() {
5132 let pth = self.parse_path(PathStyle::Expr)?;
5134 if !self.eat(&token::Not) {
5135 let expr = if self.check(&token::OpenDelim(token::Brace)) {
5136 self.parse_struct_expr(lo, pth, ThinVec::new())?
5138 let hi = self.prev_span;
5139 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
5142 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
5143 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
5144 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
5147 return Ok(Some(Stmt {
5148 id: ast::DUMMY_NODE_ID,
5149 node: StmtKind::Expr(expr),
5150 span: lo.to(self.prev_span),
5154 // it's a macro invocation
5155 let id = match self.token {
5156 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
5157 _ => self.parse_ident()?,
5160 // check that we're pointing at delimiters (need to check
5161 // again after the `if`, because of `parse_ident`
5162 // consuming more tokens).
5164 token::OpenDelim(_) => {}
5166 // we only expect an ident if we didn't parse one
5168 let ident_str = if id.name == keywords::Invalid.name() {
5173 let tok_str = self.this_token_descr();
5174 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
5177 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
5182 let (delim, tts) = self.expect_delimited_token_tree()?;
5183 let hi = self.prev_span;
5185 let style = if delim == MacDelimiter::Brace {
5186 MacStmtStyle::Braces
5188 MacStmtStyle::NoBraces
5191 if id.name == keywords::Invalid.name() {
5192 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
5193 let node = if delim == MacDelimiter::Brace ||
5194 self.token == token::Semi || self.token == token::Eof {
5195 StmtKind::Mac(P((mac, style, attrs.into())))
5197 // We used to incorrectly stop parsing macro-expanded statements here.
5198 // If the next token will be an error anyway but could have parsed with the
5199 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
5200 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
5201 // These can continue an expression, so we can't stop parsing and warn.
5202 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
5203 token::BinOp(token::Minus) | token::BinOp(token::Star) |
5204 token::BinOp(token::And) | token::BinOp(token::Or) |
5205 token::AndAnd | token::OrOr |
5206 token::DotDot | token::DotDotDot | token::DotDotEq => false,
5209 self.warn_missing_semicolon();
5210 StmtKind::Mac(P((mac, style, attrs.into())))
5212 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
5213 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
5214 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
5218 id: ast::DUMMY_NODE_ID,
5223 // if it has a special ident, it's definitely an item
5225 // Require a semicolon or braces.
5226 if style != MacStmtStyle::Braces {
5227 if !self.eat(&token::Semi) {
5228 self.span_err(self.prev_span,
5229 "macros that expand to items must \
5230 either be surrounded with braces or \
5231 followed by a semicolon");
5234 let span = lo.to(hi);
5236 id: ast::DUMMY_NODE_ID,
5238 node: StmtKind::Item({
5240 span, id /*id is good here*/,
5241 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
5242 respan(lo, VisibilityKind::Inherited),
5248 // FIXME: Bad copy of attrs
5249 let old_directory_ownership =
5250 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
5251 let item = self.parse_item_(attrs.clone(), false, true)?;
5252 self.directory.ownership = old_directory_ownership;
5256 id: ast::DUMMY_NODE_ID,
5257 span: lo.to(i.span),
5258 node: StmtKind::Item(i),
5261 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
5262 if !attrs.is_empty() {
5263 if s.prev_token_kind == PrevTokenKind::DocComment {
5264 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
5265 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
5266 s.span_err(s.span, "expected statement after outer attribute");
5271 // Do not attempt to parse an expression if we're done here.
5272 if self.token == token::Semi {
5273 unused_attrs(&attrs, self);
5278 if self.token == token::CloseDelim(token::Brace) {
5279 unused_attrs(&attrs, self);
5283 // Remainder are line-expr stmts.
5284 let e = self.parse_expr_res(
5285 Restrictions::STMT_EXPR, Some(attrs.into()))?;
5287 id: ast::DUMMY_NODE_ID,
5288 span: lo.to(e.span),
5289 node: StmtKind::Expr(e),
5296 /// Checks if this expression is a successfully parsed statement.
5297 fn expr_is_complete(&mut self, e: &Expr) -> bool {
5298 self.restrictions.contains(Restrictions::STMT_EXPR) &&
5299 !classify::expr_requires_semi_to_be_stmt(e)
5302 /// Parses a block. No inner attributes are allowed.
5303 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
5304 maybe_whole!(self, NtBlock, |x| x);
5308 if !self.eat(&token::OpenDelim(token::Brace)) {
5310 let tok = self.this_token_descr();
5311 let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
5312 let do_not_suggest_help =
5313 self.token.is_keyword(keywords::In) || self.token == token::Colon;
5315 if self.token.is_ident_named("and") {
5316 e.span_suggestion_short(
5318 "use `&&` instead of `and` for the boolean operator",
5320 Applicability::MaybeIncorrect,
5323 if self.token.is_ident_named("or") {
5324 e.span_suggestion_short(
5326 "use `||` instead of `or` for the boolean operator",
5328 Applicability::MaybeIncorrect,
5332 // Check to see if the user has written something like
5337 // Which is valid in other languages, but not Rust.
5338 match self.parse_stmt_without_recovery(false) {
5340 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
5341 || do_not_suggest_help {
5342 // if the next token is an open brace (e.g., `if a b {`), the place-
5343 // inside-a-block suggestion would be more likely wrong than right
5344 e.span_label(sp, "expected `{`");
5347 let mut stmt_span = stmt.span;
5348 // expand the span to include the semicolon, if it exists
5349 if self.eat(&token::Semi) {
5350 stmt_span = stmt_span.with_hi(self.prev_span.hi());
5352 let sugg = pprust::to_string(|s| {
5353 use crate::print::pprust::{PrintState, INDENT_UNIT};
5354 s.ibox(INDENT_UNIT)?;
5356 s.print_stmt(&stmt)?;
5357 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
5361 "try placing this code inside a block",
5363 // speculative, has been misleading in the past (closed Issue #46836)
5364 Applicability::MaybeIncorrect
5368 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5369 self.cancel(&mut e);
5373 e.span_label(sp, "expected `{`");
5377 self.parse_block_tail(lo, BlockCheckMode::Default)
5380 /// Parses a block. Inner attributes are allowed.
5381 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
5382 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
5385 self.expect(&token::OpenDelim(token::Brace))?;
5386 Ok((self.parse_inner_attributes()?,
5387 self.parse_block_tail(lo, BlockCheckMode::Default)?))
5390 /// Parses the rest of a block expression or function body.
5391 /// Precondition: already parsed the '{'.
5392 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
5393 let mut stmts = vec![];
5394 while !self.eat(&token::CloseDelim(token::Brace)) {
5395 let stmt = match self.parse_full_stmt(false) {
5398 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
5400 id: ast::DUMMY_NODE_ID,
5401 node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
5407 if let Some(stmt) = stmt {
5409 } else if self.token == token::Eof {
5412 // Found only `;` or `}`.
5418 id: ast::DUMMY_NODE_ID,
5420 span: lo.to(self.prev_span),
5424 /// Parses a statement, including the trailing semicolon.
5425 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5426 // skip looking for a trailing semicolon when we have an interpolated statement
5427 maybe_whole!(self, NtStmt, |x| Some(x));
5429 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5431 None => return Ok(None),
5435 StmtKind::Expr(ref expr) if self.token != token::Eof => {
5436 // expression without semicolon
5437 if classify::expr_requires_semi_to_be_stmt(expr) {
5438 // Just check for errors and recover; do not eat semicolon yet.
5440 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5443 self.recover_stmt();
5447 StmtKind::Local(..) => {
5448 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5449 if macro_legacy_warnings && self.token != token::Semi {
5450 self.warn_missing_semicolon();
5452 self.expect_one_of(&[], &[token::Semi])?;
5458 if self.eat(&token::Semi) {
5459 stmt = stmt.add_trailing_semicolon();
5462 stmt.span = stmt.span.with_hi(self.prev_span.hi());
5466 fn warn_missing_semicolon(&self) {
5467 self.diagnostic().struct_span_warn(self.span, {
5468 &format!("expected `;`, found {}", self.this_token_descr())
5470 "This was erroneously allowed and will become a hard error in a future release"
5474 fn err_dotdotdot_syntax(&self, span: Span) {
5475 self.diagnostic().struct_span_err(span, {
5476 "unexpected token: `...`"
5478 span, "use `..` for an exclusive range", "..".to_owned(),
5479 Applicability::MaybeIncorrect
5481 span, "or `..=` for an inclusive range", "..=".to_owned(),
5482 Applicability::MaybeIncorrect
5486 /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
5489 /// BOUND = TY_BOUND | LT_BOUND
5490 /// LT_BOUND = LIFETIME (e.g., `'a`)
5491 /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5492 /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5494 fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
5495 let mut bounds = Vec::new();
5497 // This needs to be synchronized with `Token::can_begin_bound`.
5498 let is_bound_start = self.check_path() || self.check_lifetime() ||
5499 self.check(&token::Question) ||
5500 self.check_keyword(keywords::For) ||
5501 self.check(&token::OpenDelim(token::Paren));
5504 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5505 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5506 if self.token.is_lifetime() {
5507 if let Some(question_span) = question {
5508 self.span_err(question_span,
5509 "`?` may only modify trait bounds, not lifetime bounds");
5511 bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5513 self.expect(&token::CloseDelim(token::Paren))?;
5514 self.span_err(self.prev_span,
5515 "parenthesized lifetime bounds are not supported");
5518 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5519 let path = self.parse_path(PathStyle::Type)?;
5521 self.expect(&token::CloseDelim(token::Paren))?;
5523 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
5524 let modifier = if question.is_some() {
5525 TraitBoundModifier::Maybe
5527 TraitBoundModifier::None
5529 bounds.push(GenericBound::Trait(poly_trait, modifier));
5535 if !allow_plus || !self.eat_plus() {
5543 fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
5544 self.parse_generic_bounds_common(true)
5547 /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5550 /// BOUND = LT_BOUND (e.g., `'a`)
5552 fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5553 let mut lifetimes = Vec::new();
5554 while self.check_lifetime() {
5555 lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5557 if !self.eat_plus() {
5564 /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
5565 fn parse_ty_param(&mut self,
5566 preceding_attrs: Vec<Attribute>)
5567 -> PResult<'a, GenericParam> {
5568 let ident = self.parse_ident()?;
5570 // Parse optional colon and param bounds.
5571 let bounds = if self.eat(&token::Colon) {
5572 self.parse_generic_bounds()?
5577 let default = if self.eat(&token::Eq) {
5578 Some(self.parse_ty()?)
5585 id: ast::DUMMY_NODE_ID,
5586 attrs: preceding_attrs.into(),
5588 kind: GenericParamKind::Type {
5594 /// Parses the following grammar:
5596 /// TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5597 fn parse_trait_item_assoc_ty(&mut self)
5598 -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5599 let ident = self.parse_ident()?;
5600 let mut generics = self.parse_generics()?;
5602 // Parse optional colon and param bounds.
5603 let bounds = if self.eat(&token::Colon) {
5604 self.parse_generic_bounds()?
5608 generics.where_clause = self.parse_where_clause()?;
5610 let default = if self.eat(&token::Eq) {
5611 Some(self.parse_ty()?)
5615 self.expect(&token::Semi)?;
5617 Ok((ident, TraitItemKind::Type(bounds, default), generics))
5620 fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
5621 self.expect_keyword(keywords::Const)?;
5622 let ident = self.parse_ident()?;
5623 self.expect(&token::Colon)?;
5624 let ty = self.parse_ty()?;
5628 id: ast::DUMMY_NODE_ID,
5629 attrs: preceding_attrs.into(),
5631 kind: GenericParamKind::Const {
5637 /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
5638 /// a trailing comma and erroneous trailing attributes.
5639 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5640 let mut params = Vec::new();
5642 let attrs = self.parse_outer_attributes()?;
5643 if self.check_lifetime() {
5644 let lifetime = self.expect_lifetime();
5645 // Parse lifetime parameter.
5646 let bounds = if self.eat(&token::Colon) {
5647 self.parse_lt_param_bounds()
5651 params.push(ast::GenericParam {
5652 ident: lifetime.ident,
5654 attrs: attrs.into(),
5656 kind: ast::GenericParamKind::Lifetime,
5658 } else if self.check_keyword(keywords::Const) {
5659 // Parse const parameter.
5660 params.push(self.parse_const_param(attrs)?);
5661 } else if self.check_ident() {
5662 // Parse type parameter.
5663 params.push(self.parse_ty_param(attrs)?);
5665 // Check for trailing attributes and stop parsing.
5666 if !attrs.is_empty() {
5667 if !params.is_empty() {
5668 self.struct_span_err(
5670 &format!("trailing attribute after generic parameter"),
5672 .span_label(attrs[0].span, "attributes must go before parameters")
5675 self.struct_span_err(
5677 &format!("attribute without generic parameters"),
5681 "attributes are only permitted when preceding parameters",
5689 if !self.eat(&token::Comma) {
5696 /// Parses a set of optional generic type parameter declarations. Where
5697 /// clauses are not parsed here, and must be added later via
5698 /// `parse_where_clause()`.
5700 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5701 /// | ( < lifetimes , typaramseq ( , )? > )
5702 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
5703 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5704 maybe_whole!(self, NtGenerics, |x| x);
5706 let span_lo = self.span;
5708 let params = self.parse_generic_params()?;
5712 where_clause: WhereClause {
5713 id: ast::DUMMY_NODE_ID,
5714 predicates: Vec::new(),
5715 span: syntax_pos::DUMMY_SP,
5717 span: span_lo.to(self.prev_span),
5720 Ok(ast::Generics::default())
5724 /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5725 /// For the purposes of understanding the parsing logic of generic arguments, this function
5726 /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5727 /// had the correct amount of leading angle brackets.
5729 /// ```ignore (diagnostics)
5730 /// bar::<<<<T as Foo>::Output>();
5731 /// ^^ help: remove extra angle brackets
5733 fn parse_generic_args_with_leaning_angle_bracket_recovery(
5737 ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5738 // We need to detect whether there are extra leading left angle brackets and produce an
5739 // appropriate error and suggestion. This cannot be implemented by looking ahead at
5740 // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5741 // then there won't be matching `>` tokens to find.
5743 // To explain how this detection works, consider the following example:
5745 // ```ignore (diagnostics)
5746 // bar::<<<<T as Foo>::Output>();
5747 // ^^ help: remove extra angle brackets
5750 // Parsing of the left angle brackets starts in this function. We start by parsing the
5751 // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5754 // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5755 // *Unmatched count:* 1
5756 // *`parse_path_segment` calls deep:* 0
5758 // This has the effect of recursing as this function is called if a `<` character
5759 // is found within the expected generic arguments:
5761 // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5762 // *Unmatched count:* 2
5763 // *`parse_path_segment` calls deep:* 1
5765 // Eventually we will have recursed until having consumed all of the `<` tokens and
5766 // this will be reflected in the count:
5768 // *Upcoming tokens:* `T as Foo>::Output>;`
5769 // *Unmatched count:* 4
5770 // `parse_path_segment` calls deep:* 3
5772 // The parser will continue until reaching the first `>` - this will decrement the
5773 // unmatched angle bracket count and return to the parent invocation of this function
5774 // having succeeded in parsing:
5776 // *Upcoming tokens:* `::Output>;`
5777 // *Unmatched count:* 3
5778 // *`parse_path_segment` calls deep:* 2
5780 // This will continue until the next `>` character which will also return successfully
5781 // to the parent invocation of this function and decrement the count:
5783 // *Upcoming tokens:* `;`
5784 // *Unmatched count:* 2
5785 // *`parse_path_segment` calls deep:* 1
5787 // At this point, this function will expect to find another matching `>` character but
5788 // won't be able to and will return an error. This will continue all the way up the
5789 // call stack until the first invocation:
5791 // *Upcoming tokens:* `;`
5792 // *Unmatched count:* 2
5793 // *`parse_path_segment` calls deep:* 0
5795 // In doing this, we have managed to work out how many unmatched leading left angle
5796 // brackets there are, but we cannot recover as the unmatched angle brackets have
5797 // already been consumed. To remedy this, we keep a snapshot of the parser state
5798 // before we do the above. We can then inspect whether we ended up with a parsing error
5799 // and unmatched left angle brackets and if so, restore the parser state before we
5800 // consumed any `<` characters to emit an error and consume the erroneous tokens to
5801 // recover by attempting to parse again.
5803 // In practice, the recursion of this function is indirect and there will be other
5804 // locations that consume some `<` characters - as long as we update the count when
5805 // this happens, it isn't an issue.
5807 let is_first_invocation = style == PathStyle::Expr;
5808 // Take a snapshot before attempting to parse - we can restore this later.
5809 let snapshot = if is_first_invocation {
5815 debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
5816 match self.parse_generic_args() {
5817 Ok(value) => Ok(value),
5818 Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
5819 // Cancel error from being unable to find `>`. We know the error
5820 // must have been this due to a non-zero unmatched angle bracket
5824 // Swap `self` with our backup of the parser state before attempting to parse
5825 // generic arguments.
5826 let snapshot = mem::replace(self, snapshot.unwrap());
5829 "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
5830 snapshot.count={:?}",
5831 snapshot.unmatched_angle_bracket_count,
5834 // Eat the unmatched angle brackets.
5835 for _ in 0..snapshot.unmatched_angle_bracket_count {
5839 // Make a span over ${unmatched angle bracket count} characters.
5840 let span = lo.with_hi(
5841 lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
5843 let plural = snapshot.unmatched_angle_bracket_count > 1;
5848 "unmatched angle bracket{}",
5849 if plural { "s" } else { "" }
5855 "remove extra angle bracket{}",
5856 if plural { "s" } else { "" }
5859 Applicability::MachineApplicable,
5863 // Try again without unmatched angle bracket characters.
5864 self.parse_generic_args()
5870 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5871 /// possibly including trailing comma.
5872 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5873 let mut args = Vec::new();
5874 let mut bindings = Vec::new();
5875 let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new();
5876 let mut assoc_ty_bindings: Vec<Span> = Vec::new();
5878 let args_lo = self.span;
5881 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5882 // Parse lifetime argument.
5883 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5884 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
5885 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5886 // Parse associated type binding.
5888 let ident = self.parse_ident()?;
5890 let ty = self.parse_ty()?;
5891 let span = lo.to(self.prev_span);
5892 bindings.push(TypeBinding {
5893 id: ast::DUMMY_NODE_ID,
5898 assoc_ty_bindings.push(span);
5899 } else if self.check_const_arg() {
5900 // FIXME(const_generics): to distinguish between idents for types and consts,
5901 // we should introduce a GenericArg::Ident in the AST and distinguish when
5902 // lowering to the HIR. For now, idents for const args are not permitted.
5904 // Parse const argument.
5905 let expr = if let token::OpenDelim(token::Brace) = self.token {
5906 self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
5907 } else if self.token.is_ident() {
5908 // FIXME(const_generics): to distinguish between idents for types and consts,
5909 // we should introduce a GenericArg::Ident in the AST and distinguish when
5910 // lowering to the HIR. For now, idents for const args are not permitted.
5912 self.fatal("identifiers may currently not be used for const generics")
5915 // FIXME(const_generics): this currently conflicts with emplacement syntax
5916 // with negative integer literals.
5917 self.parse_literal_maybe_minus()?
5919 let value = AnonConst {
5920 id: ast::DUMMY_NODE_ID,
5923 args.push(GenericArg::Const(value));
5924 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
5925 } else if self.check_type() {
5926 // Parse type argument.
5927 args.push(GenericArg::Type(self.parse_ty()?));
5928 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
5933 if !self.eat(&token::Comma) {
5938 // FIXME: we would like to report this in ast_validation instead, but we currently do not
5939 // preserve ordering of generic parameters with respect to associated type binding, so we
5940 // lose that information after parsing.
5941 if misplaced_assoc_ty_bindings.len() > 0 {
5942 let mut err = self.struct_span_err(
5943 args_lo.to(self.prev_span),
5944 "associated type bindings must be declared after generic parameters",
5946 for span in misplaced_assoc_ty_bindings {
5949 "this associated type binding should be moved after the generic parameters",
5955 Ok((args, bindings))
5958 /// Parses an optional where-clause and places it in `generics`.
5960 /// ```ignore (only-for-syntax-highlight)
5961 /// where T : Trait<U, V> + 'b, 'a : 'b
5963 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5964 maybe_whole!(self, NtWhereClause, |x| x);
5966 let mut where_clause = WhereClause {
5967 id: ast::DUMMY_NODE_ID,
5968 predicates: Vec::new(),
5969 span: syntax_pos::DUMMY_SP,
5972 if !self.eat_keyword(keywords::Where) {
5973 return Ok(where_clause);
5975 let lo = self.prev_span;
5977 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5978 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5979 // change we parse those generics now, but report an error.
5980 if self.choose_generics_over_qpath() {
5981 let generics = self.parse_generics()?;
5982 self.struct_span_err(
5984 "generic parameters on `where` clauses are reserved for future use",
5986 .span_label(generics.span, "currently unsupported")
5992 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5993 let lifetime = self.expect_lifetime();
5994 // Bounds starting with a colon are mandatory, but possibly empty.
5995 self.expect(&token::Colon)?;
5996 let bounds = self.parse_lt_param_bounds();
5997 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5998 ast::WhereRegionPredicate {
5999 span: lo.to(self.prev_span),
6004 } else if self.check_type() {
6005 // Parse optional `for<'a, 'b>`.
6006 // This `for` is parsed greedily and applies to the whole predicate,
6007 // the bounded type can have its own `for` applying only to it.
6008 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
6009 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
6010 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
6011 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
6013 // Parse type with mandatory colon and (possibly empty) bounds,
6014 // or with mandatory equality sign and the second type.
6015 let ty = self.parse_ty()?;
6016 if self.eat(&token::Colon) {
6017 let bounds = self.parse_generic_bounds()?;
6018 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
6019 ast::WhereBoundPredicate {
6020 span: lo.to(self.prev_span),
6021 bound_generic_params: lifetime_defs,
6026 // FIXME: Decide what should be used here, `=` or `==`.
6027 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
6028 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
6029 let rhs_ty = self.parse_ty()?;
6030 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
6031 ast::WhereEqPredicate {
6032 span: lo.to(self.prev_span),
6035 id: ast::DUMMY_NODE_ID,
6039 return self.unexpected();
6045 if !self.eat(&token::Comma) {
6050 where_clause.span = lo.to(self.prev_span);
6054 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
6055 -> PResult<'a, (Vec<Arg> , bool)> {
6056 self.expect(&token::OpenDelim(token::Paren))?;
6059 let mut variadic = false;
6060 let (args, recovered): (Vec<Option<Arg>>, bool) =
6061 self.parse_seq_to_before_end(
6062 &token::CloseDelim(token::Paren),
6063 SeqSep::trailing_allowed(token::Comma),
6065 if p.token == token::DotDotDot {
6069 if p.token != token::CloseDelim(token::Paren) {
6072 "`...` must be last in argument list for variadic function");
6076 let span = p.prev_span;
6077 if p.token == token::CloseDelim(token::Paren) {
6078 // continue parsing to present any further errors
6081 "only foreign functions are allowed to be variadic"
6083 Ok(Some(dummy_arg(span)))
6085 // this function definition looks beyond recovery, stop parsing
6087 "only foreign functions are allowed to be variadic");
6092 match p.parse_arg_general(named_args, false) {
6093 Ok(arg) => Ok(Some(arg)),
6096 let lo = p.prev_span;
6097 // Skip every token until next possible arg or end.
6098 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
6099 // Create a placeholder argument for proper arg count (#34264).
6100 let span = lo.to(p.prev_span);
6101 Ok(Some(dummy_arg(span)))
6109 self.eat(&token::CloseDelim(token::Paren));
6112 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
6114 if variadic && args.is_empty() {
6116 "variadic function must be declared with at least one named argument");
6119 Ok((args, variadic))
6122 /// Parses the argument list and result type of a function declaration.
6123 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
6125 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
6126 let ret_ty = self.parse_ret_ty(true)?;
6135 /// Returns the parsed optional self argument and whether a self shortcut was used.
6136 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
6137 let expect_ident = |this: &mut Self| match this.token {
6138 // Preserve hygienic context.
6139 token::Ident(ident, _) =>
6140 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
6143 let isolated_self = |this: &mut Self, n| {
6144 this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) &&
6145 this.look_ahead(n + 1, |t| t != &token::ModSep)
6148 // Parse optional self parameter of a method.
6149 // Only a limited set of initial token sequences is considered self parameters, anything
6150 // else is parsed as a normal function parameter list, so some lookahead is required.
6151 let eself_lo = self.span;
6152 let (eself, eself_ident, eself_hi) = match self.token {
6153 token::BinOp(token::And) => {
6159 (if isolated_self(self, 1) {
6161 SelfKind::Region(None, Mutability::Immutable)
6162 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
6163 isolated_self(self, 2) {
6166 SelfKind::Region(None, Mutability::Mutable)
6167 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6168 isolated_self(self, 2) {
6170 let lt = self.expect_lifetime();
6171 SelfKind::Region(Some(lt), Mutability::Immutable)
6172 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6173 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
6174 isolated_self(self, 3) {
6176 let lt = self.expect_lifetime();
6178 SelfKind::Region(Some(lt), Mutability::Mutable)
6181 }, expect_ident(self), self.prev_span)
6183 token::BinOp(token::Star) => {
6188 // Emit special error for `self` cases.
6189 let msg = "cannot pass `self` by raw pointer";
6190 (if isolated_self(self, 1) {
6192 self.struct_span_err(self.span, msg)
6193 .span_label(self.span, msg)
6195 SelfKind::Value(Mutability::Immutable)
6196 } else if self.look_ahead(1, |t| t.is_mutability()) &&
6197 isolated_self(self, 2) {
6200 self.struct_span_err(self.span, msg)
6201 .span_label(self.span, msg)
6203 SelfKind::Value(Mutability::Immutable)
6206 }, expect_ident(self), self.prev_span)
6208 token::Ident(..) => {
6209 if isolated_self(self, 0) {
6212 let eself_ident = expect_ident(self);
6213 let eself_hi = self.prev_span;
6214 (if self.eat(&token::Colon) {
6215 let ty = self.parse_ty()?;
6216 SelfKind::Explicit(ty, Mutability::Immutable)
6218 SelfKind::Value(Mutability::Immutable)
6219 }, eself_ident, eself_hi)
6220 } else if self.token.is_keyword(keywords::Mut) &&
6221 isolated_self(self, 1) {
6225 let eself_ident = expect_ident(self);
6226 let eself_hi = self.prev_span;
6227 (if self.eat(&token::Colon) {
6228 let ty = self.parse_ty()?;
6229 SelfKind::Explicit(ty, Mutability::Mutable)
6231 SelfKind::Value(Mutability::Mutable)
6232 }, eself_ident, eself_hi)
6237 _ => return Ok(None),
6240 let eself = source_map::respan(eself_lo.to(eself_hi), eself);
6241 Ok(Some(Arg::from_self(eself, eself_ident)))
6244 /// Parses the parameter list and result type of a function that may have a `self` parameter.
6245 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
6246 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
6248 self.expect(&token::OpenDelim(token::Paren))?;
6250 // Parse optional self argument
6251 let self_arg = self.parse_self_arg()?;
6253 // Parse the rest of the function parameter list.
6254 let sep = SeqSep::trailing_allowed(token::Comma);
6255 let (fn_inputs, recovered) = if let Some(self_arg) = self_arg {
6256 if self.check(&token::CloseDelim(token::Paren)) {
6257 (vec![self_arg], false)
6258 } else if self.eat(&token::Comma) {
6259 let mut fn_inputs = vec![self_arg];
6260 let (mut input, recovered) = self.parse_seq_to_before_end(
6261 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
6262 fn_inputs.append(&mut input);
6263 (fn_inputs, recovered)
6265 return self.unexpected();
6268 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
6272 // Parse closing paren and return type.
6273 self.expect(&token::CloseDelim(token::Paren))?;
6277 output: self.parse_ret_ty(true)?,
6282 /// Parses the `|arg, arg|` header of a closure.
6283 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
6284 let inputs_captures = {
6285 if self.eat(&token::OrOr) {
6288 self.expect(&token::BinOp(token::Or))?;
6289 let args = self.parse_seq_to_before_tokens(
6290 &[&token::BinOp(token::Or), &token::OrOr],
6291 SeqSep::trailing_allowed(token::Comma),
6292 TokenExpectType::NoExpect,
6293 |p| p.parse_fn_block_arg()
6299 let output = self.parse_ret_ty(true)?;
6302 inputs: inputs_captures,
6308 /// Parses the name and optional generic types of a function header.
6309 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
6310 let id = self.parse_ident()?;
6311 let generics = self.parse_generics()?;
6315 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
6316 attrs: Vec<Attribute>) -> P<Item> {
6320 id: ast::DUMMY_NODE_ID,
6328 /// Parses an item-position function declaration.
6329 fn parse_item_fn(&mut self,
6332 constness: Spanned<Constness>,
6334 -> PResult<'a, ItemInfo> {
6335 let (ident, mut generics) = self.parse_fn_header()?;
6336 let decl = self.parse_fn_decl(false)?;
6337 generics.where_clause = self.parse_where_clause()?;
6338 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6339 let header = FnHeader { unsafety, asyncness, constness, abi };
6340 Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
6343 /// Returns `true` if we are looking at `const ID`
6344 /// (returns `false` for things like `const fn`, etc.).
6345 fn is_const_item(&mut self) -> bool {
6346 self.token.is_keyword(keywords::Const) &&
6347 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
6348 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
6351 /// Parses all the "front matter" for a `fn` declaration, up to
6352 /// and including the `fn` keyword:
6356 /// - `const unsafe fn`
6359 fn parse_fn_front_matter(&mut self)
6367 let is_const_fn = self.eat_keyword(keywords::Const);
6368 let const_span = self.prev_span;
6369 let unsafety = self.parse_unsafety();
6370 let asyncness = self.parse_asyncness();
6371 let (constness, unsafety, abi) = if is_const_fn {
6372 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
6374 let abi = if self.eat_keyword(keywords::Extern) {
6375 self.parse_opt_abi()?.unwrap_or(Abi::C)
6379 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
6381 self.expect_keyword(keywords::Fn)?;
6382 Ok((constness, unsafety, asyncness, abi))
6385 /// Parses an impl item.
6386 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
6387 maybe_whole!(self, NtImplItem, |x| x);
6388 let attrs = self.parse_outer_attributes()?;
6389 let (mut item, tokens) = self.collect_tokens(|this| {
6390 this.parse_impl_item_(at_end, attrs)
6393 // See `parse_item` for why this clause is here.
6394 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6395 item.tokens = Some(tokens);
6400 fn parse_impl_item_(&mut self,
6402 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
6404 let vis = self.parse_visibility(false)?;
6405 let defaultness = self.parse_defaultness();
6406 let (name, node, generics) = if let Some(type_) = self.eat_type() {
6407 let (name, alias, generics) = type_?;
6408 let kind = match alias {
6409 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
6410 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
6412 (name, kind, generics)
6413 } else if self.is_const_item() {
6414 // This parses the grammar:
6415 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
6416 self.expect_keyword(keywords::Const)?;
6417 let name = self.parse_ident()?;
6418 self.expect(&token::Colon)?;
6419 let typ = self.parse_ty()?;
6420 self.expect(&token::Eq)?;
6421 let expr = self.parse_expr()?;
6422 self.expect(&token::Semi)?;
6423 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
6425 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
6426 attrs.extend(inner_attrs);
6427 (name, node, generics)
6431 id: ast::DUMMY_NODE_ID,
6432 span: lo.to(self.prev_span),
6443 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
6445 VisibilityKind::Inherited => {}
6447 let is_macro_rules: bool = match self.token {
6448 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
6451 let mut err = if is_macro_rules {
6452 let mut err = self.diagnostic()
6453 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
6454 err.span_suggestion(
6456 "try exporting the macro",
6457 "#[macro_export]".to_owned(),
6458 Applicability::MaybeIncorrect // speculative
6462 let mut err = self.diagnostic()
6463 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
6464 err.help("try adjusting the macro to put `pub` inside the invocation");
6472 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
6473 -> DiagnosticBuilder<'a>
6475 let expected_kinds = if item_type == "extern" {
6476 "missing `fn`, `type`, or `static`"
6478 "missing `fn`, `type`, or `const`"
6481 // Given this code `path(`, it seems like this is not
6482 // setting the visibility of a macro invocation, but rather
6483 // a mistyped method declaration.
6484 // Create a diagnostic pointing out that `fn` is missing.
6486 // x | pub path(&self) {
6487 // | ^ missing `fn`, `type`, or `const`
6489 // ^^ `sp` below will point to this
6490 let sp = prev_span.between(self.prev_span);
6491 let mut err = self.diagnostic().struct_span_err(
6493 &format!("{} for {}-item declaration",
6494 expected_kinds, item_type));
6495 err.span_label(sp, expected_kinds);
6499 /// Parse a method or a macro invocation in a trait impl.
6500 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
6501 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
6502 ast::ImplItemKind)> {
6503 // code copied from parse_macro_use_or_failure... abstraction!
6504 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
6506 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
6507 ast::ImplItemKind::Macro(mac)))
6509 let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
6510 let ident = self.parse_ident()?;
6511 let mut generics = self.parse_generics()?;
6512 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
6513 generics.where_clause = self.parse_where_clause()?;
6515 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6516 let header = ast::FnHeader { abi, unsafety, constness, asyncness };
6517 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
6518 ast::MethodSig { header, decl },
6524 /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
6525 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
6526 let ident = self.parse_ident()?;
6527 let mut tps = self.parse_generics()?;
6529 // Parse optional colon and supertrait bounds.
6530 let bounds = if self.eat(&token::Colon) {
6531 self.parse_generic_bounds()?
6536 if self.eat(&token::Eq) {
6537 // it's a trait alias
6538 let bounds = self.parse_generic_bounds()?;
6539 tps.where_clause = self.parse_where_clause()?;
6540 self.expect(&token::Semi)?;
6541 if unsafety != Unsafety::Normal {
6542 let msg = "trait aliases cannot be unsafe";
6543 self.struct_span_err(self.prev_span, msg)
6544 .span_label(self.prev_span, msg)
6547 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
6549 // it's a normal trait
6550 tps.where_clause = self.parse_where_clause()?;
6551 self.expect(&token::OpenDelim(token::Brace))?;
6552 let mut trait_items = vec![];
6553 while !self.eat(&token::CloseDelim(token::Brace)) {
6554 let mut at_end = false;
6555 match self.parse_trait_item(&mut at_end) {
6556 Ok(item) => trait_items.push(item),
6560 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6565 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
6569 fn choose_generics_over_qpath(&self) -> bool {
6570 // There's an ambiguity between generic parameters and qualified paths in impls.
6571 // If we see `<` it may start both, so we have to inspect some following tokens.
6572 // The following combinations can only start generics,
6573 // but not qualified paths (with one exception):
6574 // `<` `>` - empty generic parameters
6575 // `<` `#` - generic parameters with attributes
6576 // `<` (LIFETIME|IDENT) `>` - single generic parameter
6577 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
6578 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
6579 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
6580 // `<` const - generic const parameter
6581 // The only truly ambiguous case is
6582 // `<` IDENT `>` `::` IDENT ...
6583 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
6584 // because this is what almost always expected in practice, qualified paths in impls
6585 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
6586 self.token == token::Lt &&
6587 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
6588 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
6589 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
6590 t == &token::Colon || t == &token::Eq) ||
6591 self.look_ahead(1, |t| t.is_keyword(keywords::Const)))
6594 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6595 self.expect(&token::OpenDelim(token::Brace))?;
6596 let attrs = self.parse_inner_attributes()?;
6598 let mut impl_items = Vec::new();
6599 while !self.eat(&token::CloseDelim(token::Brace)) {
6600 let mut at_end = false;
6601 match self.parse_impl_item(&mut at_end) {
6602 Ok(impl_item) => impl_items.push(impl_item),
6606 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6611 Ok((impl_items, attrs))
6614 /// Parses an implementation item, `impl` keyword is already parsed.
6616 /// impl<'a, T> TYPE { /* impl items */ }
6617 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
6618 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6620 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6621 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6622 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6623 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6624 -> PResult<'a, ItemInfo> {
6625 // First, parse generic parameters if necessary.
6626 let mut generics = if self.choose_generics_over_qpath() {
6627 self.parse_generics()?
6629 ast::Generics::default()
6632 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6633 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6635 ast::ImplPolarity::Negative
6637 ast::ImplPolarity::Positive
6640 // Parse both types and traits as a type, then reinterpret if necessary.
6641 let ty_first = self.parse_ty()?;
6643 // If `for` is missing we try to recover.
6644 let has_for = self.eat_keyword(keywords::For);
6645 let missing_for_span = self.prev_span.between(self.span);
6647 let ty_second = if self.token == token::DotDot {
6648 // We need to report this error after `cfg` expansion for compatibility reasons
6649 self.bump(); // `..`, do not add it to expected tokens
6650 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
6651 } else if has_for || self.token.can_begin_type() {
6652 Some(self.parse_ty()?)
6657 generics.where_clause = self.parse_where_clause()?;
6659 let (impl_items, attrs) = self.parse_impl_body()?;
6661 let item_kind = match ty_second {
6662 Some(ty_second) => {
6663 // impl Trait for Type
6665 self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6666 .span_suggestion_short(
6669 " for ".to_string(),
6670 Applicability::MachineApplicable,
6674 let ty_first = ty_first.into_inner();
6675 let path = match ty_first.node {
6676 // This notably includes paths passed through `ty` macro fragments (#46438).
6677 TyKind::Path(None, path) => path,
6679 self.span_err(ty_first.span, "expected a trait, found type");
6680 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
6683 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6685 ItemKind::Impl(unsafety, polarity, defaultness,
6686 generics, Some(trait_ref), ty_second, impl_items)
6690 ItemKind::Impl(unsafety, polarity, defaultness,
6691 generics, None, ty_first, impl_items)
6695 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
6698 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6699 if self.eat_keyword(keywords::For) {
6701 let params = self.parse_generic_params()?;
6703 // We rely on AST validation to rule out invalid cases: There must not be type
6704 // parameters, and the lifetime parameters must not have bounds.
6711 /// Parses `struct Foo { ... }`.
6712 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6713 let class_name = self.parse_ident()?;
6715 let mut generics = self.parse_generics()?;
6717 // There is a special case worth noting here, as reported in issue #17904.
6718 // If we are parsing a tuple struct it is the case that the where clause
6719 // should follow the field list. Like so:
6721 // struct Foo<T>(T) where T: Copy;
6723 // If we are parsing a normal record-style struct it is the case
6724 // that the where clause comes before the body, and after the generics.
6725 // So if we look ahead and see a brace or a where-clause we begin
6726 // parsing a record style struct.
6728 // Otherwise if we look ahead and see a paren we parse a tuple-style
6731 let vdata = if self.token.is_keyword(keywords::Where) {
6732 generics.where_clause = self.parse_where_clause()?;
6733 if self.eat(&token::Semi) {
6734 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6735 VariantData::Unit(ast::DUMMY_NODE_ID)
6737 // If we see: `struct Foo<T> where T: Copy { ... }`
6738 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6740 // No `where` so: `struct Foo<T>;`
6741 } else if self.eat(&token::Semi) {
6742 VariantData::Unit(ast::DUMMY_NODE_ID)
6743 // Record-style struct definition
6744 } else if self.token == token::OpenDelim(token::Brace) {
6745 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6746 // Tuple-style struct definition with optional where-clause.
6747 } else if self.token == token::OpenDelim(token::Paren) {
6748 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6749 generics.where_clause = self.parse_where_clause()?;
6750 self.expect(&token::Semi)?;
6753 let token_str = self.this_token_descr();
6754 let mut err = self.fatal(&format!(
6755 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6758 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6762 Ok((class_name, ItemKind::Struct(vdata, generics), None))
6765 /// Parses `union Foo { ... }`.
6766 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6767 let class_name = self.parse_ident()?;
6769 let mut generics = self.parse_generics()?;
6771 let vdata = if self.token.is_keyword(keywords::Where) {
6772 generics.where_clause = self.parse_where_clause()?;
6773 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6774 } else if self.token == token::OpenDelim(token::Brace) {
6775 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
6777 let token_str = self.this_token_descr();
6778 let mut err = self.fatal(&format!(
6779 "expected `where` or `{{` after union name, found {}", token_str));
6780 err.span_label(self.span, "expected `where` or `{` after union name");
6784 Ok((class_name, ItemKind::Union(vdata, generics), None))
6787 fn consume_block(&mut self, delim: token::DelimToken) {
6788 let mut brace_depth = 0;
6790 if self.eat(&token::OpenDelim(delim)) {
6792 } else if self.eat(&token::CloseDelim(delim)) {
6793 if brace_depth == 0 {
6799 } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
6807 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6808 let mut fields = Vec::new();
6809 if self.eat(&token::OpenDelim(token::Brace)) {
6810 while self.token != token::CloseDelim(token::Brace) {
6811 let field = self.parse_struct_decl_field().map_err(|e| {
6812 self.recover_stmt();
6816 Ok(field) => fields.push(field),
6822 self.eat(&token::CloseDelim(token::Brace));
6824 let token_str = self.this_token_descr();
6825 let mut err = self.fatal(&format!(
6826 "expected `where`, or `{{` after struct name, found {}", token_str));
6827 err.span_label(self.span, "expected `where`, or `{` after struct name");
6834 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6835 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6836 // Unit like structs are handled in parse_item_struct function
6837 let fields = self.parse_unspanned_seq(
6838 &token::OpenDelim(token::Paren),
6839 &token::CloseDelim(token::Paren),
6840 SeqSep::trailing_allowed(token::Comma),
6842 let attrs = p.parse_outer_attributes()?;
6844 let vis = p.parse_visibility(true)?;
6845 let ty = p.parse_ty()?;
6847 span: lo.to(ty.span),
6850 id: ast::DUMMY_NODE_ID,
6859 /// Parses a structure field declaration.
6860 fn parse_single_struct_field(&mut self,
6863 attrs: Vec<Attribute> )
6864 -> PResult<'a, StructField> {
6865 let mut seen_comma: bool = false;
6866 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6867 if self.token == token::Comma {
6874 token::CloseDelim(token::Brace) => {}
6875 token::DocComment(_) => {
6876 let previous_span = self.prev_span;
6877 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6878 self.bump(); // consume the doc comment
6879 let comma_after_doc_seen = self.eat(&token::Comma);
6880 // `seen_comma` is always false, because we are inside doc block
6881 // condition is here to make code more readable
6882 if seen_comma == false && comma_after_doc_seen == true {
6885 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
6888 if seen_comma == false {
6889 let sp = self.sess.source_map().next_point(previous_span);
6890 err.span_suggestion(
6892 "missing comma here",
6894 Applicability::MachineApplicable
6901 let sp = self.sess.source_map().next_point(self.prev_span);
6902 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
6903 self.this_token_descr()));
6904 if self.token.is_ident() {
6905 // This is likely another field; emit the diagnostic and keep going
6906 err.span_suggestion(
6908 "try adding a comma",
6910 Applicability::MachineApplicable,
6921 /// Parses an element of a struct declaration.
6922 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6923 let attrs = self.parse_outer_attributes()?;
6925 let vis = self.parse_visibility(false)?;
6926 self.parse_single_struct_field(lo, vis, attrs)
6929 /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
6930 /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
6931 /// If the following element can't be a tuple (i.e., it's a function definition), then
6932 /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
6933 /// so emit a proper diagnostic.
6934 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6935 maybe_whole!(self, NtVis, |x| x);
6937 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
6938 if self.is_crate_vis() {
6939 self.bump(); // `crate`
6940 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6943 if !self.eat_keyword(keywords::Pub) {
6944 // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
6945 // keyword to grab a span from for inherited visibility; an empty span at the
6946 // beginning of the current token would seem to be the "Schelling span".
6947 return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
6949 let lo = self.prev_span;
6951 if self.check(&token::OpenDelim(token::Paren)) {
6952 // We don't `self.bump()` the `(` yet because this might be a struct definition where
6953 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6954 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6955 // by the following tokens.
6956 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
6959 self.bump(); // `crate`
6960 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6962 lo.to(self.prev_span),
6963 VisibilityKind::Crate(CrateSugar::PubCrate),
6966 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
6969 self.bump(); // `in`
6970 let path = self.parse_path(PathStyle::Mod)?; // `path`
6971 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6972 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6974 id: ast::DUMMY_NODE_ID,
6977 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6978 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
6979 t.is_keyword(keywords::SelfLower))
6981 // `pub(self)` or `pub(super)`
6983 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6984 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6985 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6987 id: ast::DUMMY_NODE_ID,
6990 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
6991 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6993 let msg = "incorrect visibility restriction";
6994 let suggestion = r##"some possible visibility restrictions are:
6995 `pub(crate)`: visible only on the current crate
6996 `pub(super)`: visible only in the current module's parent
6997 `pub(in path::to::module)`: visible only on the specified path"##;
6998 let path = self.parse_path(PathStyle::Mod)?;
6999 let sp = self.prev_span;
7000 let help_msg = format!("make this visible only to module `{}` with `in`", path);
7001 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7002 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
7003 err.help(suggestion);
7004 err.span_suggestion(
7005 sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
7007 err.emit(); // emit diagnostic, but continue with public visibility
7011 Ok(respan(lo, VisibilityKind::Public))
7014 /// Parses defaultness (i.e., `default` or nothing).
7015 fn parse_defaultness(&mut self) -> Defaultness {
7016 // `pub` is included for better error messages
7017 if self.check_keyword(keywords::Default) &&
7018 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
7019 t.is_keyword(keywords::Const) ||
7020 t.is_keyword(keywords::Fn) ||
7021 t.is_keyword(keywords::Unsafe) ||
7022 t.is_keyword(keywords::Extern) ||
7023 t.is_keyword(keywords::Type) ||
7024 t.is_keyword(keywords::Pub)) {
7025 self.bump(); // `default`
7026 Defaultness::Default
7032 fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
7033 if self.eat(&token::Semi) {
7034 let mut err = self.struct_span_err(self.prev_span, "expected item, found `;`");
7035 err.span_suggestion_short(
7037 "remove this semicolon",
7039 Applicability::MachineApplicable,
7041 if !items.is_empty() {
7042 let previous_item = &items[items.len()-1];
7043 let previous_item_kind_name = match previous_item.node {
7044 // say "braced struct" because tuple-structs and
7045 // braceless-empty-struct declarations do take a semicolon
7046 ItemKind::Struct(..) => Some("braced struct"),
7047 ItemKind::Enum(..) => Some("enum"),
7048 ItemKind::Trait(..) => Some("trait"),
7049 ItemKind::Union(..) => Some("union"),
7052 if let Some(name) = previous_item_kind_name {
7053 err.help(&format!("{} declarations are not followed by a semicolon", name));
7063 /// Given a termination token, parses all of the items in a module.
7064 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
7065 let mut items = vec![];
7066 while let Some(item) = self.parse_item()? {
7068 self.maybe_consume_incorrect_semicolon(&items);
7071 if !self.eat(term) {
7072 let token_str = self.this_token_descr();
7073 if !self.maybe_consume_incorrect_semicolon(&items) {
7074 let mut err = self.fatal(&format!("expected item, found {}", token_str));
7075 err.span_label(self.span, "expected item");
7080 let hi = if self.span.is_dummy() {
7087 inner: inner_lo.to(hi),
7093 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
7094 let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
7095 self.expect(&token::Colon)?;
7096 let ty = self.parse_ty()?;
7097 self.expect(&token::Eq)?;
7098 let e = self.parse_expr()?;
7099 self.expect(&token::Semi)?;
7100 let item = match m {
7101 Some(m) => ItemKind::Static(ty, m, e),
7102 None => ItemKind::Const(ty, e),
7104 Ok((id, item, None))
7107 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
7108 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
7109 let (in_cfg, outer_attrs) = {
7110 let mut strip_unconfigured = crate::config::StripUnconfigured {
7112 features: None, // don't perform gated feature checking
7114 let mut outer_attrs = outer_attrs.to_owned();
7115 strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
7116 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
7119 let id_span = self.span;
7120 let id = self.parse_ident()?;
7121 if self.eat(&token::Semi) {
7122 if in_cfg && self.recurse_into_file_modules {
7123 // This mod is in an external file. Let's go get it!
7124 let ModulePathSuccess { path, directory_ownership, warn } =
7125 self.submod_path(id, &outer_attrs, id_span)?;
7126 let (module, mut attrs) =
7127 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
7128 // Record that we fetched the mod from an external file
7130 let attr = Attribute {
7131 id: attr::mk_attr_id(),
7132 style: ast::AttrStyle::Outer,
7133 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
7134 tokens: TokenStream::empty(),
7135 is_sugared_doc: false,
7136 span: syntax_pos::DUMMY_SP,
7138 attr::mark_known(&attr);
7141 Ok((id, ItemKind::Mod(module), Some(attrs)))
7143 let placeholder = ast::Mod {
7144 inner: syntax_pos::DUMMY_SP,
7148 Ok((id, ItemKind::Mod(placeholder), None))
7151 let old_directory = self.directory.clone();
7152 self.push_directory(id, &outer_attrs);
7154 self.expect(&token::OpenDelim(token::Brace))?;
7155 let mod_inner_lo = self.span;
7156 let attrs = self.parse_inner_attributes()?;
7157 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
7159 self.directory = old_directory;
7160 Ok((id, ItemKind::Mod(module), Some(attrs)))
7164 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
7165 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
7166 self.directory.path.to_mut().push(&path.as_str());
7167 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
7169 // We have to push on the current module name in the case of relative
7170 // paths in order to ensure that any additional module paths from inline
7171 // `mod x { ... }` come after the relative extension.
7173 // For example, a `mod z { ... }` inside `x/y.rs` should set the current
7174 // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
7175 if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
7176 if let Some(ident) = relative.take() { // remove the relative offset
7177 self.directory.path.to_mut().push(ident.as_str());
7180 self.directory.path.to_mut().push(&id.as_str());
7184 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
7185 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
7188 // On windows, the base path might have the form
7189 // `\\?\foo\bar` in which case it does not tolerate
7190 // mixed `/` and `\` separators, so canonicalize
7193 let s = s.replace("/", "\\");
7194 Some(dir_path.join(s))
7200 /// Returns a path to a module.
7201 pub fn default_submod_path(
7203 relative: Option<ast::Ident>,
7205 source_map: &SourceMap) -> ModulePath
7207 // If we're in a foo.rs file instead of a mod.rs file,
7208 // we need to look for submodules in
7209 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
7210 // `./<id>.rs` and `./<id>/mod.rs`.
7211 let relative_prefix_string;
7212 let relative_prefix = if let Some(ident) = relative {
7213 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
7214 &relative_prefix_string
7219 let mod_name = id.to_string();
7220 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
7221 let secondary_path_str = format!("{}{}{}mod.rs",
7222 relative_prefix, mod_name, path::MAIN_SEPARATOR);
7223 let default_path = dir_path.join(&default_path_str);
7224 let secondary_path = dir_path.join(&secondary_path_str);
7225 let default_exists = source_map.file_exists(&default_path);
7226 let secondary_exists = source_map.file_exists(&secondary_path);
7228 let result = match (default_exists, secondary_exists) {
7229 (true, false) => Ok(ModulePathSuccess {
7231 directory_ownership: DirectoryOwnership::Owned {
7236 (false, true) => Ok(ModulePathSuccess {
7237 path: secondary_path,
7238 directory_ownership: DirectoryOwnership::Owned {
7243 (false, false) => Err(Error::FileNotFoundForModule {
7244 mod_name: mod_name.clone(),
7245 default_path: default_path_str,
7246 secondary_path: secondary_path_str,
7247 dir_path: dir_path.display().to_string(),
7249 (true, true) => Err(Error::DuplicatePaths {
7250 mod_name: mod_name.clone(),
7251 default_path: default_path_str,
7252 secondary_path: secondary_path_str,
7258 path_exists: default_exists || secondary_exists,
7263 fn submod_path(&mut self,
7265 outer_attrs: &[Attribute],
7267 -> PResult<'a, ModulePathSuccess> {
7268 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
7269 return Ok(ModulePathSuccess {
7270 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
7271 // All `#[path]` files are treated as though they are a `mod.rs` file.
7272 // This means that `mod foo;` declarations inside `#[path]`-included
7273 // files are siblings,
7275 // Note that this will produce weirdness when a file named `foo.rs` is
7276 // `#[path]` included and contains a `mod foo;` declaration.
7277 // If you encounter this, it's your own darn fault :P
7278 Some(_) => DirectoryOwnership::Owned { relative: None },
7279 _ => DirectoryOwnership::UnownedViaMod(true),
7286 let relative = match self.directory.ownership {
7287 DirectoryOwnership::Owned { relative } => relative,
7288 DirectoryOwnership::UnownedViaBlock |
7289 DirectoryOwnership::UnownedViaMod(_) => None,
7291 let paths = Parser::default_submod_path(
7292 id, relative, &self.directory.path, self.sess.source_map());
7294 match self.directory.ownership {
7295 DirectoryOwnership::Owned { .. } => {
7296 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
7298 DirectoryOwnership::UnownedViaBlock => {
7300 "Cannot declare a non-inline module inside a block \
7301 unless it has a path attribute";
7302 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
7303 if paths.path_exists {
7304 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
7306 err.span_note(id_sp, &msg);
7310 DirectoryOwnership::UnownedViaMod(warn) => {
7312 if let Ok(result) = paths.result {
7313 return Ok(ModulePathSuccess { warn: true, ..result });
7316 let mut err = self.diagnostic().struct_span_err(id_sp,
7317 "cannot declare a new module at this location");
7318 if !id_sp.is_dummy() {
7319 let src_path = self.sess.source_map().span_to_filename(id_sp);
7320 if let FileName::Real(src_path) = src_path {
7321 if let Some(stem) = src_path.file_stem() {
7322 let mut dest_path = src_path.clone();
7323 dest_path.set_file_name(stem);
7324 dest_path.push("mod.rs");
7325 err.span_note(id_sp,
7326 &format!("maybe move this module `{}` to its own \
7327 directory via `{}`", src_path.display(),
7328 dest_path.display()));
7332 if paths.path_exists {
7333 err.span_note(id_sp,
7334 &format!("... or maybe `use` the module `{}` instead \
7335 of possibly redeclaring it",
7343 /// Reads a module from a source file.
7344 fn eval_src_mod(&mut self,
7346 directory_ownership: DirectoryOwnership,
7349 -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
7350 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
7351 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
7352 let mut err = String::from("circular modules: ");
7353 let len = included_mod_stack.len();
7354 for p in &included_mod_stack[i.. len] {
7355 err.push_str(&p.to_string_lossy());
7356 err.push_str(" -> ");
7358 err.push_str(&path.to_string_lossy());
7359 return Err(self.span_fatal(id_sp, &err[..]));
7361 included_mod_stack.push(path.clone());
7362 drop(included_mod_stack);
7365 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
7366 p0.cfg_mods = self.cfg_mods;
7367 let mod_inner_lo = p0.span;
7368 let mod_attrs = p0.parse_inner_attributes()?;
7369 let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
7371 self.sess.included_mod_stack.borrow_mut().pop();
7375 /// Parses a function declaration from a foreign module.
7376 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7377 -> PResult<'a, ForeignItem> {
7378 self.expect_keyword(keywords::Fn)?;
7380 let (ident, mut generics) = self.parse_fn_header()?;
7381 let decl = self.parse_fn_decl(true)?;
7382 generics.where_clause = self.parse_where_clause()?;
7384 self.expect(&token::Semi)?;
7385 Ok(ast::ForeignItem {
7388 node: ForeignItemKind::Fn(decl, generics),
7389 id: ast::DUMMY_NODE_ID,
7395 /// Parses a static item from a foreign module.
7396 /// Assumes that the `static` keyword is already parsed.
7397 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7398 -> PResult<'a, ForeignItem> {
7399 let mutbl = self.eat_keyword(keywords::Mut);
7400 let ident = self.parse_ident()?;
7401 self.expect(&token::Colon)?;
7402 let ty = self.parse_ty()?;
7404 self.expect(&token::Semi)?;
7408 node: ForeignItemKind::Static(ty, mutbl),
7409 id: ast::DUMMY_NODE_ID,
7415 /// Parses a type from a foreign module.
7416 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7417 -> PResult<'a, ForeignItem> {
7418 self.expect_keyword(keywords::Type)?;
7420 let ident = self.parse_ident()?;
7422 self.expect(&token::Semi)?;
7423 Ok(ast::ForeignItem {
7426 node: ForeignItemKind::Ty,
7427 id: ast::DUMMY_NODE_ID,
7433 fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
7434 let error_msg = "crate name using dashes are not valid in `extern crate` statements";
7435 let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
7437 let mut ident = if self.token.is_keyword(keywords::SelfLower) {
7438 self.parse_path_segment_ident()
7442 let mut idents = vec![];
7443 let mut replacement = vec![];
7444 let mut fixed_crate_name = false;
7445 // Accept `extern crate name-like-this` for better diagnostics
7446 let dash = token::Token::BinOp(token::BinOpToken::Minus);
7447 if self.token == dash { // Do not include `-` as part of the expected tokens list
7448 while self.eat(&dash) {
7449 fixed_crate_name = true;
7450 replacement.push((self.prev_span, "_".to_string()));
7451 idents.push(self.parse_ident()?);
7454 if fixed_crate_name {
7455 let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
7456 let mut fixed_name = format!("{}", ident.name);
7457 for part in idents {
7458 fixed_name.push_str(&format!("_{}", part.name));
7460 ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
7462 let mut err = self.struct_span_err(fixed_name_sp, error_msg);
7463 err.span_label(fixed_name_sp, "dash-separated idents are not valid");
7464 err.multipart_suggestion(
7467 Applicability::MachineApplicable,
7474 /// Parses `extern crate` links.
7479 /// extern crate foo;
7480 /// extern crate bar as foo;
7482 fn parse_item_extern_crate(&mut self,
7484 visibility: Visibility,
7485 attrs: Vec<Attribute>)
7486 -> PResult<'a, P<Item>> {
7487 // Accept `extern crate name-like-this` for better diagnostics
7488 let orig_name = self.parse_crate_name_with_dashes()?;
7489 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
7490 (rename, Some(orig_name.name))
7494 self.expect(&token::Semi)?;
7496 let span = lo.to(self.prev_span);
7497 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
7500 /// Parses `extern` for foreign ABIs modules.
7502 /// `extern` is expected to have been
7503 /// consumed before calling this method.
7507 /// ```ignore (only-for-syntax-highlight)
7511 fn parse_item_foreign_mod(&mut self,
7513 opt_abi: Option<Abi>,
7514 visibility: Visibility,
7515 mut attrs: Vec<Attribute>)
7516 -> PResult<'a, P<Item>> {
7517 self.expect(&token::OpenDelim(token::Brace))?;
7519 let abi = opt_abi.unwrap_or(Abi::C);
7521 attrs.extend(self.parse_inner_attributes()?);
7523 let mut foreign_items = vec![];
7524 while !self.eat(&token::CloseDelim(token::Brace)) {
7525 foreign_items.push(self.parse_foreign_item()?);
7528 let prev_span = self.prev_span;
7529 let m = ast::ForeignMod {
7531 items: foreign_items
7533 let invalid = keywords::Invalid.ident();
7534 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
7537 /// Parses `type Foo = Bar;`
7539 /// `existential type Foo: Bar;`
7542 /// without modifying the parser state.
7543 fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
7544 // This parses the grammar:
7545 // Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
7546 if self.check_keyword(keywords::Type) ||
7547 self.check_keyword(keywords::Existential) &&
7548 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
7549 let existential = self.eat_keyword(keywords::Existential);
7550 assert!(self.eat_keyword(keywords::Type));
7551 Some(self.parse_existential_or_alias(existential))
7557 /// Parses a type alias or existential type.
7558 fn parse_existential_or_alias(
7561 ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
7562 let ident = self.parse_ident()?;
7563 let mut tps = self.parse_generics()?;
7564 tps.where_clause = self.parse_where_clause()?;
7565 let alias = if existential {
7566 self.expect(&token::Colon)?;
7567 let bounds = self.parse_generic_bounds()?;
7568 AliasKind::Existential(bounds)
7570 self.expect(&token::Eq)?;
7571 let ty = self.parse_ty()?;
7574 self.expect(&token::Semi)?;
7575 Ok((ident, alias, tps))
7578 /// Parses the part of an enum declaration following the `{`.
7579 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
7580 let mut variants = Vec::new();
7581 let mut all_nullary = true;
7582 let mut any_disr = vec![];
7583 while self.token != token::CloseDelim(token::Brace) {
7584 let variant_attrs = self.parse_outer_attributes()?;
7585 let vlo = self.span;
7588 let mut disr_expr = None;
7589 let ident = self.parse_ident()?;
7590 if self.check(&token::OpenDelim(token::Brace)) {
7591 // Parse a struct variant.
7592 all_nullary = false;
7593 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
7594 ast::DUMMY_NODE_ID);
7595 } else if self.check(&token::OpenDelim(token::Paren)) {
7596 all_nullary = false;
7597 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
7598 ast::DUMMY_NODE_ID);
7599 } else if self.eat(&token::Eq) {
7600 disr_expr = Some(AnonConst {
7601 id: ast::DUMMY_NODE_ID,
7602 value: self.parse_expr()?,
7604 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
7607 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7609 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7612 let vr = ast::Variant_ {
7614 attrs: variant_attrs,
7618 variants.push(respan(vlo.to(self.prev_span), vr));
7620 if !self.eat(&token::Comma) { break; }
7622 self.expect(&token::CloseDelim(token::Brace))?;
7623 if !any_disr.is_empty() && !all_nullary {
7624 let mut err =self.struct_span_err(
7626 "discriminator values can only be used with a field-less enum",
7628 for sp in any_disr {
7629 err.span_label(sp, "only valid in field-less enums");
7634 Ok(ast::EnumDef { variants })
7637 /// Parses an enum declaration.
7638 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7639 let id = self.parse_ident()?;
7640 let mut generics = self.parse_generics()?;
7641 generics.where_clause = self.parse_where_clause()?;
7642 self.expect(&token::OpenDelim(token::Brace))?;
7644 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7645 self.recover_stmt();
7646 self.eat(&token::CloseDelim(token::Brace));
7649 Ok((id, ItemKind::Enum(enum_definition, generics), None))
7652 /// Parses a string as an ABI spec on an extern type or module. Consumes
7653 /// the `extern` keyword, if one is found.
7654 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7656 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
7658 self.expect_no_suffix(sp, "ABI spec", suf);
7660 match abi::lookup(&s.as_str()) {
7661 Some(abi) => Ok(Some(abi)),
7663 let prev_span = self.prev_span;
7664 let mut err = struct_span_err!(
7665 self.sess.span_diagnostic,
7668 "invalid ABI: found `{}`",
7670 err.span_label(prev_span, "invalid ABI");
7671 err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7682 fn is_static_global(&mut self) -> bool {
7683 if self.check_keyword(keywords::Static) {
7684 // Check if this could be a closure
7685 !self.look_ahead(1, |token| {
7686 if token.is_keyword(keywords::Move) {
7690 token::BinOp(token::Or) | token::OrOr => true,
7701 attrs: Vec<Attribute>,
7702 macros_allowed: bool,
7703 attributes_allowed: bool,
7704 ) -> PResult<'a, Option<P<Item>>> {
7705 let (ret, tokens) = self.collect_tokens(|this| {
7706 this.parse_item_implementation(attrs, macros_allowed, attributes_allowed)
7709 // Once we've parsed an item and recorded the tokens we got while
7710 // parsing we may want to store `tokens` into the item we're about to
7711 // return. Note, though, that we specifically didn't capture tokens
7712 // related to outer attributes. The `tokens` field here may later be
7713 // used with procedural macros to convert this item back into a token
7714 // stream, but during expansion we may be removing attributes as we go
7717 // If we've got inner attributes then the `tokens` we've got above holds
7718 // these inner attributes. If an inner attribute is expanded we won't
7719 // actually remove it from the token stream, so we'll just keep yielding
7720 // it (bad!). To work around this case for now we just avoid recording
7721 // `tokens` if we detect any inner attributes. This should help keep
7722 // expansion correct, but we should fix this bug one day!
7725 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7726 i.tokens = Some(tokens);
7733 /// Parses one of the items allowed by the flags.
7734 fn parse_item_implementation(
7736 attrs: Vec<Attribute>,
7737 macros_allowed: bool,
7738 attributes_allowed: bool,
7739 ) -> PResult<'a, Option<P<Item>>> {
7740 maybe_whole!(self, NtItem, |item| {
7741 let mut item = item.into_inner();
7742 let mut attrs = attrs;
7743 mem::swap(&mut item.attrs, &mut attrs);
7744 item.attrs.extend(attrs);
7750 let visibility = self.parse_visibility(false)?;
7752 if self.eat_keyword(keywords::Use) {
7754 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7755 self.expect(&token::Semi)?;
7757 let span = lo.to(self.prev_span);
7758 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
7759 return Ok(Some(item));
7762 if self.eat_keyword(keywords::Extern) {
7763 if self.eat_keyword(keywords::Crate) {
7764 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7767 let opt_abi = self.parse_opt_abi()?;
7769 if self.eat_keyword(keywords::Fn) {
7770 // EXTERN FUNCTION ITEM
7771 let fn_span = self.prev_span;
7772 let abi = opt_abi.unwrap_or(Abi::C);
7773 let (ident, item_, extra_attrs) =
7774 self.parse_item_fn(Unsafety::Normal,
7776 respan(fn_span, Constness::NotConst),
7778 let prev_span = self.prev_span;
7779 let item = self.mk_item(lo.to(prev_span),
7783 maybe_append(attrs, extra_attrs));
7784 return Ok(Some(item));
7785 } else if self.check(&token::OpenDelim(token::Brace)) {
7786 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7792 if self.is_static_global() {
7795 let m = if self.eat_keyword(keywords::Mut) {
7798 Mutability::Immutable
7800 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7801 let prev_span = self.prev_span;
7802 let item = self.mk_item(lo.to(prev_span),
7806 maybe_append(attrs, extra_attrs));
7807 return Ok(Some(item));
7809 if self.eat_keyword(keywords::Const) {
7810 let const_span = self.prev_span;
7811 if self.check_keyword(keywords::Fn)
7812 || (self.check_keyword(keywords::Unsafe)
7813 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
7814 // CONST FUNCTION ITEM
7815 let unsafety = self.parse_unsafety();
7817 let (ident, item_, extra_attrs) =
7818 self.parse_item_fn(unsafety,
7820 respan(const_span, Constness::Const),
7822 let prev_span = self.prev_span;
7823 let item = self.mk_item(lo.to(prev_span),
7827 maybe_append(attrs, extra_attrs));
7828 return Ok(Some(item));
7832 if self.eat_keyword(keywords::Mut) {
7833 let prev_span = self.prev_span;
7834 let mut err = self.diagnostic()
7835 .struct_span_err(prev_span, "const globals cannot be mutable");
7836 err.span_label(prev_span, "cannot be mutable");
7837 err.span_suggestion(
7839 "you might want to declare a static instead",
7840 "static".to_owned(),
7841 Applicability::MaybeIncorrect,
7845 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7846 let prev_span = self.prev_span;
7847 let item = self.mk_item(lo.to(prev_span),
7851 maybe_append(attrs, extra_attrs));
7852 return Ok(Some(item));
7855 // `unsafe async fn` or `async fn`
7857 self.check_keyword(keywords::Unsafe) &&
7858 self.look_ahead(1, |t| t.is_keyword(keywords::Async))
7860 self.check_keyword(keywords::Async) &&
7861 self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
7864 // ASYNC FUNCTION ITEM
7865 let unsafety = self.parse_unsafety();
7866 self.expect_keyword(keywords::Async)?;
7867 self.expect_keyword(keywords::Fn)?;
7868 let fn_span = self.prev_span;
7869 let (ident, item_, extra_attrs) =
7870 self.parse_item_fn(unsafety,
7872 closure_id: ast::DUMMY_NODE_ID,
7873 return_impl_trait_id: ast::DUMMY_NODE_ID,
7875 respan(fn_span, Constness::NotConst),
7877 let prev_span = self.prev_span;
7878 let item = self.mk_item(lo.to(prev_span),
7882 maybe_append(attrs, extra_attrs));
7883 return Ok(Some(item));
7885 if self.check_keyword(keywords::Unsafe) &&
7886 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
7887 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
7889 // UNSAFE TRAIT ITEM
7890 self.bump(); // `unsafe`
7891 let is_auto = if self.eat_keyword(keywords::Trait) {
7894 self.expect_keyword(keywords::Auto)?;
7895 self.expect_keyword(keywords::Trait)?;
7898 let (ident, item_, extra_attrs) =
7899 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
7900 let prev_span = self.prev_span;
7901 let item = self.mk_item(lo.to(prev_span),
7905 maybe_append(attrs, extra_attrs));
7906 return Ok(Some(item));
7908 if self.check_keyword(keywords::Impl) ||
7909 self.check_keyword(keywords::Unsafe) &&
7910 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7911 self.check_keyword(keywords::Default) &&
7912 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
7913 self.check_keyword(keywords::Default) &&
7914 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
7916 let defaultness = self.parse_defaultness();
7917 let unsafety = self.parse_unsafety();
7918 self.expect_keyword(keywords::Impl)?;
7919 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
7920 let span = lo.to(self.prev_span);
7921 return Ok(Some(self.mk_item(span, ident, item, visibility,
7922 maybe_append(attrs, extra_attrs))));
7924 if self.check_keyword(keywords::Fn) {
7927 let fn_span = self.prev_span;
7928 let (ident, item_, extra_attrs) =
7929 self.parse_item_fn(Unsafety::Normal,
7931 respan(fn_span, Constness::NotConst),
7933 let prev_span = self.prev_span;
7934 let item = self.mk_item(lo.to(prev_span),
7938 maybe_append(attrs, extra_attrs));
7939 return Ok(Some(item));
7941 if self.check_keyword(keywords::Unsafe)
7942 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
7943 // UNSAFE FUNCTION ITEM
7944 self.bump(); // `unsafe`
7945 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
7946 self.check(&token::OpenDelim(token::Brace));
7947 let abi = if self.eat_keyword(keywords::Extern) {
7948 self.parse_opt_abi()?.unwrap_or(Abi::C)
7952 self.expect_keyword(keywords::Fn)?;
7953 let fn_span = self.prev_span;
7954 let (ident, item_, extra_attrs) =
7955 self.parse_item_fn(Unsafety::Unsafe,
7957 respan(fn_span, Constness::NotConst),
7959 let prev_span = self.prev_span;
7960 let item = self.mk_item(lo.to(prev_span),
7964 maybe_append(attrs, extra_attrs));
7965 return Ok(Some(item));
7967 if self.eat_keyword(keywords::Mod) {
7969 let (ident, item_, extra_attrs) =
7970 self.parse_item_mod(&attrs[..])?;
7971 let prev_span = self.prev_span;
7972 let item = self.mk_item(lo.to(prev_span),
7976 maybe_append(attrs, extra_attrs));
7977 return Ok(Some(item));
7979 if let Some(type_) = self.eat_type() {
7980 let (ident, alias, generics) = type_?;
7982 let item_ = match alias {
7983 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
7984 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
7986 let prev_span = self.prev_span;
7987 let item = self.mk_item(lo.to(prev_span),
7992 return Ok(Some(item));
7994 if self.eat_keyword(keywords::Enum) {
7996 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
7997 let prev_span = self.prev_span;
7998 let item = self.mk_item(lo.to(prev_span),
8002 maybe_append(attrs, extra_attrs));
8003 return Ok(Some(item));
8005 if self.check_keyword(keywords::Trait)
8006 || (self.check_keyword(keywords::Auto)
8007 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
8009 let is_auto = if self.eat_keyword(keywords::Trait) {
8012 self.expect_keyword(keywords::Auto)?;
8013 self.expect_keyword(keywords::Trait)?;
8017 let (ident, item_, extra_attrs) =
8018 self.parse_item_trait(is_auto, Unsafety::Normal)?;
8019 let prev_span = self.prev_span;
8020 let item = self.mk_item(lo.to(prev_span),
8024 maybe_append(attrs, extra_attrs));
8025 return Ok(Some(item));
8027 if self.eat_keyword(keywords::Struct) {
8029 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
8030 let prev_span = self.prev_span;
8031 let item = self.mk_item(lo.to(prev_span),
8035 maybe_append(attrs, extra_attrs));
8036 return Ok(Some(item));
8038 if self.is_union_item() {
8041 let (ident, item_, extra_attrs) = self.parse_item_union()?;
8042 let prev_span = self.prev_span;
8043 let item = self.mk_item(lo.to(prev_span),
8047 maybe_append(attrs, extra_attrs));
8048 return Ok(Some(item));
8050 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
8051 return Ok(Some(macro_def));
8054 // Verify whether we have encountered a struct or method definition where the user forgot to
8055 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
8056 if visibility.node.is_pub() &&
8057 self.check_ident() &&
8058 self.look_ahead(1, |t| *t != token::Not)
8060 // Space between `pub` keyword and the identifier
8063 // ^^^ `sp` points here
8064 let sp = self.prev_span.between(self.span);
8065 let full_sp = self.prev_span.to(self.span);
8066 let ident_sp = self.span;
8067 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
8068 // possible public struct definition where `struct` was forgotten
8069 let ident = self.parse_ident().unwrap();
8070 let msg = format!("add `struct` here to parse `{}` as a public struct",
8072 let mut err = self.diagnostic()
8073 .struct_span_err(sp, "missing `struct` for struct definition");
8074 err.span_suggestion_short(
8075 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
8078 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
8079 let ident = self.parse_ident().unwrap();
8081 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
8086 self.consume_block(token::Paren);
8087 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
8088 self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
8090 ("fn", kw_name, false)
8091 } else if self.check(&token::OpenDelim(token::Brace)) {
8093 ("fn", kw_name, false)
8094 } else if self.check(&token::Colon) {
8098 ("fn` or `struct", "function or struct", true)
8100 self.consume_block(token::Brace);
8102 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8103 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8105 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
8109 err.span_suggestion_short(
8110 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
8113 if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
8114 err.span_suggestion(
8116 "if you meant to call a macro, try",
8117 format!("{}!", snippet),
8118 // this is the `ambiguous` conditional branch
8119 Applicability::MaybeIncorrect
8122 err.help("if you meant to call a macro, remove the `pub` \
8123 and add a trailing `!` after the identifier");
8127 } else if self.look_ahead(1, |t| *t == token::Lt) {
8128 let ident = self.parse_ident().unwrap();
8129 self.eat_to_tokens(&[&token::Gt]);
8131 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
8132 if let Ok(Some(_)) = self.parse_self_arg() {
8133 ("fn", "method", false)
8135 ("fn", "function", false)
8137 } else if self.check(&token::OpenDelim(token::Brace)) {
8138 ("struct", "struct", false)
8140 ("fn` or `struct", "function or struct", true)
8142 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8143 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8145 err.span_suggestion_short(
8147 &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
8148 format!(" {} ", kw),
8149 Applicability::MachineApplicable,
8155 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
8158 /// Parses a foreign item.
8159 crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
8160 maybe_whole!(self, NtForeignItem, |ni| ni);
8162 let attrs = self.parse_outer_attributes()?;
8164 let visibility = self.parse_visibility(false)?;
8166 // FOREIGN STATIC ITEM
8167 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
8168 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
8169 if self.token.is_keyword(keywords::Const) {
8171 .struct_span_err(self.span, "extern items cannot be `const`")
8174 "try using a static value",
8175 "static".to_owned(),
8176 Applicability::MachineApplicable
8179 self.bump(); // `static` or `const`
8180 return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
8182 // FOREIGN FUNCTION ITEM
8183 if self.check_keyword(keywords::Fn) {
8184 return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
8186 // FOREIGN TYPE ITEM
8187 if self.check_keyword(keywords::Type) {
8188 return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
8191 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
8195 ident: keywords::Invalid.ident(),
8196 span: lo.to(self.prev_span),
8197 id: ast::DUMMY_NODE_ID,
8200 node: ForeignItemKind::Macro(mac),
8205 if !attrs.is_empty() {
8206 self.expected_item_err(&attrs)?;
8214 /// This is the fall-through for parsing items.
8215 fn parse_macro_use_or_failure(
8217 attrs: Vec<Attribute> ,
8218 macros_allowed: bool,
8219 attributes_allowed: bool,
8221 visibility: Visibility
8222 ) -> PResult<'a, Option<P<Item>>> {
8223 if macros_allowed && self.token.is_path_start() {
8224 // MACRO INVOCATION ITEM
8226 let prev_span = self.prev_span;
8227 self.complain_if_pub_macro(&visibility.node, prev_span);
8229 let mac_lo = self.span;
8232 let pth = self.parse_path(PathStyle::Mod)?;
8233 self.expect(&token::Not)?;
8235 // a 'special' identifier (like what `macro_rules!` uses)
8236 // is optional. We should eventually unify invoc syntax
8238 let id = if self.token.is_ident() {
8241 keywords::Invalid.ident() // no special identifier
8243 // eat a matched-delimiter token tree:
8244 let (delim, tts) = self.expect_delimited_token_tree()?;
8245 if delim != MacDelimiter::Brace {
8246 if !self.eat(&token::Semi) {
8247 self.span_err(self.prev_span,
8248 "macros that expand to items must either \
8249 be surrounded with braces or followed by \
8254 let hi = self.prev_span;
8255 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
8256 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
8257 return Ok(Some(item));
8260 // FAILURE TO PARSE ITEM
8261 match visibility.node {
8262 VisibilityKind::Inherited => {}
8264 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
8268 if !attributes_allowed && !attrs.is_empty() {
8269 self.expected_item_err(&attrs)?;
8274 /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
8275 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
8276 at_end: &mut bool) -> PResult<'a, Option<Mac>>
8278 if self.token.is_path_start() {
8279 let prev_span = self.prev_span;
8281 let pth = self.parse_path(PathStyle::Mod)?;
8283 if pth.segments.len() == 1 {
8284 if !self.eat(&token::Not) {
8285 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
8288 self.expect(&token::Not)?;
8291 if let Some(vis) = vis {
8292 self.complain_if_pub_macro(&vis.node, prev_span);
8297 // eat a matched-delimiter token tree:
8298 let (delim, tts) = self.expect_delimited_token_tree()?;
8299 if delim != MacDelimiter::Brace {
8300 self.expect(&token::Semi)?;
8303 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
8309 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
8310 where F: FnOnce(&mut Self) -> PResult<'a, R>
8312 // Record all tokens we parse when parsing this item.
8313 let mut tokens = Vec::new();
8314 let prev_collecting = match self.token_cursor.frame.last_token {
8315 LastToken::Collecting(ref mut list) => {
8316 Some(mem::replace(list, Vec::new()))
8318 LastToken::Was(ref mut last) => {
8319 tokens.extend(last.take());
8323 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
8324 let prev = self.token_cursor.stack.len();
8326 let last_token = if self.token_cursor.stack.len() == prev {
8327 &mut self.token_cursor.frame.last_token
8329 &mut self.token_cursor.stack[prev].last_token
8332 // Pull out the tokens that we've collected from the call to `f` above.
8333 let mut collected_tokens = match *last_token {
8334 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
8335 LastToken::Was(_) => panic!("our vector went away?"),
8338 // If we're not at EOF our current token wasn't actually consumed by
8339 // `f`, but it'll still be in our list that we pulled out. In that case
8341 let extra_token = if self.token != token::Eof {
8342 collected_tokens.pop()
8347 // If we were previously collecting tokens, then this was a recursive
8348 // call. In that case we need to record all the tokens we collected in
8349 // our parent list as well. To do that we push a clone of our stream
8350 // onto the previous list.
8351 match prev_collecting {
8353 list.extend(collected_tokens.iter().cloned());
8354 list.extend(extra_token);
8355 *last_token = LastToken::Collecting(list);
8358 *last_token = LastToken::Was(extra_token);
8362 Ok((ret?, TokenStream::new(collected_tokens)))
8365 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
8366 let attrs = self.parse_outer_attributes()?;
8367 self.parse_item_(attrs, true, false)
8371 fn is_import_coupler(&mut self) -> bool {
8372 self.check(&token::ModSep) &&
8373 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
8374 *t == token::BinOp(token::Star))
8377 /// Parses a `UseTree`.
8380 /// USE_TREE = [`::`] `*` |
8381 /// [`::`] `{` USE_TREE_LIST `}` |
8383 /// PATH `::` `{` USE_TREE_LIST `}` |
8384 /// PATH [`as` IDENT]
8386 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
8389 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
8390 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
8391 self.check(&token::BinOp(token::Star)) ||
8392 self.is_import_coupler() {
8393 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
8394 let mod_sep_ctxt = self.span.ctxt();
8395 if self.eat(&token::ModSep) {
8396 prefix.segments.push(
8397 PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
8401 if self.eat(&token::BinOp(token::Star)) {
8404 UseTreeKind::Nested(self.parse_use_tree_list()?)
8407 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
8408 prefix = self.parse_path(PathStyle::Mod)?;
8410 if self.eat(&token::ModSep) {
8411 if self.eat(&token::BinOp(token::Star)) {
8414 UseTreeKind::Nested(self.parse_use_tree_list()?)
8417 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
8421 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
8424 /// Parses a `UseTreeKind::Nested(list)`.
8427 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
8429 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
8430 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
8431 &token::CloseDelim(token::Brace),
8432 SeqSep::trailing_allowed(token::Comma), |this| {
8433 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
8437 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
8438 if self.eat_keyword(keywords::As) {
8439 self.parse_ident_or_underscore().map(Some)
8445 /// Parses a source module as a crate. This is the main entry point for the parser.
8446 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
8448 let krate = Ok(ast::Crate {
8449 attrs: self.parse_inner_attributes()?,
8450 module: self.parse_mod_items(&token::Eof, lo)?,
8451 span: lo.to(self.span),
8453 emit_unclosed_delims(&self.unclosed_delims, self.diagnostic());
8454 self.unclosed_delims.clear();
8458 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
8459 let ret = match self.token {
8460 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
8461 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
8468 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
8469 match self.parse_optional_str() {
8470 Some((s, style, suf)) => {
8471 let sp = self.prev_span;
8472 self.expect_no_suffix(sp, "string literal", suf);
8476 let msg = "expected string literal";
8477 let mut err = self.fatal(msg);
8478 err.span_label(self.span, msg);
8485 pub fn emit_unclosed_delims(unclosed_delims: &[UnmatchedBrace], handler: &errors::Handler) {
8486 for unmatched in unclosed_delims {
8487 let mut err = handler.struct_span_err(unmatched.found_span, &format!(
8488 "incorrect close delimiter: `{}`",
8489 pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
8491 err.span_label(unmatched.found_span, "incorrect close delimiter");
8492 if let Some(sp) = unmatched.candidate_span {
8493 err.span_label(sp, "close delimiter possibly meant for this");
8495 if let Some(sp) = unmatched.unclosed_span {
8496 err.span_label(sp, "un-closed delimiter");