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.
12 use ast::{AngleBracketedParameterData, ParenthesizedParameterData, AttrStyle, BareFnTy};
13 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
15 use ast::{Mod, Arg, Arm, Attribute, BindingMode, TraitItemKind};
17 use ast::{BlockCheckMode, CaptureBy};
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::{Lifetime, LifetimeDef, Lit, LitKind, UintTy};
28 use ast::MacStmtStyle;
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, 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, BytePos, FileName, DUMMY_SP};
46 use errors::{self, DiagnosticBuilder};
47 use parse::{self, classify, token};
48 use parse::common::SeqSep;
49 use parse::lexer::TokenAndSpan;
50 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
51 use parse::obsolete::ObsoleteSyntax;
52 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
53 use util::parser::{AssocOp, Fixity};
57 use tokenstream::{self, Delimited, ThinTokenStream, TokenTree, TokenStream};
58 use symbol::{Symbol, keywords};
62 use std::collections::HashSet;
64 use std::path::{self, Path, PathBuf};
68 pub struct Restrictions: u8 {
69 const STMT_EXPR = 1 << 0;
70 const NO_STRUCT_LITERAL = 1 << 1;
74 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute> >);
76 /// How to parse a path.
77 #[derive(Copy, Clone, PartialEq)]
79 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
80 /// with something else. For example, in expressions `segment < ....` can be interpreted
81 /// as a comparison and `segment ( ....` can be interpreted as a function call.
82 /// In all such contexts the non-path interpretation is preferred by default for practical
83 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
84 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
86 /// In other contexts, notably in types, no ambiguity exists and paths can be written
87 /// without the disambiguator, e.g. `x<y>` - unambiguously a path.
88 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
90 /// A path with generic arguments disallowed, e.g. `foo::bar::Baz`, used in imports,
91 /// visibilities or attributes.
92 /// Technically, this variant is unnecessary and e.g. `Expr` can be used instead
93 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
94 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
95 /// tokens when something goes wrong.
99 #[derive(Clone, Copy, Debug, PartialEq)]
100 pub enum SemiColonMode {
105 #[derive(Clone, Copy, Debug, PartialEq)]
111 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
112 /// dropped into the token stream, which happens while parsing the result of
113 /// macro expansion). Placement of these is not as complex as I feared it would
114 /// be. The important thing is to make sure that lookahead doesn't balk at
115 /// `token::Interpolated` tokens.
116 macro_rules! maybe_whole_expr {
118 if let token::Interpolated(nt) = $p.token.clone() {
120 token::NtExpr(ref e) => {
122 return Ok((*e).clone());
124 token::NtPath(ref path) => {
127 let kind = ExprKind::Path(None, (*path).clone());
128 return Ok($p.mk_expr(span, kind, ThinVec::new()));
130 token::NtBlock(ref block) => {
133 let kind = ExprKind::Block((*block).clone());
134 return Ok($p.mk_expr(span, kind, ThinVec::new()));
142 /// As maybe_whole_expr, but for things other than expressions
143 macro_rules! maybe_whole {
144 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
145 if let token::Interpolated(nt) = $p.token.clone() {
146 if let token::$constructor($x) = nt.0.clone() {
154 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
156 if let Some(ref attrs) = rhs {
157 lhs.extend(attrs.iter().cloned())
162 #[derive(Debug, Clone, Copy, PartialEq)]
173 trait RecoverQPath: Sized {
174 const PATH_STYLE: PathStyle = PathStyle::Expr;
175 fn to_ty(&self) -> Option<P<Ty>>;
176 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self;
177 fn to_string(&self) -> String;
180 impl RecoverQPath for Ty {
181 const PATH_STYLE: PathStyle = PathStyle::Type;
182 fn to_ty(&self) -> Option<P<Ty>> {
183 Some(P(self.clone()))
185 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
186 Self { span: path.span, node: TyKind::Path(qself, path), id: self.id }
188 fn to_string(&self) -> String {
189 pprust::ty_to_string(self)
193 impl RecoverQPath for Pat {
194 fn to_ty(&self) -> Option<P<Ty>> {
197 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
198 Self { span: path.span, node: PatKind::Path(qself, path), id: self.id }
200 fn to_string(&self) -> String {
201 pprust::pat_to_string(self)
205 impl RecoverQPath for Expr {
206 fn to_ty(&self) -> Option<P<Ty>> {
209 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
210 Self { span: path.span, node: ExprKind::Path(qself, path),
211 id: self.id, attrs: self.attrs.clone() }
213 fn to_string(&self) -> String {
214 pprust::expr_to_string(self)
218 /* ident is handled by common.rs */
221 pub struct Parser<'a> {
222 pub sess: &'a ParseSess,
223 /// the current token:
224 pub token: token::Token,
225 /// the span of the current token:
227 /// the span of the previous token:
228 pub meta_var_span: Option<Span>,
230 /// the previous token kind
231 prev_token_kind: PrevTokenKind,
232 pub restrictions: Restrictions,
233 /// The set of seen errors about obsolete syntax. Used to suppress
234 /// extra detail when the same error is seen twice
235 pub obsolete_set: HashSet<ObsoleteSyntax>,
236 /// Used to determine the path to externally loaded source files
237 pub directory: Directory,
238 /// Whether to parse sub-modules in other files.
239 pub recurse_into_file_modules: bool,
240 /// Name of the root module this parser originated from. If `None`, then the
241 /// name is not known. This does not change while the parser is descending
242 /// into modules, and sub-parsers have new values for this name.
243 pub root_module_name: Option<String>,
244 pub expected_tokens: Vec<TokenType>,
245 token_cursor: TokenCursor,
246 pub desugar_doc_comments: bool,
247 /// Whether we should configure out of line modules as we parse.
254 frame: TokenCursorFrame,
255 stack: Vec<TokenCursorFrame>,
259 struct TokenCursorFrame {
260 delim: token::DelimToken,
263 tree_cursor: tokenstream::Cursor,
265 last_token: LastToken,
268 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
269 /// by the parser, and then that's transitively used to record the tokens that
270 /// each parse AST item is created with.
272 /// Right now this has two states, either collecting tokens or not collecting
273 /// tokens. If we're collecting tokens we just save everything off into a local
274 /// `Vec`. This should eventually though likely save tokens from the original
275 /// token stream and just use slicing of token streams to avoid creation of a
276 /// whole new vector.
278 /// The second state is where we're passively not recording tokens, but the last
279 /// token is still tracked for when we want to start recording tokens. This
280 /// "last token" means that when we start recording tokens we'll want to ensure
281 /// that this, the first token, is included in the output.
283 /// You can find some more example usage of this in the `collect_tokens` method
287 Collecting(Vec<TokenTree>),
288 Was(Option<TokenTree>),
291 impl TokenCursorFrame {
292 fn new(sp: Span, delimited: &Delimited) -> Self {
294 delim: delimited.delim,
296 open_delim: delimited.delim == token::NoDelim,
297 tree_cursor: delimited.stream().into_trees(),
298 close_delim: delimited.delim == token::NoDelim,
299 last_token: LastToken::Was(None),
305 fn next(&mut self) -> TokenAndSpan {
307 let tree = if !self.frame.open_delim {
308 self.frame.open_delim = true;
309 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
310 .open_tt(self.frame.span)
311 } else if let Some(tree) = self.frame.tree_cursor.next() {
313 } else if !self.frame.close_delim {
314 self.frame.close_delim = true;
315 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
316 .close_tt(self.frame.span)
317 } else if let Some(frame) = self.stack.pop() {
321 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
324 match self.frame.last_token {
325 LastToken::Collecting(ref mut v) => v.push(tree.clone()),
326 LastToken::Was(ref mut t) => *t = Some(tree.clone()),
330 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
331 TokenTree::Delimited(sp, ref delimited) => {
332 let frame = TokenCursorFrame::new(sp, delimited);
333 self.stack.push(mem::replace(&mut self.frame, frame));
339 fn next_desugared(&mut self) -> TokenAndSpan {
340 let (sp, name) = match self.next() {
341 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
345 let stripped = strip_doc_comment_decoration(&name.as_str());
347 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
348 // required to wrap the text.
349 let mut num_of_hashes = 0;
351 for ch in stripped.chars() {
354 '#' if count > 0 => count + 1,
357 num_of_hashes = cmp::max(num_of_hashes, count);
360 let body = TokenTree::Delimited(sp, Delimited {
361 delim: token::Bracket,
362 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"))),
363 TokenTree::Token(sp, token::Eq),
364 TokenTree::Token(sp, token::Literal(
365 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
366 .iter().cloned().collect::<TokenStream>().into(),
369 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
370 delim: token::NoDelim,
371 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
372 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
373 .iter().cloned().collect::<TokenStream>().into()
375 [TokenTree::Token(sp, token::Pound), body]
376 .iter().cloned().collect::<TokenStream>().into()
384 #[derive(PartialEq, Eq, Clone)]
387 Keyword(keywords::Keyword),
396 fn to_string(&self) -> String {
398 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
399 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
400 TokenType::Operator => "an operator".to_string(),
401 TokenType::Lifetime => "lifetime".to_string(),
402 TokenType::Ident => "identifier".to_string(),
403 TokenType::Path => "path".to_string(),
404 TokenType::Type => "type".to_string(),
409 // Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
410 // `IDENT<<u8 as Trait>::AssocTy>`, `IDENT(u8, u8) -> u8`.
411 fn can_continue_type_after_ident(t: &token::Token) -> bool {
412 t == &token::ModSep || t == &token::Lt ||
413 t == &token::BinOp(token::Shl) || t == &token::OpenDelim(token::Paren)
416 /// Information about the path to a module.
417 pub struct ModulePath {
419 pub path_exists: bool,
420 pub result: Result<ModulePathSuccess, Error>,
423 pub struct ModulePathSuccess {
425 pub directory_ownership: DirectoryOwnership,
429 pub struct ModulePathError {
431 pub help_msg: String,
435 FileNotFoundForModule {
437 default_path: String,
438 secondary_path: String,
443 default_path: String,
444 secondary_path: String,
447 InclusiveRangeWithNoEnd,
451 pub fn span_err(self, sp: Span, handler: &errors::Handler) -> DiagnosticBuilder {
453 Error::FileNotFoundForModule { ref mod_name,
457 let mut err = struct_span_err!(handler, sp, E0583,
458 "file not found for module `{}`", mod_name);
459 err.help(&format!("name the file either {} or {} inside the directory {:?}",
465 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
466 let mut err = struct_span_err!(handler, sp, E0584,
467 "file for module `{}` found at both {} and {}",
471 err.help("delete or rename one of them to remove the ambiguity");
474 Error::UselessDocComment => {
475 let mut err = struct_span_err!(handler, sp, E0585,
476 "found a documentation comment that doesn't document anything");
477 err.help("doc comments must come before what they document, maybe a comment was \
478 intended with `//`?");
481 Error::InclusiveRangeWithNoEnd => {
482 let mut err = struct_span_err!(handler, sp, E0586,
483 "inclusive range with no end");
484 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
494 AttributesParsed(ThinVec<Attribute>),
495 AlreadyParsed(P<Expr>),
498 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
499 fn from(o: Option<ThinVec<Attribute>>) -> Self {
500 if let Some(attrs) = o {
501 LhsExpr::AttributesParsed(attrs)
503 LhsExpr::NotYetParsed
508 impl From<P<Expr>> for LhsExpr {
509 fn from(expr: P<Expr>) -> Self {
510 LhsExpr::AlreadyParsed(expr)
514 /// Create a placeholder argument.
515 fn dummy_arg(span: Span) -> Arg {
516 let spanned = Spanned {
518 node: keywords::Invalid.ident()
521 id: ast::DUMMY_NODE_ID,
522 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), spanned, None),
528 id: ast::DUMMY_NODE_ID
530 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
533 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
534 enum TokenExpectType {
539 impl<'a> Parser<'a> {
540 pub fn new(sess: &'a ParseSess,
542 directory: Option<Directory>,
543 recurse_into_file_modules: bool,
544 desugar_doc_comments: bool)
546 let mut parser = Parser {
548 token: token::Underscore,
549 span: syntax_pos::DUMMY_SP,
550 prev_span: syntax_pos::DUMMY_SP,
552 prev_token_kind: PrevTokenKind::Other,
553 restrictions: Restrictions::empty(),
554 obsolete_set: HashSet::new(),
555 recurse_into_file_modules,
556 directory: Directory {
557 path: PathBuf::new(),
558 ownership: DirectoryOwnership::Owned { relative: None }
560 root_module_name: None,
561 expected_tokens: Vec::new(),
562 token_cursor: TokenCursor {
563 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
564 delim: token::NoDelim,
569 desugar_doc_comments,
573 let tok = parser.next_tok();
574 parser.token = tok.tok;
575 parser.span = tok.sp;
577 if let Some(directory) = directory {
578 parser.directory = directory;
579 } else if !parser.span.source_equal(&DUMMY_SP) {
580 if let FileName::Real(path) = sess.codemap().span_to_unmapped_path(parser.span) {
581 parser.directory.path = path;
582 parser.directory.path.pop();
586 parser.process_potential_macro_variable();
590 fn next_tok(&mut self) -> TokenAndSpan {
591 let mut next = if self.desugar_doc_comments {
592 self.token_cursor.next_desugared()
594 self.token_cursor.next()
596 if next.sp == syntax_pos::DUMMY_SP {
597 next.sp = self.prev_span;
602 /// Convert a token to a string using self's reader
603 pub fn token_to_string(token: &token::Token) -> String {
604 pprust::token_to_string(token)
607 /// Convert the current token to a string using self's reader
608 pub fn this_token_to_string(&self) -> String {
609 Parser::token_to_string(&self.token)
612 pub fn this_token_descr(&self) -> String {
613 let prefix = match &self.token {
614 t if t.is_special_ident() => "reserved identifier ",
615 t if t.is_used_keyword() => "keyword ",
616 t if t.is_unused_keyword() => "reserved keyword ",
619 format!("{}`{}`", prefix, self.this_token_to_string())
622 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
623 let token_str = Parser::token_to_string(t);
624 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
627 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
628 match self.expect_one_of(&[], &[]) {
630 Ok(_) => unreachable!(),
634 /// Expect and consume the token t. Signal an error if
635 /// the next token is not t.
636 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
637 if self.expected_tokens.is_empty() {
638 if self.token == *t {
642 let token_str = Parser::token_to_string(t);
643 let this_token_str = self.this_token_to_string();
644 Err(self.fatal(&format!("expected `{}`, found `{}`",
649 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
653 /// Expect next token to be edible or inedible token. If edible,
654 /// then consume it; if inedible, then return without consuming
655 /// anything. Signal a fatal error if next token is unexpected.
656 pub fn expect_one_of(&mut self,
657 edible: &[token::Token],
658 inedible: &[token::Token]) -> PResult<'a, ()>{
659 fn tokens_to_string(tokens: &[TokenType]) -> String {
660 let mut i = tokens.iter();
661 // This might be a sign we need a connect method on Iterator.
663 .map_or("".to_string(), |t| t.to_string());
664 i.enumerate().fold(b, |mut b, (i, a)| {
665 if tokens.len() > 2 && i == tokens.len() - 2 {
667 } else if tokens.len() == 2 && i == tokens.len() - 2 {
672 b.push_str(&a.to_string());
676 if edible.contains(&self.token) {
679 } else if inedible.contains(&self.token) {
680 // leave it in the input
683 let mut expected = edible.iter()
684 .map(|x| TokenType::Token(x.clone()))
685 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
686 .chain(self.expected_tokens.iter().cloned())
687 .collect::<Vec<_>>();
688 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
690 let expect = tokens_to_string(&expected[..]);
691 let actual = self.this_token_to_string();
692 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
693 let short_expect = if expected.len() > 6 {
694 format!("{} possible tokens", expected.len())
698 (format!("expected one of {}, found `{}`", expect, actual),
699 (self.prev_span.next_point(), format!("expected one of {} here", short_expect)))
700 } else if expected.is_empty() {
701 (format!("unexpected token: `{}`", actual),
702 (self.prev_span, "unexpected token after this".to_string()))
704 (format!("expected {}, found `{}`", expect, actual),
705 (self.prev_span.next_point(), format!("expected {} here", expect)))
707 let mut err = self.fatal(&msg_exp);
708 let sp = if self.token == token::Token::Eof {
709 // This is EOF, don't want to point at the following char, but rather the last token
715 let cm = self.sess.codemap();
716 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
717 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
718 // When the spans are in the same line, it means that the only content between
719 // them is whitespace, point at the found token in that case:
721 // X | () => { syntax error };
722 // | ^^^^^ expected one of 8 possible tokens here
724 // instead of having:
726 // X | () => { syntax error };
727 // | -^^^^^ unexpected token
729 // | expected one of 8 possible tokens here
730 err.span_label(self.span, label_exp);
733 err.span_label(sp, label_exp);
734 err.span_label(self.span, "unexpected token");
741 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
742 fn interpolated_or_expr_span(&self,
743 expr: PResult<'a, P<Expr>>)
744 -> PResult<'a, (Span, P<Expr>)> {
746 if self.prev_token_kind == PrevTokenKind::Interpolated {
754 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
757 if self.token.is_reserved_ident() {
758 self.span_err(self.span, &format!("expected identifier, found {}",
759 self.this_token_descr()));
765 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
766 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
768 let mut err = self.fatal(&format!("expected identifier, found `{}`",
769 self.this_token_to_string()));
770 if self.token == token::Underscore {
771 err.note("`_` is a wildcard pattern, not an identifier");
779 /// Check if the next token is `tok`, and return `true` if so.
781 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
783 pub fn check(&mut self, tok: &token::Token) -> bool {
784 let is_present = self.token == *tok;
785 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
789 /// Consume token 'tok' if it exists. Returns true if the given
790 /// token was present, false otherwise.
791 pub fn eat(&mut self, tok: &token::Token) -> bool {
792 let is_present = self.check(tok);
793 if is_present { self.bump() }
797 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
798 self.expected_tokens.push(TokenType::Keyword(kw));
799 self.token.is_keyword(kw)
802 /// If the next token is the given keyword, eat it and return
803 /// true. Otherwise, return false.
804 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
805 if self.check_keyword(kw) {
813 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
814 if self.token.is_keyword(kw) {
822 /// If the given word is not a keyword, signal an error.
823 /// If the next token is not the given word, signal an error.
824 /// Otherwise, eat it.
825 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
826 if !self.eat_keyword(kw) {
833 fn check_ident(&mut self) -> bool {
834 if self.token.is_ident() {
837 self.expected_tokens.push(TokenType::Ident);
842 fn check_path(&mut self) -> bool {
843 if self.token.is_path_start() {
846 self.expected_tokens.push(TokenType::Path);
851 fn check_type(&mut self) -> bool {
852 if self.token.can_begin_type() {
855 self.expected_tokens.push(TokenType::Type);
860 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
861 /// `&` and continue. If an `&` is not seen, signal an error.
862 fn expect_and(&mut self) -> PResult<'a, ()> {
863 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
865 token::BinOp(token::And) => {
870 let span = self.span.with_lo(self.span.lo() + BytePos(1));
871 Ok(self.bump_with(token::BinOp(token::And), span))
873 _ => self.unexpected()
877 /// Expect and consume an `|`. If `||` is seen, replace it with a single
878 /// `|` and continue. If an `|` is not seen, signal an error.
879 fn expect_or(&mut self) -> PResult<'a, ()> {
880 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
882 token::BinOp(token::Or) => {
887 let span = self.span.with_lo(self.span.lo() + BytePos(1));
888 Ok(self.bump_with(token::BinOp(token::Or), span))
890 _ => self.unexpected()
894 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
896 None => {/* everything ok */}
898 let text = suf.as_str();
900 self.span_bug(sp, "found empty literal suffix in Some")
902 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
907 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
908 /// `<` and continue. If a `<` is not seen, return false.
910 /// This is meant to be used when parsing generics on a path to get the
912 fn eat_lt(&mut self) -> bool {
913 self.expected_tokens.push(TokenType::Token(token::Lt));
919 token::BinOp(token::Shl) => {
920 let span = self.span.with_lo(self.span.lo() + BytePos(1));
921 self.bump_with(token::Lt, span);
928 fn expect_lt(&mut self) -> PResult<'a, ()> {
936 /// Expect and consume a GT. if a >> is seen, replace it
937 /// with a single > and continue. If a GT is not seen,
939 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
940 self.expected_tokens.push(TokenType::Token(token::Gt));
946 token::BinOp(token::Shr) => {
947 let span = self.span.with_lo(self.span.lo() + BytePos(1));
948 Ok(self.bump_with(token::Gt, span))
950 token::BinOpEq(token::Shr) => {
951 let span = self.span.with_lo(self.span.lo() + BytePos(1));
952 Ok(self.bump_with(token::Ge, span))
955 let span = self.span.with_lo(self.span.lo() + BytePos(1));
956 Ok(self.bump_with(token::Eq, span))
958 _ => self.unexpected()
962 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
963 sep: Option<token::Token>,
965 -> PResult<'a, (Vec<T>, bool)>
966 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
968 let mut v = Vec::new();
969 // This loop works by alternating back and forth between parsing types
970 // and commas. For example, given a string `A, B,>`, the parser would
971 // first parse `A`, then a comma, then `B`, then a comma. After that it
972 // would encounter a `>` and stop. This lets the parser handle trailing
973 // commas in generic parameters, because it can stop either after
974 // parsing a type or after parsing a comma.
976 if self.check(&token::Gt)
977 || self.token == token::BinOp(token::Shr)
978 || self.token == token::Ge
979 || self.token == token::BinOpEq(token::Shr) {
985 Some(result) => v.push(result),
986 None => return Ok((v, true))
989 if let Some(t) = sep.as_ref() {
995 return Ok((v, false));
998 /// Parse a sequence bracketed by '<' and '>', stopping
1000 pub fn parse_seq_to_before_gt<T, F>(&mut self,
1001 sep: Option<token::Token>,
1003 -> PResult<'a, Vec<T>> where
1004 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1006 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
1007 |p| Ok(Some(f(p)?)))?;
1012 pub fn parse_seq_to_gt<T, F>(&mut self,
1013 sep: Option<token::Token>,
1015 -> PResult<'a, Vec<T>> where
1016 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1018 let v = self.parse_seq_to_before_gt(sep, f)?;
1023 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
1024 sep: Option<token::Token>,
1026 -> PResult<'a, (Vec<T>, bool)> where
1027 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
1029 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
1033 return Ok((v, returned));
1036 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1037 /// passes through any errors encountered. Used for error recovery.
1038 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1039 let handler = self.diagnostic();
1041 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1043 TokenExpectType::Expect,
1044 |p| Ok(p.parse_token_tree())) {
1045 handler.cancel(err);
1049 /// Parse a sequence, including the closing delimiter. The function
1050 /// f must consume tokens until reaching the next separator or
1051 /// closing bracket.
1052 pub fn parse_seq_to_end<T, F>(&mut self,
1056 -> PResult<'a, Vec<T>> where
1057 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1059 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1064 /// Parse a sequence, not including the closing delimiter. The function
1065 /// f must consume tokens until reaching the next separator or
1066 /// closing bracket.
1067 pub fn parse_seq_to_before_end<T, F>(&mut self,
1071 -> PResult<'a, Vec<T>>
1072 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1074 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1077 fn parse_seq_to_before_tokens<T, F>(&mut self,
1078 kets: &[&token::Token],
1080 expect: TokenExpectType,
1082 -> PResult<'a, Vec<T>>
1083 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1085 let mut first: bool = true;
1087 while !kets.contains(&&self.token) {
1089 token::CloseDelim(..) | token::Eof => break,
1092 if let Some(ref t) = sep.sep {
1096 if let Err(mut e) = self.expect(t) {
1097 // Attempt to keep parsing if it was a similar separator
1098 if let Some(ref tokens) = t.similar_tokens() {
1099 if tokens.contains(&self.token) {
1104 // Attempt to keep parsing if it was an omitted separator
1118 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1120 TokenExpectType::Expect => self.check(k),
1121 TokenExpectType::NoExpect => self.token == **k,
1134 /// Parse a sequence, including the closing delimiter. The function
1135 /// f must consume tokens until reaching the next separator or
1136 /// closing bracket.
1137 pub fn parse_unspanned_seq<T, F>(&mut self,
1142 -> PResult<'a, Vec<T>> where
1143 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1146 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1147 if self.token == *ket {
1153 // NB: Do not use this function unless you actually plan to place the
1154 // spanned list in the AST.
1155 pub fn parse_seq<T, F>(&mut self,
1160 -> PResult<'a, Spanned<Vec<T>>> where
1161 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1165 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1168 Ok(respan(lo.to(hi), result))
1171 /// Advance the parser by one token
1172 pub fn bump(&mut self) {
1173 if self.prev_token_kind == PrevTokenKind::Eof {
1174 // Bumping after EOF is a bad sign, usually an infinite loop.
1175 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1178 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1180 // Record last token kind for possible error recovery.
1181 self.prev_token_kind = match self.token {
1182 token::DocComment(..) => PrevTokenKind::DocComment,
1183 token::Comma => PrevTokenKind::Comma,
1184 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1185 token::Interpolated(..) => PrevTokenKind::Interpolated,
1186 token::Eof => PrevTokenKind::Eof,
1187 token::Ident(..) => PrevTokenKind::Ident,
1188 _ => PrevTokenKind::Other,
1191 let next = self.next_tok();
1192 self.span = next.sp;
1193 self.token = next.tok;
1194 self.expected_tokens.clear();
1195 // check after each token
1196 self.process_potential_macro_variable();
1199 /// Advance the parser using provided token as a next one. Use this when
1200 /// consuming a part of a token. For example a single `<` from `<<`.
1201 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1202 self.prev_span = self.span.with_hi(span.lo());
1203 // It would be incorrect to record the kind of the current token, but
1204 // fortunately for tokens currently using `bump_with`, the
1205 // prev_token_kind will be of no use anyway.
1206 self.prev_token_kind = PrevTokenKind::Other;
1209 self.expected_tokens.clear();
1212 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1213 F: FnOnce(&token::Token) -> R,
1216 return f(&self.token)
1219 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1220 Some(tree) => match tree {
1221 TokenTree::Token(_, tok) => tok,
1222 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1224 None => token::CloseDelim(self.token_cursor.frame.delim),
1228 fn look_ahead_span(&self, dist: usize) -> Span {
1233 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1234 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1235 None => self.look_ahead_span(dist - 1),
1238 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1239 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1241 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1242 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1244 pub fn span_fatal_err(&self, sp: Span, err: Error) -> DiagnosticBuilder<'a> {
1245 err.span_err(sp, self.diagnostic())
1247 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1248 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1252 pub fn bug(&self, m: &str) -> ! {
1253 self.sess.span_diagnostic.span_bug(self.span, m)
1255 pub fn warn(&self, m: &str) {
1256 self.sess.span_diagnostic.span_warn(self.span, m)
1258 pub fn span_warn(&self, sp: Span, m: &str) {
1259 self.sess.span_diagnostic.span_warn(sp, m)
1261 pub fn span_err(&self, sp: Span, m: &str) {
1262 self.sess.span_diagnostic.span_err(sp, m)
1264 pub fn struct_span_err(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1265 self.sess.span_diagnostic.struct_span_err(sp, m)
1267 pub fn span_err_help(&self, sp: Span, m: &str, h: &str) {
1268 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1272 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1273 self.sess.span_diagnostic.span_bug(sp, m)
1275 pub fn abort_if_errors(&self) {
1276 self.sess.span_diagnostic.abort_if_errors();
1279 fn cancel(&self, err: &mut DiagnosticBuilder) {
1280 self.sess.span_diagnostic.cancel(err)
1283 pub fn diagnostic(&self) -> &'a errors::Handler {
1284 &self.sess.span_diagnostic
1287 /// Is the current token one of the keywords that signals a bare function
1289 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1290 self.check_keyword(keywords::Fn) ||
1291 self.check_keyword(keywords::Unsafe) ||
1292 self.check_keyword(keywords::Extern)
1295 fn get_label(&mut self) -> ast::Ident {
1297 token::Lifetime(ref ident) => *ident,
1298 _ => self.bug("not a lifetime"),
1302 /// parse a TyKind::BareFn type:
1303 pub fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>)
1304 -> PResult<'a, TyKind> {
1307 [unsafe] [extern "ABI"] fn (S) -> T
1317 let unsafety = self.parse_unsafety()?;
1318 let abi = if self.eat_keyword(keywords::Extern) {
1319 self.parse_opt_abi()?.unwrap_or(Abi::C)
1324 self.expect_keyword(keywords::Fn)?;
1325 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1326 let ret_ty = self.parse_ret_ty()?;
1327 let decl = P(FnDecl {
1332 Ok(TyKind::BareFn(P(BareFnTy {
1340 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1341 if self.eat_keyword(keywords::Unsafe) {
1342 return Ok(Unsafety::Unsafe);
1344 return Ok(Unsafety::Normal);
1348 /// Parse the items in a trait declaration
1349 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1350 maybe_whole!(self, NtTraitItem, |x| x);
1351 let attrs = self.parse_outer_attributes()?;
1352 let (mut item, tokens) = self.collect_tokens(|this| {
1353 this.parse_trait_item_(at_end, attrs)
1355 // See `parse_item` for why this clause is here.
1356 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1357 item.tokens = Some(tokens);
1362 fn parse_trait_item_(&mut self,
1364 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1367 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1368 let (generics, TyParam {ident, bounds, default, ..}) =
1369 self.parse_trait_item_assoc_ty(vec![])?;
1370 (ident, TraitItemKind::Type(bounds, default), generics)
1371 } else if self.is_const_item() {
1372 self.expect_keyword(keywords::Const)?;
1373 let ident = self.parse_ident()?;
1374 self.expect(&token::Colon)?;
1375 let ty = self.parse_ty()?;
1376 let default = if self.check(&token::Eq) {
1378 let expr = self.parse_expr()?;
1379 self.expect(&token::Semi)?;
1382 self.expect(&token::Semi)?;
1385 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1386 } else if self.token.is_path_start() {
1387 // trait item macro.
1388 // code copied from parse_macro_use_or_failure... abstraction!
1389 let prev_span = self.prev_span;
1391 let pth = self.parse_path(PathStyle::Mod)?;
1393 if pth.segments.len() == 1 {
1394 if !self.eat(&token::Not) {
1395 return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1398 self.expect(&token::Not)?;
1401 // eat a matched-delimiter token tree:
1402 let (delim, tts) = self.expect_delimited_token_tree()?;
1403 if delim != token::Brace {
1404 self.expect(&token::Semi)?
1407 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1408 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1410 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
1412 let ident = self.parse_ident()?;
1413 let mut generics = self.parse_generics()?;
1415 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1416 // This is somewhat dubious; We don't want to allow
1417 // argument names to be left off if there is a
1419 p.parse_arg_general(false)
1421 generics.where_clause = self.parse_where_clause()?;
1423 let sig = ast::MethodSig {
1430 let body = match self.token {
1434 debug!("parse_trait_methods(): parsing required method");
1437 token::OpenDelim(token::Brace) => {
1438 debug!("parse_trait_methods(): parsing provided method");
1440 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1441 attrs.extend(inner_attrs.iter().cloned());
1445 let token_str = self.this_token_to_string();
1446 return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1449 (ident, ast::TraitItemKind::Method(sig, body), generics)
1453 id: ast::DUMMY_NODE_ID,
1458 span: lo.to(self.prev_span),
1463 /// Parse optional return type [ -> TY ] in function decl
1464 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1465 if self.eat(&token::RArrow) {
1466 Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
1468 Ok(FunctionRetTy::Default(self.span.with_hi(self.span.lo())))
1473 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1474 self.parse_ty_common(true, true)
1477 /// Parse a type in restricted contexts where `+` is not permitted.
1478 /// Example 1: `&'a TYPE`
1479 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1480 /// Example 2: `value1 as TYPE + value2`
1481 /// `+` is prohibited to avoid interactions with expression grammar.
1482 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1483 self.parse_ty_common(false, true)
1486 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1487 -> PResult<'a, P<Ty>> {
1488 maybe_whole!(self, NtTy, |x| x);
1491 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1492 // `(TYPE)` is a parenthesized type.
1493 // `(TYPE,)` is a tuple with a single field of type TYPE.
1494 let mut ts = vec![];
1495 let mut last_comma = false;
1496 while self.token != token::CloseDelim(token::Paren) {
1497 ts.push(self.parse_ty()?);
1498 if self.eat(&token::Comma) {
1505 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1506 self.expect(&token::CloseDelim(token::Paren))?;
1508 if ts.len() == 1 && !last_comma {
1509 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1510 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1512 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1513 TyKind::Path(None, ref path) if maybe_bounds => {
1514 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1516 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1517 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1518 let path = match bounds[0] {
1519 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1520 _ => self.bug("unexpected lifetime bound"),
1522 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1525 _ => TyKind::Paren(P(ty))
1530 } else if self.eat(&token::Not) {
1533 } else if self.eat(&token::BinOp(token::Star)) {
1535 TyKind::Ptr(self.parse_ptr()?)
1536 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1538 let t = self.parse_ty()?;
1539 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1540 let t = match self.maybe_parse_fixed_length_of_vec()? {
1541 None => TyKind::Slice(t),
1542 Some(suffix) => TyKind::Array(t, suffix),
1544 self.expect(&token::CloseDelim(token::Bracket))?;
1546 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1549 self.parse_borrowed_pointee()?
1550 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1552 // In order to not be ambiguous, the type must be surrounded by parens.
1553 self.expect(&token::OpenDelim(token::Paren))?;
1554 let e = self.parse_expr()?;
1555 self.expect(&token::CloseDelim(token::Paren))?;
1557 } else if self.eat(&token::Underscore) {
1558 // A type to be inferred `_`
1560 } else if self.token_is_bare_fn_keyword() {
1561 // Function pointer type
1562 self.parse_ty_bare_fn(Vec::new())?
1563 } else if self.check_keyword(keywords::For) {
1564 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1565 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1566 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1568 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1569 if self.token_is_bare_fn_keyword() {
1570 self.parse_ty_bare_fn(lifetime_defs)?
1572 let path = self.parse_path(PathStyle::Type)?;
1573 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1574 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1576 } else if self.eat_keyword(keywords::Impl) {
1577 // FIXME: figure out priority of `+` in `impl Trait1 + Trait2` (#34511).
1578 TyKind::ImplTrait(self.parse_ty_param_bounds()?)
1579 } else if self.check_keyword(keywords::Dyn) &&
1580 self.look_ahead(1, |t| t.can_begin_bound() && !can_continue_type_after_ident(t)) {
1581 // FIXME: figure out priority of `+` in `dyn Trait1 + Trait2` (#34511).
1582 self.bump(); // `dyn`
1583 TyKind::TraitObject(self.parse_ty_param_bounds()?, TraitObjectSyntax::Dyn)
1584 } else if self.check(&token::Question) ||
1585 self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)) {
1586 // Bound list (trait object type)
1587 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?,
1588 TraitObjectSyntax::None)
1589 } else if self.eat_lt() {
1591 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1592 TyKind::Path(Some(qself), path)
1593 } else if self.token.is_path_start() {
1595 let path = self.parse_path(PathStyle::Type)?;
1596 if self.eat(&token::Not) {
1597 // Macro invocation in type position
1598 let (_, tts) = self.expect_delimited_token_tree()?;
1599 TyKind::Mac(respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts }))
1601 // Just a type path or bound list (trait object type) starting with a trait.
1603 // `Trait1 + Trait2 + 'a`
1604 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1605 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1607 TyKind::Path(None, path)
1611 let msg = format!("expected type, found {}", self.this_token_descr());
1612 return Err(self.fatal(&msg));
1615 let span = lo.to(self.prev_span);
1616 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1618 // Try to recover from use of `+` with incorrect priority.
1619 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1620 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1625 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1626 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1627 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1628 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1631 bounds.append(&mut self.parse_ty_param_bounds()?);
1633 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1636 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1637 // Do not add `+` to expected tokens.
1638 if !allow_plus || self.token != token::BinOp(token::Plus) {
1643 let bounds = self.parse_ty_param_bounds()?;
1644 let sum_span = ty.span.to(self.prev_span);
1646 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1647 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1650 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1651 let sum_with_parens = pprust::to_string(|s| {
1652 use print::pprust::PrintState;
1655 s.print_opt_lifetime(lifetime)?;
1656 s.print_mutability(mut_ty.mutbl)?;
1658 s.print_type(&mut_ty.ty)?;
1659 s.print_bounds(" +", &bounds)?;
1662 err.span_suggestion(sum_span, "try adding parentheses", sum_with_parens);
1664 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1665 err.span_label(sum_span, "perhaps you forgot parentheses?");
1668 err.span_label(sum_span, "expected a path");
1675 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1676 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1678 // Do not add `::` to expected tokens.
1679 if !allow_recovery || self.token != token::ModSep {
1682 let ty = match base.to_ty() {
1684 None => return Ok(base),
1687 self.bump(); // `::`
1688 let mut segments = Vec::new();
1689 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1691 let span = ty.span.to(self.prev_span);
1693 base.to_recovered(Some(QSelf { ty, position: 0 }), ast::Path { segments, span });
1696 .struct_span_err(span, "missing angle brackets in associated item path")
1697 .span_suggestion(span, "try", recovered.to_string()).emit();
1702 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1703 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1704 let mutbl = self.parse_mutability();
1705 let ty = self.parse_ty_no_plus()?;
1706 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1709 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1710 let mutbl = if self.eat_keyword(keywords::Mut) {
1712 } else if self.eat_keyword(keywords::Const) {
1713 Mutability::Immutable
1715 let span = self.prev_span;
1717 "expected mut or const in raw pointer type (use \
1718 `*mut T` or `*const T` as appropriate)");
1719 Mutability::Immutable
1721 let t = self.parse_ty_no_plus()?;
1722 Ok(MutTy { ty: t, mutbl: mutbl })
1725 fn is_named_argument(&mut self) -> bool {
1726 let offset = match self.token {
1727 token::Interpolated(ref nt) => match nt.0 {
1728 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1731 token::BinOp(token::And) | token::AndAnd => 1,
1732 _ if self.token.is_keyword(keywords::Mut) => 1,
1736 self.look_ahead(offset, |t| t.is_ident() || t == &token::Underscore) &&
1737 self.look_ahead(offset + 1, |t| t == &token::Colon)
1740 /// This version of parse arg doesn't necessarily require
1741 /// identifier names.
1742 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1743 maybe_whole!(self, NtArg, |x| x);
1745 let pat = if require_name || self.is_named_argument() {
1746 debug!("parse_arg_general parse_pat (require_name:{})",
1748 let pat = self.parse_pat()?;
1750 self.expect(&token::Colon)?;
1753 debug!("parse_arg_general ident_to_pat");
1754 let sp = self.prev_span;
1755 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1757 id: ast::DUMMY_NODE_ID,
1758 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1764 let t = self.parse_ty()?;
1769 id: ast::DUMMY_NODE_ID,
1773 /// Parse a single function argument
1774 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1775 self.parse_arg_general(true)
1778 /// Parse an argument in a lambda header e.g. |arg, arg|
1779 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1780 let pat = self.parse_pat()?;
1781 let t = if self.eat(&token::Colon) {
1785 id: ast::DUMMY_NODE_ID,
1786 node: TyKind::Infer,
1793 id: ast::DUMMY_NODE_ID
1797 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1798 if self.eat(&token::Semi) {
1799 Ok(Some(self.parse_expr()?))
1805 /// Matches token_lit = LIT_INTEGER | ...
1806 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1807 let out = match self.token {
1808 token::Interpolated(ref nt) => match nt.0 {
1809 token::NtExpr(ref v) => match v.node {
1810 ExprKind::Lit(ref lit) => { lit.node.clone() }
1811 _ => { return self.unexpected_last(&self.token); }
1813 _ => { return self.unexpected_last(&self.token); }
1815 token::Literal(lit, suf) => {
1816 let diag = Some((self.span, &self.sess.span_diagnostic));
1817 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1821 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1826 _ => { return self.unexpected_last(&self.token); }
1833 /// Matches lit = true | false | token_lit
1834 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1836 let lit = if self.eat_keyword(keywords::True) {
1838 } else if self.eat_keyword(keywords::False) {
1839 LitKind::Bool(false)
1841 let lit = self.parse_lit_token()?;
1844 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1847 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1848 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1849 maybe_whole_expr!(self);
1851 let minus_lo = self.span;
1852 let minus_present = self.eat(&token::BinOp(token::Minus));
1854 let literal = P(self.parse_lit()?);
1855 let hi = self.prev_span;
1856 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1859 let minus_hi = self.prev_span;
1860 let unary = self.mk_unary(UnOp::Neg, expr);
1861 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1867 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1869 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1873 _ => self.parse_ident(),
1877 /// Parses qualified path.
1878 /// Assumes that the leading `<` has been parsed already.
1880 /// `qualified_path = <type [as trait_ref]>::path`
1884 /// `<T as U>::F::a<S>` (without disambiguator)
1885 /// `<T as U>::F::a::<S>` (with disambiguator)
1886 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1887 let lo = self.prev_span;
1888 let ty = self.parse_ty()?;
1889 let mut path = if self.eat_keyword(keywords::As) {
1890 self.parse_path(PathStyle::Type)?
1892 ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP }
1894 self.expect(&token::Gt)?;
1895 self.expect(&token::ModSep)?;
1897 let qself = QSelf { ty, position: path.segments.len() };
1898 self.parse_path_segments(&mut path.segments, style, true)?;
1900 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1903 /// Parses simple paths.
1905 /// `path = [::] segment+`
1906 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1909 /// `a::b::C<D>` (without disambiguator)
1910 /// `a::b::C::<D>` (with disambiguator)
1911 /// `Fn(Args)` (without disambiguator)
1912 /// `Fn::(Args)` (with disambiguator)
1913 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1914 self.parse_path_common(style, true)
1917 pub fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1918 -> PResult<'a, ast::Path> {
1919 maybe_whole!(self, NtPath, |path| {
1920 if style == PathStyle::Mod &&
1921 path.segments.iter().any(|segment| segment.parameters.is_some()) {
1922 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1927 let lo = self.meta_var_span.unwrap_or(self.span);
1928 let mut segments = Vec::new();
1929 if self.eat(&token::ModSep) {
1930 segments.push(PathSegment::crate_root(lo));
1932 self.parse_path_segments(&mut segments, style, enable_warning)?;
1934 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1937 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1938 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1939 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1940 let meta_ident = match self.token {
1941 token::Interpolated(ref nt) => match nt.0 {
1942 token::NtMeta(ref meta) => match meta.node {
1943 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
1950 if let Some(ident) = meta_ident {
1952 return Ok(ast::Path::from_ident(self.prev_span, ident));
1954 self.parse_path(style)
1957 fn parse_path_segments(&mut self,
1958 segments: &mut Vec<PathSegment>,
1960 enable_warning: bool)
1961 -> PResult<'a, ()> {
1963 segments.push(self.parse_path_segment(style, enable_warning)?);
1965 if self.is_import_coupler(false) || !self.eat(&token::ModSep) {
1971 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
1972 -> PResult<'a, PathSegment> {
1973 let ident_span = self.span;
1974 let ident = self.parse_path_segment_ident()?;
1976 let is_args_start = |token: &token::Token| match *token {
1977 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
1980 let check_args_start = |this: &mut Self| {
1981 this.expected_tokens.extend_from_slice(
1982 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1984 is_args_start(&this.token)
1987 Ok(if style == PathStyle::Type && check_args_start(self) ||
1988 style != PathStyle::Mod && self.check(&token::ModSep)
1989 && self.look_ahead(1, |t| is_args_start(t)) {
1990 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1992 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
1993 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
1994 .span_label(self.prev_span, "try removing `::`").emit();
1997 let parameters = if self.eat_lt() {
1999 let (lifetimes, types, bindings) = self.parse_generic_args()?;
2001 let span = lo.to(self.prev_span);
2002 AngleBracketedParameterData { lifetimes, types, bindings, span }.into()
2006 let inputs = self.parse_seq_to_before_tokens(
2007 &[&token::CloseDelim(token::Paren)],
2008 SeqSep::trailing_allowed(token::Comma),
2009 TokenExpectType::Expect,
2012 let output = if self.eat(&token::RArrow) {
2013 Some(self.parse_ty_common(false, false)?)
2017 let span = lo.to(self.prev_span);
2018 ParenthesizedParameterData { inputs, output, span }.into()
2021 PathSegment { identifier: ident, span: ident_span, parameters }
2023 // Generic arguments are not found.
2024 PathSegment::from_ident(ident, ident_span)
2028 fn check_lifetime(&mut self) -> bool {
2029 self.expected_tokens.push(TokenType::Lifetime);
2030 self.token.is_lifetime()
2033 /// Parse single lifetime 'a or panic.
2034 fn expect_lifetime(&mut self) -> Lifetime {
2036 token::Lifetime(ident) => {
2037 let ident_span = self.span;
2039 Lifetime { ident: ident, span: ident_span, id: ast::DUMMY_NODE_ID }
2041 _ => self.span_bug(self.span, "not a lifetime")
2045 /// Parse mutability (`mut` or nothing).
2046 fn parse_mutability(&mut self) -> Mutability {
2047 if self.eat_keyword(keywords::Mut) {
2050 Mutability::Immutable
2054 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2055 if let token::Literal(token::Integer(name), None) = self.token {
2057 Ok(Ident::with_empty_ctxt(name))
2063 /// Parse ident (COLON expr)?
2064 pub fn parse_field(&mut self) -> PResult<'a, Field> {
2065 let attrs = self.parse_outer_attributes()?;
2069 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2070 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2071 let fieldname = self.parse_field_name()?;
2073 hi = self.prev_span;
2074 (fieldname, self.parse_expr()?, false)
2076 let fieldname = self.parse_ident()?;
2077 hi = self.prev_span;
2079 // Mimic `x: x` for the `x` field shorthand.
2080 let path = ast::Path::from_ident(lo.to(hi), fieldname);
2081 (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
2084 ident: respan(lo.to(hi), fieldname),
2085 span: lo.to(expr.span),
2088 attrs: attrs.into(),
2092 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2093 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2096 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2097 ExprKind::Unary(unop, expr)
2100 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2101 ExprKind::Binary(binop, lhs, rhs)
2104 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2105 ExprKind::Call(f, args)
2108 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2109 ExprKind::Index(expr, idx)
2112 pub fn mk_range(&mut self,
2113 start: Option<P<Expr>>,
2114 end: Option<P<Expr>>,
2115 limits: RangeLimits)
2116 -> PResult<'a, ast::ExprKind> {
2117 if end.is_none() && limits == RangeLimits::Closed {
2118 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2120 Ok(ExprKind::Range(start, end, limits))
2124 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2125 ExprKind::TupField(expr, idx)
2128 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2129 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2130 ExprKind::AssignOp(binop, lhs, rhs)
2133 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2135 id: ast::DUMMY_NODE_ID,
2136 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2142 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2143 let span = &self.span;
2144 let lv_lit = P(codemap::Spanned {
2145 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2150 id: ast::DUMMY_NODE_ID,
2151 node: ExprKind::Lit(lv_lit),
2157 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2159 token::OpenDelim(delim) => match self.parse_token_tree() {
2160 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2161 _ => unreachable!(),
2163 _ => Err(self.fatal("expected open delimiter")),
2167 /// At the bottom (top?) of the precedence hierarchy,
2168 /// parse things like parenthesized exprs,
2169 /// macros, return, etc.
2171 /// NB: This does not parse outer attributes,
2172 /// and is private because it only works
2173 /// correctly if called from parse_dot_or_call_expr().
2174 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2175 maybe_whole_expr!(self);
2177 // Outer attributes are already parsed and will be
2178 // added to the return value after the fact.
2180 // Therefore, prevent sub-parser from parsing
2181 // attributes by giving them a empty "already parsed" list.
2182 let mut attrs = ThinVec::new();
2185 let mut hi = self.span;
2189 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2191 token::OpenDelim(token::Paren) => {
2194 attrs.extend(self.parse_inner_attributes()?);
2196 // (e) is parenthesized e
2197 // (e,) is a tuple with only one field, e
2198 let mut es = vec![];
2199 let mut trailing_comma = false;
2200 while self.token != token::CloseDelim(token::Paren) {
2201 es.push(self.parse_expr()?);
2202 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2203 if self.check(&token::Comma) {
2204 trailing_comma = true;
2208 trailing_comma = false;
2214 hi = self.prev_span;
2215 ex = if es.len() == 1 && !trailing_comma {
2216 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2221 token::OpenDelim(token::Brace) => {
2222 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2224 token::BinOp(token::Or) | token::OrOr => {
2226 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2228 token::OpenDelim(token::Bracket) => {
2231 attrs.extend(self.parse_inner_attributes()?);
2233 if self.check(&token::CloseDelim(token::Bracket)) {
2236 ex = ExprKind::Array(Vec::new());
2239 let first_expr = self.parse_expr()?;
2240 if self.check(&token::Semi) {
2241 // Repeating array syntax: [ 0; 512 ]
2243 let count = self.parse_expr()?;
2244 self.expect(&token::CloseDelim(token::Bracket))?;
2245 ex = ExprKind::Repeat(first_expr, count);
2246 } else if self.check(&token::Comma) {
2247 // Vector with two or more elements.
2249 let remaining_exprs = self.parse_seq_to_end(
2250 &token::CloseDelim(token::Bracket),
2251 SeqSep::trailing_allowed(token::Comma),
2252 |p| Ok(p.parse_expr()?)
2254 let mut exprs = vec![first_expr];
2255 exprs.extend(remaining_exprs);
2256 ex = ExprKind::Array(exprs);
2258 // Vector with one element.
2259 self.expect(&token::CloseDelim(token::Bracket))?;
2260 ex = ExprKind::Array(vec![first_expr]);
2263 hi = self.prev_span;
2267 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2269 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2271 if self.eat_keyword(keywords::Move) {
2272 let lo = self.prev_span;
2273 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2275 if self.eat_keyword(keywords::If) {
2276 return self.parse_if_expr(attrs);
2278 if self.eat_keyword(keywords::For) {
2279 let lo = self.prev_span;
2280 return self.parse_for_expr(None, lo, attrs);
2282 if self.eat_keyword(keywords::While) {
2283 let lo = self.prev_span;
2284 return self.parse_while_expr(None, lo, attrs);
2286 if self.token.is_lifetime() {
2287 let label = Spanned { node: self.get_label(),
2291 self.expect(&token::Colon)?;
2292 if self.eat_keyword(keywords::While) {
2293 return self.parse_while_expr(Some(label), lo, attrs)
2295 if self.eat_keyword(keywords::For) {
2296 return self.parse_for_expr(Some(label), lo, attrs)
2298 if self.eat_keyword(keywords::Loop) {
2299 return self.parse_loop_expr(Some(label), lo, attrs)
2301 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2303 if self.eat_keyword(keywords::Loop) {
2304 let lo = self.prev_span;
2305 return self.parse_loop_expr(None, lo, attrs);
2307 if self.eat_keyword(keywords::Continue) {
2308 let ex = if self.token.is_lifetime() {
2309 let ex = ExprKind::Continue(Some(Spanned{
2310 node: self.get_label(),
2316 ExprKind::Continue(None)
2318 let hi = self.prev_span;
2319 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2321 if self.eat_keyword(keywords::Match) {
2322 return self.parse_match_expr(attrs);
2324 if self.eat_keyword(keywords::Unsafe) {
2325 return self.parse_block_expr(
2327 BlockCheckMode::Unsafe(ast::UserProvided),
2330 if self.is_catch_expr() {
2332 assert!(self.eat_keyword(keywords::Do));
2333 assert!(self.eat_keyword(keywords::Catch));
2334 return self.parse_catch_expr(lo, attrs);
2336 if self.eat_keyword(keywords::Return) {
2337 if self.token.can_begin_expr() {
2338 let e = self.parse_expr()?;
2340 ex = ExprKind::Ret(Some(e));
2342 ex = ExprKind::Ret(None);
2344 } else if self.eat_keyword(keywords::Break) {
2345 let lt = if self.token.is_lifetime() {
2346 let spanned_lt = Spanned {
2347 node: self.get_label(),
2355 let e = if self.token.can_begin_expr()
2356 && !(self.token == token::OpenDelim(token::Brace)
2357 && self.restrictions.contains(
2358 Restrictions::NO_STRUCT_LITERAL)) {
2359 Some(self.parse_expr()?)
2363 ex = ExprKind::Break(lt, e);
2364 hi = self.prev_span;
2365 } else if self.eat_keyword(keywords::Yield) {
2366 if self.token.can_begin_expr() {
2367 let e = self.parse_expr()?;
2369 ex = ExprKind::Yield(Some(e));
2371 ex = ExprKind::Yield(None);
2373 } else if self.token.is_keyword(keywords::Let) {
2374 // Catch this syntax error here, instead of in `parse_ident`, so
2375 // that we can explicitly mention that let is not to be used as an expression
2376 let mut db = self.fatal("expected expression, found statement (`let`)");
2377 db.note("variable declaration using `let` is a statement");
2379 } else if self.token.is_path_start() {
2380 let pth = self.parse_path(PathStyle::Expr)?;
2382 // `!`, as an operator, is prefix, so we know this isn't that
2383 if self.eat(&token::Not) {
2384 // MACRO INVOCATION expression
2385 let (_, tts) = self.expect_delimited_token_tree()?;
2386 let hi = self.prev_span;
2387 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2389 if self.check(&token::OpenDelim(token::Brace)) {
2390 // This is a struct literal, unless we're prohibited
2391 // from parsing struct literals here.
2392 let prohibited = self.restrictions.contains(
2393 Restrictions::NO_STRUCT_LITERAL
2396 return self.parse_struct_expr(lo, pth, attrs);
2401 ex = ExprKind::Path(None, pth);
2403 match self.parse_lit() {
2406 ex = ExprKind::Lit(P(lit));
2409 self.cancel(&mut err);
2410 let msg = format!("expected expression, found {}",
2411 self.this_token_descr());
2412 return Err(self.fatal(&msg));
2419 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2420 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2425 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2426 -> PResult<'a, P<Expr>> {
2428 let mut fields = Vec::new();
2429 let mut base = None;
2431 attrs.extend(self.parse_inner_attributes()?);
2433 while self.token != token::CloseDelim(token::Brace) {
2434 if self.eat(&token::DotDot) {
2435 let exp_span = self.prev_span;
2436 match self.parse_expr() {
2442 self.recover_stmt();
2445 if self.token == token::Comma {
2446 let mut err = self.sess.span_diagnostic.mut_span_err(
2447 exp_span.to(self.prev_span),
2448 "cannot use a comma after the base struct",
2450 err.span_suggestion_short(self.span, "remove this comma", "".to_owned());
2451 err.note("the base struct must always be the last field");
2453 self.recover_stmt();
2458 match self.parse_field() {
2459 Ok(f) => fields.push(f),
2462 self.recover_stmt();
2467 match self.expect_one_of(&[token::Comma],
2468 &[token::CloseDelim(token::Brace)]) {
2472 self.recover_stmt();
2478 let span = lo.to(self.span);
2479 self.expect(&token::CloseDelim(token::Brace))?;
2480 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2483 fn parse_or_use_outer_attributes(&mut self,
2484 already_parsed_attrs: Option<ThinVec<Attribute>>)
2485 -> PResult<'a, ThinVec<Attribute>> {
2486 if let Some(attrs) = already_parsed_attrs {
2489 self.parse_outer_attributes().map(|a| a.into())
2493 /// Parse a block or unsafe block
2494 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2495 outer_attrs: ThinVec<Attribute>)
2496 -> PResult<'a, P<Expr>> {
2497 self.expect(&token::OpenDelim(token::Brace))?;
2499 let mut attrs = outer_attrs;
2500 attrs.extend(self.parse_inner_attributes()?);
2502 let blk = self.parse_block_tail(lo, blk_mode)?;
2503 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2506 /// parse a.b or a(13) or a[4] or just a
2507 pub fn parse_dot_or_call_expr(&mut self,
2508 already_parsed_attrs: Option<ThinVec<Attribute>>)
2509 -> PResult<'a, P<Expr>> {
2510 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2512 let b = self.parse_bottom_expr();
2513 let (span, b) = self.interpolated_or_expr_span(b)?;
2514 self.parse_dot_or_call_expr_with(b, span, attrs)
2517 pub fn parse_dot_or_call_expr_with(&mut self,
2520 mut attrs: ThinVec<Attribute>)
2521 -> PResult<'a, P<Expr>> {
2522 // Stitch the list of outer attributes onto the return value.
2523 // A little bit ugly, but the best way given the current code
2525 self.parse_dot_or_call_expr_with_(e0, lo)
2527 expr.map(|mut expr| {
2528 attrs.extend::<Vec<_>>(expr.attrs.into());
2531 ExprKind::If(..) | ExprKind::IfLet(..) => {
2532 if !expr.attrs.is_empty() {
2533 // Just point to the first attribute in there...
2534 let span = expr.attrs[0].span;
2537 "attributes are not yet allowed on `if` \
2548 // Assuming we have just parsed `.`, continue parsing into an expression.
2549 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2550 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2551 Ok(match self.token {
2552 token::OpenDelim(token::Paren) => {
2553 // Method call `expr.f()`
2554 let mut args = self.parse_unspanned_seq(
2555 &token::OpenDelim(token::Paren),
2556 &token::CloseDelim(token::Paren),
2557 SeqSep::trailing_allowed(token::Comma),
2558 |p| Ok(p.parse_expr()?)
2560 args.insert(0, self_arg);
2562 let span = lo.to(self.prev_span);
2563 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2566 // Field access `expr.f`
2567 if let Some(parameters) = segment.parameters {
2568 self.span_err(parameters.span(),
2569 "field expressions may not have generic arguments");
2572 let span = lo.to(self.prev_span);
2573 let ident = respan(segment.span, segment.identifier);
2574 self.mk_expr(span, ExprKind::Field(self_arg, ident), ThinVec::new())
2579 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2584 while self.eat(&token::Question) {
2585 let hi = self.prev_span;
2586 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2590 if self.eat(&token::Dot) {
2592 token::Ident(..) => {
2593 e = self.parse_dot_suffix(e, lo)?;
2595 token::Literal(token::Integer(index_ident), suf) => {
2598 // A tuple index may not have a suffix
2599 self.expect_no_suffix(sp, "tuple index", suf);
2601 let dot_span = self.prev_span;
2605 let invalid_msg = "invalid tuple or struct index";
2607 let index = index_ident.as_str().parse::<usize>().ok();
2610 if n.to_string() != index_ident.as_str() {
2611 let mut err = self.struct_span_err(self.prev_span, invalid_msg);
2612 err.span_suggestion(self.prev_span,
2613 "try simplifying the index",
2617 let id = respan(dot_span.to(hi), n);
2618 let field = self.mk_tup_field(e, id);
2619 e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2622 let prev_span = self.prev_span;
2623 self.span_err(prev_span, invalid_msg);
2627 token::Literal(token::Float(n), _suf) => {
2629 let fstr = n.as_str();
2630 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2631 &format!("unexpected token: `{}`", n));
2632 err.span_label(self.prev_span, "unexpected token");
2633 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2634 let float = match fstr.parse::<f64>().ok() {
2638 let sugg = pprust::to_string(|s| {
2639 use print::pprust::PrintState;
2643 s.print_usize(float.trunc() as usize)?;
2646 s.s.word(fstr.splitn(2, ".").last().unwrap())
2648 err.span_suggestion(
2649 lo.to(self.prev_span),
2650 "try parenthesizing the first index",
2657 // FIXME Could factor this out into non_fatal_unexpected or something.
2658 let actual = self.this_token_to_string();
2659 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2664 if self.expr_is_complete(&e) { break; }
2667 token::OpenDelim(token::Paren) => {
2668 let es = self.parse_unspanned_seq(
2669 &token::OpenDelim(token::Paren),
2670 &token::CloseDelim(token::Paren),
2671 SeqSep::trailing_allowed(token::Comma),
2672 |p| Ok(p.parse_expr()?)
2674 hi = self.prev_span;
2676 let nd = self.mk_call(e, es);
2677 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2681 // Could be either an index expression or a slicing expression.
2682 token::OpenDelim(token::Bracket) => {
2684 let ix = self.parse_expr()?;
2686 self.expect(&token::CloseDelim(token::Bracket))?;
2687 let index = self.mk_index(e, ix);
2688 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2696 pub fn process_potential_macro_variable(&mut self) {
2697 let ident = match self.token {
2698 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2699 self.look_ahead(1, |t| t.is_ident()) => {
2701 let name = match self.token { token::Ident(ident) => ident, _ => unreachable!() };
2702 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2705 token::Interpolated(ref nt) => {
2706 self.meta_var_span = Some(self.span);
2708 token::NtIdent(ident) => ident,
2714 self.token = token::Ident(ident.node);
2715 self.span = ident.span;
2718 /// parse a single token tree from the input.
2719 pub fn parse_token_tree(&mut self) -> TokenTree {
2721 token::OpenDelim(..) => {
2722 let frame = mem::replace(&mut self.token_cursor.frame,
2723 self.token_cursor.stack.pop().unwrap());
2724 self.span = frame.span;
2726 TokenTree::Delimited(frame.span, Delimited {
2728 tts: frame.tree_cursor.original_stream().into(),
2731 token::CloseDelim(_) | token::Eof => unreachable!(),
2733 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2735 TokenTree::Token(span, token)
2740 // parse a stream of tokens into a list of TokenTree's,
2742 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2743 let mut tts = Vec::new();
2744 while self.token != token::Eof {
2745 tts.push(self.parse_token_tree());
2750 pub fn parse_tokens(&mut self) -> TokenStream {
2751 let mut result = Vec::new();
2754 token::Eof | token::CloseDelim(..) => break,
2755 _ => result.push(self.parse_token_tree().into()),
2758 TokenStream::concat(result)
2761 /// Parse a prefix-unary-operator expr
2762 pub fn parse_prefix_expr(&mut self,
2763 already_parsed_attrs: Option<ThinVec<Attribute>>)
2764 -> PResult<'a, P<Expr>> {
2765 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2767 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2768 let (hi, ex) = match self.token {
2771 let e = self.parse_prefix_expr(None);
2772 let (span, e) = self.interpolated_or_expr_span(e)?;
2773 (lo.to(span), self.mk_unary(UnOp::Not, e))
2775 // Suggest `!` for bitwise negation when encountering a `~`
2778 let e = self.parse_prefix_expr(None);
2779 let (span, e) = self.interpolated_or_expr_span(e)?;
2780 let span_of_tilde = lo;
2781 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2782 "`~` can not be used as a unary operator");
2783 err.span_label(span_of_tilde, "did you mean `!`?");
2784 err.help("use `!` instead of `~` if you meant to perform bitwise negation");
2786 (lo.to(span), self.mk_unary(UnOp::Not, e))
2788 token::BinOp(token::Minus) => {
2790 let e = self.parse_prefix_expr(None);
2791 let (span, e) = self.interpolated_or_expr_span(e)?;
2792 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2794 token::BinOp(token::Star) => {
2796 let e = self.parse_prefix_expr(None);
2797 let (span, e) = self.interpolated_or_expr_span(e)?;
2798 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2800 token::BinOp(token::And) | token::AndAnd => {
2802 let m = self.parse_mutability();
2803 let e = self.parse_prefix_expr(None);
2804 let (span, e) = self.interpolated_or_expr_span(e)?;
2805 (lo.to(span), ExprKind::AddrOf(m, e))
2807 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2809 let place = self.parse_expr_res(
2810 Restrictions::NO_STRUCT_LITERAL,
2813 let blk = self.parse_block()?;
2814 let span = blk.span;
2815 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2816 (lo.to(span), ExprKind::InPlace(place, blk_expr))
2818 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2820 let e = self.parse_prefix_expr(None);
2821 let (span, e) = self.interpolated_or_expr_span(e)?;
2822 (lo.to(span), ExprKind::Box(e))
2824 _ => return self.parse_dot_or_call_expr(Some(attrs))
2826 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2829 /// Parse an associative expression
2831 /// This parses an expression accounting for associativity and precedence of the operators in
2833 pub fn parse_assoc_expr(&mut self,
2834 already_parsed_attrs: Option<ThinVec<Attribute>>)
2835 -> PResult<'a, P<Expr>> {
2836 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2839 /// Parse an associative expression with operators of at least `min_prec` precedence
2840 pub fn parse_assoc_expr_with(&mut self,
2843 -> PResult<'a, P<Expr>> {
2844 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2847 let attrs = match lhs {
2848 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2851 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2852 return self.parse_prefix_range_expr(attrs);
2854 self.parse_prefix_expr(attrs)?
2858 if self.expr_is_complete(&lhs) {
2859 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2862 self.expected_tokens.push(TokenType::Operator);
2863 while let Some(op) = AssocOp::from_token(&self.token) {
2865 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2866 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2867 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2868 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2869 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2870 (PrevTokenKind::Interpolated, _) => self.prev_span,
2871 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2872 if path.segments.len() == 1 => self.prev_span,
2876 let cur_op_span = self.span;
2877 let restrictions = if op.is_assign_like() {
2878 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2882 if op.precedence() < min_prec {
2885 // Check for deprecated `...` syntax
2886 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2887 self.err_dotdotdot_syntax(self.span);
2891 if op.is_comparison() {
2892 self.check_no_chained_comparison(&lhs, &op);
2895 if op == AssocOp::As {
2896 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2898 } else if op == AssocOp::Colon {
2899 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2902 err.span_label(self.span,
2903 "expecting a type here because of type ascription");
2904 let cm = self.sess.codemap();
2905 let cur_pos = cm.lookup_char_pos(self.span.lo());
2906 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
2907 if cur_pos.line != op_pos.line {
2908 err.span_suggestion_short(cur_op_span,
2909 "did you mean to use `;` here?",
2916 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2917 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2918 // generalise it to the Fixity::None code.
2920 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2921 // two variants are handled with `parse_prefix_range_expr` call above.
2922 let rhs = if self.is_at_start_of_range_notation_rhs() {
2923 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2924 LhsExpr::NotYetParsed)?)
2928 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2933 let limits = if op == AssocOp::DotDot {
2934 RangeLimits::HalfOpen
2939 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2940 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2944 let rhs = match op.fixity() {
2945 Fixity::Right => self.with_res(
2946 restrictions - Restrictions::STMT_EXPR,
2948 this.parse_assoc_expr_with(op.precedence(),
2949 LhsExpr::NotYetParsed)
2951 Fixity::Left => self.with_res(
2952 restrictions - Restrictions::STMT_EXPR,
2954 this.parse_assoc_expr_with(op.precedence() + 1,
2955 LhsExpr::NotYetParsed)
2957 // We currently have no non-associative operators that are not handled above by
2958 // the special cases. The code is here only for future convenience.
2959 Fixity::None => self.with_res(
2960 restrictions - Restrictions::STMT_EXPR,
2962 this.parse_assoc_expr_with(op.precedence() + 1,
2963 LhsExpr::NotYetParsed)
2967 let span = lhs_span.to(rhs.span);
2969 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2970 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2971 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2972 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2973 AssocOp::Greater | AssocOp::GreaterEqual => {
2974 let ast_op = op.to_ast_binop().unwrap();
2975 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2976 self.mk_expr(span, binary, ThinVec::new())
2979 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2981 self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
2982 AssocOp::AssignOp(k) => {
2984 token::Plus => BinOpKind::Add,
2985 token::Minus => BinOpKind::Sub,
2986 token::Star => BinOpKind::Mul,
2987 token::Slash => BinOpKind::Div,
2988 token::Percent => BinOpKind::Rem,
2989 token::Caret => BinOpKind::BitXor,
2990 token::And => BinOpKind::BitAnd,
2991 token::Or => BinOpKind::BitOr,
2992 token::Shl => BinOpKind::Shl,
2993 token::Shr => BinOpKind::Shr,
2995 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2996 self.mk_expr(span, aopexpr, ThinVec::new())
2998 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
2999 self.bug("AssocOp should have been handled by special case")
3003 if op.fixity() == Fixity::None { break }
3008 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3009 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3010 -> PResult<'a, P<Expr>> {
3011 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3012 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3015 // Save the state of the parser before parsing type normally, in case there is a
3016 // LessThan comparison after this cast.
3017 let parser_snapshot_before_type = self.clone();
3018 match self.parse_ty_no_plus() {
3020 Ok(mk_expr(self, rhs))
3022 Err(mut type_err) => {
3023 // Rewind to before attempting to parse the type with generics, to recover
3024 // from situations like `x as usize < y` in which we first tried to parse
3025 // `usize < y` as a type with generic arguments.
3026 let parser_snapshot_after_type = self.clone();
3027 mem::replace(self, parser_snapshot_before_type);
3029 match self.parse_path(PathStyle::Expr) {
3031 let (op_noun, op_verb) = match self.token {
3032 token::Lt => ("comparison", "comparing"),
3033 token::BinOp(token::Shl) => ("shift", "shifting"),
3035 // We can end up here even without `<` being the next token, for
3036 // example because `parse_ty_no_plus` returns `Err` on keywords,
3037 // but `parse_path` returns `Ok` on them due to error recovery.
3038 // Return original error and parser state.
3039 mem::replace(self, parser_snapshot_after_type);
3040 return Err(type_err);
3044 // Successfully parsed the type path leaving a `<` yet to parse.
3047 // Report non-fatal diagnostics, keep `x as usize` as an expression
3048 // in AST and continue parsing.
3049 let msg = format!("`<` is interpreted as a start of generic \
3050 arguments for `{}`, not a {}", path, op_noun);
3051 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3052 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3053 "interpreted as generic arguments");
3054 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3056 let expr = mk_expr(self, P(Ty {
3058 node: TyKind::Path(None, path),
3059 id: ast::DUMMY_NODE_ID
3062 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
3063 .unwrap_or(pprust::expr_to_string(&expr));
3064 err.span_suggestion(expr.span,
3065 &format!("try {} the casted value", op_verb),
3066 format!("({})", expr_str));
3071 Err(mut path_err) => {
3072 // Couldn't parse as a path, return original error and parser state.
3074 mem::replace(self, parser_snapshot_after_type);
3082 /// Produce an error if comparison operators are chained (RFC #558).
3083 /// We only need to check lhs, not rhs, because all comparison ops
3084 /// have same precedence and are left-associative
3085 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3086 debug_assert!(outer_op.is_comparison(),
3087 "check_no_chained_comparison: {:?} is not comparison",
3090 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3091 // respan to include both operators
3092 let op_span = op.span.to(self.span);
3093 let mut err = self.diagnostic().struct_span_err(op_span,
3094 "chained comparison operators require parentheses");
3095 if op.node == BinOpKind::Lt &&
3096 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3097 *outer_op == AssocOp::Greater // even in a case like the following:
3098 { // Foo<Bar<Baz<Qux, ()>>>
3100 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3101 err.help("or use `(...)` if you meant to specify fn arguments");
3109 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3110 fn parse_prefix_range_expr(&mut self,
3111 already_parsed_attrs: Option<ThinVec<Attribute>>)
3112 -> PResult<'a, P<Expr>> {
3113 // Check for deprecated `...` syntax
3114 if self.token == token::DotDotDot {
3115 self.err_dotdotdot_syntax(self.span);
3118 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3119 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3121 let tok = self.token.clone();
3122 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3124 let mut hi = self.span;
3126 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3127 // RHS must be parsed with more associativity than the dots.
3128 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3129 Some(self.parse_assoc_expr_with(next_prec,
3130 LhsExpr::NotYetParsed)
3138 let limits = if tok == token::DotDot {
3139 RangeLimits::HalfOpen
3144 let r = try!(self.mk_range(None,
3147 Ok(self.mk_expr(lo.to(hi), r, attrs))
3150 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3151 if self.token.can_begin_expr() {
3152 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3153 if self.token == token::OpenDelim(token::Brace) {
3154 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3162 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3163 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3164 if self.check_keyword(keywords::Let) {
3165 return self.parse_if_let_expr(attrs);
3167 let lo = self.prev_span;
3168 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3170 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3171 // verify that the last statement is either an implicit return (no `;`) or an explicit
3172 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3173 // the dead code lint.
3174 if self.eat_keyword(keywords::Else) || !cond.returns() {
3175 let sp = lo.next_point();
3176 let mut err = self.diagnostic()
3177 .struct_span_err(sp, "missing condition for `if` statemement");
3178 err.span_label(sp, "expected if condition here");
3181 let thn = self.parse_block()?;
3182 let mut els: Option<P<Expr>> = None;
3183 let mut hi = thn.span;
3184 if self.eat_keyword(keywords::Else) {
3185 let elexpr = self.parse_else_expr()?;
3189 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3192 /// Parse an 'if let' expression ('if' token already eaten)
3193 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3194 -> PResult<'a, P<Expr>> {
3195 let lo = self.prev_span;
3196 self.expect_keyword(keywords::Let)?;
3197 let pat = self.parse_pat()?;
3198 self.expect(&token::Eq)?;
3199 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3200 let thn = self.parse_block()?;
3201 let (hi, els) = if self.eat_keyword(keywords::Else) {
3202 let expr = self.parse_else_expr()?;
3203 (expr.span, Some(expr))
3207 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
3210 // `move |args| expr`
3211 pub fn parse_lambda_expr(&mut self,
3213 capture_clause: CaptureBy,
3214 attrs: ThinVec<Attribute>)
3215 -> PResult<'a, P<Expr>>
3217 let decl = self.parse_fn_block_decl()?;
3218 let decl_hi = self.prev_span;
3219 let body = match decl.output {
3220 FunctionRetTy::Default(_) => {
3221 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3222 self.parse_expr_res(restrictions, None)?
3225 // If an explicit return type is given, require a
3226 // block to appear (RFC 968).
3227 let body_lo = self.span;
3228 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3234 ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3238 // `else` token already eaten
3239 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3240 if self.eat_keyword(keywords::If) {
3241 return self.parse_if_expr(ThinVec::new());
3243 let blk = self.parse_block()?;
3244 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3248 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3249 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3251 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3252 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3254 let pat = self.parse_pat()?;
3255 if !self.eat_keyword(keywords::In) {
3256 let in_span = self.prev_span.between(self.span);
3257 let mut err = self.sess.span_diagnostic
3258 .struct_span_err(in_span, "missing `in` in `for` loop");
3259 err.span_suggestion_short(in_span, "try adding `in` here", " in ".into());
3262 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3263 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3264 attrs.extend(iattrs);
3266 let hi = self.prev_span;
3267 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3270 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3271 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3273 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3274 if self.token.is_keyword(keywords::Let) {
3275 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3277 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3278 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3279 attrs.extend(iattrs);
3280 let span = span_lo.to(body.span);
3281 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3284 /// Parse a 'while let' expression ('while' token already eaten)
3285 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3287 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3288 self.expect_keyword(keywords::Let)?;
3289 let pat = self.parse_pat()?;
3290 self.expect(&token::Eq)?;
3291 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3292 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3293 attrs.extend(iattrs);
3294 let span = span_lo.to(body.span);
3295 return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3298 // parse `loop {...}`, `loop` token already eaten
3299 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3301 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3302 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3303 attrs.extend(iattrs);
3304 let span = span_lo.to(body.span);
3305 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3308 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3309 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3310 -> PResult<'a, P<Expr>>
3312 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3313 attrs.extend(iattrs);
3314 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3317 // `match` token already eaten
3318 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3319 let match_span = self.prev_span;
3320 let lo = self.prev_span;
3321 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3323 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3324 if self.token == token::Token::Semi {
3325 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3329 attrs.extend(self.parse_inner_attributes()?);
3331 let mut arms: Vec<Arm> = Vec::new();
3332 while self.token != token::CloseDelim(token::Brace) {
3333 match self.parse_arm() {
3334 Ok(arm) => arms.push(arm),
3336 // Recover by skipping to the end of the block.
3338 self.recover_stmt();
3339 let span = lo.to(self.span);
3340 if self.token == token::CloseDelim(token::Brace) {
3343 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3349 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3352 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3353 maybe_whole!(self, NtArm, |x| x);
3355 let attrs = self.parse_outer_attributes()?;
3356 // Allow a '|' before the pats (RFC 1925)
3357 let beginning_vert = if self.eat(&token::BinOp(token::Or)) {
3358 Some(self.prev_span)
3362 let pats = self.parse_pats()?;
3363 let guard = if self.eat_keyword(keywords::If) {
3364 Some(self.parse_expr()?)
3368 self.expect(&token::FatArrow)?;
3369 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)?;
3371 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3372 && self.token != token::CloseDelim(token::Brace);
3375 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3377 self.eat(&token::Comma);
3389 /// Parse an expression
3390 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3391 self.parse_expr_res(Restrictions::empty(), None)
3394 /// Evaluate the closure with restrictions in place.
3396 /// After the closure is evaluated, restrictions are reset.
3397 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3398 where F: FnOnce(&mut Self) -> T
3400 let old = self.restrictions;
3401 self.restrictions = r;
3403 self.restrictions = old;
3408 /// Parse an expression, subject to the given restrictions
3409 pub fn parse_expr_res(&mut self, r: Restrictions,
3410 already_parsed_attrs: Option<ThinVec<Attribute>>)
3411 -> PResult<'a, P<Expr>> {
3412 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3415 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3416 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3417 if self.check(&token::Eq) {
3419 Ok(Some(self.parse_expr()?))
3421 Ok(Some(self.parse_expr()?))
3427 /// Parse patterns, separated by '|' s
3428 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3429 let mut pats = Vec::new();
3431 pats.push(self.parse_pat()?);
3432 if self.check(&token::BinOp(token::Or)) { self.bump();}
3433 else { return Ok(pats); }
3437 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3438 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3439 let mut fields = vec![];
3440 let mut ddpos = None;
3442 while !self.check(&token::CloseDelim(token::Paren)) {
3443 if ddpos.is_none() && self.eat(&token::DotDot) {
3444 ddpos = Some(fields.len());
3445 if self.eat(&token::Comma) {
3446 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3447 fields.push(self.parse_pat()?);
3449 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3450 // Emit a friendly error, ignore `..` and continue parsing
3451 self.span_err(self.prev_span, "`..` can only be used once per \
3452 tuple or tuple struct pattern");
3454 fields.push(self.parse_pat()?);
3457 if !self.check(&token::CloseDelim(token::Paren)) ||
3458 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3459 self.expect(&token::Comma)?;
3466 fn parse_pat_vec_elements(
3468 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3469 let mut before = Vec::new();
3470 let mut slice = None;
3471 let mut after = Vec::new();
3472 let mut first = true;
3473 let mut before_slice = true;
3475 while self.token != token::CloseDelim(token::Bracket) {
3479 self.expect(&token::Comma)?;
3481 if self.token == token::CloseDelim(token::Bracket)
3482 && (before_slice || !after.is_empty()) {
3488 if self.eat(&token::DotDot) {
3490 if self.check(&token::Comma) ||
3491 self.check(&token::CloseDelim(token::Bracket)) {
3492 slice = Some(P(Pat {
3493 id: ast::DUMMY_NODE_ID,
3494 node: PatKind::Wild,
3497 before_slice = false;
3503 let subpat = self.parse_pat()?;
3504 if before_slice && self.eat(&token::DotDot) {
3505 slice = Some(subpat);
3506 before_slice = false;
3507 } else if before_slice {
3508 before.push(subpat);
3514 Ok((before, slice, after))
3517 /// Parse the fields of a struct-like pattern
3518 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3519 let mut fields = Vec::new();
3520 let mut etc = false;
3521 let mut first = true;
3522 while self.token != token::CloseDelim(token::Brace) {
3526 self.expect(&token::Comma)?;
3527 // accept trailing commas
3528 if self.check(&token::CloseDelim(token::Brace)) { break }
3531 let attrs = self.parse_outer_attributes()?;
3535 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3536 if self.token == token::DotDotDot { // Issue #46718
3537 let mut err = self.struct_span_err(self.span,
3538 "expected field pattern, found `...`");
3539 err.span_suggestion(self.span,
3540 "to omit remaining fields, use one fewer `.`",
3546 if self.token != token::CloseDelim(token::Brace) {
3547 let token_str = self.this_token_to_string();
3548 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3555 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3556 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3557 // Parsing a pattern of the form "fieldname: pat"
3558 let fieldname = self.parse_field_name()?;
3560 let pat = self.parse_pat()?;
3562 (pat, fieldname, false)
3564 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3565 let is_box = self.eat_keyword(keywords::Box);
3566 let boxed_span = self.span;
3567 let is_ref = self.eat_keyword(keywords::Ref);
3568 let is_mut = self.eat_keyword(keywords::Mut);
3569 let fieldname = self.parse_ident()?;
3570 hi = self.prev_span;
3572 let bind_type = match (is_ref, is_mut) {
3573 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3574 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3575 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3576 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3578 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3579 let fieldpat = P(Pat {
3580 id: ast::DUMMY_NODE_ID,
3581 node: PatKind::Ident(bind_type, fieldpath, None),
3582 span: boxed_span.to(hi),
3585 let subpat = if is_box {
3587 id: ast::DUMMY_NODE_ID,
3588 node: PatKind::Box(fieldpat),
3594 (subpat, fieldname, true)
3597 fields.push(codemap::Spanned { span: lo.to(hi),
3598 node: ast::FieldPat {
3602 attrs: attrs.into(),
3606 return Ok((fields, etc));
3609 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3610 if self.token.is_path_start() {
3612 let (qself, path) = if self.eat_lt() {
3613 // Parse a qualified path
3614 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3617 // Parse an unqualified path
3618 (None, self.parse_path(PathStyle::Expr)?)
3620 let hi = self.prev_span;
3621 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3623 self.parse_pat_literal_maybe_minus()
3627 // helper function to decide whether to parse as ident binding or to try to do
3628 // something more complex like range patterns
3629 fn parse_as_ident(&mut self) -> bool {
3630 self.look_ahead(1, |t| match *t {
3631 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3632 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3633 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3634 // range pattern branch
3635 token::DotDot => None,
3637 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3638 token::Comma | token::CloseDelim(token::Bracket) => true,
3643 /// Parse a pattern.
3644 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3645 maybe_whole!(self, NtPat, |x| x);
3650 token::Underscore => {
3653 pat = PatKind::Wild;
3655 token::BinOp(token::And) | token::AndAnd => {
3656 // Parse &pat / &mut pat
3658 let mutbl = self.parse_mutability();
3659 if let token::Lifetime(ident) = self.token {
3660 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3662 let subpat = self.parse_pat()?;
3663 pat = PatKind::Ref(subpat, mutbl);
3665 token::OpenDelim(token::Paren) => {
3666 // Parse (pat,pat,pat,...) as tuple pattern
3668 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3669 self.expect(&token::CloseDelim(token::Paren))?;
3670 pat = PatKind::Tuple(fields, ddpos);
3672 token::OpenDelim(token::Bracket) => {
3673 // Parse [pat,pat,...] as slice pattern
3675 let (before, slice, after) = self.parse_pat_vec_elements()?;
3676 self.expect(&token::CloseDelim(token::Bracket))?;
3677 pat = PatKind::Slice(before, slice, after);
3679 // At this point, token != _, &, &&, (, [
3680 _ => if self.eat_keyword(keywords::Mut) {
3681 // Parse mut ident @ pat / mut ref ident @ pat
3682 let mutref_span = self.prev_span.to(self.span);
3683 let binding_mode = if self.eat_keyword(keywords::Ref) {
3685 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3686 .span_suggestion(mutref_span, "try switching the order", "ref mut".into())
3688 BindingMode::ByRef(Mutability::Mutable)
3690 BindingMode::ByValue(Mutability::Mutable)
3692 pat = self.parse_pat_ident(binding_mode)?;
3693 } else if self.eat_keyword(keywords::Ref) {
3694 // Parse ref ident @ pat / ref mut ident @ pat
3695 let mutbl = self.parse_mutability();
3696 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3697 } else if self.eat_keyword(keywords::Box) {
3699 let subpat = self.parse_pat()?;
3700 pat = PatKind::Box(subpat);
3701 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3702 self.parse_as_ident() {
3703 // Parse ident @ pat
3704 // This can give false positives and parse nullary enums,
3705 // they are dealt with later in resolve
3706 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3707 pat = self.parse_pat_ident(binding_mode)?;
3708 } else if self.token.is_path_start() {
3709 // Parse pattern starting with a path
3710 let (qself, path) = if self.eat_lt() {
3711 // Parse a qualified path
3712 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3715 // Parse an unqualified path
3716 (None, self.parse_path(PathStyle::Expr)?)
3719 token::Not if qself.is_none() => {
3720 // Parse macro invocation
3722 let (_, tts) = self.expect_delimited_token_tree()?;
3723 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3724 pat = PatKind::Mac(mac);
3726 token::DotDotDot | token::DotDotEq | token::DotDot => {
3727 let end_kind = match self.token {
3728 token::DotDot => RangeEnd::Excluded,
3729 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
3730 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
3731 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
3735 let span = lo.to(self.prev_span);
3736 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3738 let end = self.parse_pat_range_end()?;
3739 pat = PatKind::Range(begin, end, end_kind);
3741 token::OpenDelim(token::Brace) => {
3742 if qself.is_some() {
3743 return Err(self.fatal("unexpected `{` after qualified path"));
3745 // Parse struct pattern
3747 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3749 self.recover_stmt();
3753 pat = PatKind::Struct(path, fields, etc);
3755 token::OpenDelim(token::Paren) => {
3756 if qself.is_some() {
3757 return Err(self.fatal("unexpected `(` after qualified path"));
3759 // Parse tuple struct or enum pattern
3761 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3762 self.expect(&token::CloseDelim(token::Paren))?;
3763 pat = PatKind::TupleStruct(path, fields, ddpos)
3765 _ => pat = PatKind::Path(qself, path),
3768 // Try to parse everything else as literal with optional minus
3769 match self.parse_pat_literal_maybe_minus() {
3771 if self.eat(&token::DotDotDot) {
3772 let end = self.parse_pat_range_end()?;
3773 pat = PatKind::Range(begin, end,
3774 RangeEnd::Included(RangeSyntax::DotDotDot));
3775 } else if self.eat(&token::DotDotEq) {
3776 let end = self.parse_pat_range_end()?;
3777 pat = PatKind::Range(begin, end,
3778 RangeEnd::Included(RangeSyntax::DotDotEq));
3779 } else if self.eat(&token::DotDot) {
3780 let end = self.parse_pat_range_end()?;
3781 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3783 pat = PatKind::Lit(begin);
3787 self.cancel(&mut err);
3788 let msg = format!("expected pattern, found {}", self.this_token_descr());
3789 return Err(self.fatal(&msg));
3795 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
3796 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
3801 /// Parse ident or ident @ pat
3802 /// used by the copy foo and ref foo patterns to give a good
3803 /// error message when parsing mistakes like ref foo(a,b)
3804 fn parse_pat_ident(&mut self,
3805 binding_mode: ast::BindingMode)
3806 -> PResult<'a, PatKind> {
3807 let ident_span = self.span;
3808 let ident = self.parse_ident()?;
3809 let name = codemap::Spanned{span: ident_span, node: ident};
3810 let sub = if self.eat(&token::At) {
3811 Some(self.parse_pat()?)
3816 // just to be friendly, if they write something like
3818 // we end up here with ( as the current token. This shortly
3819 // leads to a parse error. Note that if there is no explicit
3820 // binding mode then we do not end up here, because the lookahead
3821 // will direct us over to parse_enum_variant()
3822 if self.token == token::OpenDelim(token::Paren) {
3823 return Err(self.span_fatal(
3825 "expected identifier, found enum pattern"))
3828 Ok(PatKind::Ident(binding_mode, name, sub))
3831 /// Parse a local variable declaration
3832 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3833 let lo = self.prev_span;
3834 let pat = self.parse_pat()?;
3836 let (err, ty) = if self.eat(&token::Colon) {
3837 // Save the state of the parser before parsing type normally, in case there is a `:`
3838 // instead of an `=` typo.
3839 let parser_snapshot_before_type = self.clone();
3840 let colon_sp = self.prev_span;
3841 match self.parse_ty() {
3842 Ok(ty) => (None, Some(ty)),
3844 // Rewind to before attempting to parse the type and continue parsing
3845 let parser_snapshot_after_type = self.clone();
3846 mem::replace(self, parser_snapshot_before_type);
3848 let snippet = self.sess.codemap().span_to_snippet(pat.span).unwrap();
3849 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
3850 (Some((parser_snapshot_after_type, colon_sp, err)), None)
3856 let init = match (self.parse_initializer(err.is_some()), err) {
3857 (Ok(init), None) => { // init parsed, ty parsed
3860 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
3861 // Could parse the type as if it were the initializer, it is likely there was a
3862 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
3863 err.span_suggestion_short(colon_sp,
3864 "use `=` if you meant to assign",
3867 // As this was parsed successfuly, continue as if the code has been fixed for the
3868 // rest of the file. It will still fail due to the emitted error, but we avoid
3872 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
3874 // Couldn't parse the type nor the initializer, only raise the type error and
3875 // return to the parser state before parsing the type as the initializer.
3876 // let x: <parse_error>;
3877 mem::replace(self, snapshot);
3880 (Err(err), None) => { // init error, ty parsed
3881 // Couldn't parse the initializer and we're not attempting to recover a failed
3882 // parse of the type, return the error.
3886 let hi = if self.token == token::Semi {
3895 id: ast::DUMMY_NODE_ID,
3901 /// Parse a structure field
3902 fn parse_name_and_ty(&mut self,
3905 attrs: Vec<Attribute>)
3906 -> PResult<'a, StructField> {
3907 let name = self.parse_ident()?;
3908 self.expect(&token::Colon)?;
3909 let ty = self.parse_ty()?;
3911 span: lo.to(self.prev_span),
3914 id: ast::DUMMY_NODE_ID,
3920 /// Emit an expected item after attributes error.
3921 fn expected_item_err(&self, attrs: &[Attribute]) {
3922 let message = match attrs.last() {
3923 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3924 _ => "expected item after attributes",
3927 self.span_err(self.prev_span, message);
3930 /// Parse a statement. This stops just before trailing semicolons on everything but items.
3931 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3932 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3933 Ok(self.parse_stmt_(true))
3936 // Eat tokens until we can be relatively sure we reached the end of the
3937 // statement. This is something of a best-effort heuristic.
3939 // We terminate when we find an unmatched `}` (without consuming it).
3940 fn recover_stmt(&mut self) {
3941 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
3944 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3945 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3946 // approximate - it can mean we break too early due to macros, but that
3947 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3949 // If `break_on_block` is `Break`, then we will stop consuming tokens
3950 // after finding (and consuming) a brace-delimited block.
3951 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
3952 let mut brace_depth = 0;
3953 let mut bracket_depth = 0;
3954 let mut in_block = false;
3955 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
3956 break_on_semi, break_on_block);
3958 debug!("recover_stmt_ loop {:?}", self.token);
3960 token::OpenDelim(token::DelimToken::Brace) => {
3963 if break_on_block == BlockMode::Break &&
3965 bracket_depth == 0 {
3969 token::OpenDelim(token::DelimToken::Bracket) => {
3973 token::CloseDelim(token::DelimToken::Brace) => {
3974 if brace_depth == 0 {
3975 debug!("recover_stmt_ return - close delim {:?}", self.token);
3980 if in_block && bracket_depth == 0 && brace_depth == 0 {
3981 debug!("recover_stmt_ return - block end {:?}", self.token);
3985 token::CloseDelim(token::DelimToken::Bracket) => {
3987 if bracket_depth < 0 {
3993 debug!("recover_stmt_ return - Eof");
3998 if break_on_semi == SemiColonMode::Break &&
4000 bracket_depth == 0 {
4001 debug!("recover_stmt_ return - Semi");
4012 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4013 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4015 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4020 fn is_catch_expr(&mut self) -> bool {
4021 self.token.is_keyword(keywords::Do) &&
4022 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4023 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4025 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
4026 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4029 fn is_union_item(&self) -> bool {
4030 self.token.is_keyword(keywords::Union) &&
4031 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4034 fn is_crate_vis(&self) -> bool {
4035 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4038 fn eat_auto_trait(&mut self) -> bool {
4039 if self.token.is_keyword(keywords::Auto)
4040 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
4042 self.eat_keyword(keywords::Auto) && self.eat_keyword(keywords::Trait)
4048 fn is_defaultness(&self) -> bool {
4049 // `pub` is included for better error messages
4050 self.token.is_keyword(keywords::Default) &&
4051 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
4052 t.is_keyword(keywords::Const) ||
4053 t.is_keyword(keywords::Fn) ||
4054 t.is_keyword(keywords::Unsafe) ||
4055 t.is_keyword(keywords::Extern) ||
4056 t.is_keyword(keywords::Type) ||
4057 t.is_keyword(keywords::Pub))
4060 fn eat_defaultness(&mut self) -> bool {
4061 let is_defaultness = self.is_defaultness();
4065 self.expected_tokens.push(TokenType::Keyword(keywords::Default));
4070 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4071 -> PResult<'a, Option<P<Item>>> {
4072 let token_lo = self.span;
4073 let (ident, def) = match self.token {
4074 token::Ident(ident) if ident.name == keywords::Macro.name() => {
4076 let ident = self.parse_ident()?;
4077 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4078 match self.parse_token_tree() {
4079 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4080 _ => unreachable!(),
4082 } else if self.check(&token::OpenDelim(token::Paren)) {
4083 let args = self.parse_token_tree();
4084 let body = if self.check(&token::OpenDelim(token::Brace)) {
4085 self.parse_token_tree()
4090 TokenStream::concat(vec![
4092 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4100 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4102 token::Ident(ident) if ident.name == "macro_rules" &&
4103 self.look_ahead(1, |t| *t == token::Not) => {
4104 let prev_span = self.prev_span;
4105 self.complain_if_pub_macro(vis, prev_span);
4109 let ident = self.parse_ident()?;
4110 let (delim, tokens) = self.expect_delimited_token_tree()?;
4111 if delim != token::Brace {
4112 if !self.eat(&token::Semi) {
4113 let msg = "macros that expand to items must either \
4114 be surrounded with braces or followed by a semicolon";
4115 self.span_err(self.prev_span, msg);
4119 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4121 _ => return Ok(None),
4124 let span = lo.to(self.prev_span);
4125 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4128 fn parse_stmt_without_recovery(&mut self,
4129 macro_legacy_warnings: bool)
4130 -> PResult<'a, Option<Stmt>> {
4131 maybe_whole!(self, NtStmt, |x| Some(x));
4133 let attrs = self.parse_outer_attributes()?;
4136 Ok(Some(if self.eat_keyword(keywords::Let) {
4138 id: ast::DUMMY_NODE_ID,
4139 node: StmtKind::Local(self.parse_local(attrs.into())?),
4140 span: lo.to(self.prev_span),
4142 } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited, lo)? {
4144 id: ast::DUMMY_NODE_ID,
4145 node: StmtKind::Item(macro_def),
4146 span: lo.to(self.prev_span),
4148 // Starts like a simple path, but not a union item or item with `crate` visibility.
4149 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4150 // like a path (1 token), but it fact not a path.
4151 // `union::b::c` - path, `union U { ... }` - not a path.
4152 // `crate::b::c` - path, `crate struct S;` - not a path.
4153 } else if self.token.is_path_start() &&
4154 !self.token.is_qpath_start() &&
4155 !self.is_union_item() &&
4156 !self.is_crate_vis() {
4157 let pth = self.parse_path(PathStyle::Expr)?;
4159 if !self.eat(&token::Not) {
4160 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4161 self.parse_struct_expr(lo, pth, ThinVec::new())?
4163 let hi = self.prev_span;
4164 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4167 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4168 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4169 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4172 return Ok(Some(Stmt {
4173 id: ast::DUMMY_NODE_ID,
4174 node: StmtKind::Expr(expr),
4175 span: lo.to(self.prev_span),
4179 // it's a macro invocation
4180 let id = match self.token {
4181 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4182 _ => self.parse_ident()?,
4185 // check that we're pointing at delimiters (need to check
4186 // again after the `if`, because of `parse_ident`
4187 // consuming more tokens).
4188 let delim = match self.token {
4189 token::OpenDelim(delim) => delim,
4191 // we only expect an ident if we didn't parse one
4193 let ident_str = if id.name == keywords::Invalid.name() {
4198 let tok_str = self.this_token_to_string();
4199 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4205 let (_, tts) = self.expect_delimited_token_tree()?;
4206 let hi = self.prev_span;
4208 let style = if delim == token::Brace {
4209 MacStmtStyle::Braces
4211 MacStmtStyle::NoBraces
4214 if id.name == keywords::Invalid.name() {
4215 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
4216 let node = if delim == token::Brace ||
4217 self.token == token::Semi || self.token == token::Eof {
4218 StmtKind::Mac(P((mac, style, attrs.into())))
4220 // We used to incorrectly stop parsing macro-expanded statements here.
4221 // If the next token will be an error anyway but could have parsed with the
4222 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4223 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4224 // These can continue an expression, so we can't stop parsing and warn.
4225 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4226 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4227 token::BinOp(token::And) | token::BinOp(token::Or) |
4228 token::AndAnd | token::OrOr |
4229 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4232 self.warn_missing_semicolon();
4233 StmtKind::Mac(P((mac, style, attrs.into())))
4235 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4236 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4237 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4241 id: ast::DUMMY_NODE_ID,
4246 // if it has a special ident, it's definitely an item
4248 // Require a semicolon or braces.
4249 if style != MacStmtStyle::Braces {
4250 if !self.eat(&token::Semi) {
4251 self.span_err(self.prev_span,
4252 "macros that expand to items must \
4253 either be surrounded with braces or \
4254 followed by a semicolon");
4257 let span = lo.to(hi);
4259 id: ast::DUMMY_NODE_ID,
4261 node: StmtKind::Item({
4263 span, id /*id is good here*/,
4264 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
4265 Visibility::Inherited,
4271 // FIXME: Bad copy of attrs
4272 let old_directory_ownership =
4273 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4274 let item = self.parse_item_(attrs.clone(), false, true)?;
4275 self.directory.ownership = old_directory_ownership;
4279 id: ast::DUMMY_NODE_ID,
4280 span: lo.to(i.span),
4281 node: StmtKind::Item(i),
4284 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4285 if !attrs.is_empty() {
4286 if s.prev_token_kind == PrevTokenKind::DocComment {
4287 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4288 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4289 s.span_err(s.span, "expected statement after outer attribute");
4294 // Do not attempt to parse an expression if we're done here.
4295 if self.token == token::Semi {
4296 unused_attrs(&attrs, self);
4301 if self.token == token::CloseDelim(token::Brace) {
4302 unused_attrs(&attrs, self);
4306 // Remainder are line-expr stmts.
4307 let e = self.parse_expr_res(
4308 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4310 id: ast::DUMMY_NODE_ID,
4311 span: lo.to(e.span),
4312 node: StmtKind::Expr(e),
4319 /// Is this expression a successfully-parsed statement?
4320 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4321 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4322 !classify::expr_requires_semi_to_be_stmt(e)
4325 /// Parse a block. No inner attrs are allowed.
4326 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4327 maybe_whole!(self, NtBlock, |x| x);
4331 if !self.eat(&token::OpenDelim(token::Brace)) {
4333 let tok = self.this_token_to_string();
4334 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4336 // Check to see if the user has written something like
4341 // Which is valid in other languages, but not Rust.
4342 match self.parse_stmt_without_recovery(false) {
4344 let mut stmt_span = stmt.span;
4345 // expand the span to include the semicolon, if it exists
4346 if self.eat(&token::Semi) {
4347 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4349 let sugg = pprust::to_string(|s| {
4350 use print::pprust::{PrintState, INDENT_UNIT};
4351 s.ibox(INDENT_UNIT)?;
4353 s.print_stmt(&stmt)?;
4354 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4356 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4359 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4360 self.cancel(&mut e);
4367 self.parse_block_tail(lo, BlockCheckMode::Default)
4370 /// Parse a block. Inner attrs are allowed.
4371 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4372 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4375 self.expect(&token::OpenDelim(token::Brace))?;
4376 Ok((self.parse_inner_attributes()?,
4377 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4380 /// Parse the rest of a block expression or function body
4381 /// Precondition: already parsed the '{'.
4382 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4383 let mut stmts = vec![];
4384 let mut recovered = false;
4386 while !self.eat(&token::CloseDelim(token::Brace)) {
4387 let stmt = match self.parse_full_stmt(false) {
4390 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4391 self.eat(&token::CloseDelim(token::Brace));
4397 if let Some(stmt) = stmt {
4399 } else if self.token == token::Eof {
4402 // Found only `;` or `}`.
4408 id: ast::DUMMY_NODE_ID,
4410 span: lo.to(self.prev_span),
4415 /// Parse a statement, including the trailing semicolon.
4416 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4417 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4419 None => return Ok(None),
4423 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4424 // expression without semicolon
4425 if classify::expr_requires_semi_to_be_stmt(expr) {
4426 // Just check for errors and recover; do not eat semicolon yet.
4428 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4431 self.recover_stmt();
4435 StmtKind::Local(..) => {
4436 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4437 if macro_legacy_warnings && self.token != token::Semi {
4438 self.warn_missing_semicolon();
4440 self.expect_one_of(&[token::Semi], &[])?;
4446 if self.eat(&token::Semi) {
4447 stmt = stmt.add_trailing_semicolon();
4450 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4454 fn warn_missing_semicolon(&self) {
4455 self.diagnostic().struct_span_warn(self.span, {
4456 &format!("expected `;`, found `{}`", self.this_token_to_string())
4458 "This was erroneously allowed and will become a hard error in a future release"
4462 fn err_dotdotdot_syntax(&self, span: Span) {
4463 self.diagnostic().struct_span_err(span, {
4464 "`...` syntax cannot be used in expressions"
4466 "Use `..` if you need an exclusive range (a < b)"
4468 "or `..=` if you need an inclusive range (a <= b)"
4472 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4473 // BOUND = TY_BOUND | LT_BOUND
4474 // LT_BOUND = LIFETIME (e.g. `'a`)
4475 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4476 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4477 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4478 let mut bounds = Vec::new();
4480 // This needs to be syncronized with `Token::can_begin_bound`.
4481 let is_bound_start = self.check_path() || self.check_lifetime() ||
4482 self.check(&token::Question) ||
4483 self.check_keyword(keywords::For) ||
4484 self.check(&token::OpenDelim(token::Paren));
4486 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4487 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4488 if self.token.is_lifetime() {
4489 if let Some(question_span) = question {
4490 self.span_err(question_span,
4491 "`?` may only modify trait bounds, not lifetime bounds");
4493 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4496 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4497 let path = self.parse_path(PathStyle::Type)?;
4498 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4499 let modifier = if question.is_some() {
4500 TraitBoundModifier::Maybe
4502 TraitBoundModifier::None
4504 bounds.push(TraitTyParamBound(poly_trait, modifier));
4507 self.expect(&token::CloseDelim(token::Paren))?;
4508 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4509 self.span_err(self.prev_span,
4510 "parenthesized lifetime bounds are not supported");
4517 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4525 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4526 self.parse_ty_param_bounds_common(true)
4529 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4530 // BOUND = LT_BOUND (e.g. `'a`)
4531 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4532 let mut lifetimes = Vec::new();
4533 while self.check_lifetime() {
4534 lifetimes.push(self.expect_lifetime());
4536 if !self.eat(&token::BinOp(token::Plus)) {
4543 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4544 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4545 let span = self.span;
4546 let ident = self.parse_ident()?;
4548 // Parse optional colon and param bounds.
4549 let bounds = if self.eat(&token::Colon) {
4550 self.parse_ty_param_bounds()?
4555 let default = if self.eat(&token::Eq) {
4556 Some(self.parse_ty()?)
4562 attrs: preceding_attrs.into(),
4564 id: ast::DUMMY_NODE_ID,
4571 /// Parses the following grammar:
4572 /// TraitItemAssocTy = Ident ["<"...">"] [":" [TyParamBounds]] ["where" ...] ["=" Ty]
4573 fn parse_trait_item_assoc_ty(&mut self, preceding_attrs: Vec<Attribute>)
4574 -> PResult<'a, (ast::Generics, TyParam)> {
4575 let span = self.span;
4576 let ident = self.parse_ident()?;
4577 let mut generics = self.parse_generics()?;
4579 // Parse optional colon and param bounds.
4580 let bounds = if self.eat(&token::Colon) {
4581 self.parse_ty_param_bounds()?
4585 generics.where_clause = self.parse_where_clause()?;
4587 let default = if self.eat(&token::Eq) {
4588 Some(self.parse_ty()?)
4592 self.expect(&token::Semi)?;
4594 Ok((generics, TyParam {
4595 attrs: preceding_attrs.into(),
4597 id: ast::DUMMY_NODE_ID,
4604 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4605 /// trailing comma and erroneous trailing attributes.
4606 pub fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4607 let mut params = Vec::new();
4608 let mut seen_ty_param = false;
4610 let attrs = self.parse_outer_attributes()?;
4611 if self.check_lifetime() {
4612 let lifetime = self.expect_lifetime();
4613 // Parse lifetime parameter.
4614 let bounds = if self.eat(&token::Colon) {
4615 self.parse_lt_param_bounds()
4619 params.push(ast::GenericParam::Lifetime(LifetimeDef {
4620 attrs: attrs.into(),
4625 self.span_err(self.prev_span,
4626 "lifetime parameters must be declared prior to type parameters");
4628 } else if self.check_ident() {
4629 // Parse type parameter.
4630 params.push(ast::GenericParam::Type(self.parse_ty_param(attrs)?));
4631 seen_ty_param = true;
4633 // Check for trailing attributes and stop parsing.
4634 if !attrs.is_empty() {
4635 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4636 self.span_err(attrs[0].span,
4637 &format!("trailing attribute after {} parameters", param_kind));
4642 if !self.eat(&token::Comma) {
4649 /// Parse a set of optional generic type parameter declarations. Where
4650 /// clauses are not parsed here, and must be added later via
4651 /// `parse_where_clause()`.
4653 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4654 /// | ( < lifetimes , typaramseq ( , )? > )
4655 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4656 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4657 maybe_whole!(self, NtGenerics, |x| x);
4659 let span_lo = self.span;
4661 let params = self.parse_generic_params()?;
4665 where_clause: WhereClause {
4666 id: ast::DUMMY_NODE_ID,
4667 predicates: Vec::new(),
4668 span: syntax_pos::DUMMY_SP,
4670 span: span_lo.to(self.prev_span),
4673 Ok(ast::Generics::default())
4677 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4678 /// possibly including trailing comma.
4679 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4680 let mut lifetimes = Vec::new();
4681 let mut types = Vec::new();
4682 let mut bindings = Vec::new();
4683 let mut seen_type = false;
4684 let mut seen_binding = false;
4686 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4687 // Parse lifetime argument.
4688 lifetimes.push(self.expect_lifetime());
4689 if seen_type || seen_binding {
4690 self.span_err(self.prev_span,
4691 "lifetime parameters must be declared prior to type parameters");
4693 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4694 // Parse associated type binding.
4696 let ident = self.parse_ident()?;
4698 let ty = self.parse_ty()?;
4699 bindings.push(TypeBinding {
4700 id: ast::DUMMY_NODE_ID,
4703 span: lo.to(self.prev_span),
4705 seen_binding = true;
4706 } else if self.check_type() {
4707 // Parse type argument.
4708 types.push(self.parse_ty()?);
4710 self.span_err(types[types.len() - 1].span,
4711 "type parameters must be declared prior to associated type bindings");
4718 if !self.eat(&token::Comma) {
4722 Ok((lifetimes, types, bindings))
4725 /// Parses an optional `where` clause and places it in `generics`.
4727 /// ```ignore (only-for-syntax-highlight)
4728 /// where T : Trait<U, V> + 'b, 'a : 'b
4730 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4731 maybe_whole!(self, NtWhereClause, |x| x);
4733 let mut where_clause = WhereClause {
4734 id: ast::DUMMY_NODE_ID,
4735 predicates: Vec::new(),
4736 span: syntax_pos::DUMMY_SP,
4739 if !self.eat_keyword(keywords::Where) {
4740 return Ok(where_clause);
4742 let lo = self.prev_span;
4744 // This is a temporary future proofing.
4746 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4747 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4748 // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4749 if token::Lt == self.token {
4750 let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4751 if ident_or_lifetime {
4752 let gt_comma_or_colon = self.look_ahead(2, |t| {
4753 *t == token::Gt || *t == token::Comma || *t == token::Colon
4755 if gt_comma_or_colon {
4756 self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4763 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4764 let lifetime = self.expect_lifetime();
4765 // Bounds starting with a colon are mandatory, but possibly empty.
4766 self.expect(&token::Colon)?;
4767 let bounds = self.parse_lt_param_bounds();
4768 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4769 ast::WhereRegionPredicate {
4770 span: lo.to(self.prev_span),
4775 } else if self.check_type() {
4776 // Parse optional `for<'a, 'b>`.
4777 // This `for` is parsed greedily and applies to the whole predicate,
4778 // the bounded type can have its own `for` applying only to it.
4779 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4780 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4781 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4782 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4784 // Parse type with mandatory colon and (possibly empty) bounds,
4785 // or with mandatory equality sign and the second type.
4786 let ty = self.parse_ty()?;
4787 if self.eat(&token::Colon) {
4788 let bounds = self.parse_ty_param_bounds()?;
4789 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4790 ast::WhereBoundPredicate {
4791 span: lo.to(self.prev_span),
4792 bound_generic_params: lifetime_defs,
4797 // FIXME: Decide what should be used here, `=` or `==`.
4798 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4799 let rhs_ty = self.parse_ty()?;
4800 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4801 ast::WhereEqPredicate {
4802 span: lo.to(self.prev_span),
4805 id: ast::DUMMY_NODE_ID,
4809 return self.unexpected();
4815 if !self.eat(&token::Comma) {
4820 where_clause.span = lo.to(self.prev_span);
4824 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4825 -> PResult<'a, (Vec<Arg> , bool)> {
4827 let mut variadic = false;
4828 let args: Vec<Option<Arg>> =
4829 self.parse_unspanned_seq(
4830 &token::OpenDelim(token::Paren),
4831 &token::CloseDelim(token::Paren),
4832 SeqSep::trailing_allowed(token::Comma),
4834 if p.token == token::DotDotDot {
4837 if p.token != token::CloseDelim(token::Paren) {
4840 "`...` must be last in argument list for variadic function");
4845 "only foreign functions are allowed to be variadic");
4850 match p.parse_arg_general(named_args) {
4851 Ok(arg) => Ok(Some(arg)),
4854 let lo = p.prev_span;
4855 // Skip every token until next possible arg or end.
4856 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4857 // Create a placeholder argument for proper arg count (#34264).
4858 let span = lo.to(p.prev_span);
4859 Ok(Some(dummy_arg(span)))
4866 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4868 if variadic && args.is_empty() {
4870 "variadic function must be declared with at least one named argument");
4873 Ok((args, variadic))
4876 /// Parse the argument list and result type of a function declaration
4877 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4879 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4880 let ret_ty = self.parse_ret_ty()?;
4889 /// Returns the parsed optional self argument and whether a self shortcut was used.
4890 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4891 let expect_ident = |this: &mut Self| match this.token {
4892 // Preserve hygienic context.
4893 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4896 let isolated_self = |this: &mut Self, n| {
4897 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4898 this.look_ahead(n + 1, |t| t != &token::ModSep)
4901 // Parse optional self parameter of a method.
4902 // Only a limited set of initial token sequences is considered self parameters, anything
4903 // else is parsed as a normal function parameter list, so some lookahead is required.
4904 let eself_lo = self.span;
4905 let (eself, eself_ident) = match self.token {
4906 token::BinOp(token::And) => {
4912 if isolated_self(self, 1) {
4914 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4915 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4916 isolated_self(self, 2) {
4919 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4920 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4921 isolated_self(self, 2) {
4923 let lt = self.expect_lifetime();
4924 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4925 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4926 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4927 isolated_self(self, 3) {
4929 let lt = self.expect_lifetime();
4931 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4936 token::BinOp(token::Star) => {
4941 // Emit special error for `self` cases.
4942 if isolated_self(self, 1) {
4944 self.span_err(self.span, "cannot pass `self` by raw pointer");
4945 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4946 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4947 isolated_self(self, 2) {
4950 self.span_err(self.span, "cannot pass `self` by raw pointer");
4951 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4956 token::Ident(..) => {
4957 if isolated_self(self, 0) {
4960 let eself_ident = expect_ident(self);
4961 if self.eat(&token::Colon) {
4962 let ty = self.parse_ty()?;
4963 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4965 (SelfKind::Value(Mutability::Immutable), eself_ident)
4967 } else if self.token.is_keyword(keywords::Mut) &&
4968 isolated_self(self, 1) {
4972 let eself_ident = expect_ident(self);
4973 if self.eat(&token::Colon) {
4974 let ty = self.parse_ty()?;
4975 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4977 (SelfKind::Value(Mutability::Mutable), eself_ident)
4983 _ => return Ok(None),
4986 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
4987 Ok(Some(Arg::from_self(eself, eself_ident)))
4990 /// Parse the parameter list and result type of a function that may have a `self` parameter.
4991 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
4992 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4994 self.expect(&token::OpenDelim(token::Paren))?;
4996 // Parse optional self argument
4997 let self_arg = self.parse_self_arg()?;
4999 // Parse the rest of the function parameter list.
5000 let sep = SeqSep::trailing_allowed(token::Comma);
5001 let fn_inputs = if let Some(self_arg) = self_arg {
5002 if self.check(&token::CloseDelim(token::Paren)) {
5004 } else if self.eat(&token::Comma) {
5005 let mut fn_inputs = vec![self_arg];
5006 fn_inputs.append(&mut self.parse_seq_to_before_end(
5007 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5011 return self.unexpected();
5014 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5017 // Parse closing paren and return type.
5018 self.expect(&token::CloseDelim(token::Paren))?;
5021 output: self.parse_ret_ty()?,
5026 // parse the |arg, arg| header on a lambda
5027 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5028 let inputs_captures = {
5029 if self.eat(&token::OrOr) {
5032 self.expect(&token::BinOp(token::Or))?;
5033 let args = self.parse_seq_to_before_tokens(
5034 &[&token::BinOp(token::Or), &token::OrOr],
5035 SeqSep::trailing_allowed(token::Comma),
5036 TokenExpectType::NoExpect,
5037 |p| p.parse_fn_block_arg()
5043 let output = self.parse_ret_ty()?;
5046 inputs: inputs_captures,
5052 /// Parse the name and optional generic types of a function header.
5053 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5054 let id = self.parse_ident()?;
5055 let generics = self.parse_generics()?;
5059 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5060 attrs: Vec<Attribute>) -> P<Item> {
5064 id: ast::DUMMY_NODE_ID,
5072 /// Parse an item-position function declaration.
5073 fn parse_item_fn(&mut self,
5075 constness: Spanned<Constness>,
5077 -> PResult<'a, ItemInfo> {
5078 let (ident, mut generics) = self.parse_fn_header()?;
5079 let decl = self.parse_fn_decl(false)?;
5080 generics.where_clause = self.parse_where_clause()?;
5081 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5082 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
5085 /// true if we are looking at `const ID`, false for things like `const fn` etc
5086 pub fn is_const_item(&mut self) -> bool {
5087 self.token.is_keyword(keywords::Const) &&
5088 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5089 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5092 /// parses all the "front matter" for a `fn` declaration, up to
5093 /// and including the `fn` keyword:
5097 /// - `const unsafe fn`
5100 pub fn parse_fn_front_matter(&mut self)
5101 -> PResult<'a, (Spanned<ast::Constness>,
5104 let is_const_fn = self.eat_keyword(keywords::Const);
5105 let const_span = self.prev_span;
5106 let unsafety = self.parse_unsafety()?;
5107 let (constness, unsafety, abi) = if is_const_fn {
5108 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5110 let abi = if self.eat_keyword(keywords::Extern) {
5111 self.parse_opt_abi()?.unwrap_or(Abi::C)
5115 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5117 self.expect_keyword(keywords::Fn)?;
5118 Ok((constness, unsafety, abi))
5121 /// Parse an impl item.
5122 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5123 maybe_whole!(self, NtImplItem, |x| x);
5124 let attrs = self.parse_outer_attributes()?;
5125 let (mut item, tokens) = self.collect_tokens(|this| {
5126 this.parse_impl_item_(at_end, attrs)
5129 // See `parse_item` for why this clause is here.
5130 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5131 item.tokens = Some(tokens);
5136 fn parse_impl_item_(&mut self,
5138 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5140 let vis = self.parse_visibility(false)?;
5141 let defaultness = self.parse_defaultness()?;
5142 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
5143 // This parses the grammar:
5144 // ImplItemAssocTy = Ident ["<"...">"] ["where" ...] "=" Ty ";"
5145 let name = self.parse_ident()?;
5146 let mut generics = self.parse_generics()?;
5147 generics.where_clause = self.parse_where_clause()?;
5148 self.expect(&token::Eq)?;
5149 let typ = self.parse_ty()?;
5150 self.expect(&token::Semi)?;
5151 (name, ast::ImplItemKind::Type(typ), generics)
5152 } else if self.is_const_item() {
5153 // This parses the grammar:
5154 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5155 self.expect_keyword(keywords::Const)?;
5156 let name = self.parse_ident()?;
5157 self.expect(&token::Colon)?;
5158 let typ = self.parse_ty()?;
5159 self.expect(&token::Eq)?;
5160 let expr = self.parse_expr()?;
5161 self.expect(&token::Semi)?;
5162 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5164 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5165 attrs.extend(inner_attrs);
5166 (name, node, generics)
5170 id: ast::DUMMY_NODE_ID,
5171 span: lo.to(self.prev_span),
5182 fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
5183 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5188 fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
5190 Visibility::Inherited => Ok(()),
5192 let is_macro_rules: bool = match self.token {
5193 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
5197 let mut err = self.diagnostic()
5198 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5199 err.help("did you mean #[macro_export]?");
5202 let mut err = self.diagnostic()
5203 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5204 err.help("try adjusting the macro to put `pub` inside the invocation");
5211 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5212 -> DiagnosticBuilder<'a>
5214 // Given this code `path(`, it seems like this is not
5215 // setting the visibility of a macro invocation, but rather
5216 // a mistyped method declaration.
5217 // Create a diagnostic pointing out that `fn` is missing.
5219 // x | pub path(&self) {
5220 // | ^ missing `fn`, `type`, or `const`
5222 // ^^ `sp` below will point to this
5223 let sp = prev_span.between(self.prev_span);
5224 let mut err = self.diagnostic().struct_span_err(
5226 &format!("missing `fn`, `type`, or `const` for {}-item declaration",
5228 err.span_label(sp, "missing `fn`, `type`, or `const`");
5232 /// Parse a method or a macro invocation in a trait impl.
5233 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5234 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::Generics,
5235 ast::ImplItemKind)> {
5236 // code copied from parse_macro_use_or_failure... abstraction!
5237 if self.token.is_path_start() {
5240 let prev_span = self.prev_span;
5243 let pth = self.parse_path(PathStyle::Mod)?;
5244 if pth.segments.len() == 1 {
5245 if !self.eat(&token::Not) {
5246 return Err(self.missing_assoc_item_kind_err("impl", prev_span));
5249 self.expect(&token::Not)?;
5252 self.complain_if_pub_macro(vis, prev_span);
5254 // eat a matched-delimiter token tree:
5256 let (delim, tts) = self.expect_delimited_token_tree()?;
5257 if delim != token::Brace {
5258 self.expect(&token::Semi)?
5261 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
5262 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5263 ast::ImplItemKind::Macro(mac)))
5265 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
5266 let ident = self.parse_ident()?;
5267 let mut generics = self.parse_generics()?;
5268 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5269 generics.where_clause = self.parse_where_clause()?;
5271 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5272 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(ast::MethodSig {
5281 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5282 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5283 let ident = self.parse_ident()?;
5284 let mut tps = self.parse_generics()?;
5286 // Parse optional colon and supertrait bounds.
5287 let bounds = if self.eat(&token::Colon) {
5288 self.parse_ty_param_bounds()?
5293 if self.eat(&token::Eq) {
5294 // it's a trait alias
5295 let bounds = self.parse_ty_param_bounds()?;
5296 tps.where_clause = self.parse_where_clause()?;
5297 self.expect(&token::Semi)?;
5298 if unsafety != Unsafety::Normal {
5299 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5301 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5303 // it's a normal trait
5304 tps.where_clause = self.parse_where_clause()?;
5305 self.expect(&token::OpenDelim(token::Brace))?;
5306 let mut trait_items = vec![];
5307 while !self.eat(&token::CloseDelim(token::Brace)) {
5308 let mut at_end = false;
5309 match self.parse_trait_item(&mut at_end) {
5310 Ok(item) => trait_items.push(item),
5314 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5319 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5323 /// Parses items implementations variants
5324 /// impl<T> Foo { ... }
5325 /// impl<T> ToString for &'static T { ... }
5326 /// impl Send for .. {}
5327 fn parse_item_impl(&mut self,
5328 unsafety: ast::Unsafety,
5329 defaultness: Defaultness) -> PResult<'a, ItemInfo> {
5330 let impl_span = self.span;
5332 // First, parse type parameters if necessary.
5333 let mut generics = self.parse_generics()?;
5335 // Special case: if the next identifier that follows is '(', don't
5336 // allow this to be parsed as a trait.
5337 let could_be_trait = self.token != token::OpenDelim(token::Paren);
5339 let neg_span = self.span;
5340 let polarity = if self.eat(&token::Not) {
5341 ast::ImplPolarity::Negative
5343 ast::ImplPolarity::Positive
5347 let mut ty = self.parse_ty()?;
5349 // Parse traits, if necessary.
5350 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
5351 // New-style trait. Reinterpret the type as a trait.
5353 TyKind::Path(None, ref path) => {
5355 path: (*path).clone(),
5360 self.span_err(ty.span, "not a trait");
5365 if polarity == ast::ImplPolarity::Negative {
5366 // This is a negated type implementation
5367 // `impl !MyType {}`, which is not allowed.
5368 self.span_err(neg_span, "inherent implementation can't be negated");
5373 if opt_trait.is_some() && self.eat(&token::DotDot) {
5374 if generics.is_parameterized() {
5375 self.span_err(impl_span, "auto trait implementations are not \
5376 allowed to have generics");
5379 if let ast::Defaultness::Default = defaultness {
5380 self.span_err(impl_span, "`default impl` is not allowed for \
5381 auto trait implementations");
5384 self.expect(&token::OpenDelim(token::Brace))?;
5385 self.expect(&token::CloseDelim(token::Brace))?;
5386 Ok((keywords::Invalid.ident(),
5387 ItemKind::AutoImpl(unsafety, opt_trait.unwrap()), None))
5389 if opt_trait.is_some() {
5390 ty = self.parse_ty()?;
5392 generics.where_clause = self.parse_where_clause()?;
5394 self.expect(&token::OpenDelim(token::Brace))?;
5395 let attrs = self.parse_inner_attributes()?;
5397 let mut impl_items = vec![];
5398 while !self.eat(&token::CloseDelim(token::Brace)) {
5399 let mut at_end = false;
5400 match self.parse_impl_item(&mut at_end) {
5401 Ok(item) => impl_items.push(item),
5405 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5411 Ok((keywords::Invalid.ident(),
5412 ItemKind::Impl(unsafety, polarity, defaultness, generics, opt_trait, ty, impl_items),
5417 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5418 if self.eat_keyword(keywords::For) {
5420 let params = self.parse_generic_params()?;
5423 let first_non_lifetime_param_span = params.iter()
5424 .filter_map(|param| match *param {
5425 ast::GenericParam::Lifetime(_) => None,
5426 ast::GenericParam::Type(ref t) => Some(t.span),
5430 if let Some(span) = first_non_lifetime_param_span {
5431 self.span_err(span, "only lifetime parameters can be used in this context");
5440 /// Parse struct Foo { ... }
5441 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5442 let class_name = self.parse_ident()?;
5444 let mut generics = self.parse_generics()?;
5446 // There is a special case worth noting here, as reported in issue #17904.
5447 // If we are parsing a tuple struct it is the case that the where clause
5448 // should follow the field list. Like so:
5450 // struct Foo<T>(T) where T: Copy;
5452 // If we are parsing a normal record-style struct it is the case
5453 // that the where clause comes before the body, and after the generics.
5454 // So if we look ahead and see a brace or a where-clause we begin
5455 // parsing a record style struct.
5457 // Otherwise if we look ahead and see a paren we parse a tuple-style
5460 let vdata = if self.token.is_keyword(keywords::Where) {
5461 generics.where_clause = self.parse_where_clause()?;
5462 if self.eat(&token::Semi) {
5463 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5464 VariantData::Unit(ast::DUMMY_NODE_ID)
5466 // If we see: `struct Foo<T> where T: Copy { ... }`
5467 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5469 // No `where` so: `struct Foo<T>;`
5470 } else if self.eat(&token::Semi) {
5471 VariantData::Unit(ast::DUMMY_NODE_ID)
5472 // Record-style struct definition
5473 } else if self.token == token::OpenDelim(token::Brace) {
5474 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5475 // Tuple-style struct definition with optional where-clause.
5476 } else if self.token == token::OpenDelim(token::Paren) {
5477 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5478 generics.where_clause = self.parse_where_clause()?;
5479 self.expect(&token::Semi)?;
5482 let token_str = self.this_token_to_string();
5483 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5484 name, found `{}`", token_str)))
5487 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5490 /// Parse union Foo { ... }
5491 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5492 let class_name = self.parse_ident()?;
5494 let mut generics = self.parse_generics()?;
5496 let vdata = if self.token.is_keyword(keywords::Where) {
5497 generics.where_clause = self.parse_where_clause()?;
5498 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5499 } else if self.token == token::OpenDelim(token::Brace) {
5500 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5502 let token_str = self.this_token_to_string();
5503 return Err(self.fatal(&format!("expected `where` or `{{` after union \
5504 name, found `{}`", token_str)))
5507 Ok((class_name, ItemKind::Union(vdata, generics), None))
5510 fn consume_block(&mut self, delim: token::DelimToken) {
5511 let mut brace_depth = 0;
5512 if !self.eat(&token::OpenDelim(delim)) {
5516 if self.eat(&token::OpenDelim(delim)) {
5518 } else if self.eat(&token::CloseDelim(delim)) {
5519 if brace_depth == 0 {
5525 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5533 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5534 let mut fields = Vec::new();
5535 if self.eat(&token::OpenDelim(token::Brace)) {
5536 while self.token != token::CloseDelim(token::Brace) {
5537 let field = self.parse_struct_decl_field().map_err(|e| {
5538 self.recover_stmt();
5542 Ok(field) => fields.push(field),
5548 self.eat(&token::CloseDelim(token::Brace));
5550 let token_str = self.this_token_to_string();
5551 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5559 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5560 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5561 // Unit like structs are handled in parse_item_struct function
5562 let fields = self.parse_unspanned_seq(
5563 &token::OpenDelim(token::Paren),
5564 &token::CloseDelim(token::Paren),
5565 SeqSep::trailing_allowed(token::Comma),
5567 let attrs = p.parse_outer_attributes()?;
5569 let vis = p.parse_visibility(true)?;
5570 let ty = p.parse_ty()?;
5572 span: lo.to(p.span),
5575 id: ast::DUMMY_NODE_ID,
5584 /// Parse a structure field declaration
5585 pub fn parse_single_struct_field(&mut self,
5588 attrs: Vec<Attribute> )
5589 -> PResult<'a, StructField> {
5590 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5595 token::CloseDelim(token::Brace) => {}
5596 token::DocComment(_) => {
5597 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
5598 self.bump(); // consume the doc comment
5599 if self.eat(&token::Comma) || self.token == token::CloseDelim(token::Brace) {
5605 _ => return Err(self.span_fatal_help(self.span,
5606 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5607 "struct fields should be separated by commas")),
5612 /// Parse an element of a struct definition
5613 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5614 let attrs = self.parse_outer_attributes()?;
5616 let vis = self.parse_visibility(false)?;
5617 self.parse_single_struct_field(lo, vis, attrs)
5620 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5621 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5622 /// a function definition, it's not a tuple struct field) and the contents within the parens
5623 /// isn't valid, emit a proper diagnostic.
5624 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5625 maybe_whole!(self, NtVis, |x| x);
5627 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
5628 if self.is_crate_vis() {
5629 self.bump(); // `crate`
5630 return Ok(Visibility::Crate(self.prev_span, CrateSugar::JustCrate));
5633 if !self.eat_keyword(keywords::Pub) {
5634 return Ok(Visibility::Inherited)
5637 if self.check(&token::OpenDelim(token::Paren)) {
5638 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5639 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5640 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5641 // by the following tokens.
5642 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5645 self.bump(); // `crate`
5646 let vis = Visibility::Crate(self.prev_span, CrateSugar::PubCrate);
5647 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5649 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5652 self.bump(); // `in`
5653 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5654 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5655 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5657 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5658 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5659 t.is_keyword(keywords::SelfValue)) {
5660 // `pub(self)` or `pub(super)`
5662 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5663 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5664 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5666 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5667 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5669 let msg = "incorrect visibility restriction";
5670 let suggestion = r##"some possible visibility restrictions are:
5671 `pub(crate)`: visible only on the current crate
5672 `pub(super)`: visible only in the current module's parent
5673 `pub(in path::to::module)`: visible only on the specified path"##;
5674 let path = self.parse_path(PathStyle::Mod)?;
5675 let path_span = self.prev_span;
5676 let help_msg = format!("make this visible only to module `{}` with `in`", path);
5677 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5678 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5679 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5680 err.emit(); // emit diagnostic, but continue with public visibility
5684 Ok(Visibility::Public)
5687 /// Parse defaultness: DEFAULT or nothing
5688 fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5689 if self.eat_defaultness() {
5690 Ok(Defaultness::Default)
5692 Ok(Defaultness::Final)
5696 /// Given a termination token, parse all of the items in a module
5697 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5698 let mut items = vec![];
5699 while let Some(item) = self.parse_item()? {
5703 if !self.eat(term) {
5704 let token_str = self.this_token_to_string();
5705 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
5706 let msg = "consider removing this semicolon";
5707 if token_str == ";" {
5708 err.span_suggestion_short(self.span, msg, "".to_string());
5713 let hi = if self.span == syntax_pos::DUMMY_SP {
5720 inner: inner_lo.to(hi),
5725 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5726 let id = self.parse_ident()?;
5727 self.expect(&token::Colon)?;
5728 let ty = self.parse_ty()?;
5729 self.expect(&token::Eq)?;
5730 let e = self.parse_expr()?;
5731 self.expect(&token::Semi)?;
5732 let item = match m {
5733 Some(m) => ItemKind::Static(ty, m, e),
5734 None => ItemKind::Const(ty, e),
5736 Ok((id, item, None))
5739 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5740 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5741 let (in_cfg, outer_attrs) = {
5742 let mut strip_unconfigured = ::config::StripUnconfigured {
5744 should_test: false, // irrelevant
5745 features: None, // don't perform gated feature checking
5747 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5748 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5751 let id_span = self.span;
5752 let id = self.parse_ident()?;
5753 if self.check(&token::Semi) {
5755 if in_cfg && self.recurse_into_file_modules {
5756 // This mod is in an external file. Let's go get it!
5757 let ModulePathSuccess { path, directory_ownership, warn } =
5758 self.submod_path(id, &outer_attrs, id_span)?;
5759 let (module, mut attrs) =
5760 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5762 let attr = ast::Attribute {
5763 id: attr::mk_attr_id(),
5764 style: ast::AttrStyle::Outer,
5765 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5766 Ident::from_str("warn_directory_ownership")),
5767 tokens: TokenStream::empty(),
5768 is_sugared_doc: false,
5769 span: syntax_pos::DUMMY_SP,
5771 attr::mark_known(&attr);
5774 Ok((id, module, Some(attrs)))
5776 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5777 Ok((id, ItemKind::Mod(placeholder), None))
5780 let old_directory = self.directory.clone();
5781 self.push_directory(id, &outer_attrs);
5783 self.expect(&token::OpenDelim(token::Brace))?;
5784 let mod_inner_lo = self.span;
5785 let attrs = self.parse_inner_attributes()?;
5786 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5788 self.directory = old_directory;
5789 Ok((id, ItemKind::Mod(module), Some(attrs)))
5793 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5794 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5795 self.directory.path.push(&path.as_str());
5796 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
5798 self.directory.path.push(&id.name.as_str());
5802 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5803 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5806 /// Returns either a path to a module, or .
5807 pub fn default_submod_path(
5809 relative: Option<ast::Ident>,
5811 codemap: &CodeMap) -> ModulePath
5813 // If we're in a foo.rs file instead of a mod.rs file,
5814 // we need to look for submodules in
5815 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
5816 // `./<id>.rs` and `./<id>/mod.rs`.
5817 let relative_prefix_string;
5818 let relative_prefix = if let Some(ident) = relative {
5819 relative_prefix_string = format!("{}{}", ident.name.as_str(), path::MAIN_SEPARATOR);
5820 &relative_prefix_string
5825 let mod_name = id.to_string();
5826 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
5827 let secondary_path_str = format!("{}{}{}mod.rs",
5828 relative_prefix, mod_name, path::MAIN_SEPARATOR);
5829 let default_path = dir_path.join(&default_path_str);
5830 let secondary_path = dir_path.join(&secondary_path_str);
5831 let default_exists = codemap.file_exists(&default_path);
5832 let secondary_exists = codemap.file_exists(&secondary_path);
5834 let result = match (default_exists, secondary_exists) {
5835 (true, false) => Ok(ModulePathSuccess {
5837 directory_ownership: DirectoryOwnership::Owned {
5842 (false, true) => Ok(ModulePathSuccess {
5843 path: secondary_path,
5844 directory_ownership: DirectoryOwnership::Owned {
5849 (false, false) => Err(Error::FileNotFoundForModule {
5850 mod_name: mod_name.clone(),
5851 default_path: default_path_str,
5852 secondary_path: secondary_path_str,
5853 dir_path: format!("{}", dir_path.display()),
5855 (true, true) => Err(Error::DuplicatePaths {
5856 mod_name: mod_name.clone(),
5857 default_path: default_path_str,
5858 secondary_path: secondary_path_str,
5864 path_exists: default_exists || secondary_exists,
5869 fn submod_path(&mut self,
5871 outer_attrs: &[ast::Attribute],
5873 -> PResult<'a, ModulePathSuccess> {
5874 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5875 return Ok(ModulePathSuccess {
5876 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5877 Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
5879 DirectoryOwnership::Owned { relative: Some(id) }
5881 _ => DirectoryOwnership::UnownedViaMod(true),
5888 let relative = match self.directory.ownership {
5889 DirectoryOwnership::Owned { relative } => {
5890 // Push the usage onto the list of non-mod.rs mod uses.
5891 // This is used later for feature-gate error reporting.
5892 if let Some(cur_file_ident) = relative {
5894 .non_modrs_mods.borrow_mut()
5895 .push((cur_file_ident, id_sp));
5899 DirectoryOwnership::UnownedViaBlock |
5900 DirectoryOwnership::UnownedViaMod(_) => None,
5902 let paths = Parser::default_submod_path(
5903 id, relative, &self.directory.path, self.sess.codemap());
5905 match self.directory.ownership {
5906 DirectoryOwnership::Owned { .. } => {
5907 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5909 DirectoryOwnership::UnownedViaBlock => {
5911 "Cannot declare a non-inline module inside a block \
5912 unless it has a path attribute";
5913 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5914 if paths.path_exists {
5915 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5917 err.span_note(id_sp, &msg);
5921 DirectoryOwnership::UnownedViaMod(warn) => {
5923 if let Ok(result) = paths.result {
5924 return Ok(ModulePathSuccess { warn: true, ..result });
5927 let mut err = self.diagnostic().struct_span_err(id_sp,
5928 "cannot declare a new module at this location");
5929 if id_sp != syntax_pos::DUMMY_SP {
5930 let src_path = self.sess.codemap().span_to_filename(id_sp);
5931 if let FileName::Real(src_path) = src_path {
5932 if let Some(stem) = src_path.file_stem() {
5933 let mut dest_path = src_path.clone();
5934 dest_path.set_file_name(stem);
5935 dest_path.push("mod.rs");
5936 err.span_note(id_sp,
5937 &format!("maybe move this module `{}` to its own \
5938 directory via `{}`", src_path.display(),
5939 dest_path.display()));
5943 if paths.path_exists {
5944 err.span_note(id_sp,
5945 &format!("... or maybe `use` the module `{}` instead \
5946 of possibly redeclaring it",
5954 /// Read a module from a source file.
5955 fn eval_src_mod(&mut self,
5957 directory_ownership: DirectoryOwnership,
5960 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5961 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5962 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5963 let mut err = String::from("circular modules: ");
5964 let len = included_mod_stack.len();
5965 for p in &included_mod_stack[i.. len] {
5966 err.push_str(&p.to_string_lossy());
5967 err.push_str(" -> ");
5969 err.push_str(&path.to_string_lossy());
5970 return Err(self.span_fatal(id_sp, &err[..]));
5972 included_mod_stack.push(path.clone());
5973 drop(included_mod_stack);
5976 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5977 p0.cfg_mods = self.cfg_mods;
5978 let mod_inner_lo = p0.span;
5979 let mod_attrs = p0.parse_inner_attributes()?;
5980 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5981 self.sess.included_mod_stack.borrow_mut().pop();
5982 Ok((ast::ItemKind::Mod(m0), mod_attrs))
5985 /// Parse a function declaration from a foreign module
5986 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5987 -> PResult<'a, ForeignItem> {
5988 self.expect_keyword(keywords::Fn)?;
5990 let (ident, mut generics) = self.parse_fn_header()?;
5991 let decl = self.parse_fn_decl(true)?;
5992 generics.where_clause = self.parse_where_clause()?;
5994 self.expect(&token::Semi)?;
5995 Ok(ast::ForeignItem {
5998 node: ForeignItemKind::Fn(decl, generics),
5999 id: ast::DUMMY_NODE_ID,
6005 /// Parse a static item from a foreign module.
6006 /// Assumes that the `static` keyword is already parsed.
6007 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6008 -> PResult<'a, ForeignItem> {
6009 let mutbl = self.eat_keyword(keywords::Mut);
6010 let ident = self.parse_ident()?;
6011 self.expect(&token::Colon)?;
6012 let ty = self.parse_ty()?;
6014 self.expect(&token::Semi)?;
6018 node: ForeignItemKind::Static(ty, mutbl),
6019 id: ast::DUMMY_NODE_ID,
6025 /// Parse a type from a foreign module
6026 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6027 -> PResult<'a, ForeignItem> {
6028 self.expect_keyword(keywords::Type)?;
6030 let ident = self.parse_ident()?;
6032 self.expect(&token::Semi)?;
6033 Ok(ast::ForeignItem {
6036 node: ForeignItemKind::Ty,
6037 id: ast::DUMMY_NODE_ID,
6043 /// Parse extern crate links
6047 /// extern crate foo;
6048 /// extern crate bar as foo;
6049 fn parse_item_extern_crate(&mut self,
6051 visibility: Visibility,
6052 attrs: Vec<Attribute>)
6053 -> PResult<'a, P<Item>> {
6055 let crate_name = self.parse_ident()?;
6056 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
6057 (Some(crate_name.name), ident)
6061 self.expect(&token::Semi)?;
6063 let prev_span = self.prev_span;
6064 Ok(self.mk_item(lo.to(prev_span),
6066 ItemKind::ExternCrate(maybe_path),
6071 /// Parse `extern` for foreign ABIs
6074 /// `extern` is expected to have been
6075 /// consumed before calling this method
6081 fn parse_item_foreign_mod(&mut self,
6083 opt_abi: Option<abi::Abi>,
6084 visibility: Visibility,
6085 mut attrs: Vec<Attribute>)
6086 -> PResult<'a, P<Item>> {
6087 self.expect(&token::OpenDelim(token::Brace))?;
6089 let abi = opt_abi.unwrap_or(Abi::C);
6091 attrs.extend(self.parse_inner_attributes()?);
6093 let mut foreign_items = vec![];
6094 while let Some(item) = self.parse_foreign_item()? {
6095 foreign_items.push(item);
6097 self.expect(&token::CloseDelim(token::Brace))?;
6099 let prev_span = self.prev_span;
6100 let m = ast::ForeignMod {
6102 items: foreign_items
6104 let invalid = keywords::Invalid.ident();
6105 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6108 /// Parse type Foo = Bar;
6109 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
6110 let ident = self.parse_ident()?;
6111 let mut tps = self.parse_generics()?;
6112 tps.where_clause = self.parse_where_clause()?;
6113 self.expect(&token::Eq)?;
6114 let ty = self.parse_ty()?;
6115 self.expect(&token::Semi)?;
6116 Ok((ident, ItemKind::Ty(ty, tps), None))
6119 /// Parse the part of an "enum" decl following the '{'
6120 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6121 let mut variants = Vec::new();
6122 let mut all_nullary = true;
6123 let mut any_disr = None;
6124 while self.token != token::CloseDelim(token::Brace) {
6125 let variant_attrs = self.parse_outer_attributes()?;
6126 let vlo = self.span;
6129 let mut disr_expr = None;
6130 let ident = self.parse_ident()?;
6131 if self.check(&token::OpenDelim(token::Brace)) {
6132 // Parse a struct variant.
6133 all_nullary = false;
6134 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6135 ast::DUMMY_NODE_ID);
6136 } else if self.check(&token::OpenDelim(token::Paren)) {
6137 all_nullary = false;
6138 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6139 ast::DUMMY_NODE_ID);
6140 } else if self.eat(&token::Eq) {
6141 disr_expr = Some(self.parse_expr()?);
6142 any_disr = disr_expr.as_ref().map(|expr| expr.span);
6143 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6145 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6148 let vr = ast::Variant_ {
6150 attrs: variant_attrs,
6154 variants.push(respan(vlo.to(self.prev_span), vr));
6156 if !self.eat(&token::Comma) { break; }
6158 self.expect(&token::CloseDelim(token::Brace))?;
6160 Some(disr_span) if !all_nullary =>
6161 self.span_err(disr_span,
6162 "discriminator values can only be used with a field-less enum"),
6166 Ok(ast::EnumDef { variants: variants })
6169 /// Parse an "enum" declaration
6170 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6171 let id = self.parse_ident()?;
6172 let mut generics = self.parse_generics()?;
6173 generics.where_clause = self.parse_where_clause()?;
6174 self.expect(&token::OpenDelim(token::Brace))?;
6176 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6177 self.recover_stmt();
6178 self.eat(&token::CloseDelim(token::Brace));
6181 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6184 /// Parses a string as an ABI spec on an extern type or module. Consumes
6185 /// the `extern` keyword, if one is found.
6186 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
6188 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6190 self.expect_no_suffix(sp, "ABI spec", suf);
6192 match abi::lookup(&s.as_str()) {
6193 Some(abi) => Ok(Some(abi)),
6195 let prev_span = self.prev_span;
6198 &format!("invalid ABI: expected one of [{}], \
6200 abi::all_names().join(", "),
6211 /// Parse one of the items allowed by the flags.
6212 /// NB: this function no longer parses the items inside an
6214 fn parse_item_(&mut self, attrs: Vec<Attribute>,
6215 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
6216 maybe_whole!(self, NtItem, |item| {
6217 let mut item = item.into_inner();
6218 let mut attrs = attrs;
6219 mem::swap(&mut item.attrs, &mut attrs);
6220 item.attrs.extend(attrs);
6226 let visibility = self.parse_visibility(false)?;
6228 if self.eat_keyword(keywords::Use) {
6230 let item_ = ItemKind::Use(P(self.parse_use_tree(false)?));
6231 self.expect(&token::Semi)?;
6233 let prev_span = self.prev_span;
6234 let invalid = keywords::Invalid.ident();
6235 let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
6236 return Ok(Some(item));
6239 if self.eat_keyword(keywords::Extern) {
6240 if self.eat_keyword(keywords::Crate) {
6241 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6244 let opt_abi = self.parse_opt_abi()?;
6246 if self.eat_keyword(keywords::Fn) {
6247 // EXTERN FUNCTION ITEM
6248 let fn_span = self.prev_span;
6249 let abi = opt_abi.unwrap_or(Abi::C);
6250 let (ident, item_, extra_attrs) =
6251 self.parse_item_fn(Unsafety::Normal,
6252 respan(fn_span, Constness::NotConst),
6254 let prev_span = self.prev_span;
6255 let item = self.mk_item(lo.to(prev_span),
6259 maybe_append(attrs, extra_attrs));
6260 return Ok(Some(item));
6261 } else if self.check(&token::OpenDelim(token::Brace)) {
6262 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6268 if self.eat_keyword(keywords::Static) {
6270 let m = if self.eat_keyword(keywords::Mut) {
6273 Mutability::Immutable
6275 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6276 let prev_span = self.prev_span;
6277 let item = self.mk_item(lo.to(prev_span),
6281 maybe_append(attrs, extra_attrs));
6282 return Ok(Some(item));
6284 if self.eat_keyword(keywords::Const) {
6285 let const_span = self.prev_span;
6286 if self.check_keyword(keywords::Fn)
6287 || (self.check_keyword(keywords::Unsafe)
6288 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6289 // CONST FUNCTION ITEM
6290 let unsafety = if self.eat_keyword(keywords::Unsafe) {
6296 let (ident, item_, extra_attrs) =
6297 self.parse_item_fn(unsafety,
6298 respan(const_span, Constness::Const),
6300 let prev_span = self.prev_span;
6301 let item = self.mk_item(lo.to(prev_span),
6305 maybe_append(attrs, extra_attrs));
6306 return Ok(Some(item));
6310 if self.eat_keyword(keywords::Mut) {
6311 let prev_span = self.prev_span;
6312 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6313 .help("did you mean to declare a static?")
6316 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6317 let prev_span = self.prev_span;
6318 let item = self.mk_item(lo.to(prev_span),
6322 maybe_append(attrs, extra_attrs));
6323 return Ok(Some(item));
6325 if self.check_keyword(keywords::Unsafe) &&
6326 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
6327 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
6329 // UNSAFE TRAIT ITEM
6330 self.expect_keyword(keywords::Unsafe)?;
6331 let is_auto = if self.eat_keyword(keywords::Trait) {
6334 self.eat_auto_trait();
6337 let (ident, item_, extra_attrs) =
6338 self.parse_item_trait(is_auto, ast::Unsafety::Unsafe)?;
6339 let prev_span = self.prev_span;
6340 let item = self.mk_item(lo.to(prev_span),
6344 maybe_append(attrs, extra_attrs));
6345 return Ok(Some(item));
6347 if (self.check_keyword(keywords::Unsafe) &&
6348 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))) ||
6349 (self.check_keyword(keywords::Default) &&
6350 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) &&
6351 self.look_ahead(2, |t| t.is_keyword(keywords::Impl)))
6354 let defaultness = self.parse_defaultness()?;
6355 self.expect_keyword(keywords::Unsafe)?;
6356 self.expect_keyword(keywords::Impl)?;
6359 extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe, defaultness)?;
6360 let prev_span = self.prev_span;
6361 let item = self.mk_item(lo.to(prev_span),
6365 maybe_append(attrs, extra_attrs));
6366 return Ok(Some(item));
6368 if self.check_keyword(keywords::Fn) {
6371 let fn_span = self.prev_span;
6372 let (ident, item_, extra_attrs) =
6373 self.parse_item_fn(Unsafety::Normal,
6374 respan(fn_span, Constness::NotConst),
6376 let prev_span = self.prev_span;
6377 let item = self.mk_item(lo.to(prev_span),
6381 maybe_append(attrs, extra_attrs));
6382 return Ok(Some(item));
6384 if self.check_keyword(keywords::Unsafe)
6385 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
6386 // UNSAFE FUNCTION ITEM
6388 let abi = if self.eat_keyword(keywords::Extern) {
6389 self.parse_opt_abi()?.unwrap_or(Abi::C)
6393 self.expect_keyword(keywords::Fn)?;
6394 let fn_span = self.prev_span;
6395 let (ident, item_, extra_attrs) =
6396 self.parse_item_fn(Unsafety::Unsafe,
6397 respan(fn_span, Constness::NotConst),
6399 let prev_span = self.prev_span;
6400 let item = self.mk_item(lo.to(prev_span),
6404 maybe_append(attrs, extra_attrs));
6405 return Ok(Some(item));
6407 if self.eat_keyword(keywords::Mod) {
6409 let (ident, item_, extra_attrs) =
6410 self.parse_item_mod(&attrs[..])?;
6411 let prev_span = self.prev_span;
6412 let item = self.mk_item(lo.to(prev_span),
6416 maybe_append(attrs, extra_attrs));
6417 return Ok(Some(item));
6419 if self.eat_keyword(keywords::Type) {
6421 let (ident, item_, extra_attrs) = self.parse_item_type()?;
6422 let prev_span = self.prev_span;
6423 let item = self.mk_item(lo.to(prev_span),
6427 maybe_append(attrs, extra_attrs));
6428 return Ok(Some(item));
6430 if self.eat_keyword(keywords::Enum) {
6432 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
6433 let prev_span = self.prev_span;
6434 let item = self.mk_item(lo.to(prev_span),
6438 maybe_append(attrs, extra_attrs));
6439 return Ok(Some(item));
6441 if self.check_keyword(keywords::Trait)
6442 || (self.check_keyword(keywords::Auto)
6443 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
6445 let is_auto = if self.eat_keyword(keywords::Trait) {
6448 self.eat_auto_trait();
6452 let (ident, item_, extra_attrs) =
6453 self.parse_item_trait(is_auto, ast::Unsafety::Normal)?;
6454 let prev_span = self.prev_span;
6455 let item = self.mk_item(lo.to(prev_span),
6459 maybe_append(attrs, extra_attrs));
6460 return Ok(Some(item));
6462 if (self.check_keyword(keywords::Impl)) ||
6463 (self.check_keyword(keywords::Default) &&
6464 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)))
6467 let defaultness = self.parse_defaultness()?;
6468 self.expect_keyword(keywords::Impl)?;
6471 extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal, defaultness)?;
6472 let prev_span = self.prev_span;
6473 let item = self.mk_item(lo.to(prev_span),
6477 maybe_append(attrs, extra_attrs));
6478 return Ok(Some(item));
6480 if self.eat_keyword(keywords::Struct) {
6482 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6483 let prev_span = self.prev_span;
6484 let item = self.mk_item(lo.to(prev_span),
6488 maybe_append(attrs, extra_attrs));
6489 return Ok(Some(item));
6491 if self.is_union_item() {
6494 let (ident, item_, extra_attrs) = self.parse_item_union()?;
6495 let prev_span = self.prev_span;
6496 let item = self.mk_item(lo.to(prev_span),
6500 maybe_append(attrs, extra_attrs));
6501 return Ok(Some(item));
6503 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
6504 return Ok(Some(macro_def));
6507 // Verify wether we have encountered a struct or method definition where the user forgot to
6508 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
6509 if visibility == Visibility::Public &&
6510 self.check_ident() &&
6511 self.look_ahead(1, |t| *t != token::Not)
6513 // Space between `pub` keyword and the identifier
6516 // ^^^ `sp` points here
6517 let sp = self.prev_span.between(self.span);
6518 let full_sp = self.prev_span.to(self.span);
6519 let ident_sp = self.span;
6520 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
6521 // possible public struct definition where `struct` was forgotten
6522 let ident = self.parse_ident().unwrap();
6523 let msg = format!("add `struct` here to parse `{}` as a public struct",
6525 let mut err = self.diagnostic()
6526 .struct_span_err(sp, "missing `struct` for struct definition");
6527 err.span_suggestion_short(sp, &msg, " struct ".into());
6529 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
6530 let ident = self.parse_ident().unwrap();
6531 self.consume_block(token::Paren);
6532 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
6533 self.check(&token::OpenDelim(token::Brace))
6535 ("fn", "method", false)
6536 } else if self.check(&token::Colon) {
6540 ("fn` or `struct", "method or struct", true)
6543 let msg = format!("missing `{}` for {} definition", kw, kw_name);
6544 let mut err = self.diagnostic().struct_span_err(sp, &msg);
6546 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
6550 err.span_suggestion_short(sp, &suggestion, format!(" {} ", kw));
6552 if let Ok(snippet) = self.sess.codemap().span_to_snippet(ident_sp) {
6553 err.span_suggestion(
6555 "if you meant to call a macro, write instead",
6556 format!("{}!", snippet));
6558 err.help("if you meant to call a macro, remove the `pub` \
6559 and add a trailing `!` after the identifier");
6565 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
6568 /// Parse a foreign item.
6569 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
6570 let attrs = self.parse_outer_attributes()?;
6572 let visibility = self.parse_visibility(false)?;
6574 // FOREIGN STATIC ITEM
6575 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
6576 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
6577 if self.token.is_keyword(keywords::Const) {
6579 .struct_span_err(self.span, "extern items cannot be `const`")
6580 .span_suggestion(self.span, "instead try using", "static".to_owned())
6583 self.bump(); // `static` or `const`
6584 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6586 // FOREIGN FUNCTION ITEM
6587 if self.check_keyword(keywords::Fn) {
6588 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6590 // FOREIGN TYPE ITEM
6591 if self.check_keyword(keywords::Type) {
6592 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
6595 // FIXME #5668: this will occur for a macro invocation:
6596 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
6598 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
6604 /// This is the fall-through for parsing items.
6605 fn parse_macro_use_or_failure(
6607 attrs: Vec<Attribute> ,
6608 macros_allowed: bool,
6609 attributes_allowed: bool,
6611 visibility: Visibility
6612 ) -> PResult<'a, Option<P<Item>>> {
6613 if macros_allowed && self.token.is_path_start() {
6614 // MACRO INVOCATION ITEM
6616 let prev_span = self.prev_span;
6617 self.complain_if_pub_macro(&visibility, prev_span);
6619 let mac_lo = self.span;
6622 let pth = self.parse_path(PathStyle::Mod)?;
6623 self.expect(&token::Not)?;
6625 // a 'special' identifier (like what `macro_rules!` uses)
6626 // is optional. We should eventually unify invoc syntax
6628 let id = if self.token.is_ident() {
6631 keywords::Invalid.ident() // no special identifier
6633 // eat a matched-delimiter token tree:
6634 let (delim, tts) = self.expect_delimited_token_tree()?;
6635 if delim != token::Brace {
6636 if !self.eat(&token::Semi) {
6637 self.span_err(self.prev_span,
6638 "macros that expand to items must either \
6639 be surrounded with braces or followed by \
6644 let hi = self.prev_span;
6645 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6646 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6647 return Ok(Some(item));
6650 // FAILURE TO PARSE ITEM
6652 Visibility::Inherited => {}
6654 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
6658 if !attributes_allowed && !attrs.is_empty() {
6659 self.expected_item_err(&attrs);
6664 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
6665 where F: FnOnce(&mut Self) -> PResult<'a, R>
6667 // Record all tokens we parse when parsing this item.
6668 let mut tokens = Vec::new();
6669 match self.token_cursor.frame.last_token {
6670 LastToken::Collecting(_) => {
6671 panic!("cannot collect tokens recursively yet")
6673 LastToken::Was(ref mut last) => tokens.extend(last.take()),
6675 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
6676 let prev = self.token_cursor.stack.len();
6678 let last_token = if self.token_cursor.stack.len() == prev {
6679 &mut self.token_cursor.frame.last_token
6681 &mut self.token_cursor.stack[prev].last_token
6683 let mut tokens = match *last_token {
6684 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
6685 LastToken::Was(_) => panic!("our vector went away?"),
6688 // If we're not at EOF our current token wasn't actually consumed by
6689 // `f`, but it'll still be in our list that we pulled out. In that case
6691 if self.token == token::Eof {
6692 *last_token = LastToken::Was(None);
6694 *last_token = LastToken::Was(tokens.pop());
6697 Ok((ret?, tokens.into_iter().collect()))
6700 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6701 let attrs = self.parse_outer_attributes()?;
6703 let (ret, tokens) = self.collect_tokens(|this| {
6704 this.parse_item_(attrs, true, false)
6707 // Once we've parsed an item and recorded the tokens we got while
6708 // parsing we may want to store `tokens` into the item we're about to
6709 // return. Note, though, that we specifically didn't capture tokens
6710 // related to outer attributes. The `tokens` field here may later be
6711 // used with procedural macros to convert this item back into a token
6712 // stream, but during expansion we may be removing attributes as we go
6715 // If we've got inner attributes then the `tokens` we've got above holds
6716 // these inner attributes. If an inner attribute is expanded we won't
6717 // actually remove it from the token stream, so we'll just keep yielding
6718 // it (bad!). To work around this case for now we just avoid recording
6719 // `tokens` if we detect any inner attributes. This should help keep
6720 // expansion correct, but we should fix this bug one day!
6723 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6724 i.tokens = Some(tokens);
6731 /// `{` or `::{` or `*` or `::*`
6732 /// `::{` or `::*` (also `{` or `*` if unprefixed is true)
6733 fn is_import_coupler(&mut self, unprefixed: bool) -> bool {
6734 self.is_import_coupler_inner(&token::OpenDelim(token::Brace), unprefixed) ||
6735 self.is_import_coupler_inner(&token::BinOp(token::Star), unprefixed)
6738 fn is_import_coupler_inner(&mut self, token: &token::Token, unprefixed: bool) -> bool {
6739 if self.check(&token::ModSep) {
6740 self.look_ahead(1, |t| t == token)
6741 } else if unprefixed {
6750 /// USE_TREE = `*` |
6751 /// `{` USE_TREE_LIST `}` |
6753 /// PATH `::` `{` USE_TREE_LIST `}` |
6754 /// PATH [`as` IDENT]
6755 fn parse_use_tree(&mut self, nested: bool) -> PResult<'a, UseTree> {
6758 let mut prefix = ast::Path {
6760 span: lo.to(self.span),
6763 let kind = if self.is_import_coupler(true) {
6764 // `use *;` or `use ::*;` or `use {...};` `use ::{...};`
6766 // Remove the first `::`
6767 if self.eat(&token::ModSep) {
6768 prefix.segments.push(PathSegment::crate_root(self.prev_span));
6770 prefix.segments.push(PathSegment::crate_root(self.span));
6773 if self.eat(&token::BinOp(token::Star)) {
6776 } else if self.check(&token::OpenDelim(token::Brace)) {
6778 UseTreeKind::Nested(self.parse_use_tree_list()?)
6780 return self.unexpected();
6784 let mut parsed = self.parse_path(PathStyle::Mod)?;
6786 parsed = parsed.default_to_global();
6789 prefix.segments.append(&mut parsed.segments);
6790 prefix.span = prefix.span.to(parsed.span);
6792 if self.eat(&token::ModSep) {
6793 if self.eat(&token::BinOp(token::Star)) {
6796 } else if self.check(&token::OpenDelim(token::Brace)) {
6797 // `use path::{...};`
6798 UseTreeKind::Nested(self.parse_use_tree_list()?)
6800 return self.unexpected();
6803 // `use path::foo;` or `use path::foo as bar;`
6804 let rename = self.parse_rename()?.
6805 unwrap_or(prefix.segments.last().unwrap().identifier);
6806 UseTreeKind::Simple(rename)
6811 span: lo.to(self.prev_span),
6817 /// Parse UseTreeKind::Nested(list)
6819 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
6820 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
6821 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
6822 &token::CloseDelim(token::Brace),
6823 SeqSep::trailing_allowed(token::Comma), |this| {
6824 Ok((this.parse_use_tree(true)?, ast::DUMMY_NODE_ID))
6828 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6829 if self.eat_keyword(keywords::As) {
6830 self.parse_ident().map(Some)
6836 /// Parses a source module as a crate. This is the main
6837 /// entry point for the parser.
6838 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6841 attrs: self.parse_inner_attributes()?,
6842 module: self.parse_mod_items(&token::Eof, lo)?,
6843 span: lo.to(self.span),
6847 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6848 let ret = match self.token {
6849 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6850 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6857 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6858 match self.parse_optional_str() {
6859 Some((s, style, suf)) => {
6860 let sp = self.prev_span;
6861 self.expect_no_suffix(sp, "string literal", suf);
6864 _ => Err(self.fatal("expected string literal"))