1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use rustc_target::spec::abi::{self, Abi};
12 use ast::{AngleBracketedParameterData, ParenthesizedParameterData, AttrStyle, BareFnTy};
13 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
15 use ast::{Mod, AnonConst, Arg, Arm, Attribute, BindingMode, TraitItemKind};
17 use ast::{BlockCheckMode, CaptureBy, Movability};
18 use ast::{Constness, Crate};
21 use ast::{Expr, ExprKind, RangeLimits};
22 use ast::{Field, FnDecl};
23 use ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
24 use ast::GenericParam;
25 use ast::{Ident, ImplItem, IsAuto, Item, ItemKind};
26 use ast::{Label, Lifetime, LifetimeDef, Lit, LitKind};
28 use ast::MacStmtStyle;
29 use ast::{Mac, Mac_, MacDelimiter};
30 use ast::{MutTy, Mutability};
31 use ast::{Pat, PatKind, PathSegment};
32 use ast::{PolyTraitRef, QSelf};
33 use ast::{Stmt, StmtKind};
34 use ast::{VariantData, StructField};
37 use ast::{TraitItem, TraitRef, TraitObjectSyntax};
38 use ast::{Ty, TyKind, TypeBinding, TyParam, TyParamBounds};
39 use ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
40 use ast::{UseTree, UseTreeKind};
41 use ast::{BinOpKind, UnOp};
42 use ast::{RangeEnd, RangeSyntax};
44 use codemap::{self, CodeMap, Spanned, respan};
45 use syntax_pos::{self, Span, MultiSpan, BytePos, FileName, DUMMY_SP};
46 use errors::{self, Applicability, DiagnosticBuilder};
47 use parse::{self, SeqSep, classify, token};
48 use parse::lexer::TokenAndSpan;
49 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
50 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
51 use util::parser::{AssocOp, Fixity};
55 use tokenstream::{self, Delimited, ThinTokenStream, TokenTree, TokenStream};
56 use symbol::{Symbol, keywords};
62 use std::path::{self, Path, PathBuf};
66 struct Restrictions: u8 {
67 const STMT_EXPR = 1 << 0;
68 const NO_STRUCT_LITERAL = 1 << 1;
72 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
74 /// How to parse a path.
75 #[derive(Copy, Clone, PartialEq)]
77 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
78 /// with something else. For example, in expressions `segment < ....` can be interpreted
79 /// as a comparison and `segment ( ....` can be interpreted as a function call.
80 /// In all such contexts the non-path interpretation is preferred by default for practical
81 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
82 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
84 /// In other contexts, notably in types, no ambiguity exists and paths can be written
85 /// without the disambiguator, e.g. `x<y>` - unambiguously a path.
86 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
88 /// A path with generic arguments disallowed, e.g. `foo::bar::Baz`, used in imports,
89 /// visibilities or attributes.
90 /// Technically, this variant is unnecessary and e.g. `Expr` can be used instead
91 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
92 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
93 /// tokens when something goes wrong.
97 #[derive(Clone, Copy, Debug, PartialEq)]
103 #[derive(Clone, Copy, Debug, PartialEq)]
109 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
110 /// dropped into the token stream, which happens while parsing the result of
111 /// macro expansion). Placement of these is not as complex as I feared it would
112 /// be. The important thing is to make sure that lookahead doesn't balk at
113 /// `token::Interpolated` tokens.
114 macro_rules! maybe_whole_expr {
116 if let token::Interpolated(nt) = $p.token.clone() {
118 token::NtExpr(ref e) | token::NtLiteral(ref e) => {
120 return Ok((*e).clone());
122 token::NtPath(ref path) => {
125 let kind = ExprKind::Path(None, (*path).clone());
126 return Ok($p.mk_expr(span, kind, ThinVec::new()));
128 token::NtBlock(ref block) => {
131 let kind = ExprKind::Block((*block).clone(), None);
132 return Ok($p.mk_expr(span, kind, ThinVec::new()));
140 /// As maybe_whole_expr, but for things other than expressions
141 macro_rules! maybe_whole {
142 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
143 if let token::Interpolated(nt) = $p.token.clone() {
144 if let token::$constructor($x) = nt.0.clone() {
152 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
153 if let Some(ref mut rhs) = rhs {
159 #[derive(Debug, Clone, Copy, PartialEq)]
170 trait RecoverQPath: Sized {
171 const PATH_STYLE: PathStyle = PathStyle::Expr;
172 fn to_ty(&self) -> Option<P<Ty>>;
173 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self;
174 fn to_string(&self) -> String;
177 impl RecoverQPath for Ty {
178 const PATH_STYLE: PathStyle = PathStyle::Type;
179 fn to_ty(&self) -> Option<P<Ty>> {
180 Some(P(self.clone()))
182 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
183 Self { span: path.span, node: TyKind::Path(qself, path), id: self.id }
185 fn to_string(&self) -> String {
186 pprust::ty_to_string(self)
190 impl RecoverQPath for Pat {
191 fn to_ty(&self) -> Option<P<Ty>> {
194 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
195 Self { span: path.span, node: PatKind::Path(qself, path), id: self.id }
197 fn to_string(&self) -> String {
198 pprust::pat_to_string(self)
202 impl RecoverQPath for Expr {
203 fn to_ty(&self) -> Option<P<Ty>> {
206 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
207 Self { span: path.span, node: ExprKind::Path(qself, path),
208 id: self.id, attrs: self.attrs.clone() }
210 fn to_string(&self) -> String {
211 pprust::expr_to_string(self)
215 /* ident is handled by common.rs */
218 pub struct Parser<'a> {
219 pub sess: &'a ParseSess,
220 /// the current token:
221 pub token: token::Token,
222 /// the span of the current token:
224 /// the span of the previous token:
225 meta_var_span: Option<Span>,
227 /// the previous token kind
228 prev_token_kind: PrevTokenKind,
229 restrictions: Restrictions,
230 /// Used to determine the path to externally loaded source files
231 crate directory: Directory<'a>,
232 /// Whether to parse sub-modules in other files.
233 pub recurse_into_file_modules: bool,
234 /// Name of the root module this parser originated from. If `None`, then the
235 /// name is not known. This does not change while the parser is descending
236 /// into modules, and sub-parsers have new values for this name.
237 pub root_module_name: Option<String>,
238 crate expected_tokens: Vec<TokenType>,
239 token_cursor: TokenCursor,
240 desugar_doc_comments: bool,
241 /// Whether we should configure out of line modules as we parse.
248 frame: TokenCursorFrame,
249 stack: Vec<TokenCursorFrame>,
253 struct TokenCursorFrame {
254 delim: token::DelimToken,
257 tree_cursor: tokenstream::Cursor,
259 last_token: LastToken,
262 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
263 /// by the parser, and then that's transitively used to record the tokens that
264 /// each parse AST item is created with.
266 /// Right now this has two states, either collecting tokens or not collecting
267 /// tokens. If we're collecting tokens we just save everything off into a local
268 /// `Vec`. This should eventually though likely save tokens from the original
269 /// token stream and just use slicing of token streams to avoid creation of a
270 /// whole new vector.
272 /// The second state is where we're passively not recording tokens, but the last
273 /// token is still tracked for when we want to start recording tokens. This
274 /// "last token" means that when we start recording tokens we'll want to ensure
275 /// that this, the first token, is included in the output.
277 /// You can find some more example usage of this in the `collect_tokens` method
281 Collecting(Vec<TokenTree>),
282 Was(Option<TokenTree>),
285 impl TokenCursorFrame {
286 fn new(sp: Span, delimited: &Delimited) -> Self {
288 delim: delimited.delim,
290 open_delim: delimited.delim == token::NoDelim,
291 tree_cursor: delimited.stream().into_trees(),
292 close_delim: delimited.delim == token::NoDelim,
293 last_token: LastToken::Was(None),
299 fn next(&mut self) -> TokenAndSpan {
301 let tree = if !self.frame.open_delim {
302 self.frame.open_delim = true;
303 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
304 .open_tt(self.frame.span)
305 } else if let Some(tree) = self.frame.tree_cursor.next() {
307 } else if !self.frame.close_delim {
308 self.frame.close_delim = true;
309 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
310 .close_tt(self.frame.span)
311 } else if let Some(frame) = self.stack.pop() {
315 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
318 match self.frame.last_token {
319 LastToken::Collecting(ref mut v) => v.push(tree.clone()),
320 LastToken::Was(ref mut t) => *t = Some(tree.clone()),
324 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
325 TokenTree::Delimited(sp, ref delimited) => {
326 let frame = TokenCursorFrame::new(sp, delimited);
327 self.stack.push(mem::replace(&mut self.frame, frame));
333 fn next_desugared(&mut self) -> TokenAndSpan {
334 let (sp, name) = match self.next() {
335 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
339 let stripped = strip_doc_comment_decoration(&name.as_str());
341 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
342 // required to wrap the text.
343 let mut num_of_hashes = 0;
345 for ch in stripped.chars() {
348 '#' if count > 0 => count + 1,
351 num_of_hashes = cmp::max(num_of_hashes, count);
354 let body = TokenTree::Delimited(sp, Delimited {
355 delim: token::Bracket,
356 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
357 TokenTree::Token(sp, token::Eq),
358 TokenTree::Token(sp, token::Literal(
359 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
360 .iter().cloned().collect::<TokenStream>().into(),
363 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
364 delim: token::NoDelim,
365 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
366 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
367 .iter().cloned().collect::<TokenStream>().into()
369 [TokenTree::Token(sp, token::Pound), body]
370 .iter().cloned().collect::<TokenStream>().into()
378 #[derive(PartialEq, Eq, Clone)]
379 crate enum TokenType {
381 Keyword(keywords::Keyword),
390 fn to_string(&self) -> String {
392 TokenType::Token(ref t) => format!("`{}`", pprust::token_to_string(t)),
393 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
394 TokenType::Operator => "an operator".to_string(),
395 TokenType::Lifetime => "lifetime".to_string(),
396 TokenType::Ident => "identifier".to_string(),
397 TokenType::Path => "path".to_string(),
398 TokenType::Type => "type".to_string(),
403 /// Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
404 /// `IDENT<<u8 as Trait>::AssocTy>`.
406 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
407 /// that IDENT is not the ident of a fn trait
408 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
409 t == &token::ModSep || t == &token::Lt ||
410 t == &token::BinOp(token::Shl)
413 /// Information about the path to a module.
414 pub struct ModulePath {
417 pub result: Result<ModulePathSuccess, Error>,
420 pub struct ModulePathSuccess {
422 pub directory_ownership: DirectoryOwnership,
427 FileNotFoundForModule {
429 default_path: String,
430 secondary_path: String,
435 default_path: String,
436 secondary_path: String,
439 InclusiveRangeWithNoEnd,
443 fn span_err<S: Into<MultiSpan>>(self,
445 handler: &errors::Handler) -> DiagnosticBuilder {
447 Error::FileNotFoundForModule { ref mod_name,
451 let mut err = struct_span_err!(handler, sp, E0583,
452 "file not found for module `{}`", mod_name);
453 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
459 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
460 let mut err = struct_span_err!(handler, sp, E0584,
461 "file for module `{}` found at both {} and {}",
465 err.help("delete or rename one of them to remove the ambiguity");
468 Error::UselessDocComment => {
469 let mut err = struct_span_err!(handler, sp, E0585,
470 "found a documentation comment that doesn't document anything");
471 err.help("doc comments must come before what they document, maybe a comment was \
472 intended with `//`?");
475 Error::InclusiveRangeWithNoEnd => {
476 let mut err = struct_span_err!(handler, sp, E0586,
477 "inclusive range with no end");
478 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
488 AttributesParsed(ThinVec<Attribute>),
489 AlreadyParsed(P<Expr>),
492 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
493 fn from(o: Option<ThinVec<Attribute>>) -> Self {
494 if let Some(attrs) = o {
495 LhsExpr::AttributesParsed(attrs)
497 LhsExpr::NotYetParsed
502 impl From<P<Expr>> for LhsExpr {
503 fn from(expr: P<Expr>) -> Self {
504 LhsExpr::AlreadyParsed(expr)
508 /// Create a placeholder argument.
509 fn dummy_arg(span: Span) -> Arg {
510 let ident = Ident::new(keywords::Invalid.name(), span);
512 id: ast::DUMMY_NODE_ID,
513 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
519 id: ast::DUMMY_NODE_ID
521 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
524 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
525 enum TokenExpectType {
530 impl<'a> Parser<'a> {
531 pub fn new(sess: &'a ParseSess,
533 directory: Option<Directory<'a>>,
534 recurse_into_file_modules: bool,
535 desugar_doc_comments: bool)
537 let mut parser = Parser {
539 token: token::Whitespace,
540 span: syntax_pos::DUMMY_SP,
541 prev_span: syntax_pos::DUMMY_SP,
543 prev_token_kind: PrevTokenKind::Other,
544 restrictions: Restrictions::empty(),
545 recurse_into_file_modules,
546 directory: Directory {
547 path: Cow::from(PathBuf::new()),
548 ownership: DirectoryOwnership::Owned { relative: None }
550 root_module_name: None,
551 expected_tokens: Vec::new(),
552 token_cursor: TokenCursor {
553 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
554 delim: token::NoDelim,
559 desugar_doc_comments,
563 let tok = parser.next_tok();
564 parser.token = tok.tok;
565 parser.span = tok.sp;
567 if let Some(directory) = directory {
568 parser.directory = directory;
569 } else if !parser.span.source_equal(&DUMMY_SP) {
570 if let FileName::Real(mut path) = sess.codemap().span_to_unmapped_path(parser.span) {
572 parser.directory.path = Cow::from(path);
576 parser.process_potential_macro_variable();
580 fn next_tok(&mut self) -> TokenAndSpan {
581 let mut next = if self.desugar_doc_comments {
582 self.token_cursor.next_desugared()
584 self.token_cursor.next()
586 if next.sp == syntax_pos::DUMMY_SP {
587 // Tweak the location for better diagnostics, but keep syntactic context intact.
588 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
593 /// Convert the current token to a string using self's reader
594 pub fn this_token_to_string(&self) -> String {
595 pprust::token_to_string(&self.token)
598 fn token_descr(&self) -> Option<&'static str> {
599 Some(match &self.token {
600 t if t.is_special_ident() => "reserved identifier",
601 t if t.is_used_keyword() => "keyword",
602 t if t.is_unused_keyword() => "reserved keyword",
607 fn this_token_descr(&self) -> String {
608 if let Some(prefix) = self.token_descr() {
609 format!("{} `{}`", prefix, self.this_token_to_string())
611 format!("`{}`", self.this_token_to_string())
615 fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
616 let token_str = pprust::token_to_string(t);
617 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
620 crate fn unexpected<T>(&mut self) -> PResult<'a, T> {
621 match self.expect_one_of(&[], &[]) {
623 Ok(_) => unreachable!(),
627 /// Expect and consume the token t. Signal an error if
628 /// the next token is not t.
629 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
630 if self.expected_tokens.is_empty() {
631 if self.token == *t {
635 let token_str = pprust::token_to_string(t);
636 let this_token_str = self.this_token_to_string();
637 let mut err = self.fatal(&format!("expected `{}`, found `{}`",
640 err.span_label(self.span, format!("expected `{}`", token_str));
644 self.expect_one_of(slice::from_ref(t), &[])
648 /// Expect next token to be edible or inedible token. If edible,
649 /// then consume it; if inedible, then return without consuming
650 /// anything. Signal a fatal error if next token is unexpected.
651 fn expect_one_of(&mut self,
652 edible: &[token::Token],
653 inedible: &[token::Token]) -> PResult<'a, ()>{
654 fn tokens_to_string(tokens: &[TokenType]) -> String {
655 let mut i = tokens.iter();
656 // This might be a sign we need a connect method on Iterator.
658 .map_or("".to_string(), |t| t.to_string());
659 i.enumerate().fold(b, |mut b, (i, a)| {
660 if tokens.len() > 2 && i == tokens.len() - 2 {
662 } else if tokens.len() == 2 && i == tokens.len() - 2 {
667 b.push_str(&a.to_string());
671 if edible.contains(&self.token) {
674 } else if inedible.contains(&self.token) {
675 // leave it in the input
678 let mut expected = edible.iter()
679 .map(|x| TokenType::Token(x.clone()))
680 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
681 .chain(self.expected_tokens.iter().cloned())
682 .collect::<Vec<_>>();
683 expected.sort_by_cached_key(|x| x.to_string());
685 let expect = tokens_to_string(&expected[..]);
686 let actual = self.this_token_to_string();
687 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
688 let short_expect = if expected.len() > 6 {
689 format!("{} possible tokens", expected.len())
693 (format!("expected one of {}, found `{}`", expect, actual),
694 (self.sess.codemap().next_point(self.prev_span),
695 format!("expected one of {} here", short_expect)))
696 } else if expected.is_empty() {
697 (format!("unexpected token: `{}`", actual),
698 (self.prev_span, "unexpected token after this".to_string()))
700 (format!("expected {}, found `{}`", expect, actual),
701 (self.sess.codemap().next_point(self.prev_span),
702 format!("expected {} here", expect)))
704 let mut err = self.fatal(&msg_exp);
705 let sp = if self.token == token::Token::Eof {
706 // This is EOF, don't want to point at the following char, but rather the last token
712 let cm = self.sess.codemap();
713 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
714 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
715 // When the spans are in the same line, it means that the only content between
716 // them is whitespace, point at the found token in that case:
718 // X | () => { syntax error };
719 // | ^^^^^ expected one of 8 possible tokens here
721 // instead of having:
723 // X | () => { syntax error };
724 // | -^^^^^ unexpected token
726 // | expected one of 8 possible tokens here
727 err.span_label(self.span, label_exp);
730 err.span_label(sp, label_exp);
731 err.span_label(self.span, "unexpected token");
738 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
739 fn interpolated_or_expr_span(&self,
740 expr: PResult<'a, P<Expr>>)
741 -> PResult<'a, (Span, P<Expr>)> {
743 if self.prev_token_kind == PrevTokenKind::Interpolated {
751 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
752 let mut err = self.struct_span_err(self.span,
753 &format!("expected identifier, found {}",
754 self.this_token_descr()));
755 if let Some(token_descr) = self.token_descr() {
756 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
758 err.span_label(self.span, "expected identifier");
763 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
764 self.parse_ident_common(true)
767 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
769 token::Ident(ident, _) => {
770 if self.token.is_reserved_ident() {
771 let mut err = self.expected_ident_found();
778 let span = self.span;
780 Ok(Ident::new(ident.name, span))
783 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
784 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
786 self.expected_ident_found()
792 /// Check if the next token is `tok`, and return `true` if so.
794 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
796 fn check(&mut self, tok: &token::Token) -> bool {
797 let is_present = self.token == *tok;
798 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
802 /// Consume token 'tok' if it exists. Returns true if the given
803 /// token was present, false otherwise.
804 pub fn eat(&mut self, tok: &token::Token) -> bool {
805 let is_present = self.check(tok);
806 if is_present { self.bump() }
810 fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
811 self.expected_tokens.push(TokenType::Keyword(kw));
812 self.token.is_keyword(kw)
815 /// If the next token is the given keyword, eat it and return
816 /// true. Otherwise, return false.
817 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
818 if self.check_keyword(kw) {
826 fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
827 if self.token.is_keyword(kw) {
835 /// If the given word is not a keyword, signal an error.
836 /// If the next token is not the given word, signal an error.
837 /// Otherwise, eat it.
838 fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
839 if !self.eat_keyword(kw) {
846 fn check_ident(&mut self) -> bool {
847 if self.token.is_ident() {
850 self.expected_tokens.push(TokenType::Ident);
855 fn check_path(&mut self) -> bool {
856 if self.token.is_path_start() {
859 self.expected_tokens.push(TokenType::Path);
864 fn check_type(&mut self) -> bool {
865 if self.token.can_begin_type() {
868 self.expected_tokens.push(TokenType::Type);
873 /// Expect and consume a `+`. if `+=` is seen, replace it with a `=`
874 /// and continue. If a `+` is not seen, return false.
876 /// This is using when token splitting += into +.
877 /// See issue 47856 for an example of when this may occur.
878 fn eat_plus(&mut self) -> bool {
879 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
881 token::BinOp(token::Plus) => {
885 token::BinOpEq(token::Plus) => {
886 let span = self.span.with_lo(self.span.lo() + BytePos(1));
887 self.bump_with(token::Eq, span);
895 /// Checks to see if the next token is either `+` or `+=`.
896 /// Otherwise returns false.
897 fn check_plus(&mut self) -> bool {
898 if self.token.is_like_plus() {
902 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Plus)));
907 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
908 /// `&` and continue. If an `&` is not seen, signal an error.
909 fn expect_and(&mut self) -> PResult<'a, ()> {
910 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
912 token::BinOp(token::And) => {
917 let span = self.span.with_lo(self.span.lo() + BytePos(1));
918 Ok(self.bump_with(token::BinOp(token::And), span))
920 _ => self.unexpected()
924 /// Expect and consume an `|`. If `||` is seen, replace it with a single
925 /// `|` and continue. If an `|` is not seen, signal an error.
926 fn expect_or(&mut self) -> PResult<'a, ()> {
927 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
929 token::BinOp(token::Or) => {
934 let span = self.span.with_lo(self.span.lo() + BytePos(1));
935 Ok(self.bump_with(token::BinOp(token::Or), span))
937 _ => self.unexpected()
941 fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
943 None => {/* everything ok */}
945 let text = suf.as_str();
947 self.span_bug(sp, "found empty literal suffix in Some")
949 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
954 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
955 /// `<` and continue. If a `<` is not seen, return false.
957 /// This is meant to be used when parsing generics on a path to get the
959 fn eat_lt(&mut self) -> bool {
960 self.expected_tokens.push(TokenType::Token(token::Lt));
966 token::BinOp(token::Shl) => {
967 let span = self.span.with_lo(self.span.lo() + BytePos(1));
968 self.bump_with(token::Lt, span);
975 fn expect_lt(&mut self) -> PResult<'a, ()> {
983 /// Expect and consume a GT. if a >> is seen, replace it
984 /// with a single > and continue. If a GT is not seen,
986 fn expect_gt(&mut self) -> PResult<'a, ()> {
987 self.expected_tokens.push(TokenType::Token(token::Gt));
993 token::BinOp(token::Shr) => {
994 let span = self.span.with_lo(self.span.lo() + BytePos(1));
995 Ok(self.bump_with(token::Gt, span))
997 token::BinOpEq(token::Shr) => {
998 let span = self.span.with_lo(self.span.lo() + BytePos(1));
999 Ok(self.bump_with(token::Ge, span))
1002 let span = self.span.with_lo(self.span.lo() + BytePos(1));
1003 Ok(self.bump_with(token::Eq, span))
1005 _ => self.unexpected()
1009 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1010 /// passes through any errors encountered. Used for error recovery.
1011 fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1012 let handler = self.diagnostic();
1014 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1016 TokenExpectType::Expect,
1017 |p| Ok(p.parse_token_tree())) {
1018 handler.cancel(err);
1022 /// Parse a sequence, including the closing delimiter. The function
1023 /// f must consume tokens until reaching the next separator or
1024 /// closing bracket.
1025 pub fn parse_seq_to_end<T, F>(&mut self,
1029 -> PResult<'a, Vec<T>> where
1030 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1032 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1037 /// Parse a sequence, not including the closing delimiter. The function
1038 /// f must consume tokens until reaching the next separator or
1039 /// closing bracket.
1040 fn parse_seq_to_before_end<T, F>(&mut self,
1044 -> PResult<'a, Vec<T>>
1045 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1047 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1050 fn parse_seq_to_before_tokens<T, F>(&mut self,
1051 kets: &[&token::Token],
1053 expect: TokenExpectType,
1055 -> PResult<'a, Vec<T>>
1056 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1058 let mut first: bool = true;
1060 while !kets.iter().any(|k| {
1062 TokenExpectType::Expect => self.check(k),
1063 TokenExpectType::NoExpect => self.token == **k,
1067 token::CloseDelim(..) | token::Eof => break,
1070 if let Some(ref t) = sep.sep {
1074 if let Err(mut e) = self.expect(t) {
1075 // Attempt to keep parsing if it was a similar separator
1076 if let Some(ref tokens) = t.similar_tokens() {
1077 if tokens.contains(&self.token) {
1082 // Attempt to keep parsing if it was an omitted separator
1096 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1098 TokenExpectType::Expect => self.check(k),
1099 TokenExpectType::NoExpect => self.token == **k,
1112 /// Parse a sequence, including the closing delimiter. The function
1113 /// f must consume tokens until reaching the next separator or
1114 /// closing bracket.
1115 fn parse_unspanned_seq<T, F>(&mut self,
1120 -> PResult<'a, Vec<T>> where
1121 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1124 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1125 if self.token == *ket {
1131 /// Advance the parser by one token
1132 pub fn bump(&mut self) {
1133 if self.prev_token_kind == PrevTokenKind::Eof {
1134 // Bumping after EOF is a bad sign, usually an infinite loop.
1135 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1138 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1140 // Record last token kind for possible error recovery.
1141 self.prev_token_kind = match self.token {
1142 token::DocComment(..) => PrevTokenKind::DocComment,
1143 token::Comma => PrevTokenKind::Comma,
1144 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1145 token::Interpolated(..) => PrevTokenKind::Interpolated,
1146 token::Eof => PrevTokenKind::Eof,
1147 token::Ident(..) => PrevTokenKind::Ident,
1148 _ => PrevTokenKind::Other,
1151 let next = self.next_tok();
1152 self.span = next.sp;
1153 self.token = next.tok;
1154 self.expected_tokens.clear();
1155 // check after each token
1156 self.process_potential_macro_variable();
1159 /// Advance the parser using provided token as a next one. Use this when
1160 /// consuming a part of a token. For example a single `<` from `<<`.
1161 fn bump_with(&mut self, next: token::Token, span: Span) {
1162 self.prev_span = self.span.with_hi(span.lo());
1163 // It would be incorrect to record the kind of the current token, but
1164 // fortunately for tokens currently using `bump_with`, the
1165 // prev_token_kind will be of no use anyway.
1166 self.prev_token_kind = PrevTokenKind::Other;
1169 self.expected_tokens.clear();
1172 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1173 F: FnOnce(&token::Token) -> R,
1176 return f(&self.token)
1179 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1180 Some(tree) => match tree {
1181 TokenTree::Token(_, tok) => tok,
1182 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1184 None => token::CloseDelim(self.token_cursor.frame.delim),
1188 fn look_ahead_span(&self, dist: usize) -> Span {
1193 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1194 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1195 None => self.look_ahead_span(dist - 1),
1198 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1199 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1201 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1202 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1204 fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1205 err.span_err(sp, self.diagnostic())
1207 fn span_fatal_help<S: Into<MultiSpan>>(&self,
1210 help: &str) -> DiagnosticBuilder<'a> {
1211 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1215 fn bug(&self, m: &str) -> ! {
1216 self.sess.span_diagnostic.span_bug(self.span, m)
1218 fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1219 self.sess.span_diagnostic.span_err(sp, m)
1221 fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1222 self.sess.span_diagnostic.struct_span_err(sp, m)
1224 crate fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1225 self.sess.span_diagnostic.span_bug(sp, m)
1227 crate fn abort_if_errors(&self) {
1228 self.sess.span_diagnostic.abort_if_errors();
1231 fn cancel(&self, err: &mut DiagnosticBuilder) {
1232 self.sess.span_diagnostic.cancel(err)
1235 crate fn diagnostic(&self) -> &'a errors::Handler {
1236 &self.sess.span_diagnostic
1239 /// Is the current token one of the keywords that signals a bare function
1241 fn token_is_bare_fn_keyword(&mut self) -> bool {
1242 self.check_keyword(keywords::Fn) ||
1243 self.check_keyword(keywords::Unsafe) ||
1244 self.check_keyword(keywords::Extern) && self.is_extern_non_path()
1247 /// parse a TyKind::BareFn type:
1248 fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>)
1249 -> PResult<'a, TyKind> {
1252 [unsafe] [extern "ABI"] fn (S) -> T
1262 let unsafety = self.parse_unsafety();
1263 let abi = if self.eat_keyword(keywords::Extern) {
1264 self.parse_opt_abi()?.unwrap_or(Abi::C)
1269 self.expect_keyword(keywords::Fn)?;
1270 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1271 let ret_ty = self.parse_ret_ty(false)?;
1272 let decl = P(FnDecl {
1277 Ok(TyKind::BareFn(P(BareFnTy {
1285 /// Parse unsafety: `unsafe` or nothing.
1286 fn parse_unsafety(&mut self) -> Unsafety {
1287 if self.eat_keyword(keywords::Unsafe) {
1294 /// Parse the items in a trait declaration
1295 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1296 maybe_whole!(self, NtTraitItem, |x| x);
1297 let attrs = self.parse_outer_attributes()?;
1298 let (mut item, tokens) = self.collect_tokens(|this| {
1299 this.parse_trait_item_(at_end, attrs)
1301 // See `parse_item` for why this clause is here.
1302 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1303 item.tokens = Some(tokens);
1308 fn parse_trait_item_(&mut self,
1310 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1313 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1314 let (generics, TyParam {ident, bounds, default, ..}) =
1315 self.parse_trait_item_assoc_ty(vec![])?;
1316 (ident, TraitItemKind::Type(bounds, default), generics)
1317 } else if self.is_const_item() {
1318 self.expect_keyword(keywords::Const)?;
1319 let ident = self.parse_ident()?;
1320 self.expect(&token::Colon)?;
1321 let ty = self.parse_ty()?;
1322 let default = if self.check(&token::Eq) {
1324 let expr = self.parse_expr()?;
1325 self.expect(&token::Semi)?;
1328 self.expect(&token::Semi)?;
1331 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1332 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1333 // trait item macro.
1334 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1336 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
1338 let ident = self.parse_ident()?;
1339 let mut generics = self.parse_generics()?;
1341 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1342 // This is somewhat dubious; We don't want to allow
1343 // argument names to be left off if there is a
1345 p.parse_arg_general(false)
1347 generics.where_clause = self.parse_where_clause()?;
1349 let sig = ast::MethodSig {
1356 let body = match self.token {
1360 debug!("parse_trait_methods(): parsing required method");
1363 token::OpenDelim(token::Brace) => {
1364 debug!("parse_trait_methods(): parsing provided method");
1366 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1367 attrs.extend(inner_attrs.iter().cloned());
1371 let token_str = self.this_token_to_string();
1372 let mut err = self.fatal(&format!("expected `;` or `{{`, found `{}`",
1374 err.span_label(self.span, "expected `;` or `{`");
1378 (ident, ast::TraitItemKind::Method(sig, body), generics)
1382 id: ast::DUMMY_NODE_ID,
1387 span: lo.to(self.prev_span),
1392 /// Parse optional return type [ -> TY ] in function decl
1393 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1394 if self.eat(&token::RArrow) {
1395 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1397 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1402 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1403 self.parse_ty_common(true, true)
1406 /// Parse a type in restricted contexts where `+` is not permitted.
1407 /// Example 1: `&'a TYPE`
1408 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1409 /// Example 2: `value1 as TYPE + value2`
1410 /// `+` is prohibited to avoid interactions with expression grammar.
1411 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1412 self.parse_ty_common(false, true)
1415 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1416 -> PResult<'a, P<Ty>> {
1417 maybe_whole!(self, NtTy, |x| x);
1420 let mut impl_dyn_multi = false;
1421 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1422 // `(TYPE)` is a parenthesized type.
1423 // `(TYPE,)` is a tuple with a single field of type TYPE.
1424 let mut ts = vec![];
1425 let mut last_comma = false;
1426 while self.token != token::CloseDelim(token::Paren) {
1427 ts.push(self.parse_ty()?);
1428 if self.eat(&token::Comma) {
1435 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1436 self.expect(&token::CloseDelim(token::Paren))?;
1438 if ts.len() == 1 && !last_comma {
1439 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1440 let maybe_bounds = allow_plus && self.token.is_like_plus();
1442 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1443 TyKind::Path(None, ref path) if maybe_bounds => {
1444 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1446 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1447 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1448 let path = match bounds[0] {
1449 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1450 _ => self.bug("unexpected lifetime bound"),
1452 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1455 _ => TyKind::Paren(P(ty))
1460 } else if self.eat(&token::Not) {
1463 } else if self.eat(&token::BinOp(token::Star)) {
1465 TyKind::Ptr(self.parse_ptr()?)
1466 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1468 let t = self.parse_ty()?;
1469 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1470 let t = match self.maybe_parse_fixed_length_of_vec()? {
1471 None => TyKind::Slice(t),
1472 Some(length) => TyKind::Array(t, AnonConst {
1473 id: ast::DUMMY_NODE_ID,
1477 self.expect(&token::CloseDelim(token::Bracket))?;
1479 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1482 self.parse_borrowed_pointee()?
1483 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1485 // In order to not be ambiguous, the type must be surrounded by parens.
1486 self.expect(&token::OpenDelim(token::Paren))?;
1488 id: ast::DUMMY_NODE_ID,
1489 value: self.parse_expr()?,
1491 self.expect(&token::CloseDelim(token::Paren))?;
1493 } else if self.eat_keyword(keywords::Underscore) {
1494 // A type to be inferred `_`
1496 } else if self.token_is_bare_fn_keyword() {
1497 // Function pointer type
1498 self.parse_ty_bare_fn(Vec::new())?
1499 } else if self.check_keyword(keywords::For) {
1500 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1501 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1502 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1504 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1505 if self.token_is_bare_fn_keyword() {
1506 self.parse_ty_bare_fn(lifetime_defs)?
1508 let path = self.parse_path(PathStyle::Type)?;
1509 let parse_plus = allow_plus && self.check_plus();
1510 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1512 } else if self.eat_keyword(keywords::Impl) {
1513 // Always parse bounds greedily for better error recovery.
1514 let bounds = self.parse_ty_param_bounds()?;
1515 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1516 TyKind::ImplTrait(bounds)
1517 } else if self.check_keyword(keywords::Dyn) &&
1518 self.look_ahead(1, |t| t.can_begin_bound() &&
1519 !can_continue_type_after_non_fn_ident(t)) {
1520 self.bump(); // `dyn`
1521 // Always parse bounds greedily for better error recovery.
1522 let bounds = self.parse_ty_param_bounds()?;
1523 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1524 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1525 } else if self.check(&token::Question) ||
1526 self.check_lifetime() && self.look_ahead(1, |t| t.is_like_plus()) {
1527 // Bound list (trait object type)
1528 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?,
1529 TraitObjectSyntax::None)
1530 } else if self.eat_lt() {
1532 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1533 TyKind::Path(Some(qself), path)
1534 } else if self.token.is_path_start() {
1536 let path = self.parse_path(PathStyle::Type)?;
1537 if self.eat(&token::Not) {
1538 // Macro invocation in type position
1539 let (delim, tts) = self.expect_delimited_token_tree()?;
1540 let node = Mac_ { path, tts, delim };
1541 TyKind::Mac(respan(lo.to(self.prev_span), node))
1543 // Just a type path or bound list (trait object type) starting with a trait.
1545 // `Trait1 + Trait2 + 'a`
1546 if allow_plus && self.check_plus() {
1547 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1549 TyKind::Path(None, path)
1553 let msg = format!("expected type, found {}", self.this_token_descr());
1554 return Err(self.fatal(&msg));
1557 let span = lo.to(self.prev_span);
1558 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1560 // Try to recover from use of `+` with incorrect priority.
1561 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1562 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1563 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1568 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1569 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1570 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1571 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1573 self.eat_plus(); // `+`, or `+=` gets split and `+` is discarded
1574 bounds.append(&mut self.parse_ty_param_bounds()?);
1576 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1579 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1580 if !allow_plus && impl_dyn_multi {
1581 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1582 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1583 .span_suggestion_with_applicability(
1585 "use parentheses to disambiguate",
1587 Applicability::MachineApplicable
1592 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1593 // Do not add `+` to expected tokens.
1594 if !allow_plus || !self.token.is_like_plus() {
1599 let bounds = self.parse_ty_param_bounds()?;
1600 let sum_span = ty.span.to(self.prev_span);
1602 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1603 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1606 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1607 let sum_with_parens = pprust::to_string(|s| {
1608 use print::pprust::PrintState;
1611 s.print_opt_lifetime(lifetime)?;
1612 s.print_mutability(mut_ty.mutbl)?;
1614 s.print_type(&mut_ty.ty)?;
1615 s.print_bounds(" +", &bounds)?;
1618 err.span_suggestion_with_applicability(
1620 "try adding parentheses",
1622 Applicability::MachineApplicable
1625 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1626 err.span_label(sum_span, "perhaps you forgot parentheses?");
1629 err.span_label(sum_span, "expected a path");
1636 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1637 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1639 // Do not add `::` to expected tokens.
1640 if !allow_recovery || self.token != token::ModSep {
1643 let ty = match base.to_ty() {
1645 None => return Ok(base),
1648 self.bump(); // `::`
1649 let mut segments = Vec::new();
1650 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1652 let span = ty.span.to(self.prev_span);
1653 let path_span = span.to(span); // use an empty path since `position` == 0
1654 let recovered = base.to_recovered(
1655 Some(QSelf { ty, path_span, position: 0 }),
1656 ast::Path { segments, span },
1660 .struct_span_err(span, "missing angle brackets in associated item path")
1661 .span_suggestion_with_applicability( // this is a best-effort recovery
1662 span, "try", recovered.to_string(), Applicability::MaybeIncorrect
1668 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1669 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1670 let mutbl = self.parse_mutability();
1671 let ty = self.parse_ty_no_plus()?;
1672 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1675 fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1676 let mutbl = if self.eat_keyword(keywords::Mut) {
1678 } else if self.eat_keyword(keywords::Const) {
1679 Mutability::Immutable
1681 let span = self.prev_span;
1683 "expected mut or const in raw pointer type (use \
1684 `*mut T` or `*const T` as appropriate)");
1685 Mutability::Immutable
1687 let t = self.parse_ty_no_plus()?;
1688 Ok(MutTy { ty: t, mutbl: mutbl })
1691 fn is_named_argument(&mut self) -> bool {
1692 let offset = match self.token {
1693 token::Interpolated(ref nt) => match nt.0 {
1694 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1697 token::BinOp(token::And) | token::AndAnd => 1,
1698 _ if self.token.is_keyword(keywords::Mut) => 1,
1702 self.look_ahead(offset, |t| t.is_ident()) &&
1703 self.look_ahead(offset + 1, |t| t == &token::Colon)
1706 /// This version of parse arg doesn't necessarily require
1707 /// identifier names.
1708 fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1709 maybe_whole!(self, NtArg, |x| x);
1711 let (pat, ty) = if require_name || self.is_named_argument() {
1712 debug!("parse_arg_general parse_pat (require_name:{})",
1714 let pat = self.parse_pat()?;
1716 self.expect(&token::Colon)?;
1717 (pat, self.parse_ty()?)
1719 debug!("parse_arg_general ident_to_pat");
1720 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1721 let ty = self.parse_ty()?;
1723 id: ast::DUMMY_NODE_ID,
1724 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
1733 id: ast::DUMMY_NODE_ID,
1737 /// Parse a single function argument
1738 crate fn parse_arg(&mut self) -> PResult<'a, Arg> {
1739 self.parse_arg_general(true)
1742 /// Parse an argument in a lambda header e.g. |arg, arg|
1743 fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1744 let pat = self.parse_pat()?;
1745 let t = if self.eat(&token::Colon) {
1749 id: ast::DUMMY_NODE_ID,
1750 node: TyKind::Infer,
1757 id: ast::DUMMY_NODE_ID
1761 fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1762 if self.eat(&token::Semi) {
1763 Ok(Some(self.parse_expr()?))
1769 /// Matches token_lit = LIT_INTEGER | ...
1770 fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1771 let out = match self.token {
1772 token::Interpolated(ref nt) => match nt.0 {
1773 token::NtExpr(ref v) | token::NtLiteral(ref v) => match v.node {
1774 ExprKind::Lit(ref lit) => { lit.node.clone() }
1775 _ => { return self.unexpected_last(&self.token); }
1777 _ => { return self.unexpected_last(&self.token); }
1779 token::Literal(lit, suf) => {
1780 let diag = Some((self.span, &self.sess.span_diagnostic));
1781 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1785 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1790 _ => { return self.unexpected_last(&self.token); }
1797 /// Matches lit = true | false | token_lit
1798 crate fn parse_lit(&mut self) -> PResult<'a, Lit> {
1800 let lit = if self.eat_keyword(keywords::True) {
1802 } else if self.eat_keyword(keywords::False) {
1803 LitKind::Bool(false)
1805 let lit = self.parse_lit_token()?;
1808 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1811 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1812 crate fn parse_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1813 maybe_whole_expr!(self);
1815 let minus_lo = self.span;
1816 let minus_present = self.eat(&token::BinOp(token::Minus));
1818 let literal = P(self.parse_lit()?);
1819 let hi = self.prev_span;
1820 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1823 let minus_hi = self.prev_span;
1824 let unary = self.mk_unary(UnOp::Neg, expr);
1825 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1831 fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1833 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
1834 let span = self.span;
1836 Ok(Ident::new(ident.name, span))
1838 _ => self.parse_ident(),
1842 /// Parses qualified path.
1843 /// Assumes that the leading `<` has been parsed already.
1845 /// `qualified_path = <type [as trait_ref]>::path`
1850 /// `<T as U>::F::a<S>` (without disambiguator)
1851 /// `<T as U>::F::a::<S>` (with disambiguator)
1852 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1853 let lo = self.prev_span;
1854 let ty = self.parse_ty()?;
1856 // `path` will contain the prefix of the path up to the `>`,
1857 // if any (e.g., `U` in the `<T as U>::*` examples
1858 // above). `path_span` has the span of that path, or an empty
1859 // span in the case of something like `<T>::Bar`.
1860 let (mut path, path_span);
1861 if self.eat_keyword(keywords::As) {
1862 let path_lo = self.span;
1863 path = self.parse_path(PathStyle::Type)?;
1864 path_span = path_lo.to(self.prev_span);
1866 path = ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP };
1867 path_span = self.span.to(self.span);
1870 self.expect(&token::Gt)?;
1871 self.expect(&token::ModSep)?;
1873 let qself = QSelf { ty, path_span, position: path.segments.len() };
1874 self.parse_path_segments(&mut path.segments, style, true)?;
1876 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1879 /// Parses simple paths.
1881 /// `path = [::] segment+`
1882 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1885 /// `a::b::C<D>` (without disambiguator)
1886 /// `a::b::C::<D>` (with disambiguator)
1887 /// `Fn(Args)` (without disambiguator)
1888 /// `Fn::(Args)` (with disambiguator)
1889 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1890 self.parse_path_common(style, true)
1893 crate fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1894 -> PResult<'a, ast::Path> {
1895 maybe_whole!(self, NtPath, |path| {
1896 if style == PathStyle::Mod &&
1897 path.segments.iter().any(|segment| segment.parameters.is_some()) {
1898 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1903 let lo = self.meta_var_span.unwrap_or(self.span);
1904 let mut segments = Vec::new();
1905 if self.eat(&token::ModSep) {
1906 segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
1908 self.parse_path_segments(&mut segments, style, enable_warning)?;
1910 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1913 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1914 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1915 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1916 let meta_ident = match self.token {
1917 token::Interpolated(ref nt) => match nt.0 {
1918 token::NtMeta(ref meta) => match meta.node {
1919 ast::MetaItemKind::Word => Some(meta.ident.clone()),
1926 if let Some(path) = meta_ident {
1930 self.parse_path(style)
1933 fn parse_path_segments(&mut self,
1934 segments: &mut Vec<PathSegment>,
1936 enable_warning: bool)
1937 -> PResult<'a, ()> {
1939 segments.push(self.parse_path_segment(style, enable_warning)?);
1941 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1947 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
1948 -> PResult<'a, PathSegment> {
1949 let ident = self.parse_path_segment_ident()?;
1951 let is_args_start = |token: &token::Token| match *token {
1952 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
1955 let check_args_start = |this: &mut Self| {
1956 this.expected_tokens.extend_from_slice(
1957 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1959 is_args_start(&this.token)
1962 Ok(if style == PathStyle::Type && check_args_start(self) ||
1963 style != PathStyle::Mod && self.check(&token::ModSep)
1964 && self.look_ahead(1, |t| is_args_start(t)) {
1965 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1967 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
1968 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
1969 .span_label(self.prev_span, "try removing `::`").emit();
1972 let parameters = if self.eat_lt() {
1974 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1976 let span = lo.to(self.prev_span);
1977 AngleBracketedParameterData { lifetimes, types, bindings, span }.into()
1981 let inputs = self.parse_seq_to_before_tokens(
1982 &[&token::CloseDelim(token::Paren)],
1983 SeqSep::trailing_allowed(token::Comma),
1984 TokenExpectType::Expect,
1987 let output = if self.eat(&token::RArrow) {
1988 Some(self.parse_ty_common(false, false)?)
1992 let span = lo.to(self.prev_span);
1993 ParenthesizedParameterData { inputs, output, span }.into()
1996 PathSegment { ident, parameters }
1998 // Generic arguments are not found.
1999 PathSegment::from_ident(ident)
2003 crate fn check_lifetime(&mut self) -> bool {
2004 self.expected_tokens.push(TokenType::Lifetime);
2005 self.token.is_lifetime()
2008 /// Parse single lifetime 'a or panic.
2009 crate fn expect_lifetime(&mut self) -> Lifetime {
2010 if let Some(ident) = self.token.lifetime() {
2011 let span = self.span;
2013 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2015 self.span_bug(self.span, "not a lifetime")
2019 fn eat_label(&mut self) -> Option<Label> {
2020 if let Some(ident) = self.token.lifetime() {
2021 let span = self.span;
2023 Some(Label { ident: Ident::new(ident.name, span) })
2029 /// Parse mutability (`mut` or nothing).
2030 fn parse_mutability(&mut self) -> Mutability {
2031 if self.eat_keyword(keywords::Mut) {
2034 Mutability::Immutable
2038 fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2039 if let token::Literal(token::Integer(name), None) = self.token {
2041 Ok(Ident::new(name, self.prev_span))
2043 self.parse_ident_common(false)
2047 /// Parse ident (COLON expr)?
2048 fn parse_field(&mut self) -> PResult<'a, Field> {
2049 let attrs = self.parse_outer_attributes()?;
2052 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2053 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2054 let fieldname = self.parse_field_name()?;
2056 (fieldname, self.parse_expr()?, false)
2058 let fieldname = self.parse_ident_common(false)?;
2060 // Mimic `x: x` for the `x` field shorthand.
2061 let path = ast::Path::from_ident(fieldname);
2062 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2063 (fieldname, expr, true)
2067 span: lo.to(expr.span),
2070 attrs: attrs.into(),
2074 fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2075 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2078 fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2079 ExprKind::Unary(unop, expr)
2082 fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2083 ExprKind::Binary(binop, lhs, rhs)
2086 fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2087 ExprKind::Call(f, args)
2090 fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2091 ExprKind::Index(expr, idx)
2094 fn mk_range(&mut self,
2095 start: Option<P<Expr>>,
2096 end: Option<P<Expr>>,
2097 limits: RangeLimits)
2098 -> PResult<'a, ast::ExprKind> {
2099 if end.is_none() && limits == RangeLimits::Closed {
2100 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2102 Ok(ExprKind::Range(start, end, limits))
2106 fn mk_assign_op(&mut self, binop: ast::BinOp,
2107 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2108 ExprKind::AssignOp(binop, lhs, rhs)
2111 fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2113 id: ast::DUMMY_NODE_ID,
2114 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2120 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, ThinTokenStream)> {
2121 let delim = match self.token {
2122 token::OpenDelim(delim) => delim,
2124 let msg = "expected open delimiter";
2125 let mut err = self.fatal(msg);
2126 err.span_label(self.span, msg);
2130 let delimited = match self.parse_token_tree() {
2131 TokenTree::Delimited(_, delimited) => delimited,
2132 _ => unreachable!(),
2134 let delim = match delim {
2135 token::Paren => MacDelimiter::Parenthesis,
2136 token::Bracket => MacDelimiter::Bracket,
2137 token::Brace => MacDelimiter::Brace,
2138 token::NoDelim => self.bug("unexpected no delimiter"),
2140 Ok((delim, delimited.stream().into()))
2143 /// At the bottom (top?) of the precedence hierarchy,
2144 /// parse things like parenthesized exprs,
2145 /// macros, return, etc.
2147 /// NB: This does not parse outer attributes,
2148 /// and is private because it only works
2149 /// correctly if called from parse_dot_or_call_expr().
2150 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2151 maybe_whole_expr!(self);
2153 // Outer attributes are already parsed and will be
2154 // added to the return value after the fact.
2156 // Therefore, prevent sub-parser from parsing
2157 // attributes by giving them a empty "already parsed" list.
2158 let mut attrs = ThinVec::new();
2161 let mut hi = self.span;
2165 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2167 token::OpenDelim(token::Paren) => {
2170 attrs.extend(self.parse_inner_attributes()?);
2172 // (e) is parenthesized e
2173 // (e,) is a tuple with only one field, e
2174 let mut es = vec![];
2175 let mut trailing_comma = false;
2176 while self.token != token::CloseDelim(token::Paren) {
2177 es.push(self.parse_expr()?);
2178 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2179 if self.check(&token::Comma) {
2180 trailing_comma = true;
2184 trailing_comma = false;
2190 hi = self.prev_span;
2191 ex = if es.len() == 1 && !trailing_comma {
2192 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2197 token::OpenDelim(token::Brace) => {
2198 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2200 token::BinOp(token::Or) | token::OrOr => {
2201 return self.parse_lambda_expr(attrs);
2203 token::OpenDelim(token::Bracket) => {
2206 attrs.extend(self.parse_inner_attributes()?);
2208 if self.check(&token::CloseDelim(token::Bracket)) {
2211 ex = ExprKind::Array(Vec::new());
2214 let first_expr = self.parse_expr()?;
2215 if self.check(&token::Semi) {
2216 // Repeating array syntax: [ 0; 512 ]
2218 let count = AnonConst {
2219 id: ast::DUMMY_NODE_ID,
2220 value: self.parse_expr()?,
2222 self.expect(&token::CloseDelim(token::Bracket))?;
2223 ex = ExprKind::Repeat(first_expr, count);
2224 } else if self.check(&token::Comma) {
2225 // Vector with two or more elements.
2227 let remaining_exprs = self.parse_seq_to_end(
2228 &token::CloseDelim(token::Bracket),
2229 SeqSep::trailing_allowed(token::Comma),
2230 |p| Ok(p.parse_expr()?)
2232 let mut exprs = vec![first_expr];
2233 exprs.extend(remaining_exprs);
2234 ex = ExprKind::Array(exprs);
2236 // Vector with one element.
2237 self.expect(&token::CloseDelim(token::Bracket))?;
2238 ex = ExprKind::Array(vec![first_expr]);
2241 hi = self.prev_span;
2245 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2247 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2249 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2250 return self.parse_lambda_expr(attrs);
2252 if self.eat_keyword(keywords::If) {
2253 return self.parse_if_expr(attrs);
2255 if self.eat_keyword(keywords::For) {
2256 let lo = self.prev_span;
2257 return self.parse_for_expr(None, lo, attrs);
2259 if self.eat_keyword(keywords::While) {
2260 let lo = self.prev_span;
2261 return self.parse_while_expr(None, lo, attrs);
2263 if let Some(label) = self.eat_label() {
2264 let lo = label.ident.span;
2265 self.expect(&token::Colon)?;
2266 if self.eat_keyword(keywords::While) {
2267 return self.parse_while_expr(Some(label), lo, attrs)
2269 if self.eat_keyword(keywords::For) {
2270 return self.parse_for_expr(Some(label), lo, attrs)
2272 if self.eat_keyword(keywords::Loop) {
2273 return self.parse_loop_expr(Some(label), lo, attrs)
2275 if self.token == token::OpenDelim(token::Brace) {
2276 return self.parse_block_expr(Some(label),
2278 BlockCheckMode::Default,
2281 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2282 let mut err = self.fatal(msg);
2283 err.span_label(self.span, msg);
2286 if self.eat_keyword(keywords::Loop) {
2287 let lo = self.prev_span;
2288 return self.parse_loop_expr(None, lo, attrs);
2290 if self.eat_keyword(keywords::Continue) {
2291 let label = self.eat_label();
2292 let ex = ExprKind::Continue(label);
2293 let hi = self.prev_span;
2294 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2296 if self.eat_keyword(keywords::Match) {
2297 return self.parse_match_expr(attrs);
2299 if self.eat_keyword(keywords::Unsafe) {
2300 return self.parse_block_expr(
2303 BlockCheckMode::Unsafe(ast::UserProvided),
2306 if self.is_catch_expr() {
2308 assert!(self.eat_keyword(keywords::Do));
2309 assert!(self.eat_keyword(keywords::Catch));
2310 return self.parse_catch_expr(lo, attrs);
2312 if self.eat_keyword(keywords::Return) {
2313 if self.token.can_begin_expr() {
2314 let e = self.parse_expr()?;
2316 ex = ExprKind::Ret(Some(e));
2318 ex = ExprKind::Ret(None);
2320 } else if self.eat_keyword(keywords::Break) {
2321 let label = self.eat_label();
2322 let e = if self.token.can_begin_expr()
2323 && !(self.token == token::OpenDelim(token::Brace)
2324 && self.restrictions.contains(
2325 Restrictions::NO_STRUCT_LITERAL)) {
2326 Some(self.parse_expr()?)
2330 ex = ExprKind::Break(label, e);
2331 hi = self.prev_span;
2332 } else if self.eat_keyword(keywords::Yield) {
2333 if self.token.can_begin_expr() {
2334 let e = self.parse_expr()?;
2336 ex = ExprKind::Yield(Some(e));
2338 ex = ExprKind::Yield(None);
2340 } else if self.token.is_keyword(keywords::Let) {
2341 // Catch this syntax error here, instead of in `parse_ident`, so
2342 // that we can explicitly mention that let is not to be used as an expression
2343 let mut db = self.fatal("expected expression, found statement (`let`)");
2344 db.span_label(self.span, "expected expression");
2345 db.note("variable declaration using `let` is a statement");
2347 } else if self.token.is_path_start() {
2348 let pth = self.parse_path(PathStyle::Expr)?;
2350 // `!`, as an operator, is prefix, so we know this isn't that
2351 if self.eat(&token::Not) {
2352 // MACRO INVOCATION expression
2353 let (delim, tts) = self.expect_delimited_token_tree()?;
2354 let hi = self.prev_span;
2355 let node = Mac_ { path: pth, tts, delim };
2356 return Ok(self.mk_mac_expr(lo.to(hi), node, attrs))
2358 if self.check(&token::OpenDelim(token::Brace)) {
2359 // This is a struct literal, unless we're prohibited
2360 // from parsing struct literals here.
2361 let prohibited = self.restrictions.contains(
2362 Restrictions::NO_STRUCT_LITERAL
2365 return self.parse_struct_expr(lo, pth, attrs);
2370 ex = ExprKind::Path(None, pth);
2372 match self.parse_literal_maybe_minus() {
2375 ex = expr.node.clone();
2378 self.cancel(&mut err);
2379 let msg = format!("expected expression, found {}",
2380 self.this_token_descr());
2381 let mut err = self.fatal(&msg);
2382 err.span_label(self.span, "expected expression");
2390 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2391 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2396 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2397 -> PResult<'a, P<Expr>> {
2398 let struct_sp = lo.to(self.prev_span);
2400 let mut fields = Vec::new();
2401 let mut base = None;
2403 attrs.extend(self.parse_inner_attributes()?);
2405 while self.token != token::CloseDelim(token::Brace) {
2406 if self.eat(&token::DotDot) {
2407 let exp_span = self.prev_span;
2408 match self.parse_expr() {
2414 self.recover_stmt();
2417 if self.token == token::Comma {
2418 let mut err = self.sess.span_diagnostic.mut_span_err(
2419 exp_span.to(self.prev_span),
2420 "cannot use a comma after the base struct",
2422 err.span_suggestion_short_with_applicability(
2424 "remove this comma",
2426 Applicability::MachineApplicable
2428 err.note("the base struct must always be the last field");
2430 self.recover_stmt();
2435 match self.parse_field() {
2436 Ok(f) => fields.push(f),
2438 e.span_label(struct_sp, "while parsing this struct");
2440 self.recover_stmt();
2445 match self.expect_one_of(&[token::Comma],
2446 &[token::CloseDelim(token::Brace)]) {
2450 self.recover_stmt();
2456 let span = lo.to(self.span);
2457 self.expect(&token::CloseDelim(token::Brace))?;
2458 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2461 fn parse_or_use_outer_attributes(&mut self,
2462 already_parsed_attrs: Option<ThinVec<Attribute>>)
2463 -> PResult<'a, ThinVec<Attribute>> {
2464 if let Some(attrs) = already_parsed_attrs {
2467 self.parse_outer_attributes().map(|a| a.into())
2471 /// Parse a block or unsafe block
2472 fn parse_block_expr(&mut self, opt_label: Option<Label>,
2473 lo: Span, blk_mode: BlockCheckMode,
2474 outer_attrs: ThinVec<Attribute>)
2475 -> PResult<'a, P<Expr>> {
2476 self.expect(&token::OpenDelim(token::Brace))?;
2478 let mut attrs = outer_attrs;
2479 attrs.extend(self.parse_inner_attributes()?);
2481 let blk = self.parse_block_tail(lo, blk_mode)?;
2482 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2485 /// parse a.b or a(13) or a[4] or just a
2486 fn parse_dot_or_call_expr(&mut self,
2487 already_parsed_attrs: Option<ThinVec<Attribute>>)
2488 -> PResult<'a, P<Expr>> {
2489 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2491 let b = self.parse_bottom_expr();
2492 let (span, b) = self.interpolated_or_expr_span(b)?;
2493 self.parse_dot_or_call_expr_with(b, span, attrs)
2496 fn parse_dot_or_call_expr_with(&mut self,
2499 mut attrs: ThinVec<Attribute>)
2500 -> PResult<'a, P<Expr>> {
2501 // Stitch the list of outer attributes onto the return value.
2502 // A little bit ugly, but the best way given the current code
2504 self.parse_dot_or_call_expr_with_(e0, lo)
2506 expr.map(|mut expr| {
2507 attrs.extend::<Vec<_>>(expr.attrs.into());
2510 ExprKind::If(..) | ExprKind::IfLet(..) => {
2511 if !expr.attrs.is_empty() {
2512 // Just point to the first attribute in there...
2513 let span = expr.attrs[0].span;
2516 "attributes are not yet allowed on `if` \
2527 // Assuming we have just parsed `.`, continue parsing into an expression.
2528 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2529 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2530 Ok(match self.token {
2531 token::OpenDelim(token::Paren) => {
2532 // Method call `expr.f()`
2533 let mut args = self.parse_unspanned_seq(
2534 &token::OpenDelim(token::Paren),
2535 &token::CloseDelim(token::Paren),
2536 SeqSep::trailing_allowed(token::Comma),
2537 |p| Ok(p.parse_expr()?)
2539 args.insert(0, self_arg);
2541 let span = lo.to(self.prev_span);
2542 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2545 // Field access `expr.f`
2546 if let Some(parameters) = segment.parameters {
2547 self.span_err(parameters.span(),
2548 "field expressions may not have generic arguments");
2551 let span = lo.to(self.prev_span);
2552 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2557 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2562 while self.eat(&token::Question) {
2563 let hi = self.prev_span;
2564 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2568 if self.eat(&token::Dot) {
2570 token::Ident(..) => {
2571 e = self.parse_dot_suffix(e, lo)?;
2573 token::Literal(token::Integer(name), _) => {
2574 let span = self.span;
2576 let field = ExprKind::Field(e, Ident::new(name, span));
2577 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2579 token::Literal(token::Float(n), _suf) => {
2581 let fstr = n.as_str();
2582 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2583 &format!("unexpected token: `{}`", n));
2584 err.span_label(self.prev_span, "unexpected token");
2585 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2586 let float = match fstr.parse::<f64>().ok() {
2590 let sugg = pprust::to_string(|s| {
2591 use print::pprust::PrintState;
2595 s.print_usize(float.trunc() as usize)?;
2598 s.s.word(fstr.splitn(2, ".").last().unwrap())
2600 err.span_suggestion_with_applicability(
2601 lo.to(self.prev_span),
2602 "try parenthesizing the first index",
2604 Applicability::MachineApplicable
2611 // FIXME Could factor this out into non_fatal_unexpected or something.
2612 let actual = self.this_token_to_string();
2613 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2618 if self.expr_is_complete(&e) { break; }
2621 token::OpenDelim(token::Paren) => {
2622 let es = self.parse_unspanned_seq(
2623 &token::OpenDelim(token::Paren),
2624 &token::CloseDelim(token::Paren),
2625 SeqSep::trailing_allowed(token::Comma),
2626 |p| Ok(p.parse_expr()?)
2628 hi = self.prev_span;
2630 let nd = self.mk_call(e, es);
2631 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2635 // Could be either an index expression or a slicing expression.
2636 token::OpenDelim(token::Bracket) => {
2638 let ix = self.parse_expr()?;
2640 self.expect(&token::CloseDelim(token::Bracket))?;
2641 let index = self.mk_index(e, ix);
2642 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2650 crate fn process_potential_macro_variable(&mut self) {
2651 let (token, span) = match self.token {
2652 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2653 self.look_ahead(1, |t| t.is_ident()) => {
2655 let name = match self.token {
2656 token::Ident(ident, _) => ident,
2659 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2660 err.span_label(self.span, "unknown macro variable");
2664 token::Interpolated(ref nt) => {
2665 self.meta_var_span = Some(self.span);
2666 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2667 // and lifetime tokens, so the former are never encountered during normal parsing.
2669 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2670 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2680 /// parse a single token tree from the input.
2681 crate fn parse_token_tree(&mut self) -> TokenTree {
2683 token::OpenDelim(..) => {
2684 let frame = mem::replace(&mut self.token_cursor.frame,
2685 self.token_cursor.stack.pop().unwrap());
2686 self.span = frame.span;
2688 TokenTree::Delimited(frame.span, Delimited {
2690 tts: frame.tree_cursor.original_stream().into(),
2693 token::CloseDelim(_) | token::Eof => unreachable!(),
2695 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2697 TokenTree::Token(span, token)
2702 // parse a stream of tokens into a list of TokenTree's,
2704 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2705 let mut tts = Vec::new();
2706 while self.token != token::Eof {
2707 tts.push(self.parse_token_tree());
2712 pub fn parse_tokens(&mut self) -> TokenStream {
2713 let mut result = Vec::new();
2716 token::Eof | token::CloseDelim(..) => break,
2717 _ => result.push(self.parse_token_tree().into()),
2720 TokenStream::concat(result)
2723 /// Parse a prefix-unary-operator expr
2724 fn parse_prefix_expr(&mut self,
2725 already_parsed_attrs: Option<ThinVec<Attribute>>)
2726 -> PResult<'a, P<Expr>> {
2727 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2729 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2730 let (hi, ex) = match self.token {
2733 let e = self.parse_prefix_expr(None);
2734 let (span, e) = self.interpolated_or_expr_span(e)?;
2735 (lo.to(span), self.mk_unary(UnOp::Not, e))
2737 // Suggest `!` for bitwise negation when encountering a `~`
2740 let e = self.parse_prefix_expr(None);
2741 let (span, e) = self.interpolated_or_expr_span(e)?;
2742 let span_of_tilde = lo;
2743 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2744 "`~` cannot be used as a unary operator");
2745 err.span_suggestion_short_with_applicability(
2747 "use `!` to perform bitwise negation",
2749 Applicability::MachineApplicable
2752 (lo.to(span), self.mk_unary(UnOp::Not, e))
2754 token::BinOp(token::Minus) => {
2756 let e = self.parse_prefix_expr(None);
2757 let (span, e) = self.interpolated_or_expr_span(e)?;
2758 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2760 token::BinOp(token::Star) => {
2762 let e = self.parse_prefix_expr(None);
2763 let (span, e) = self.interpolated_or_expr_span(e)?;
2764 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2766 token::BinOp(token::And) | token::AndAnd => {
2768 let m = self.parse_mutability();
2769 let e = self.parse_prefix_expr(None);
2770 let (span, e) = self.interpolated_or_expr_span(e)?;
2771 (lo.to(span), ExprKind::AddrOf(m, e))
2773 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2775 let place = self.parse_expr_res(
2776 Restrictions::NO_STRUCT_LITERAL,
2779 let blk = self.parse_block()?;
2780 let span = blk.span;
2781 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
2782 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
2784 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2786 let e = self.parse_prefix_expr(None);
2787 let (span, e) = self.interpolated_or_expr_span(e)?;
2788 (lo.to(span), ExprKind::Box(e))
2790 token::Ident(..) if self.token.is_ident_named("not") => {
2791 // `not` is just an ordinary identifier in Rust-the-language,
2792 // but as `rustc`-the-compiler, we can issue clever diagnostics
2793 // for confused users who really want to say `!`
2794 let token_cannot_continue_expr = |t: &token::Token| match *t {
2795 // These tokens can start an expression after `!`, but
2796 // can't continue an expression after an ident
2797 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
2798 token::Literal(..) | token::Pound => true,
2799 token::Interpolated(ref nt) => match nt.0 {
2800 token::NtIdent(..) | token::NtExpr(..) |
2801 token::NtBlock(..) | token::NtPath(..) => true,
2806 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2807 if cannot_continue_expr {
2809 // Emit the error ...
2810 let mut err = self.diagnostic()
2811 .struct_span_err(self.span,
2812 &format!("unexpected {} after identifier",
2813 self.this_token_descr()));
2814 // span the `not` plus trailing whitespace to avoid
2815 // trailing whitespace after the `!` in our suggestion
2816 let to_replace = self.sess.codemap()
2817 .span_until_non_whitespace(lo.to(self.span));
2818 err.span_suggestion_short_with_applicability(
2820 "use `!` to perform logical negation",
2822 Applicability::MachineApplicable
2825 // —and recover! (just as if we were in the block
2826 // for the `token::Not` arm)
2827 let e = self.parse_prefix_expr(None);
2828 let (span, e) = self.interpolated_or_expr_span(e)?;
2829 (lo.to(span), self.mk_unary(UnOp::Not, e))
2831 return self.parse_dot_or_call_expr(Some(attrs));
2834 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2836 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2839 /// Parse an associative expression
2841 /// This parses an expression accounting for associativity and precedence of the operators in
2843 fn parse_assoc_expr(&mut self,
2844 already_parsed_attrs: Option<ThinVec<Attribute>>)
2845 -> PResult<'a, P<Expr>> {
2846 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2849 /// Parse an associative expression with operators of at least `min_prec` precedence
2850 fn parse_assoc_expr_with(&mut self,
2853 -> PResult<'a, P<Expr>> {
2854 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2857 let attrs = match lhs {
2858 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2861 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2862 return self.parse_prefix_range_expr(attrs);
2864 self.parse_prefix_expr(attrs)?
2868 if self.expr_is_complete(&lhs) {
2869 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2872 self.expected_tokens.push(TokenType::Operator);
2873 while let Some(op) = AssocOp::from_token(&self.token) {
2875 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2876 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2877 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2878 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2879 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2880 (PrevTokenKind::Interpolated, _) => self.prev_span,
2881 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2882 if path.segments.len() == 1 => self.prev_span,
2886 let cur_op_span = self.span;
2887 let restrictions = if op.is_assign_like() {
2888 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2892 if op.precedence() < min_prec {
2895 // Check for deprecated `...` syntax
2896 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2897 self.err_dotdotdot_syntax(self.span);
2901 if op.is_comparison() {
2902 self.check_no_chained_comparison(&lhs, &op);
2905 if op == AssocOp::As {
2906 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2908 } else if op == AssocOp::Colon {
2909 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2912 err.span_label(self.span,
2913 "expecting a type here because of type ascription");
2914 let cm = self.sess.codemap();
2915 let cur_pos = cm.lookup_char_pos(self.span.lo());
2916 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
2917 if cur_pos.line != op_pos.line {
2918 err.span_suggestion_with_applicability(
2920 "try using a semicolon",
2922 Applicability::MaybeIncorrect // speculative
2929 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2930 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2931 // generalise it to the Fixity::None code.
2933 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2934 // two variants are handled with `parse_prefix_range_expr` call above.
2935 let rhs = if self.is_at_start_of_range_notation_rhs() {
2936 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2937 LhsExpr::NotYetParsed)?)
2941 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2946 let limits = if op == AssocOp::DotDot {
2947 RangeLimits::HalfOpen
2952 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2953 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2957 let rhs = match op.fixity() {
2958 Fixity::Right => self.with_res(
2959 restrictions - Restrictions::STMT_EXPR,
2961 this.parse_assoc_expr_with(op.precedence(),
2962 LhsExpr::NotYetParsed)
2964 Fixity::Left => self.with_res(
2965 restrictions - Restrictions::STMT_EXPR,
2967 this.parse_assoc_expr_with(op.precedence() + 1,
2968 LhsExpr::NotYetParsed)
2970 // We currently have no non-associative operators that are not handled above by
2971 // the special cases. The code is here only for future convenience.
2972 Fixity::None => self.with_res(
2973 restrictions - Restrictions::STMT_EXPR,
2975 this.parse_assoc_expr_with(op.precedence() + 1,
2976 LhsExpr::NotYetParsed)
2980 let span = lhs_span.to(rhs.span);
2982 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2983 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2984 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2985 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2986 AssocOp::Greater | AssocOp::GreaterEqual => {
2987 let ast_op = op.to_ast_binop().unwrap();
2988 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2989 self.mk_expr(span, binary, ThinVec::new())
2992 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2993 AssocOp::ObsoleteInPlace =>
2994 self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
2995 AssocOp::AssignOp(k) => {
2997 token::Plus => BinOpKind::Add,
2998 token::Minus => BinOpKind::Sub,
2999 token::Star => BinOpKind::Mul,
3000 token::Slash => BinOpKind::Div,
3001 token::Percent => BinOpKind::Rem,
3002 token::Caret => BinOpKind::BitXor,
3003 token::And => BinOpKind::BitAnd,
3004 token::Or => BinOpKind::BitOr,
3005 token::Shl => BinOpKind::Shl,
3006 token::Shr => BinOpKind::Shr,
3008 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
3009 self.mk_expr(span, aopexpr, ThinVec::new())
3011 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3012 self.bug("AssocOp should have been handled by special case")
3016 if op.fixity() == Fixity::None { break }
3021 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3022 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3023 -> PResult<'a, P<Expr>> {
3024 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3025 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3028 // Save the state of the parser before parsing type normally, in case there is a
3029 // LessThan comparison after this cast.
3030 let parser_snapshot_before_type = self.clone();
3031 match self.parse_ty_no_plus() {
3033 Ok(mk_expr(self, rhs))
3035 Err(mut type_err) => {
3036 // Rewind to before attempting to parse the type with generics, to recover
3037 // from situations like `x as usize < y` in which we first tried to parse
3038 // `usize < y` as a type with generic arguments.
3039 let parser_snapshot_after_type = self.clone();
3040 mem::replace(self, parser_snapshot_before_type);
3042 match self.parse_path(PathStyle::Expr) {
3044 let (op_noun, op_verb) = match self.token {
3045 token::Lt => ("comparison", "comparing"),
3046 token::BinOp(token::Shl) => ("shift", "shifting"),
3048 // We can end up here even without `<` being the next token, for
3049 // example because `parse_ty_no_plus` returns `Err` on keywords,
3050 // but `parse_path` returns `Ok` on them due to error recovery.
3051 // Return original error and parser state.
3052 mem::replace(self, parser_snapshot_after_type);
3053 return Err(type_err);
3057 // Successfully parsed the type path leaving a `<` yet to parse.
3060 // Report non-fatal diagnostics, keep `x as usize` as an expression
3061 // in AST and continue parsing.
3062 let msg = format!("`<` is interpreted as a start of generic \
3063 arguments for `{}`, not a {}", path, op_noun);
3064 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3065 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3066 "interpreted as generic arguments");
3067 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3069 let expr = mk_expr(self, P(Ty {
3071 node: TyKind::Path(None, path),
3072 id: ast::DUMMY_NODE_ID
3075 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
3076 .unwrap_or(pprust::expr_to_string(&expr));
3077 err.span_suggestion_with_applicability(
3079 &format!("try {} the cast value", op_verb),
3080 format!("({})", expr_str),
3081 Applicability::MachineApplicable
3087 Err(mut path_err) => {
3088 // Couldn't parse as a path, return original error and parser state.
3090 mem::replace(self, parser_snapshot_after_type);
3098 /// Produce an error if comparison operators are chained (RFC #558).
3099 /// We only need to check lhs, not rhs, because all comparison ops
3100 /// have same precedence and are left-associative
3101 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3102 debug_assert!(outer_op.is_comparison(),
3103 "check_no_chained_comparison: {:?} is not comparison",
3106 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3107 // respan to include both operators
3108 let op_span = op.span.to(self.span);
3109 let mut err = self.diagnostic().struct_span_err(op_span,
3110 "chained comparison operators require parentheses");
3111 if op.node == BinOpKind::Lt &&
3112 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3113 *outer_op == AssocOp::Greater // even in a case like the following:
3114 { // Foo<Bar<Baz<Qux, ()>>>
3116 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3117 err.help("or use `(...)` if you meant to specify fn arguments");
3125 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3126 fn parse_prefix_range_expr(&mut self,
3127 already_parsed_attrs: Option<ThinVec<Attribute>>)
3128 -> PResult<'a, P<Expr>> {
3129 // Check for deprecated `...` syntax
3130 if self.token == token::DotDotDot {
3131 self.err_dotdotdot_syntax(self.span);
3134 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3135 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3137 let tok = self.token.clone();
3138 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3140 let mut hi = self.span;
3142 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3143 // RHS must be parsed with more associativity than the dots.
3144 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3145 Some(self.parse_assoc_expr_with(next_prec,
3146 LhsExpr::NotYetParsed)
3154 let limits = if tok == token::DotDot {
3155 RangeLimits::HalfOpen
3160 let r = try!(self.mk_range(None,
3163 Ok(self.mk_expr(lo.to(hi), r, attrs))
3166 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3167 if self.token.can_begin_expr() {
3168 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3169 if self.token == token::OpenDelim(token::Brace) {
3170 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3178 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3179 fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3180 if self.check_keyword(keywords::Let) {
3181 return self.parse_if_let_expr(attrs);
3183 let lo = self.prev_span;
3184 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3186 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3187 // verify that the last statement is either an implicit return (no `;`) or an explicit
3188 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3189 // the dead code lint.
3190 if self.eat_keyword(keywords::Else) || !cond.returns() {
3191 let sp = self.sess.codemap().next_point(lo);
3192 let mut err = self.diagnostic()
3193 .struct_span_err(sp, "missing condition for `if` statemement");
3194 err.span_label(sp, "expected if condition here");
3197 let not_block = self.token != token::OpenDelim(token::Brace);
3198 let thn = self.parse_block().map_err(|mut err| {
3200 err.span_label(lo, "this `if` statement has a condition, but no block");
3204 let mut els: Option<P<Expr>> = None;
3205 let mut hi = thn.span;
3206 if self.eat_keyword(keywords::Else) {
3207 let elexpr = self.parse_else_expr()?;
3211 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3214 /// Parse an 'if let' expression ('if' token already eaten)
3215 fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3216 -> PResult<'a, P<Expr>> {
3217 let lo = self.prev_span;
3218 self.expect_keyword(keywords::Let)?;
3219 let pats = self.parse_pats()?;
3220 self.expect(&token::Eq)?;
3221 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3222 let thn = self.parse_block()?;
3223 let (hi, els) = if self.eat_keyword(keywords::Else) {
3224 let expr = self.parse_else_expr()?;
3225 (expr.span, Some(expr))
3229 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3232 // `move |args| expr`
3233 fn parse_lambda_expr(&mut self,
3234 attrs: ThinVec<Attribute>)
3235 -> PResult<'a, P<Expr>>
3238 let movability = if self.eat_keyword(keywords::Static) {
3243 let capture_clause = if self.eat_keyword(keywords::Move) {
3248 let decl = self.parse_fn_block_decl()?;
3249 let decl_hi = self.prev_span;
3250 let body = match decl.output {
3251 FunctionRetTy::Default(_) => {
3252 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3253 self.parse_expr_res(restrictions, None)?
3256 // If an explicit return type is given, require a
3257 // block to appear (RFC 968).
3258 let body_lo = self.span;
3259 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3265 ExprKind::Closure(capture_clause, movability, decl, body, lo.to(decl_hi)),
3269 // `else` token already eaten
3270 fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3271 if self.eat_keyword(keywords::If) {
3272 return self.parse_if_expr(ThinVec::new());
3274 let blk = self.parse_block()?;
3275 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3279 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3280 fn parse_for_expr(&mut self, opt_label: Option<Label>,
3282 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3283 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3285 let pat = self.parse_top_level_pat()?;
3286 if !self.eat_keyword(keywords::In) {
3287 let in_span = self.prev_span.between(self.span);
3288 let mut err = self.sess.span_diagnostic
3289 .struct_span_err(in_span, "missing `in` in `for` loop");
3290 err.span_suggestion_short_with_applicability(
3291 in_span, "try adding `in` here", " in ".into(),
3292 // has been misleading, at least in the past (closed Issue #48492)
3293 Applicability::MaybeIncorrect
3297 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3298 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3299 attrs.extend(iattrs);
3301 let hi = self.prev_span;
3302 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3305 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3306 fn parse_while_expr(&mut self, opt_label: Option<Label>,
3308 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3309 if self.token.is_keyword(keywords::Let) {
3310 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3312 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3313 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3314 attrs.extend(iattrs);
3315 let span = span_lo.to(body.span);
3316 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3319 /// Parse a 'while let' expression ('while' token already eaten)
3320 fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3322 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3323 self.expect_keyword(keywords::Let)?;
3324 let pats = self.parse_pats()?;
3325 self.expect(&token::Eq)?;
3326 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3327 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3328 attrs.extend(iattrs);
3329 let span = span_lo.to(body.span);
3330 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3333 // parse `loop {...}`, `loop` token already eaten
3334 fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3336 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3337 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3338 attrs.extend(iattrs);
3339 let span = span_lo.to(body.span);
3340 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3343 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3344 fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3345 -> PResult<'a, P<Expr>>
3347 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3348 attrs.extend(iattrs);
3349 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3352 // `match` token already eaten
3353 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3354 let match_span = self.prev_span;
3355 let lo = self.prev_span;
3356 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3358 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3359 if self.token == token::Token::Semi {
3360 e.span_suggestion_short_with_applicability(
3362 "try removing this `match`",
3364 Applicability::MaybeIncorrect // speculative
3369 attrs.extend(self.parse_inner_attributes()?);
3371 let mut arms: Vec<Arm> = Vec::new();
3372 while self.token != token::CloseDelim(token::Brace) {
3373 match self.parse_arm() {
3374 Ok(arm) => arms.push(arm),
3376 // Recover by skipping to the end of the block.
3378 self.recover_stmt();
3379 let span = lo.to(self.span);
3380 if self.token == token::CloseDelim(token::Brace) {
3383 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3389 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3392 crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
3393 maybe_whole!(self, NtArm, |x| x);
3395 let attrs = self.parse_outer_attributes()?;
3396 // Allow a '|' before the pats (RFC 1925)
3397 self.eat(&token::BinOp(token::Or));
3398 let pats = self.parse_pats()?;
3399 let guard = if self.eat_keyword(keywords::If) {
3400 Some(self.parse_expr()?)
3404 let arrow_span = self.span;
3405 self.expect(&token::FatArrow)?;
3406 let arm_start_span = self.span;
3408 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3409 .map_err(|mut err| {
3410 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3414 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3415 && self.token != token::CloseDelim(token::Brace);
3418 let cm = self.sess.codemap();
3419 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3420 .map_err(|mut err| {
3421 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3422 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3423 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3424 && expr_lines.lines.len() == 2
3425 && self.token == token::FatArrow => {
3426 // We check wether there's any trailing code in the parse span, if there
3427 // isn't, we very likely have the following:
3430 // | -- - missing comma
3436 // | parsed until here as `"y" & X`
3437 err.span_suggestion_short_with_applicability(
3438 cm.next_point(arm_start_span),
3439 "missing a comma here to end this `match` arm",
3441 Applicability::MachineApplicable
3445 err.span_label(arrow_span,
3446 "while parsing the `match` arm starting here");
3452 self.eat(&token::Comma);
3463 /// Parse an expression
3464 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3465 self.parse_expr_res(Restrictions::empty(), None)
3468 /// Evaluate the closure with restrictions in place.
3470 /// After the closure is evaluated, restrictions are reset.
3471 fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3472 where F: FnOnce(&mut Self) -> T
3474 let old = self.restrictions;
3475 self.restrictions = r;
3477 self.restrictions = old;
3482 /// Parse an expression, subject to the given restrictions
3483 fn parse_expr_res(&mut self, r: Restrictions,
3484 already_parsed_attrs: Option<ThinVec<Attribute>>)
3485 -> PResult<'a, P<Expr>> {
3486 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3489 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3490 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3491 if self.check(&token::Eq) {
3493 Ok(Some(self.parse_expr()?))
3495 Ok(Some(self.parse_expr()?))
3501 /// Parse patterns, separated by '|' s
3502 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3503 let mut pats = Vec::new();
3505 pats.push(self.parse_top_level_pat()?);
3507 if self.token == token::OrOr {
3508 let mut err = self.struct_span_err(self.span,
3509 "unexpected token `||` after pattern");
3510 err.span_suggestion_with_applicability(
3512 "use a single `|` to specify multiple patterns",
3514 Applicability::MachineApplicable
3518 } else if self.check(&token::BinOp(token::Or)) {
3526 // Parses a parenthesized list of patterns like
3527 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3528 // - a vector of the patterns that were parsed
3529 // - an option indicating the index of the `..` element
3530 // - a boolean indicating whether a trailing comma was present.
3531 // Trailing commas are significant because (p) and (p,) are different patterns.
3532 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3533 self.expect(&token::OpenDelim(token::Paren))?;
3534 let result = self.parse_pat_list()?;
3535 self.expect(&token::CloseDelim(token::Paren))?;
3539 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3540 let mut fields = Vec::new();
3541 let mut ddpos = None;
3542 let mut trailing_comma = false;
3544 if self.eat(&token::DotDot) {
3545 if ddpos.is_none() {
3546 ddpos = Some(fields.len());
3548 // Emit a friendly error, ignore `..` and continue parsing
3549 self.span_err(self.prev_span,
3550 "`..` can only be used once per tuple or tuple struct pattern");
3552 } else if !self.check(&token::CloseDelim(token::Paren)) {
3553 fields.push(self.parse_pat()?);
3558 trailing_comma = self.eat(&token::Comma);
3559 if !trailing_comma {
3564 if ddpos == Some(fields.len()) && trailing_comma {
3565 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3566 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3569 Ok((fields, ddpos, trailing_comma))
3572 fn parse_pat_vec_elements(
3574 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3575 let mut before = Vec::new();
3576 let mut slice = None;
3577 let mut after = Vec::new();
3578 let mut first = true;
3579 let mut before_slice = true;
3581 while self.token != token::CloseDelim(token::Bracket) {
3585 self.expect(&token::Comma)?;
3587 if self.token == token::CloseDelim(token::Bracket)
3588 && (before_slice || !after.is_empty()) {
3594 if self.eat(&token::DotDot) {
3596 if self.check(&token::Comma) ||
3597 self.check(&token::CloseDelim(token::Bracket)) {
3598 slice = Some(P(Pat {
3599 id: ast::DUMMY_NODE_ID,
3600 node: PatKind::Wild,
3601 span: self.prev_span,
3603 before_slice = false;
3609 let subpat = self.parse_pat()?;
3610 if before_slice && self.eat(&token::DotDot) {
3611 slice = Some(subpat);
3612 before_slice = false;
3613 } else if before_slice {
3614 before.push(subpat);
3620 Ok((before, slice, after))
3626 attrs: Vec<Attribute>
3627 ) -> PResult<'a, codemap::Spanned<ast::FieldPat>> {
3628 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3630 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3631 // Parsing a pattern of the form "fieldname: pat"
3632 let fieldname = self.parse_field_name()?;
3634 let pat = self.parse_pat()?;
3636 (pat, fieldname, false)
3638 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3639 let is_box = self.eat_keyword(keywords::Box);
3640 let boxed_span = self.span;
3641 let is_ref = self.eat_keyword(keywords::Ref);
3642 let is_mut = self.eat_keyword(keywords::Mut);
3643 let fieldname = self.parse_ident()?;
3644 hi = self.prev_span;
3646 let bind_type = match (is_ref, is_mut) {
3647 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3648 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3649 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3650 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3652 let fieldpat = P(Pat {
3653 id: ast::DUMMY_NODE_ID,
3654 node: PatKind::Ident(bind_type, fieldname, None),
3655 span: boxed_span.to(hi),
3658 let subpat = if is_box {
3660 id: ast::DUMMY_NODE_ID,
3661 node: PatKind::Box(fieldpat),
3667 (subpat, fieldname, true)
3670 Ok(codemap::Spanned {
3672 node: ast::FieldPat {
3676 attrs: attrs.into(),
3681 /// Parse the fields of a struct-like pattern
3682 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3683 let mut fields = Vec::new();
3684 let mut etc = false;
3685 let mut ate_comma = true;
3686 let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
3687 let mut etc_span = None;
3689 while self.token != token::CloseDelim(token::Brace) {
3690 let attrs = self.parse_outer_attributes()?;
3693 // check that a comma comes after every field
3695 let err = self.struct_span_err(self.prev_span, "expected `,`");
3700 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3702 let mut etc_sp = self.span;
3704 if self.token == token::DotDotDot { // Issue #46718
3705 // Accept `...` as if it were `..` to avoid further errors
3706 let mut err = self.struct_span_err(self.span,
3707 "expected field pattern, found `...`");
3708 err.span_suggestion_with_applicability(
3710 "to omit remaining fields, use one fewer `.`",
3712 Applicability::MachineApplicable
3716 self.bump(); // `..` || `...`:w
3718 if self.token == token::CloseDelim(token::Brace) {
3719 etc_span = Some(etc_sp);
3722 let token_str = self.this_token_to_string();
3723 let mut err = self.fatal(&format!("expected `}}`, found `{}`", token_str));
3725 err.span_label(self.span, "expected `}`");
3726 let mut comma_sp = None;
3727 if self.token == token::Comma { // Issue #49257
3728 etc_sp = etc_sp.to(self.sess.codemap().span_until_non_whitespace(self.span));
3729 err.span_label(etc_sp,
3730 "`..` must be at the end and cannot have a trailing comma");
3731 comma_sp = Some(self.span);
3736 etc_span = Some(etc_sp);
3737 if self.token == token::CloseDelim(token::Brace) {
3738 // If the struct looks otherwise well formed, recover and continue.
3739 if let Some(sp) = comma_sp {
3740 err.span_suggestion_short(sp, "remove this comma", "".into());
3744 } else if self.token.is_ident() && ate_comma {
3745 // Accept fields coming after `..,`.
3746 // This way we avoid "pattern missing fields" errors afterwards.
3747 // We delay this error until the end in order to have a span for a
3749 if let Some(mut delayed_err) = delayed_err {
3753 delayed_err = Some(err);
3756 if let Some(mut err) = delayed_err {
3763 fields.push(match self.parse_pat_field(lo, attrs) {
3766 if let Some(mut delayed_err) = delayed_err {
3772 ate_comma = self.eat(&token::Comma);
3775 if let Some(mut err) = delayed_err {
3776 if let Some(etc_span) = etc_span {
3777 err.multipart_suggestion(
3778 "move the `..` to the end of the field list",
3780 (etc_span, "".into()),
3781 (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
3787 return Ok((fields, etc));
3790 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3791 if self.token.is_path_start() {
3793 let (qself, path) = if self.eat_lt() {
3794 // Parse a qualified path
3795 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3798 // Parse an unqualified path
3799 (None, self.parse_path(PathStyle::Expr)?)
3801 let hi = self.prev_span;
3802 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3804 self.parse_literal_maybe_minus()
3808 // helper function to decide whether to parse as ident binding or to try to do
3809 // something more complex like range patterns
3810 fn parse_as_ident(&mut self) -> bool {
3811 self.look_ahead(1, |t| match *t {
3812 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3813 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3814 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3815 // range pattern branch
3816 token::DotDot => None,
3818 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3819 token::Comma | token::CloseDelim(token::Bracket) => true,
3824 /// A wrapper around `parse_pat` with some special error handling for the
3825 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contast
3826 /// to subpatterns within such).
3827 fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3828 let pat = self.parse_pat()?;
3829 if self.token == token::Comma {
3830 // An unexpected comma after a top-level pattern is a clue that the
3831 // user (perhaps more accustomed to some other language) forgot the
3832 // parentheses in what should have been a tuple pattern; return a
3833 // suggestion-enhanced error here rather than choking on the comma
3835 let comma_span = self.span;
3837 if let Err(mut err) = self.parse_pat_list() {
3838 // We didn't expect this to work anyway; we just wanted
3839 // to advance to the end of the comma-sequence so we know
3840 // the span to suggest parenthesizing
3843 let seq_span = pat.span.to(self.prev_span);
3844 let mut err = self.struct_span_err(comma_span,
3845 "unexpected `,` in pattern");
3846 if let Ok(seq_snippet) = self.sess.codemap().span_to_snippet(seq_span) {
3847 err.span_suggestion_with_applicability(
3849 "try adding parentheses",
3850 format!("({})", seq_snippet),
3851 Applicability::MachineApplicable
3859 /// Parse a pattern.
3860 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3861 self.parse_pat_with_range_pat(true)
3864 /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
3866 fn parse_pat_with_range_pat(&mut self, allow_range_pat: bool) -> PResult<'a, P<Pat>> {
3867 maybe_whole!(self, NtPat, |x| x);
3872 token::BinOp(token::And) | token::AndAnd => {
3873 // Parse &pat / &mut pat
3875 let mutbl = self.parse_mutability();
3876 if let token::Lifetime(ident) = self.token {
3877 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
3879 err.span_label(self.span, "unexpected lifetime");
3882 let subpat = self.parse_pat_with_range_pat(false)?;
3883 pat = PatKind::Ref(subpat, mutbl);
3885 token::OpenDelim(token::Paren) => {
3886 // Parse (pat,pat,pat,...) as tuple pattern
3887 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
3888 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
3889 PatKind::Paren(fields.into_iter().nth(0).unwrap())
3891 PatKind::Tuple(fields, ddpos)
3894 token::OpenDelim(token::Bracket) => {
3895 // Parse [pat,pat,...] as slice pattern
3897 let (before, slice, after) = self.parse_pat_vec_elements()?;
3898 self.expect(&token::CloseDelim(token::Bracket))?;
3899 pat = PatKind::Slice(before, slice, after);
3901 // At this point, token != &, &&, (, [
3902 _ => if self.eat_keyword(keywords::Underscore) {
3904 pat = PatKind::Wild;
3905 } else if self.eat_keyword(keywords::Mut) {
3906 // Parse mut ident @ pat / mut ref ident @ pat
3907 let mutref_span = self.prev_span.to(self.span);
3908 let binding_mode = if self.eat_keyword(keywords::Ref) {
3910 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3911 .span_suggestion_with_applicability(
3913 "try switching the order",
3915 Applicability::MachineApplicable
3917 BindingMode::ByRef(Mutability::Mutable)
3919 BindingMode::ByValue(Mutability::Mutable)
3921 pat = self.parse_pat_ident(binding_mode)?;
3922 } else if self.eat_keyword(keywords::Ref) {
3923 // Parse ref ident @ pat / ref mut ident @ pat
3924 let mutbl = self.parse_mutability();
3925 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3926 } else if self.eat_keyword(keywords::Box) {
3928 let subpat = self.parse_pat_with_range_pat(false)?;
3929 pat = PatKind::Box(subpat);
3930 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3931 self.parse_as_ident() {
3932 // Parse ident @ pat
3933 // This can give false positives and parse nullary enums,
3934 // they are dealt with later in resolve
3935 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3936 pat = self.parse_pat_ident(binding_mode)?;
3937 } else if self.token.is_path_start() {
3938 // Parse pattern starting with a path
3939 let (qself, path) = if self.eat_lt() {
3940 // Parse a qualified path
3941 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3944 // Parse an unqualified path
3945 (None, self.parse_path(PathStyle::Expr)?)
3948 token::Not if qself.is_none() => {
3949 // Parse macro invocation
3951 let (delim, tts) = self.expect_delimited_token_tree()?;
3952 let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
3953 pat = PatKind::Mac(mac);
3955 token::DotDotDot | token::DotDotEq | token::DotDot => {
3956 let end_kind = match self.token {
3957 token::DotDot => RangeEnd::Excluded,
3958 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
3959 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
3960 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
3964 let span = lo.to(self.prev_span);
3965 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3967 let end = self.parse_pat_range_end()?;
3968 pat = PatKind::Range(begin, end, end_kind);
3970 token::OpenDelim(token::Brace) => {
3971 if qself.is_some() {
3972 let msg = "unexpected `{` after qualified path";
3973 let mut err = self.fatal(msg);
3974 err.span_label(self.span, msg);
3977 // Parse struct pattern
3979 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3981 self.recover_stmt();
3985 pat = PatKind::Struct(path, fields, etc);
3987 token::OpenDelim(token::Paren) => {
3988 if qself.is_some() {
3989 let msg = "unexpected `(` after qualified path";
3990 let mut err = self.fatal(msg);
3991 err.span_label(self.span, msg);
3994 // Parse tuple struct or enum pattern
3995 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
3996 pat = PatKind::TupleStruct(path, fields, ddpos)
3998 _ => pat = PatKind::Path(qself, path),
4001 // Try to parse everything else as literal with optional minus
4002 match self.parse_literal_maybe_minus() {
4004 if self.eat(&token::DotDotDot) {
4005 let end = self.parse_pat_range_end()?;
4006 pat = PatKind::Range(begin, end,
4007 RangeEnd::Included(RangeSyntax::DotDotDot));
4008 } else if self.eat(&token::DotDotEq) {
4009 let end = self.parse_pat_range_end()?;
4010 pat = PatKind::Range(begin, end,
4011 RangeEnd::Included(RangeSyntax::DotDotEq));
4012 } else if self.eat(&token::DotDot) {
4013 let end = self.parse_pat_range_end()?;
4014 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
4016 pat = PatKind::Lit(begin);
4020 self.cancel(&mut err);
4021 let msg = format!("expected pattern, found {}", self.this_token_descr());
4022 let mut err = self.fatal(&msg);
4023 err.span_label(self.span, "expected pattern");
4030 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4031 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4033 if !allow_range_pat {
4035 PatKind::Range(_, _, RangeEnd::Included(RangeSyntax::DotDotDot)) => {}
4036 PatKind::Range(..) => {
4037 let mut err = self.struct_span_err(
4039 "the range pattern here has ambiguous interpretation",
4041 err.span_suggestion_with_applicability(
4043 "add parentheses to clarify the precedence",
4044 format!("({})", pprust::pat_to_string(&pat)),
4045 // "ambiguous interpretation" implies that we have to be guessing
4046 Applicability::MaybeIncorrect
4057 /// Parse ident or ident @ pat
4058 /// used by the copy foo and ref foo patterns to give a good
4059 /// error message when parsing mistakes like ref foo(a,b)
4060 fn parse_pat_ident(&mut self,
4061 binding_mode: ast::BindingMode)
4062 -> PResult<'a, PatKind> {
4063 let ident = self.parse_ident()?;
4064 let sub = if self.eat(&token::At) {
4065 Some(self.parse_pat()?)
4070 // just to be friendly, if they write something like
4072 // we end up here with ( as the current token. This shortly
4073 // leads to a parse error. Note that if there is no explicit
4074 // binding mode then we do not end up here, because the lookahead
4075 // will direct us over to parse_enum_variant()
4076 if self.token == token::OpenDelim(token::Paren) {
4077 return Err(self.span_fatal(
4079 "expected identifier, found enum pattern"))
4082 Ok(PatKind::Ident(binding_mode, ident, sub))
4085 /// Parse a local variable declaration
4086 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4087 let lo = self.prev_span;
4088 let pat = self.parse_top_level_pat()?;
4090 let (err, ty) = if self.eat(&token::Colon) {
4091 // Save the state of the parser before parsing type normally, in case there is a `:`
4092 // instead of an `=` typo.
4093 let parser_snapshot_before_type = self.clone();
4094 let colon_sp = self.prev_span;
4095 match self.parse_ty() {
4096 Ok(ty) => (None, Some(ty)),
4098 // Rewind to before attempting to parse the type and continue parsing
4099 let parser_snapshot_after_type = self.clone();
4100 mem::replace(self, parser_snapshot_before_type);
4102 let snippet = self.sess.codemap().span_to_snippet(pat.span).unwrap();
4103 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4104 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4110 let init = match (self.parse_initializer(err.is_some()), err) {
4111 (Ok(init), None) => { // init parsed, ty parsed
4114 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4115 // Could parse the type as if it were the initializer, it is likely there was a
4116 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4117 err.span_suggestion_short_with_applicability(
4119 "use `=` if you meant to assign",
4121 Applicability::MachineApplicable
4124 // As this was parsed successfully, continue as if the code has been fixed for the
4125 // rest of the file. It will still fail due to the emitted error, but we avoid
4129 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4131 // Couldn't parse the type nor the initializer, only raise the type error and
4132 // return to the parser state before parsing the type as the initializer.
4133 // let x: <parse_error>;
4134 mem::replace(self, snapshot);
4137 (Err(err), None) => { // init error, ty parsed
4138 // Couldn't parse the initializer and we're not attempting to recover a failed
4139 // parse of the type, return the error.
4143 let hi = if self.token == token::Semi {
4152 id: ast::DUMMY_NODE_ID,
4158 /// Parse a structure field
4159 fn parse_name_and_ty(&mut self,
4162 attrs: Vec<Attribute>)
4163 -> PResult<'a, StructField> {
4164 let name = self.parse_ident()?;
4165 self.expect(&token::Colon)?;
4166 let ty = self.parse_ty()?;
4168 span: lo.to(self.prev_span),
4171 id: ast::DUMMY_NODE_ID,
4177 /// Emit an expected item after attributes error.
4178 fn expected_item_err(&self, attrs: &[Attribute]) {
4179 let message = match attrs.last() {
4180 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4181 _ => "expected item after attributes",
4184 self.span_err(self.prev_span, message);
4187 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4188 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4189 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4190 Ok(self.parse_stmt_(true))
4193 // Eat tokens until we can be relatively sure we reached the end of the
4194 // statement. This is something of a best-effort heuristic.
4196 // We terminate when we find an unmatched `}` (without consuming it).
4197 fn recover_stmt(&mut self) {
4198 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4201 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4202 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4203 // approximate - it can mean we break too early due to macros, but that
4204 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
4206 // If `break_on_block` is `Break`, then we will stop consuming tokens
4207 // after finding (and consuming) a brace-delimited block.
4208 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4209 let mut brace_depth = 0;
4210 let mut bracket_depth = 0;
4211 let mut in_block = false;
4212 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4213 break_on_semi, break_on_block);
4215 debug!("recover_stmt_ loop {:?}", self.token);
4217 token::OpenDelim(token::DelimToken::Brace) => {
4220 if break_on_block == BlockMode::Break &&
4222 bracket_depth == 0 {
4226 token::OpenDelim(token::DelimToken::Bracket) => {
4230 token::CloseDelim(token::DelimToken::Brace) => {
4231 if brace_depth == 0 {
4232 debug!("recover_stmt_ return - close delim {:?}", self.token);
4237 if in_block && bracket_depth == 0 && brace_depth == 0 {
4238 debug!("recover_stmt_ return - block end {:?}", self.token);
4242 token::CloseDelim(token::DelimToken::Bracket) => {
4244 if bracket_depth < 0 {
4250 debug!("recover_stmt_ return - Eof");
4255 if break_on_semi == SemiColonMode::Break &&
4257 bracket_depth == 0 {
4258 debug!("recover_stmt_ return - Semi");
4269 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4270 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4272 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4277 fn is_catch_expr(&mut self) -> bool {
4278 self.token.is_keyword(keywords::Do) &&
4279 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4280 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4282 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
4283 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4286 fn is_union_item(&self) -> bool {
4287 self.token.is_keyword(keywords::Union) &&
4288 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4291 fn is_crate_vis(&self) -> bool {
4292 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4295 fn is_extern_non_path(&self) -> bool {
4296 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4299 fn is_auto_trait_item(&mut self) -> bool {
4301 (self.token.is_keyword(keywords::Auto)
4302 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4303 || // unsafe auto trait
4304 (self.token.is_keyword(keywords::Unsafe) &&
4305 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4306 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4309 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4310 -> PResult<'a, Option<P<Item>>> {
4311 let token_lo = self.span;
4312 let (ident, def) = match self.token {
4313 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4315 let ident = self.parse_ident()?;
4316 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4317 match self.parse_token_tree() {
4318 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4319 _ => unreachable!(),
4321 } else if self.check(&token::OpenDelim(token::Paren)) {
4322 let args = self.parse_token_tree();
4323 let body = if self.check(&token::OpenDelim(token::Brace)) {
4324 self.parse_token_tree()
4329 TokenStream::concat(vec![
4331 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4339 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4341 token::Ident(ident, _) if ident.name == "macro_rules" &&
4342 self.look_ahead(1, |t| *t == token::Not) => {
4343 let prev_span = self.prev_span;
4344 self.complain_if_pub_macro(&vis.node, prev_span);
4348 let ident = self.parse_ident()?;
4349 let (delim, tokens) = self.expect_delimited_token_tree()?;
4350 if delim != MacDelimiter::Brace {
4351 if !self.eat(&token::Semi) {
4352 let msg = "macros that expand to items must either \
4353 be surrounded with braces or followed by a semicolon";
4354 self.span_err(self.prev_span, msg);
4358 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4360 _ => return Ok(None),
4363 let span = lo.to(self.prev_span);
4364 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4367 fn parse_stmt_without_recovery(&mut self,
4368 macro_legacy_warnings: bool)
4369 -> PResult<'a, Option<Stmt>> {
4370 maybe_whole!(self, NtStmt, |x| Some(x));
4372 let attrs = self.parse_outer_attributes()?;
4375 Ok(Some(if self.eat_keyword(keywords::Let) {
4377 id: ast::DUMMY_NODE_ID,
4378 node: StmtKind::Local(self.parse_local(attrs.into())?),
4379 span: lo.to(self.prev_span),
4381 } else if let Some(macro_def) = self.eat_macro_def(
4383 &codemap::respan(lo, VisibilityKind::Inherited),
4387 id: ast::DUMMY_NODE_ID,
4388 node: StmtKind::Item(macro_def),
4389 span: lo.to(self.prev_span),
4391 // Starts like a simple path, being careful to avoid contextual keywords
4392 // such as a union items, item with `crate` visibility or auto trait items.
4393 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4394 // like a path (1 token), but it fact not a path.
4395 // `union::b::c` - path, `union U { ... }` - not a path.
4396 // `crate::b::c` - path, `crate struct S;` - not a path.
4397 // `extern::b::c` - path, `extern crate c;` - not a path.
4398 } else if self.token.is_path_start() &&
4399 !self.token.is_qpath_start() &&
4400 !self.is_union_item() &&
4401 !self.is_crate_vis() &&
4402 !self.is_extern_non_path() &&
4403 !self.is_auto_trait_item() {
4404 let pth = self.parse_path(PathStyle::Expr)?;
4406 if !self.eat(&token::Not) {
4407 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4408 self.parse_struct_expr(lo, pth, ThinVec::new())?
4410 let hi = self.prev_span;
4411 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4414 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4415 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4416 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4419 return Ok(Some(Stmt {
4420 id: ast::DUMMY_NODE_ID,
4421 node: StmtKind::Expr(expr),
4422 span: lo.to(self.prev_span),
4426 // it's a macro invocation
4427 let id = match self.token {
4428 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4429 _ => self.parse_ident()?,
4432 // check that we're pointing at delimiters (need to check
4433 // again after the `if`, because of `parse_ident`
4434 // consuming more tokens).
4436 token::OpenDelim(_) => {}
4438 // we only expect an ident if we didn't parse one
4440 let ident_str = if id.name == keywords::Invalid.name() {
4445 let tok_str = self.this_token_to_string();
4446 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4449 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4454 let (delim, tts) = self.expect_delimited_token_tree()?;
4455 let hi = self.prev_span;
4457 let style = if delim == MacDelimiter::Brace {
4458 MacStmtStyle::Braces
4460 MacStmtStyle::NoBraces
4463 if id.name == keywords::Invalid.name() {
4464 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4465 let node = if delim == MacDelimiter::Brace ||
4466 self.token == token::Semi || self.token == token::Eof {
4467 StmtKind::Mac(P((mac, style, attrs.into())))
4469 // We used to incorrectly stop parsing macro-expanded statements here.
4470 // If the next token will be an error anyway but could have parsed with the
4471 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4472 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4473 // These can continue an expression, so we can't stop parsing and warn.
4474 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4475 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4476 token::BinOp(token::And) | token::BinOp(token::Or) |
4477 token::AndAnd | token::OrOr |
4478 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4481 self.warn_missing_semicolon();
4482 StmtKind::Mac(P((mac, style, attrs.into())))
4484 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4485 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4486 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4490 id: ast::DUMMY_NODE_ID,
4495 // if it has a special ident, it's definitely an item
4497 // Require a semicolon or braces.
4498 if style != MacStmtStyle::Braces {
4499 if !self.eat(&token::Semi) {
4500 self.span_err(self.prev_span,
4501 "macros that expand to items must \
4502 either be surrounded with braces or \
4503 followed by a semicolon");
4506 let span = lo.to(hi);
4508 id: ast::DUMMY_NODE_ID,
4510 node: StmtKind::Item({
4512 span, id /*id is good here*/,
4513 ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4514 respan(lo, VisibilityKind::Inherited),
4520 // FIXME: Bad copy of attrs
4521 let old_directory_ownership =
4522 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4523 let item = self.parse_item_(attrs.clone(), false, true)?;
4524 self.directory.ownership = old_directory_ownership;
4528 id: ast::DUMMY_NODE_ID,
4529 span: lo.to(i.span),
4530 node: StmtKind::Item(i),
4533 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4534 if !attrs.is_empty() {
4535 if s.prev_token_kind == PrevTokenKind::DocComment {
4536 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4537 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4538 s.span_err(s.span, "expected statement after outer attribute");
4543 // Do not attempt to parse an expression if we're done here.
4544 if self.token == token::Semi {
4545 unused_attrs(&attrs, self);
4550 if self.token == token::CloseDelim(token::Brace) {
4551 unused_attrs(&attrs, self);
4555 // Remainder are line-expr stmts.
4556 let e = self.parse_expr_res(
4557 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4559 id: ast::DUMMY_NODE_ID,
4560 span: lo.to(e.span),
4561 node: StmtKind::Expr(e),
4568 /// Is this expression a successfully-parsed statement?
4569 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4570 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4571 !classify::expr_requires_semi_to_be_stmt(e)
4574 /// Parse a block. No inner attrs are allowed.
4575 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4576 maybe_whole!(self, NtBlock, |x| x);
4580 if !self.eat(&token::OpenDelim(token::Brace)) {
4582 let tok = self.this_token_to_string();
4583 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4585 // Check to see if the user has written something like
4590 // Which is valid in other languages, but not Rust.
4591 match self.parse_stmt_without_recovery(false) {
4593 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) {
4594 // if the next token is an open brace (e.g., `if a b {`), the place-
4595 // inside-a-block suggestion would be more likely wrong than right
4598 let mut stmt_span = stmt.span;
4599 // expand the span to include the semicolon, if it exists
4600 if self.eat(&token::Semi) {
4601 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4603 let sugg = pprust::to_string(|s| {
4604 use print::pprust::{PrintState, INDENT_UNIT};
4605 s.ibox(INDENT_UNIT)?;
4607 s.print_stmt(&stmt)?;
4608 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4610 e.span_suggestion_with_applicability(
4612 "try placing this code inside a block",
4614 // speculative, has been misleading in the past (closed Issue #46836)
4615 Applicability::MaybeIncorrect
4619 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4620 self.cancel(&mut e);
4627 self.parse_block_tail(lo, BlockCheckMode::Default)
4630 /// Parse a block. Inner attrs are allowed.
4631 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4632 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4635 self.expect(&token::OpenDelim(token::Brace))?;
4636 Ok((self.parse_inner_attributes()?,
4637 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4640 /// Parse the rest of a block expression or function body
4641 /// Precondition: already parsed the '{'.
4642 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4643 let mut stmts = vec![];
4644 let mut recovered = false;
4646 while !self.eat(&token::CloseDelim(token::Brace)) {
4647 let stmt = match self.parse_full_stmt(false) {
4650 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4651 self.eat(&token::CloseDelim(token::Brace));
4657 if let Some(stmt) = stmt {
4659 } else if self.token == token::Eof {
4662 // Found only `;` or `}`.
4668 id: ast::DUMMY_NODE_ID,
4670 span: lo.to(self.prev_span),
4675 /// Parse a statement, including the trailing semicolon.
4676 crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4677 // skip looking for a trailing semicolon when we have an interpolated statement
4678 maybe_whole!(self, NtStmt, |x| Some(x));
4680 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4682 None => return Ok(None),
4686 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4687 // expression without semicolon
4688 if classify::expr_requires_semi_to_be_stmt(expr) {
4689 // Just check for errors and recover; do not eat semicolon yet.
4691 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4694 self.recover_stmt();
4698 StmtKind::Local(..) => {
4699 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4700 if macro_legacy_warnings && self.token != token::Semi {
4701 self.warn_missing_semicolon();
4703 self.expect_one_of(&[token::Semi], &[])?;
4709 if self.eat(&token::Semi) {
4710 stmt = stmt.add_trailing_semicolon();
4713 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4717 fn warn_missing_semicolon(&self) {
4718 self.diagnostic().struct_span_warn(self.span, {
4719 &format!("expected `;`, found `{}`", self.this_token_to_string())
4721 "This was erroneously allowed and will become a hard error in a future release"
4725 fn err_dotdotdot_syntax(&self, span: Span) {
4726 self.diagnostic().struct_span_err(span, {
4727 "`...` syntax cannot be used in expressions"
4729 "Use `..` if you need an exclusive range (a < b)"
4731 "or `..=` if you need an inclusive range (a <= b)"
4735 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4736 // BOUND = TY_BOUND | LT_BOUND
4737 // LT_BOUND = LIFETIME (e.g. `'a`)
4738 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4739 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4740 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4741 let mut bounds = Vec::new();
4743 // This needs to be syncronized with `Token::can_begin_bound`.
4744 let is_bound_start = self.check_path() || self.check_lifetime() ||
4745 self.check(&token::Question) ||
4746 self.check_keyword(keywords::For) ||
4747 self.check(&token::OpenDelim(token::Paren));
4750 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4751 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4752 if self.token.is_lifetime() {
4753 if let Some(question_span) = question {
4754 self.span_err(question_span,
4755 "`?` may only modify trait bounds, not lifetime bounds");
4757 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4759 self.expect(&token::CloseDelim(token::Paren))?;
4760 self.span_err(self.prev_span,
4761 "parenthesized lifetime bounds are not supported");
4764 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4765 let path = self.parse_path(PathStyle::Type)?;
4767 self.expect(&token::CloseDelim(token::Paren))?;
4769 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4770 let modifier = if question.is_some() {
4771 TraitBoundModifier::Maybe
4773 TraitBoundModifier::None
4775 bounds.push(TraitTyParamBound(poly_trait, modifier));
4781 if !allow_plus || !self.eat_plus() {
4789 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4790 self.parse_ty_param_bounds_common(true)
4793 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4794 // BOUND = LT_BOUND (e.g. `'a`)
4795 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4796 let mut lifetimes = Vec::new();
4797 while self.check_lifetime() {
4798 lifetimes.push(self.expect_lifetime());
4800 if !self.eat_plus() {
4807 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4808 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4809 let ident = self.parse_ident()?;
4811 // Parse optional colon and param bounds.
4812 let bounds = if self.eat(&token::Colon) {
4813 self.parse_ty_param_bounds()?
4818 let default = if self.eat(&token::Eq) {
4819 Some(self.parse_ty()?)
4825 attrs: preceding_attrs.into(),
4827 id: ast::DUMMY_NODE_ID,
4833 /// Parses the following grammar:
4834 /// TraitItemAssocTy = Ident ["<"...">"] [":" [TyParamBounds]] ["where" ...] ["=" Ty]
4835 fn parse_trait_item_assoc_ty(&mut self, preceding_attrs: Vec<Attribute>)
4836 -> PResult<'a, (ast::Generics, TyParam)> {
4837 let ident = self.parse_ident()?;
4838 let mut generics = self.parse_generics()?;
4840 // Parse optional colon and param bounds.
4841 let bounds = if self.eat(&token::Colon) {
4842 self.parse_ty_param_bounds()?
4846 generics.where_clause = self.parse_where_clause()?;
4848 let default = if self.eat(&token::Eq) {
4849 Some(self.parse_ty()?)
4853 self.expect(&token::Semi)?;
4855 Ok((generics, TyParam {
4856 attrs: preceding_attrs.into(),
4858 id: ast::DUMMY_NODE_ID,
4864 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4865 /// trailing comma and erroneous trailing attributes.
4866 crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4867 let mut params = Vec::new();
4868 let mut seen_ty_param = false;
4870 let attrs = self.parse_outer_attributes()?;
4871 if self.check_lifetime() {
4872 let lifetime = self.expect_lifetime();
4873 // Parse lifetime parameter.
4874 let bounds = if self.eat(&token::Colon) {
4875 self.parse_lt_param_bounds()
4879 params.push(ast::GenericParam::Lifetime(LifetimeDef {
4880 attrs: attrs.into(),
4885 self.span_err(self.prev_span,
4886 "lifetime parameters must be declared prior to type parameters");
4888 } else if self.check_ident() {
4889 // Parse type parameter.
4890 params.push(ast::GenericParam::Type(self.parse_ty_param(attrs)?));
4891 seen_ty_param = true;
4893 // Check for trailing attributes and stop parsing.
4894 if !attrs.is_empty() {
4895 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4896 self.span_err(attrs[0].span,
4897 &format!("trailing attribute after {} parameters", param_kind));
4902 if !self.eat(&token::Comma) {
4909 /// Parse a set of optional generic type parameter declarations. Where
4910 /// clauses are not parsed here, and must be added later via
4911 /// `parse_where_clause()`.
4913 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4914 /// | ( < lifetimes , typaramseq ( , )? > )
4915 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4916 fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4917 maybe_whole!(self, NtGenerics, |x| x);
4919 let span_lo = self.span;
4921 let params = self.parse_generic_params()?;
4925 where_clause: WhereClause {
4926 id: ast::DUMMY_NODE_ID,
4927 predicates: Vec::new(),
4928 span: syntax_pos::DUMMY_SP,
4930 span: span_lo.to(self.prev_span),
4933 Ok(ast::Generics::default())
4937 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4938 /// possibly including trailing comma.
4939 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4940 let mut lifetimes = Vec::new();
4941 let mut types = Vec::new();
4942 let mut bindings = Vec::new();
4943 let mut seen_type = false;
4944 let mut seen_binding = false;
4946 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
4947 // Parse lifetime argument.
4948 lifetimes.push(self.expect_lifetime());
4949 if seen_type || seen_binding {
4950 self.span_err(self.prev_span,
4951 "lifetime parameters must be declared prior to type parameters");
4953 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4954 // Parse associated type binding.
4956 let ident = self.parse_ident()?;
4958 let ty = self.parse_ty()?;
4959 bindings.push(TypeBinding {
4960 id: ast::DUMMY_NODE_ID,
4963 span: lo.to(self.prev_span),
4965 seen_binding = true;
4966 } else if self.check_type() {
4967 // Parse type argument.
4968 types.push(self.parse_ty()?);
4970 self.span_err(types[types.len() - 1].span,
4971 "type parameters must be declared prior to associated type bindings");
4978 if !self.eat(&token::Comma) {
4982 Ok((lifetimes, types, bindings))
4985 /// Parses an optional `where` clause and places it in `generics`.
4987 /// ```ignore (only-for-syntax-highlight)
4988 /// where T : Trait<U, V> + 'b, 'a : 'b
4990 fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4991 maybe_whole!(self, NtWhereClause, |x| x);
4993 let mut where_clause = WhereClause {
4994 id: ast::DUMMY_NODE_ID,
4995 predicates: Vec::new(),
4996 span: syntax_pos::DUMMY_SP,
4999 if !self.eat_keyword(keywords::Where) {
5000 return Ok(where_clause);
5002 let lo = self.prev_span;
5004 // We are considering adding generics to the `where` keyword as an alternative higher-rank
5005 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5006 // change we parse those generics now, but report an error.
5007 if self.choose_generics_over_qpath() {
5008 let generics = self.parse_generics()?;
5009 self.span_err(generics.span,
5010 "generic parameters on `where` clauses are reserved for future use");
5015 if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5016 let lifetime = self.expect_lifetime();
5017 // Bounds starting with a colon are mandatory, but possibly empty.
5018 self.expect(&token::Colon)?;
5019 let bounds = self.parse_lt_param_bounds();
5020 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5021 ast::WhereRegionPredicate {
5022 span: lo.to(self.prev_span),
5027 } else if self.check_type() {
5028 // Parse optional `for<'a, 'b>`.
5029 // This `for` is parsed greedily and applies to the whole predicate,
5030 // the bounded type can have its own `for` applying only to it.
5031 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5032 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5033 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5034 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5036 // Parse type with mandatory colon and (possibly empty) bounds,
5037 // or with mandatory equality sign and the second type.
5038 let ty = self.parse_ty()?;
5039 if self.eat(&token::Colon) {
5040 let bounds = self.parse_ty_param_bounds()?;
5041 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5042 ast::WhereBoundPredicate {
5043 span: lo.to(self.prev_span),
5044 bound_generic_params: lifetime_defs,
5049 // FIXME: Decide what should be used here, `=` or `==`.
5050 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5051 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5052 let rhs_ty = self.parse_ty()?;
5053 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5054 ast::WhereEqPredicate {
5055 span: lo.to(self.prev_span),
5058 id: ast::DUMMY_NODE_ID,
5062 return self.unexpected();
5068 if !self.eat(&token::Comma) {
5073 where_clause.span = lo.to(self.prev_span);
5077 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5078 -> PResult<'a, (Vec<Arg> , bool)> {
5080 let mut variadic = false;
5081 let args: Vec<Option<Arg>> =
5082 self.parse_unspanned_seq(
5083 &token::OpenDelim(token::Paren),
5084 &token::CloseDelim(token::Paren),
5085 SeqSep::trailing_allowed(token::Comma),
5087 if p.token == token::DotDotDot {
5091 if p.token != token::CloseDelim(token::Paren) {
5094 "`...` must be last in argument list for variadic function");
5098 let span = p.prev_span;
5099 if p.token == token::CloseDelim(token::Paren) {
5100 // continue parsing to present any further errors
5103 "only foreign functions are allowed to be variadic"
5105 Ok(Some(dummy_arg(span)))
5107 // this function definition looks beyond recovery, stop parsing
5109 "only foreign functions are allowed to be variadic");
5114 match p.parse_arg_general(named_args) {
5115 Ok(arg) => Ok(Some(arg)),
5118 let lo = p.prev_span;
5119 // Skip every token until next possible arg or end.
5120 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5121 // Create a placeholder argument for proper arg count (#34264).
5122 let span = lo.to(p.prev_span);
5123 Ok(Some(dummy_arg(span)))
5130 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5132 if variadic && args.is_empty() {
5134 "variadic function must be declared with at least one named argument");
5137 Ok((args, variadic))
5140 /// Parse the argument list and result type of a function declaration
5141 fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5143 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5144 let ret_ty = self.parse_ret_ty(true)?;
5153 /// Returns the parsed optional self argument and whether a self shortcut was used.
5154 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5155 let expect_ident = |this: &mut Self| match this.token {
5156 // Preserve hygienic context.
5157 token::Ident(ident, _) =>
5158 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5161 let isolated_self = |this: &mut Self, n| {
5162 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5163 this.look_ahead(n + 1, |t| t != &token::ModSep)
5166 // Parse optional self parameter of a method.
5167 // Only a limited set of initial token sequences is considered self parameters, anything
5168 // else is parsed as a normal function parameter list, so some lookahead is required.
5169 let eself_lo = self.span;
5170 let (eself, eself_ident, eself_hi) = match self.token {
5171 token::BinOp(token::And) => {
5177 (if isolated_self(self, 1) {
5179 SelfKind::Region(None, Mutability::Immutable)
5180 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5181 isolated_self(self, 2) {
5184 SelfKind::Region(None, Mutability::Mutable)
5185 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5186 isolated_self(self, 2) {
5188 let lt = self.expect_lifetime();
5189 SelfKind::Region(Some(lt), Mutability::Immutable)
5190 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5191 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5192 isolated_self(self, 3) {
5194 let lt = self.expect_lifetime();
5196 SelfKind::Region(Some(lt), Mutability::Mutable)
5199 }, expect_ident(self), self.prev_span)
5201 token::BinOp(token::Star) => {
5206 // Emit special error for `self` cases.
5207 (if isolated_self(self, 1) {
5209 self.span_err(self.span, "cannot pass `self` by raw pointer");
5210 SelfKind::Value(Mutability::Immutable)
5211 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5212 isolated_self(self, 2) {
5215 self.span_err(self.span, "cannot pass `self` by raw pointer");
5216 SelfKind::Value(Mutability::Immutable)
5219 }, expect_ident(self), self.prev_span)
5221 token::Ident(..) => {
5222 if isolated_self(self, 0) {
5225 let eself_ident = expect_ident(self);
5226 let eself_hi = self.prev_span;
5227 (if self.eat(&token::Colon) {
5228 let ty = self.parse_ty()?;
5229 SelfKind::Explicit(ty, Mutability::Immutable)
5231 SelfKind::Value(Mutability::Immutable)
5232 }, eself_ident, eself_hi)
5233 } else if self.token.is_keyword(keywords::Mut) &&
5234 isolated_self(self, 1) {
5238 let eself_ident = expect_ident(self);
5239 let eself_hi = self.prev_span;
5240 (if self.eat(&token::Colon) {
5241 let ty = self.parse_ty()?;
5242 SelfKind::Explicit(ty, Mutability::Mutable)
5244 SelfKind::Value(Mutability::Mutable)
5245 }, eself_ident, eself_hi)
5250 _ => return Ok(None),
5253 let eself = codemap::respan(eself_lo.to(eself_hi), eself);
5254 Ok(Some(Arg::from_self(eself, eself_ident)))
5257 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5258 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5259 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5261 self.expect(&token::OpenDelim(token::Paren))?;
5263 // Parse optional self argument
5264 let self_arg = self.parse_self_arg()?;
5266 // Parse the rest of the function parameter list.
5267 let sep = SeqSep::trailing_allowed(token::Comma);
5268 let fn_inputs = if let Some(self_arg) = self_arg {
5269 if self.check(&token::CloseDelim(token::Paren)) {
5271 } else if self.eat(&token::Comma) {
5272 let mut fn_inputs = vec![self_arg];
5273 fn_inputs.append(&mut self.parse_seq_to_before_end(
5274 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5278 return self.unexpected();
5281 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5284 // Parse closing paren and return type.
5285 self.expect(&token::CloseDelim(token::Paren))?;
5288 output: self.parse_ret_ty(true)?,
5293 // parse the |arg, arg| header on a lambda
5294 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5295 let inputs_captures = {
5296 if self.eat(&token::OrOr) {
5299 self.expect(&token::BinOp(token::Or))?;
5300 let args = self.parse_seq_to_before_tokens(
5301 &[&token::BinOp(token::Or), &token::OrOr],
5302 SeqSep::trailing_allowed(token::Comma),
5303 TokenExpectType::NoExpect,
5304 |p| p.parse_fn_block_arg()
5310 let output = self.parse_ret_ty(true)?;
5313 inputs: inputs_captures,
5319 /// Parse the name and optional generic types of a function header.
5320 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5321 let id = self.parse_ident()?;
5322 let generics = self.parse_generics()?;
5326 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5327 attrs: Vec<Attribute>) -> P<Item> {
5331 id: ast::DUMMY_NODE_ID,
5339 /// Parse an item-position function declaration.
5340 fn parse_item_fn(&mut self,
5342 constness: Spanned<Constness>,
5344 -> PResult<'a, ItemInfo> {
5345 let (ident, mut generics) = self.parse_fn_header()?;
5346 let decl = self.parse_fn_decl(false)?;
5347 generics.where_clause = self.parse_where_clause()?;
5348 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5349 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
5352 /// true if we are looking at `const ID`, false for things like `const fn` etc
5353 fn is_const_item(&mut self) -> bool {
5354 self.token.is_keyword(keywords::Const) &&
5355 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5356 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5359 /// parses all the "front matter" for a `fn` declaration, up to
5360 /// and including the `fn` keyword:
5364 /// - `const unsafe fn`
5367 fn parse_fn_front_matter(&mut self) -> PResult<'a, (Spanned<Constness>, Unsafety, Abi)> {
5368 let is_const_fn = self.eat_keyword(keywords::Const);
5369 let const_span = self.prev_span;
5370 let unsafety = self.parse_unsafety();
5371 let (constness, unsafety, abi) = if is_const_fn {
5372 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5374 let abi = if self.eat_keyword(keywords::Extern) {
5375 self.parse_opt_abi()?.unwrap_or(Abi::C)
5379 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5381 self.expect_keyword(keywords::Fn)?;
5382 Ok((constness, unsafety, abi))
5385 /// Parse an impl item.
5386 crate fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5387 maybe_whole!(self, NtImplItem, |x| x);
5388 let attrs = self.parse_outer_attributes()?;
5389 let (mut item, tokens) = self.collect_tokens(|this| {
5390 this.parse_impl_item_(at_end, attrs)
5393 // See `parse_item` for why this clause is here.
5394 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5395 item.tokens = Some(tokens);
5400 fn parse_impl_item_(&mut self,
5402 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5404 let vis = self.parse_visibility(false)?;
5405 let defaultness = self.parse_defaultness();
5406 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
5407 // This parses the grammar:
5408 // ImplItemAssocTy = Ident ["<"...">"] ["where" ...] "=" Ty ";"
5409 let name = self.parse_ident()?;
5410 let mut generics = self.parse_generics()?;
5411 generics.where_clause = self.parse_where_clause()?;
5412 self.expect(&token::Eq)?;
5413 let typ = self.parse_ty()?;
5414 self.expect(&token::Semi)?;
5415 (name, ast::ImplItemKind::Type(typ), generics)
5416 } else if self.is_const_item() {
5417 // This parses the grammar:
5418 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5419 self.expect_keyword(keywords::Const)?;
5420 let name = self.parse_ident()?;
5421 self.expect(&token::Colon)?;
5422 let typ = self.parse_ty()?;
5423 self.expect(&token::Eq)?;
5424 let expr = self.parse_expr()?;
5425 self.expect(&token::Semi)?;
5426 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5428 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5429 attrs.extend(inner_attrs);
5430 (name, node, generics)
5434 id: ast::DUMMY_NODE_ID,
5435 span: lo.to(self.prev_span),
5446 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5447 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5452 fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5454 VisibilityKind::Inherited => Ok(()),
5456 let is_macro_rules: bool = match self.token {
5457 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5461 let mut err = self.diagnostic()
5462 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5463 err.span_suggestion_with_applicability(
5465 "try exporting the macro",
5466 "#[macro_export]".to_owned(),
5467 Applicability::MaybeIncorrect // speculative
5471 let mut err = self.diagnostic()
5472 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5473 err.help("try adjusting the macro to put `pub` inside the invocation");
5480 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5481 -> DiagnosticBuilder<'a>
5483 let expected_kinds = if item_type == "extern" {
5484 "missing `fn`, `type`, or `static`"
5486 "missing `fn`, `type`, or `const`"
5489 // Given this code `path(`, it seems like this is not
5490 // setting the visibility of a macro invocation, but rather
5491 // a mistyped method declaration.
5492 // Create a diagnostic pointing out that `fn` is missing.
5494 // x | pub path(&self) {
5495 // | ^ missing `fn`, `type`, or `const`
5497 // ^^ `sp` below will point to this
5498 let sp = prev_span.between(self.prev_span);
5499 let mut err = self.diagnostic().struct_span_err(
5501 &format!("{} for {}-item declaration",
5502 expected_kinds, item_type));
5503 err.span_label(sp, expected_kinds);
5507 /// Parse a method or a macro invocation in a trait impl.
5508 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5509 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5510 ast::ImplItemKind)> {
5511 // code copied from parse_macro_use_or_failure... abstraction!
5512 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5514 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5515 ast::ImplItemKind::Macro(mac)))
5517 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
5518 let ident = self.parse_ident()?;
5519 let mut generics = self.parse_generics()?;
5520 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5521 generics.where_clause = self.parse_where_clause()?;
5523 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5524 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(ast::MethodSig {
5533 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5534 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5535 let ident = self.parse_ident()?;
5536 let mut tps = self.parse_generics()?;
5538 // Parse optional colon and supertrait bounds.
5539 let bounds = if self.eat(&token::Colon) {
5540 self.parse_ty_param_bounds()?
5545 if self.eat(&token::Eq) {
5546 // it's a trait alias
5547 let bounds = self.parse_ty_param_bounds()?;
5548 tps.where_clause = self.parse_where_clause()?;
5549 self.expect(&token::Semi)?;
5550 if unsafety != Unsafety::Normal {
5551 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5553 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5555 // it's a normal trait
5556 tps.where_clause = self.parse_where_clause()?;
5557 self.expect(&token::OpenDelim(token::Brace))?;
5558 let mut trait_items = vec![];
5559 while !self.eat(&token::CloseDelim(token::Brace)) {
5560 let mut at_end = false;
5561 match self.parse_trait_item(&mut at_end) {
5562 Ok(item) => trait_items.push(item),
5566 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5571 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5575 fn choose_generics_over_qpath(&self) -> bool {
5576 // There's an ambiguity between generic parameters and qualified paths in impls.
5577 // If we see `<` it may start both, so we have to inspect some following tokens.
5578 // The following combinations can only start generics,
5579 // but not qualified paths (with one exception):
5580 // `<` `>` - empty generic parameters
5581 // `<` `#` - generic parameters with attributes
5582 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5583 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5584 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5585 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5586 // The only truly ambiguous case is
5587 // `<` IDENT `>` `::` IDENT ...
5588 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5589 // because this is what almost always expected in practice, qualified paths in impls
5590 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5591 self.token == token::Lt &&
5592 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5593 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5594 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5595 t == &token::Colon || t == &token::Eq))
5598 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5599 self.expect(&token::OpenDelim(token::Brace))?;
5600 let attrs = self.parse_inner_attributes()?;
5602 let mut impl_items = Vec::new();
5603 while !self.eat(&token::CloseDelim(token::Brace)) {
5604 let mut at_end = false;
5605 match self.parse_impl_item(&mut at_end) {
5606 Ok(impl_item) => impl_items.push(impl_item),
5610 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5615 Ok((impl_items, attrs))
5618 /// Parses an implementation item, `impl` keyword is already parsed.
5619 /// impl<'a, T> TYPE { /* impl items */ }
5620 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5621 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5622 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5623 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5624 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5625 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5626 -> PResult<'a, ItemInfo> {
5627 // First, parse generic parameters if necessary.
5628 let mut generics = if self.choose_generics_over_qpath() {
5629 self.parse_generics()?
5631 ast::Generics::default()
5634 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5635 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5637 ast::ImplPolarity::Negative
5639 ast::ImplPolarity::Positive
5642 // Parse both types and traits as a type, then reinterpret if necessary.
5643 let ty_first = self.parse_ty()?;
5645 // If `for` is missing we try to recover.
5646 let has_for = self.eat_keyword(keywords::For);
5647 let missing_for_span = self.prev_span.between(self.span);
5649 let ty_second = if self.token == token::DotDot {
5650 // We need to report this error after `cfg` expansion for compatibility reasons
5651 self.bump(); // `..`, do not add it to expected tokens
5652 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5653 } else if has_for || self.token.can_begin_type() {
5654 Some(self.parse_ty()?)
5659 generics.where_clause = self.parse_where_clause()?;
5661 let (impl_items, attrs) = self.parse_impl_body()?;
5663 let item_kind = match ty_second {
5664 Some(ty_second) => {
5665 // impl Trait for Type
5667 self.span_err(missing_for_span, "missing `for` in a trait impl");
5670 let ty_first = ty_first.into_inner();
5671 let path = match ty_first.node {
5672 // This notably includes paths passed through `ty` macro fragments (#46438).
5673 TyKind::Path(None, path) => path,
5675 self.span_err(ty_first.span, "expected a trait, found type");
5676 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
5679 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5681 ItemKind::Impl(unsafety, polarity, defaultness,
5682 generics, Some(trait_ref), ty_second, impl_items)
5686 ItemKind::Impl(unsafety, polarity, defaultness,
5687 generics, None, ty_first, impl_items)
5691 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5694 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5695 if self.eat_keyword(keywords::For) {
5697 let params = self.parse_generic_params()?;
5699 // We rely on AST validation to rule out invalid cases: There must not be type
5700 // parameters, and the lifetime parameters must not have bounds.
5707 /// Parse struct Foo { ... }
5708 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5709 let class_name = self.parse_ident()?;
5711 let mut generics = self.parse_generics()?;
5713 // There is a special case worth noting here, as reported in issue #17904.
5714 // If we are parsing a tuple struct it is the case that the where clause
5715 // should follow the field list. Like so:
5717 // struct Foo<T>(T) where T: Copy;
5719 // If we are parsing a normal record-style struct it is the case
5720 // that the where clause comes before the body, and after the generics.
5721 // So if we look ahead and see a brace or a where-clause we begin
5722 // parsing a record style struct.
5724 // Otherwise if we look ahead and see a paren we parse a tuple-style
5727 let vdata = if self.token.is_keyword(keywords::Where) {
5728 generics.where_clause = self.parse_where_clause()?;
5729 if self.eat(&token::Semi) {
5730 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5731 VariantData::Unit(ast::DUMMY_NODE_ID)
5733 // If we see: `struct Foo<T> where T: Copy { ... }`
5734 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5736 // No `where` so: `struct Foo<T>;`
5737 } else if self.eat(&token::Semi) {
5738 VariantData::Unit(ast::DUMMY_NODE_ID)
5739 // Record-style struct definition
5740 } else if self.token == token::OpenDelim(token::Brace) {
5741 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5742 // Tuple-style struct definition with optional where-clause.
5743 } else if self.token == token::OpenDelim(token::Paren) {
5744 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5745 generics.where_clause = self.parse_where_clause()?;
5746 self.expect(&token::Semi)?;
5749 let token_str = self.this_token_to_string();
5750 let mut err = self.fatal(&format!(
5751 "expected `where`, `{{`, `(`, or `;` after struct name, found `{}`",
5754 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
5758 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5761 /// Parse union Foo { ... }
5762 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5763 let class_name = self.parse_ident()?;
5765 let mut generics = self.parse_generics()?;
5767 let vdata = if self.token.is_keyword(keywords::Where) {
5768 generics.where_clause = self.parse_where_clause()?;
5769 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5770 } else if self.token == token::OpenDelim(token::Brace) {
5771 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5773 let token_str = self.this_token_to_string();
5774 let mut err = self.fatal(&format!(
5775 "expected `where` or `{{` after union name, found `{}`", token_str));
5776 err.span_label(self.span, "expected `where` or `{` after union name");
5780 Ok((class_name, ItemKind::Union(vdata, generics), None))
5783 fn consume_block(&mut self, delim: token::DelimToken) {
5784 let mut brace_depth = 0;
5785 if !self.eat(&token::OpenDelim(delim)) {
5789 if self.eat(&token::OpenDelim(delim)) {
5791 } else if self.eat(&token::CloseDelim(delim)) {
5792 if brace_depth == 0 {
5798 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5806 fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5807 let mut fields = Vec::new();
5808 if self.eat(&token::OpenDelim(token::Brace)) {
5809 while self.token != token::CloseDelim(token::Brace) {
5810 let field = self.parse_struct_decl_field().map_err(|e| {
5811 self.recover_stmt();
5815 Ok(field) => fields.push(field),
5821 self.eat(&token::CloseDelim(token::Brace));
5823 let token_str = self.this_token_to_string();
5824 let mut err = self.fatal(&format!(
5825 "expected `where`, or `{{` after struct name, found `{}`", token_str));
5826 err.span_label(self.span, "expected `where`, or `{` after struct name");
5833 fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5834 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5835 // Unit like structs are handled in parse_item_struct function
5836 let fields = self.parse_unspanned_seq(
5837 &token::OpenDelim(token::Paren),
5838 &token::CloseDelim(token::Paren),
5839 SeqSep::trailing_allowed(token::Comma),
5841 let attrs = p.parse_outer_attributes()?;
5843 let vis = p.parse_visibility(true)?;
5844 let ty = p.parse_ty()?;
5846 span: lo.to(ty.span),
5849 id: ast::DUMMY_NODE_ID,
5858 /// Parse a structure field declaration
5859 fn parse_single_struct_field(&mut self,
5862 attrs: Vec<Attribute> )
5863 -> PResult<'a, StructField> {
5864 let mut seen_comma: bool = false;
5865 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5866 if self.token == token::Comma {
5873 token::CloseDelim(token::Brace) => {}
5874 token::DocComment(_) => {
5875 let previous_span = self.prev_span;
5876 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
5877 self.bump(); // consume the doc comment
5878 let comma_after_doc_seen = self.eat(&token::Comma);
5879 // `seen_comma` is always false, because we are inside doc block
5880 // condition is here to make code more readable
5881 if seen_comma == false && comma_after_doc_seen == true {
5884 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
5887 if seen_comma == false {
5888 let sp = self.sess.codemap().next_point(previous_span);
5889 err.span_suggestion_with_applicability(
5891 "missing comma here",
5893 Applicability::MachineApplicable
5900 let sp = self.sess.codemap().next_point(self.prev_span);
5901 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found `{}`",
5902 self.this_token_to_string()));
5903 if self.token.is_ident() {
5904 // This is likely another field; emit the diagnostic and keep going
5905 err.span_suggestion(sp, "try adding a comma", ",".into());
5915 /// Parse an element of a struct definition
5916 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5917 let attrs = self.parse_outer_attributes()?;
5919 let vis = self.parse_visibility(false)?;
5920 self.parse_single_struct_field(lo, vis, attrs)
5923 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5924 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5925 /// a function definition, it's not a tuple struct field) and the contents within the parens
5926 /// isn't valid, emit a proper diagnostic.
5927 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5928 maybe_whole!(self, NtVis, |x| x);
5930 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
5931 if self.is_crate_vis() {
5932 self.bump(); // `crate`
5933 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
5936 if !self.eat_keyword(keywords::Pub) {
5937 return Ok(respan(self.prev_span, VisibilityKind::Inherited))
5939 let lo = self.prev_span;
5941 if self.check(&token::OpenDelim(token::Paren)) {
5942 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5943 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5944 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5945 // by the following tokens.
5946 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5949 self.bump(); // `crate`
5950 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5952 lo.to(self.prev_span),
5953 VisibilityKind::Crate(CrateSugar::PubCrate),
5956 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5959 self.bump(); // `in`
5960 let path = self.parse_path(PathStyle::Mod)?; // `path`
5961 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5962 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
5964 id: ast::DUMMY_NODE_ID,
5967 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5968 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5969 t.is_keyword(keywords::SelfValue))
5971 // `pub(self)` or `pub(super)`
5973 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
5974 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5975 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
5977 id: ast::DUMMY_NODE_ID,
5980 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5981 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5983 let msg = "incorrect visibility restriction";
5984 let suggestion = r##"some possible visibility restrictions are:
5985 `pub(crate)`: visible only on the current crate
5986 `pub(super)`: visible only in the current module's parent
5987 `pub(in path::to::module)`: visible only on the specified path"##;
5988 let path = self.parse_path(PathStyle::Mod)?;
5989 let path_span = self.prev_span;
5990 let help_msg = format!("make this visible only to module `{}` with `in`", path);
5991 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5992 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5993 err.span_suggestion_with_applicability(
5994 path_span, &help_msg, format!("in {}", path), Applicability::MachineApplicable
5996 err.emit(); // emit diagnostic, but continue with public visibility
6000 Ok(respan(lo, VisibilityKind::Public))
6003 /// Parse defaultness: `default` or nothing.
6004 fn parse_defaultness(&mut self) -> Defaultness {
6005 // `pub` is included for better error messages
6006 if self.check_keyword(keywords::Default) &&
6007 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6008 t.is_keyword(keywords::Const) ||
6009 t.is_keyword(keywords::Fn) ||
6010 t.is_keyword(keywords::Unsafe) ||
6011 t.is_keyword(keywords::Extern) ||
6012 t.is_keyword(keywords::Type) ||
6013 t.is_keyword(keywords::Pub)) {
6014 self.bump(); // `default`
6015 Defaultness::Default
6021 /// Given a termination token, parse all of the items in a module
6022 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6023 let mut items = vec![];
6024 while let Some(item) = self.parse_item()? {
6028 if !self.eat(term) {
6029 let token_str = self.this_token_to_string();
6030 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
6031 if token_str == ";" {
6032 let msg = "consider removing this semicolon";
6033 err.span_suggestion_short_with_applicability(
6034 self.span, msg, "".to_string(), Applicability::MachineApplicable
6037 err.span_label(self.span, "expected item");
6042 let hi = if self.span == syntax_pos::DUMMY_SP {
6049 inner: inner_lo.to(hi),
6054 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6055 let id = self.parse_ident()?;
6056 self.expect(&token::Colon)?;
6057 let ty = self.parse_ty()?;
6058 self.expect(&token::Eq)?;
6059 let e = self.parse_expr()?;
6060 self.expect(&token::Semi)?;
6061 let item = match m {
6062 Some(m) => ItemKind::Static(ty, m, e),
6063 None => ItemKind::Const(ty, e),
6065 Ok((id, item, None))
6068 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6069 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6070 let (in_cfg, outer_attrs) = {
6071 let mut strip_unconfigured = ::config::StripUnconfigured {
6073 should_test: false, // irrelevant
6074 features: None, // don't perform gated feature checking
6076 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
6077 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6080 let id_span = self.span;
6081 let id = self.parse_ident()?;
6082 if self.check(&token::Semi) {
6084 if in_cfg && self.recurse_into_file_modules {
6085 // This mod is in an external file. Let's go get it!
6086 let ModulePathSuccess { path, directory_ownership, warn } =
6087 self.submod_path(id, &outer_attrs, id_span)?;
6088 let (module, mut attrs) =
6089 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6091 let attr = Attribute {
6092 id: attr::mk_attr_id(),
6093 style: ast::AttrStyle::Outer,
6094 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
6095 tokens: TokenStream::empty(),
6096 is_sugared_doc: false,
6097 span: syntax_pos::DUMMY_SP,
6099 attr::mark_known(&attr);
6102 Ok((id, module, Some(attrs)))
6104 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
6105 Ok((id, ItemKind::Mod(placeholder), None))
6108 let old_directory = self.directory.clone();
6109 self.push_directory(id, &outer_attrs);
6111 self.expect(&token::OpenDelim(token::Brace))?;
6112 let mod_inner_lo = self.span;
6113 let attrs = self.parse_inner_attributes()?;
6114 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6116 self.directory = old_directory;
6117 Ok((id, ItemKind::Mod(module), Some(attrs)))
6121 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6122 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6123 self.directory.path.to_mut().push(&path.as_str());
6124 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6126 self.directory.path.to_mut().push(&id.as_str());
6130 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6131 if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
6134 // On windows, the base path might have the form
6135 // `\\?\foo\bar` in which case it does not tolerate
6136 // mixed `/` and `\` separators, so canonicalize
6139 let s = s.replace("/", "\\");
6140 Some(dir_path.join(s))
6146 /// Returns either a path to a module, or .
6147 pub fn default_submod_path(
6149 relative: Option<ast::Ident>,
6151 codemap: &CodeMap) -> ModulePath
6153 // If we're in a foo.rs file instead of a mod.rs file,
6154 // we need to look for submodules in
6155 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6156 // `./<id>.rs` and `./<id>/mod.rs`.
6157 let relative_prefix_string;
6158 let relative_prefix = if let Some(ident) = relative {
6159 relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6160 &relative_prefix_string
6165 let mod_name = id.to_string();
6166 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6167 let secondary_path_str = format!("{}{}{}mod.rs",
6168 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6169 let default_path = dir_path.join(&default_path_str);
6170 let secondary_path = dir_path.join(&secondary_path_str);
6171 let default_exists = codemap.file_exists(&default_path);
6172 let secondary_exists = codemap.file_exists(&secondary_path);
6174 let result = match (default_exists, secondary_exists) {
6175 (true, false) => Ok(ModulePathSuccess {
6177 directory_ownership: DirectoryOwnership::Owned {
6182 (false, true) => Ok(ModulePathSuccess {
6183 path: secondary_path,
6184 directory_ownership: DirectoryOwnership::Owned {
6189 (false, false) => Err(Error::FileNotFoundForModule {
6190 mod_name: mod_name.clone(),
6191 default_path: default_path_str,
6192 secondary_path: secondary_path_str,
6193 dir_path: format!("{}", dir_path.display()),
6195 (true, true) => Err(Error::DuplicatePaths {
6196 mod_name: mod_name.clone(),
6197 default_path: default_path_str,
6198 secondary_path: secondary_path_str,
6204 path_exists: default_exists || secondary_exists,
6209 fn submod_path(&mut self,
6211 outer_attrs: &[Attribute],
6213 -> PResult<'a, ModulePathSuccess> {
6214 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6215 return Ok(ModulePathSuccess {
6216 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6217 // All `#[path]` files are treated as though they are a `mod.rs` file.
6218 // This means that `mod foo;` declarations inside `#[path]`-included
6219 // files are siblings,
6221 // Note that this will produce weirdness when a file named `foo.rs` is
6222 // `#[path]` included and contains a `mod foo;` declaration.
6223 // If you encounter this, it's your own darn fault :P
6224 Some(_) => DirectoryOwnership::Owned { relative: None },
6225 _ => DirectoryOwnership::UnownedViaMod(true),
6232 let relative = match self.directory.ownership {
6233 DirectoryOwnership::Owned { relative } => {
6234 // Push the usage onto the list of non-mod.rs mod uses.
6235 // This is used later for feature-gate error reporting.
6236 if let Some(cur_file_ident) = relative {
6238 .non_modrs_mods.borrow_mut()
6239 .push((cur_file_ident, id_sp));
6243 DirectoryOwnership::UnownedViaBlock |
6244 DirectoryOwnership::UnownedViaMod(_) => None,
6246 let paths = Parser::default_submod_path(
6247 id, relative, &self.directory.path, self.sess.codemap());
6249 match self.directory.ownership {
6250 DirectoryOwnership::Owned { .. } => {
6251 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6253 DirectoryOwnership::UnownedViaBlock => {
6255 "Cannot declare a non-inline module inside a block \
6256 unless it has a path attribute";
6257 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6258 if paths.path_exists {
6259 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6261 err.span_note(id_sp, &msg);
6265 DirectoryOwnership::UnownedViaMod(warn) => {
6267 if let Ok(result) = paths.result {
6268 return Ok(ModulePathSuccess { warn: true, ..result });
6271 let mut err = self.diagnostic().struct_span_err(id_sp,
6272 "cannot declare a new module at this location");
6273 if id_sp != syntax_pos::DUMMY_SP {
6274 let src_path = self.sess.codemap().span_to_filename(id_sp);
6275 if let FileName::Real(src_path) = src_path {
6276 if let Some(stem) = src_path.file_stem() {
6277 let mut dest_path = src_path.clone();
6278 dest_path.set_file_name(stem);
6279 dest_path.push("mod.rs");
6280 err.span_note(id_sp,
6281 &format!("maybe move this module `{}` to its own \
6282 directory via `{}`", src_path.display(),
6283 dest_path.display()));
6287 if paths.path_exists {
6288 err.span_note(id_sp,
6289 &format!("... or maybe `use` the module `{}` instead \
6290 of possibly redeclaring it",
6298 /// Read a module from a source file.
6299 fn eval_src_mod(&mut self,
6301 directory_ownership: DirectoryOwnership,
6304 -> PResult<'a, (ast::ItemKind, Vec<Attribute> )> {
6305 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6306 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6307 let mut err = String::from("circular modules: ");
6308 let len = included_mod_stack.len();
6309 for p in &included_mod_stack[i.. len] {
6310 err.push_str(&p.to_string_lossy());
6311 err.push_str(" -> ");
6313 err.push_str(&path.to_string_lossy());
6314 return Err(self.span_fatal(id_sp, &err[..]));
6316 included_mod_stack.push(path.clone());
6317 drop(included_mod_stack);
6320 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6321 p0.cfg_mods = self.cfg_mods;
6322 let mod_inner_lo = p0.span;
6323 let mod_attrs = p0.parse_inner_attributes()?;
6324 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6325 self.sess.included_mod_stack.borrow_mut().pop();
6326 Ok((ast::ItemKind::Mod(m0), mod_attrs))
6329 /// Parse a function declaration from a foreign module
6330 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6331 -> PResult<'a, ForeignItem> {
6332 self.expect_keyword(keywords::Fn)?;
6334 let (ident, mut generics) = self.parse_fn_header()?;
6335 let decl = self.parse_fn_decl(true)?;
6336 generics.where_clause = self.parse_where_clause()?;
6338 self.expect(&token::Semi)?;
6339 Ok(ast::ForeignItem {
6342 node: ForeignItemKind::Fn(decl, generics),
6343 id: ast::DUMMY_NODE_ID,
6349 /// Parse a static item from a foreign module.
6350 /// Assumes that the `static` keyword is already parsed.
6351 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6352 -> PResult<'a, ForeignItem> {
6353 let mutbl = self.eat_keyword(keywords::Mut);
6354 let ident = self.parse_ident()?;
6355 self.expect(&token::Colon)?;
6356 let ty = self.parse_ty()?;
6358 self.expect(&token::Semi)?;
6362 node: ForeignItemKind::Static(ty, mutbl),
6363 id: ast::DUMMY_NODE_ID,
6369 /// Parse a type from a foreign module
6370 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6371 -> PResult<'a, ForeignItem> {
6372 self.expect_keyword(keywords::Type)?;
6374 let ident = self.parse_ident()?;
6376 self.expect(&token::Semi)?;
6377 Ok(ast::ForeignItem {
6380 node: ForeignItemKind::Ty,
6381 id: ast::DUMMY_NODE_ID,
6387 /// Parse extern crate links
6391 /// extern crate foo;
6392 /// extern crate bar as foo;
6393 fn parse_item_extern_crate(&mut self,
6395 visibility: Visibility,
6396 attrs: Vec<Attribute>)
6397 -> PResult<'a, P<Item>> {
6398 let orig_name = self.parse_ident()?;
6399 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6400 (rename, Some(orig_name.name))
6404 self.expect(&token::Semi)?;
6406 let span = lo.to(self.prev_span);
6407 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6410 /// Parse `extern` for foreign ABIs
6413 /// `extern` is expected to have been
6414 /// consumed before calling this method
6420 fn parse_item_foreign_mod(&mut self,
6422 opt_abi: Option<Abi>,
6423 visibility: Visibility,
6424 mut attrs: Vec<Attribute>)
6425 -> PResult<'a, P<Item>> {
6426 self.expect(&token::OpenDelim(token::Brace))?;
6428 let abi = opt_abi.unwrap_or(Abi::C);
6430 attrs.extend(self.parse_inner_attributes()?);
6432 let mut foreign_items = vec![];
6433 while let Some(item) = self.parse_foreign_item()? {
6434 foreign_items.push(item);
6436 self.expect(&token::CloseDelim(token::Brace))?;
6438 let prev_span = self.prev_span;
6439 let m = ast::ForeignMod {
6441 items: foreign_items
6443 let invalid = keywords::Invalid.ident();
6444 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6447 /// Parse type Foo = Bar;
6448 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
6449 let ident = self.parse_ident()?;
6450 let mut tps = self.parse_generics()?;
6451 tps.where_clause = self.parse_where_clause()?;
6452 self.expect(&token::Eq)?;
6453 let ty = self.parse_ty()?;
6454 self.expect(&token::Semi)?;
6455 Ok((ident, ItemKind::Ty(ty, tps), None))
6458 /// Parse the part of an "enum" decl following the '{'
6459 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6460 let mut variants = Vec::new();
6461 let mut all_nullary = true;
6462 let mut any_disr = None;
6463 while self.token != token::CloseDelim(token::Brace) {
6464 let variant_attrs = self.parse_outer_attributes()?;
6465 let vlo = self.span;
6468 let mut disr_expr = None;
6469 let ident = self.parse_ident()?;
6470 if self.check(&token::OpenDelim(token::Brace)) {
6471 // Parse a struct variant.
6472 all_nullary = false;
6473 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6474 ast::DUMMY_NODE_ID);
6475 } else if self.check(&token::OpenDelim(token::Paren)) {
6476 all_nullary = false;
6477 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6478 ast::DUMMY_NODE_ID);
6479 } else if self.eat(&token::Eq) {
6480 disr_expr = Some(AnonConst {
6481 id: ast::DUMMY_NODE_ID,
6482 value: self.parse_expr()?,
6484 any_disr = disr_expr.as_ref().map(|c| c.value.span);
6485 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6487 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6490 let vr = ast::Variant_ {
6492 attrs: variant_attrs,
6496 variants.push(respan(vlo.to(self.prev_span), vr));
6498 if !self.eat(&token::Comma) { break; }
6500 self.expect(&token::CloseDelim(token::Brace))?;
6502 Some(disr_span) if !all_nullary =>
6503 self.span_err(disr_span,
6504 "discriminator values can only be used with a field-less enum"),
6508 Ok(ast::EnumDef { variants: variants })
6511 /// Parse an "enum" declaration
6512 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6513 let id = self.parse_ident()?;
6514 let mut generics = self.parse_generics()?;
6515 generics.where_clause = self.parse_where_clause()?;
6516 self.expect(&token::OpenDelim(token::Brace))?;
6518 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6519 self.recover_stmt();
6520 self.eat(&token::CloseDelim(token::Brace));
6523 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6526 /// Parses a string as an ABI spec on an extern type or module. Consumes
6527 /// the `extern` keyword, if one is found.
6528 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6530 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6532 self.expect_no_suffix(sp, "ABI spec", suf);
6534 match abi::lookup(&s.as_str()) {
6535 Some(abi) => Ok(Some(abi)),
6537 let prev_span = self.prev_span;
6540 &format!("invalid ABI: expected one of [{}], \
6542 abi::all_names().join(", "),
6553 fn is_static_global(&mut self) -> bool {
6554 if self.check_keyword(keywords::Static) {
6555 // Check if this could be a closure
6556 !self.look_ahead(1, |token| {
6557 if token.is_keyword(keywords::Move) {
6561 token::BinOp(token::Or) | token::OrOr => true,
6570 /// Parse one of the items allowed by the flags.
6571 /// NB: this function no longer parses the items inside an
6573 fn parse_item_(&mut self, attrs: Vec<Attribute>,
6574 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
6575 maybe_whole!(self, NtItem, |item| {
6576 let mut item = item.into_inner();
6577 let mut attrs = attrs;
6578 mem::swap(&mut item.attrs, &mut attrs);
6579 item.attrs.extend(attrs);
6585 let visibility = self.parse_visibility(false)?;
6587 if self.eat_keyword(keywords::Use) {
6589 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
6590 self.expect(&token::Semi)?;
6592 let span = lo.to(self.prev_span);
6593 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
6594 return Ok(Some(item));
6597 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6598 self.bump(); // `extern`
6599 if self.eat_keyword(keywords::Crate) {
6600 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6603 let opt_abi = self.parse_opt_abi()?;
6605 if self.eat_keyword(keywords::Fn) {
6606 // EXTERN FUNCTION ITEM
6607 let fn_span = self.prev_span;
6608 let abi = opt_abi.unwrap_or(Abi::C);
6609 let (ident, item_, extra_attrs) =
6610 self.parse_item_fn(Unsafety::Normal,
6611 respan(fn_span, Constness::NotConst),
6613 let prev_span = self.prev_span;
6614 let item = self.mk_item(lo.to(prev_span),
6618 maybe_append(attrs, extra_attrs));
6619 return Ok(Some(item));
6620 } else if self.check(&token::OpenDelim(token::Brace)) {
6621 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6627 if self.is_static_global() {
6630 let m = if self.eat_keyword(keywords::Mut) {
6633 Mutability::Immutable
6635 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6636 let prev_span = self.prev_span;
6637 let item = self.mk_item(lo.to(prev_span),
6641 maybe_append(attrs, extra_attrs));
6642 return Ok(Some(item));
6644 if self.eat_keyword(keywords::Const) {
6645 let const_span = self.prev_span;
6646 if self.check_keyword(keywords::Fn)
6647 || (self.check_keyword(keywords::Unsafe)
6648 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6649 // CONST FUNCTION ITEM
6650 let unsafety = self.parse_unsafety();
6652 let (ident, item_, extra_attrs) =
6653 self.parse_item_fn(unsafety,
6654 respan(const_span, Constness::Const),
6656 let prev_span = self.prev_span;
6657 let item = self.mk_item(lo.to(prev_span),
6661 maybe_append(attrs, extra_attrs));
6662 return Ok(Some(item));
6666 if self.eat_keyword(keywords::Mut) {
6667 let prev_span = self.prev_span;
6668 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6669 .help("did you mean to declare a static?")
6672 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6673 let prev_span = self.prev_span;
6674 let item = self.mk_item(lo.to(prev_span),
6678 maybe_append(attrs, extra_attrs));
6679 return Ok(Some(item));
6681 if self.check_keyword(keywords::Unsafe) &&
6682 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
6683 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
6685 // UNSAFE TRAIT ITEM
6686 self.bump(); // `unsafe`
6687 let is_auto = if self.eat_keyword(keywords::Trait) {
6690 self.expect_keyword(keywords::Auto)?;
6691 self.expect_keyword(keywords::Trait)?;
6694 let (ident, item_, extra_attrs) =
6695 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
6696 let prev_span = self.prev_span;
6697 let item = self.mk_item(lo.to(prev_span),
6701 maybe_append(attrs, extra_attrs));
6702 return Ok(Some(item));
6704 if self.check_keyword(keywords::Impl) ||
6705 self.check_keyword(keywords::Unsafe) &&
6706 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6707 self.check_keyword(keywords::Default) &&
6708 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6709 self.check_keyword(keywords::Default) &&
6710 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
6712 let defaultness = self.parse_defaultness();
6713 let unsafety = self.parse_unsafety();
6714 self.expect_keyword(keywords::Impl)?;
6715 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
6716 let span = lo.to(self.prev_span);
6717 return Ok(Some(self.mk_item(span, ident, item, visibility,
6718 maybe_append(attrs, extra_attrs))));
6720 if self.check_keyword(keywords::Fn) {
6723 let fn_span = self.prev_span;
6724 let (ident, item_, extra_attrs) =
6725 self.parse_item_fn(Unsafety::Normal,
6726 respan(fn_span, Constness::NotConst),
6728 let prev_span = self.prev_span;
6729 let item = self.mk_item(lo.to(prev_span),
6733 maybe_append(attrs, extra_attrs));
6734 return Ok(Some(item));
6736 if self.check_keyword(keywords::Unsafe)
6737 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
6738 // UNSAFE FUNCTION ITEM
6739 self.bump(); // `unsafe`
6740 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
6741 self.check(&token::OpenDelim(token::Brace));
6742 let abi = if self.eat_keyword(keywords::Extern) {
6743 self.parse_opt_abi()?.unwrap_or(Abi::C)
6747 self.expect_keyword(keywords::Fn)?;
6748 let fn_span = self.prev_span;
6749 let (ident, item_, extra_attrs) =
6750 self.parse_item_fn(Unsafety::Unsafe,
6751 respan(fn_span, Constness::NotConst),
6753 let prev_span = self.prev_span;
6754 let item = self.mk_item(lo.to(prev_span),
6758 maybe_append(attrs, extra_attrs));
6759 return Ok(Some(item));
6761 if self.eat_keyword(keywords::Mod) {
6763 let (ident, item_, extra_attrs) =
6764 self.parse_item_mod(&attrs[..])?;
6765 let prev_span = self.prev_span;
6766 let item = self.mk_item(lo.to(prev_span),
6770 maybe_append(attrs, extra_attrs));
6771 return Ok(Some(item));
6773 if self.eat_keyword(keywords::Type) {
6775 let (ident, item_, extra_attrs) = self.parse_item_type()?;
6776 let prev_span = self.prev_span;
6777 let item = self.mk_item(lo.to(prev_span),
6781 maybe_append(attrs, extra_attrs));
6782 return Ok(Some(item));
6784 if self.eat_keyword(keywords::Enum) {
6786 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
6787 let prev_span = self.prev_span;
6788 let item = self.mk_item(lo.to(prev_span),
6792 maybe_append(attrs, extra_attrs));
6793 return Ok(Some(item));
6795 if self.check_keyword(keywords::Trait)
6796 || (self.check_keyword(keywords::Auto)
6797 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
6799 let is_auto = if self.eat_keyword(keywords::Trait) {
6802 self.expect_keyword(keywords::Auto)?;
6803 self.expect_keyword(keywords::Trait)?;
6807 let (ident, item_, extra_attrs) =
6808 self.parse_item_trait(is_auto, Unsafety::Normal)?;
6809 let prev_span = self.prev_span;
6810 let item = self.mk_item(lo.to(prev_span),
6814 maybe_append(attrs, extra_attrs));
6815 return Ok(Some(item));
6817 if self.eat_keyword(keywords::Struct) {
6819 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6820 let prev_span = self.prev_span;
6821 let item = self.mk_item(lo.to(prev_span),
6825 maybe_append(attrs, extra_attrs));
6826 return Ok(Some(item));
6828 if self.is_union_item() {
6831 let (ident, item_, extra_attrs) = self.parse_item_union()?;
6832 let prev_span = self.prev_span;
6833 let item = self.mk_item(lo.to(prev_span),
6837 maybe_append(attrs, extra_attrs));
6838 return Ok(Some(item));
6840 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
6841 return Ok(Some(macro_def));
6844 // Verify whether we have encountered a struct or method definition where the user forgot to
6845 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
6846 if visibility.node == VisibilityKind::Public &&
6847 self.check_ident() &&
6848 self.look_ahead(1, |t| *t != token::Not)
6850 // Space between `pub` keyword and the identifier
6853 // ^^^ `sp` points here
6854 let sp = self.prev_span.between(self.span);
6855 let full_sp = self.prev_span.to(self.span);
6856 let ident_sp = self.span;
6857 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
6858 // possible public struct definition where `struct` was forgotten
6859 let ident = self.parse_ident().unwrap();
6860 let msg = format!("add `struct` here to parse `{}` as a public struct",
6862 let mut err = self.diagnostic()
6863 .struct_span_err(sp, "missing `struct` for struct definition");
6864 err.span_suggestion_short_with_applicability(
6865 sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
6868 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
6869 let ident = self.parse_ident().unwrap();
6870 self.consume_block(token::Paren);
6871 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
6872 self.check(&token::OpenDelim(token::Brace))
6874 ("fn", "method", false)
6875 } else if self.check(&token::Colon) {
6879 ("fn` or `struct", "method or struct", true)
6882 let msg = format!("missing `{}` for {} definition", kw, kw_name);
6883 let mut err = self.diagnostic().struct_span_err(sp, &msg);
6885 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
6889 err.span_suggestion_short_with_applicability(
6890 sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
6893 if let Ok(snippet) = self.sess.codemap().span_to_snippet(ident_sp) {
6894 err.span_suggestion_with_applicability(
6896 "if you meant to call a macro, try",
6897 format!("{}!", snippet),
6898 // this is the `ambiguous` conditional branch
6899 Applicability::MaybeIncorrect
6902 err.help("if you meant to call a macro, remove the `pub` \
6903 and add a trailing `!` after the identifier");
6909 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
6912 /// Parse a foreign item.
6913 crate fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
6914 maybe_whole!(self, NtForeignItem, |ni| Some(ni));
6916 let attrs = self.parse_outer_attributes()?;
6918 let visibility = self.parse_visibility(false)?;
6920 // FOREIGN STATIC ITEM
6921 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
6922 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
6923 if self.token.is_keyword(keywords::Const) {
6925 .struct_span_err(self.span, "extern items cannot be `const`")
6926 .span_suggestion_with_applicability(
6928 "try using a static value",
6929 "static".to_owned(),
6930 Applicability::MachineApplicable
6933 self.bump(); // `static` or `const`
6934 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6936 // FOREIGN FUNCTION ITEM
6937 if self.check_keyword(keywords::Fn) {
6938 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6940 // FOREIGN TYPE ITEM
6941 if self.check_keyword(keywords::Type) {
6942 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
6945 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
6949 ident: keywords::Invalid.ident(),
6950 span: lo.to(self.prev_span),
6951 id: ast::DUMMY_NODE_ID,
6954 node: ForeignItemKind::Macro(mac),
6959 if !attrs.is_empty() {
6960 self.expected_item_err(&attrs);
6968 /// This is the fall-through for parsing items.
6969 fn parse_macro_use_or_failure(
6971 attrs: Vec<Attribute> ,
6972 macros_allowed: bool,
6973 attributes_allowed: bool,
6975 visibility: Visibility
6976 ) -> PResult<'a, Option<P<Item>>> {
6977 if macros_allowed && self.token.is_path_start() {
6978 // MACRO INVOCATION ITEM
6980 let prev_span = self.prev_span;
6981 self.complain_if_pub_macro(&visibility.node, prev_span);
6983 let mac_lo = self.span;
6986 let pth = self.parse_path(PathStyle::Mod)?;
6987 self.expect(&token::Not)?;
6989 // a 'special' identifier (like what `macro_rules!` uses)
6990 // is optional. We should eventually unify invoc syntax
6992 let id = if self.token.is_ident() {
6995 keywords::Invalid.ident() // no special identifier
6997 // eat a matched-delimiter token tree:
6998 let (delim, tts) = self.expect_delimited_token_tree()?;
6999 if delim != MacDelimiter::Brace {
7000 if !self.eat(&token::Semi) {
7001 self.span_err(self.prev_span,
7002 "macros that expand to items must either \
7003 be surrounded with braces or followed by \
7008 let hi = self.prev_span;
7009 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7010 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7011 return Ok(Some(item));
7014 // FAILURE TO PARSE ITEM
7015 match visibility.node {
7016 VisibilityKind::Inherited => {}
7018 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7022 if !attributes_allowed && !attrs.is_empty() {
7023 self.expected_item_err(&attrs);
7028 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
7029 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7030 at_end: &mut bool) -> PResult<'a, Option<Mac>>
7032 if self.token.is_path_start() && !self.is_extern_non_path() {
7033 let prev_span = self.prev_span;
7035 let pth = self.parse_path(PathStyle::Mod)?;
7037 if pth.segments.len() == 1 {
7038 if !self.eat(&token::Not) {
7039 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7042 self.expect(&token::Not)?;
7045 if let Some(vis) = vis {
7046 self.complain_if_pub_macro(&vis.node, prev_span);
7051 // eat a matched-delimiter token tree:
7052 let (delim, tts) = self.expect_delimited_token_tree()?;
7053 if delim != MacDelimiter::Brace {
7054 self.expect(&token::Semi)?
7057 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7063 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7064 where F: FnOnce(&mut Self) -> PResult<'a, R>
7066 // Record all tokens we parse when parsing this item.
7067 let mut tokens = Vec::new();
7068 match self.token_cursor.frame.last_token {
7069 LastToken::Collecting(_) => {
7070 panic!("cannot collect tokens recursively yet")
7072 LastToken::Was(ref mut last) => tokens.extend(last.take()),
7074 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7075 let prev = self.token_cursor.stack.len();
7077 let last_token = if self.token_cursor.stack.len() == prev {
7078 &mut self.token_cursor.frame.last_token
7080 &mut self.token_cursor.stack[prev].last_token
7082 let mut tokens = match *last_token {
7083 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7084 LastToken::Was(_) => panic!("our vector went away?"),
7087 // If we're not at EOF our current token wasn't actually consumed by
7088 // `f`, but it'll still be in our list that we pulled out. In that case
7090 if self.token == token::Eof {
7091 *last_token = LastToken::Was(None);
7093 *last_token = LastToken::Was(tokens.pop());
7096 Ok((ret?, tokens.into_iter().collect()))
7099 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7100 let attrs = self.parse_outer_attributes()?;
7102 let (ret, tokens) = self.collect_tokens(|this| {
7103 this.parse_item_(attrs, true, false)
7106 // Once we've parsed an item and recorded the tokens we got while
7107 // parsing we may want to store `tokens` into the item we're about to
7108 // return. Note, though, that we specifically didn't capture tokens
7109 // related to outer attributes. The `tokens` field here may later be
7110 // used with procedural macros to convert this item back into a token
7111 // stream, but during expansion we may be removing attributes as we go
7114 // If we've got inner attributes then the `tokens` we've got above holds
7115 // these inner attributes. If an inner attribute is expanded we won't
7116 // actually remove it from the token stream, so we'll just keep yielding
7117 // it (bad!). To work around this case for now we just avoid recording
7118 // `tokens` if we detect any inner attributes. This should help keep
7119 // expansion correct, but we should fix this bug one day!
7122 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7123 i.tokens = Some(tokens);
7131 fn is_import_coupler(&mut self) -> bool {
7132 self.check(&token::ModSep) &&
7133 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7134 *t == token::BinOp(token::Star))
7139 /// USE_TREE = [`::`] `*` |
7140 /// [`::`] `{` USE_TREE_LIST `}` |
7142 /// PATH `::` `{` USE_TREE_LIST `}` |
7143 /// PATH [`as` IDENT]
7144 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7147 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7148 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7149 self.check(&token::BinOp(token::Star)) ||
7150 self.is_import_coupler() {
7151 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7152 if self.eat(&token::ModSep) {
7153 prefix.segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
7156 if self.eat(&token::BinOp(token::Star)) {
7159 UseTreeKind::Nested(self.parse_use_tree_list()?)
7162 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7163 prefix = self.parse_path(PathStyle::Mod)?;
7165 if self.eat(&token::ModSep) {
7166 if self.eat(&token::BinOp(token::Star)) {
7169 UseTreeKind::Nested(self.parse_use_tree_list()?)
7172 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7176 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7179 /// Parse UseTreeKind::Nested(list)
7181 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7182 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7183 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7184 &token::CloseDelim(token::Brace),
7185 SeqSep::trailing_allowed(token::Comma), |this| {
7186 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7190 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7191 if self.eat_keyword(keywords::As) {
7193 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
7195 Ok(Some(Ident::new(ident.name.gensymed(), ident.span)))
7197 _ => self.parse_ident().map(Some),
7204 /// Parses a source module as a crate. This is the main
7205 /// entry point for the parser.
7206 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7209 attrs: self.parse_inner_attributes()?,
7210 module: self.parse_mod_items(&token::Eof, lo)?,
7211 span: lo.to(self.span),
7215 fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7216 let ret = match self.token {
7217 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7218 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7225 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7226 match self.parse_optional_str() {
7227 Some((s, style, suf)) => {
7228 let sp = self.prev_span;
7229 self.expect_no_suffix(sp, "string literal", suf);
7233 let msg = "expected string literal";
7234 let mut err = self.fatal(msg);
7235 err.span_label(self.span, msg);