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::{Ident, ImplItem, IsAuto, Item, ItemKind};
25 use ast::{Lifetime, LifetimeDef, Lit, LitKind, UintTy};
27 use ast::MacStmtStyle;
29 use ast::{MutTy, Mutability};
30 use ast::{Pat, PatKind, PathSegment};
31 use ast::{PolyTraitRef, QSelf};
32 use ast::{Stmt, StmtKind};
33 use ast::{VariantData, StructField};
36 use ast::{TraitItem, TraitRef, TraitObjectSyntax};
37 use ast::{Ty, TyKind, TypeBinding, TyParam, TyParamBounds};
38 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
39 use ast::{Visibility, WhereClause, CrateSugar};
40 use ast::{BinOpKind, UnOp};
41 use ast::{RangeEnd, RangeSyntax};
43 use codemap::{self, CodeMap, Spanned, respan};
44 use syntax_pos::{self, Span, BytePos};
45 use errors::{self, DiagnosticBuilder};
46 use parse::{self, classify, token};
47 use parse::common::SeqSep;
48 use parse::lexer::TokenAndSpan;
49 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
50 use parse::obsolete::ObsoleteSyntax;
51 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
52 use util::parser::{AssocOp, Fixity};
56 use tokenstream::{self, Delimited, ThinTokenStream, TokenTree, TokenStream};
57 use symbol::{Symbol, keywords};
61 use std::collections::HashSet;
63 use std::path::{self, Path, PathBuf};
67 pub struct Restrictions: u8 {
68 const STMT_EXPR = 1 << 0;
69 const NO_STRUCT_LITERAL = 1 << 1;
73 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute> >);
75 /// How to parse a path.
76 #[derive(Copy, Clone, PartialEq)]
78 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
79 /// with something else. For example, in expressions `segment < ....` can be interpreted
80 /// as a comparison and `segment ( ....` can be interpreted as a function call.
81 /// In all such contexts the non-path interpretation is preferred by default for practical
82 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
83 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
85 /// In other contexts, notably in types, no ambiguity exists and paths can be written
86 /// without the disambiguator, e.g. `x<y>` - unambiguously a path.
87 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
89 /// A path with generic arguments disallowed, e.g. `foo::bar::Baz`, used in imports,
90 /// visibilities or attributes.
91 /// Technically, this variant is unnecessary and e.g. `Expr` can be used instead
92 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
93 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
94 /// tokens when something goes wrong.
98 #[derive(Clone, Copy, Debug, PartialEq)]
99 pub enum SemiColonMode {
104 #[derive(Clone, Copy, Debug, PartialEq)]
110 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
111 /// dropped into the token stream, which happens while parsing the result of
112 /// macro expansion). Placement of these is not as complex as I feared it would
113 /// be. The important thing is to make sure that lookahead doesn't balk at
114 /// `token::Interpolated` tokens.
115 macro_rules! maybe_whole_expr {
117 if let token::Interpolated(nt) = $p.token.clone() {
119 token::NtExpr(ref e) => {
121 return Ok((*e).clone());
123 token::NtPath(ref path) => {
126 let kind = ExprKind::Path(None, (*path).clone());
127 return Ok($p.mk_expr(span, kind, ThinVec::new()));
129 token::NtBlock(ref block) => {
132 let kind = ExprKind::Block((*block).clone());
133 return Ok($p.mk_expr(span, kind, ThinVec::new()));
141 /// As maybe_whole_expr, but for things other than expressions
142 macro_rules! maybe_whole {
143 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
144 if let token::Interpolated(nt) = $p.token.clone() {
145 if let token::$constructor($x) = nt.0.clone() {
153 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
155 if let Some(ref attrs) = rhs {
156 lhs.extend(attrs.iter().cloned())
161 #[derive(Debug, Clone, Copy, PartialEq)]
172 /* ident is handled by common.rs */
175 pub struct Parser<'a> {
176 pub sess: &'a ParseSess,
177 /// the current token:
178 pub token: token::Token,
179 /// the span of the current token:
181 /// the span of the previous token:
182 pub meta_var_span: Option<Span>,
184 /// the previous token kind
185 prev_token_kind: PrevTokenKind,
186 pub restrictions: Restrictions,
187 /// The set of seen errors about obsolete syntax. Used to suppress
188 /// extra detail when the same error is seen twice
189 pub obsolete_set: HashSet<ObsoleteSyntax>,
190 /// Used to determine the path to externally loaded source files
191 pub directory: Directory,
192 /// Whether to parse sub-modules in other files.
193 pub recurse_into_file_modules: bool,
194 /// Name of the root module this parser originated from. If `None`, then the
195 /// name is not known. This does not change while the parser is descending
196 /// into modules, and sub-parsers have new values for this name.
197 pub root_module_name: Option<String>,
198 pub expected_tokens: Vec<TokenType>,
199 token_cursor: TokenCursor,
200 pub desugar_doc_comments: bool,
201 /// Whether we should configure out of line modules as we parse.
208 frame: TokenCursorFrame,
209 stack: Vec<TokenCursorFrame>,
213 struct TokenCursorFrame {
214 delim: token::DelimToken,
217 tree_cursor: tokenstream::Cursor,
219 last_token: LastToken,
222 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
223 /// by the parser, and then that's transitively used to record the tokens that
224 /// each parse AST item is created with.
226 /// Right now this has two states, either collecting tokens or not collecting
227 /// tokens. If we're collecting tokens we just save everything off into a local
228 /// `Vec`. This should eventually though likely save tokens from the original
229 /// token stream and just use slicing of token streams to avoid creation of a
230 /// whole new vector.
232 /// The second state is where we're passively not recording tokens, but the last
233 /// token is still tracked for when we want to start recording tokens. This
234 /// "last token" means that when we start recording tokens we'll want to ensure
235 /// that this, the first token, is included in the output.
237 /// You can find some more example usage of this in the `collect_tokens` method
241 Collecting(Vec<TokenTree>),
242 Was(Option<TokenTree>),
245 impl TokenCursorFrame {
246 fn new(sp: Span, delimited: &Delimited) -> Self {
248 delim: delimited.delim,
250 open_delim: delimited.delim == token::NoDelim,
251 tree_cursor: delimited.stream().into_trees(),
252 close_delim: delimited.delim == token::NoDelim,
253 last_token: LastToken::Was(None),
259 fn next(&mut self) -> TokenAndSpan {
261 let tree = if !self.frame.open_delim {
262 self.frame.open_delim = true;
263 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
264 .open_tt(self.frame.span)
265 } else if let Some(tree) = self.frame.tree_cursor.next() {
267 } else if !self.frame.close_delim {
268 self.frame.close_delim = true;
269 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
270 .close_tt(self.frame.span)
271 } else if let Some(frame) = self.stack.pop() {
275 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
278 match self.frame.last_token {
279 LastToken::Collecting(ref mut v) => v.push(tree.clone()),
280 LastToken::Was(ref mut t) => *t = Some(tree.clone()),
284 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
285 TokenTree::Delimited(sp, ref delimited) => {
286 let frame = TokenCursorFrame::new(sp, delimited);
287 self.stack.push(mem::replace(&mut self.frame, frame));
293 fn next_desugared(&mut self) -> TokenAndSpan {
294 let (sp, name) = match self.next() {
295 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
299 let stripped = strip_doc_comment_decoration(&name.as_str());
301 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
302 // required to wrap the text.
303 let mut num_of_hashes = 0;
305 for ch in stripped.chars() {
308 '#' if count > 0 => count + 1,
311 num_of_hashes = cmp::max(num_of_hashes, count);
314 let body = TokenTree::Delimited(sp, Delimited {
315 delim: token::Bracket,
316 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"))),
317 TokenTree::Token(sp, token::Eq),
318 TokenTree::Token(sp, token::Literal(
319 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
320 .iter().cloned().collect::<TokenStream>().into(),
323 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
324 delim: token::NoDelim,
325 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
326 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
327 .iter().cloned().collect::<TokenStream>().into()
329 [TokenTree::Token(sp, token::Pound), body]
330 .iter().cloned().collect::<TokenStream>().into()
338 #[derive(PartialEq, Eq, Clone)]
341 Keyword(keywords::Keyword),
350 fn to_string(&self) -> String {
352 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
353 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
354 TokenType::Operator => "an operator".to_string(),
355 TokenType::Lifetime => "lifetime".to_string(),
356 TokenType::Ident => "identifier".to_string(),
357 TokenType::Path => "path".to_string(),
358 TokenType::Type => "type".to_string(),
363 fn is_ident_or_underscore(t: &token::Token) -> bool {
364 t.is_ident() || *t == token::Underscore
367 // Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
368 // `IDENT<<u8 as Trait>::AssocTy>`, `IDENT(u8, u8) -> u8`.
369 fn can_continue_type_after_ident(t: &token::Token) -> bool {
370 t == &token::ModSep || t == &token::Lt ||
371 t == &token::BinOp(token::Shl) || t == &token::OpenDelim(token::Paren)
374 /// Information about the path to a module.
375 pub struct ModulePath {
377 pub path_exists: bool,
378 pub result: Result<ModulePathSuccess, Error>,
381 pub struct ModulePathSuccess {
383 pub directory_ownership: DirectoryOwnership,
387 pub struct ModulePathError {
389 pub help_msg: String,
393 FileNotFoundForModule {
395 default_path: String,
396 secondary_path: String,
401 default_path: String,
402 secondary_path: String,
405 InclusiveRangeWithNoEnd,
409 pub fn span_err(self, sp: Span, handler: &errors::Handler) -> DiagnosticBuilder {
411 Error::FileNotFoundForModule { ref mod_name,
415 let mut err = struct_span_err!(handler, sp, E0583,
416 "file not found for module `{}`", mod_name);
417 err.help(&format!("name the file either {} or {} inside the directory {:?}",
423 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
424 let mut err = struct_span_err!(handler, sp, E0584,
425 "file for module `{}` found at both {} and {}",
429 err.help("delete or rename one of them to remove the ambiguity");
432 Error::UselessDocComment => {
433 let mut err = struct_span_err!(handler, sp, E0585,
434 "found a documentation comment that doesn't document anything");
435 err.help("doc comments must come before what they document, maybe a comment was \
436 intended with `//`?");
439 Error::InclusiveRangeWithNoEnd => {
440 let mut err = struct_span_err!(handler, sp, E0586,
441 "inclusive range with no end");
442 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
452 AttributesParsed(ThinVec<Attribute>),
453 AlreadyParsed(P<Expr>),
456 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
457 fn from(o: Option<ThinVec<Attribute>>) -> Self {
458 if let Some(attrs) = o {
459 LhsExpr::AttributesParsed(attrs)
461 LhsExpr::NotYetParsed
466 impl From<P<Expr>> for LhsExpr {
467 fn from(expr: P<Expr>) -> Self {
468 LhsExpr::AlreadyParsed(expr)
472 /// Create a placeholder argument.
473 fn dummy_arg(span: Span) -> Arg {
474 let spanned = Spanned {
476 node: keywords::Invalid.ident()
479 id: ast::DUMMY_NODE_ID,
480 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), spanned, None),
486 id: ast::DUMMY_NODE_ID
488 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
491 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
492 enum TokenExpectType {
497 impl<'a> Parser<'a> {
498 pub fn new(sess: &'a ParseSess,
500 directory: Option<Directory>,
501 recurse_into_file_modules: bool,
502 desugar_doc_comments: bool)
504 let mut parser = Parser {
506 token: token::Underscore,
507 span: syntax_pos::DUMMY_SP,
508 prev_span: syntax_pos::DUMMY_SP,
510 prev_token_kind: PrevTokenKind::Other,
511 restrictions: Restrictions::empty(),
512 obsolete_set: HashSet::new(),
513 recurse_into_file_modules,
514 directory: Directory { path: PathBuf::new(), ownership: DirectoryOwnership::Owned },
515 root_module_name: None,
516 expected_tokens: Vec::new(),
517 token_cursor: TokenCursor {
518 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
519 delim: token::NoDelim,
524 desugar_doc_comments,
528 let tok = parser.next_tok();
529 parser.token = tok.tok;
530 parser.span = tok.sp;
532 if let Some(directory) = directory {
533 parser.directory = directory;
534 } else if parser.span != syntax_pos::DUMMY_SP {
535 parser.directory.path = sess.codemap().span_to_unmapped_path(parser.span);
536 parser.directory.path.pop();
539 parser.process_potential_macro_variable();
543 fn next_tok(&mut self) -> TokenAndSpan {
544 let mut next = if self.desugar_doc_comments {
545 self.token_cursor.next_desugared()
547 self.token_cursor.next()
549 if next.sp == syntax_pos::DUMMY_SP {
550 next.sp = self.prev_span;
555 /// Convert a token to a string using self's reader
556 pub fn token_to_string(token: &token::Token) -> String {
557 pprust::token_to_string(token)
560 /// Convert the current token to a string using self's reader
561 pub fn this_token_to_string(&self) -> String {
562 Parser::token_to_string(&self.token)
565 pub fn this_token_descr(&self) -> String {
566 let prefix = match &self.token {
567 t if t.is_special_ident() => "reserved identifier ",
568 t if t.is_used_keyword() => "keyword ",
569 t if t.is_unused_keyword() => "reserved keyword ",
572 format!("{}`{}`", prefix, self.this_token_to_string())
575 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
576 let token_str = Parser::token_to_string(t);
577 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
580 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
581 match self.expect_one_of(&[], &[]) {
583 Ok(_) => unreachable!(),
587 /// Expect and consume the token t. Signal an error if
588 /// the next token is not t.
589 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
590 if self.expected_tokens.is_empty() {
591 if self.token == *t {
595 let token_str = Parser::token_to_string(t);
596 let this_token_str = self.this_token_to_string();
597 Err(self.fatal(&format!("expected `{}`, found `{}`",
602 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
606 /// Expect next token to be edible or inedible token. If edible,
607 /// then consume it; if inedible, then return without consuming
608 /// anything. Signal a fatal error if next token is unexpected.
609 pub fn expect_one_of(&mut self,
610 edible: &[token::Token],
611 inedible: &[token::Token]) -> PResult<'a, ()>{
612 fn tokens_to_string(tokens: &[TokenType]) -> String {
613 let mut i = tokens.iter();
614 // This might be a sign we need a connect method on Iterator.
616 .map_or("".to_string(), |t| t.to_string());
617 i.enumerate().fold(b, |mut b, (i, a)| {
618 if tokens.len() > 2 && i == tokens.len() - 2 {
620 } else if tokens.len() == 2 && i == tokens.len() - 2 {
625 b.push_str(&a.to_string());
629 if edible.contains(&self.token) {
632 } else if inedible.contains(&self.token) {
633 // leave it in the input
636 let mut expected = edible.iter()
637 .map(|x| TokenType::Token(x.clone()))
638 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
639 .chain(self.expected_tokens.iter().cloned())
640 .collect::<Vec<_>>();
641 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
643 let expect = tokens_to_string(&expected[..]);
644 let actual = self.this_token_to_string();
645 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
646 let short_expect = if expected.len() > 6 {
647 format!("{} possible tokens", expected.len())
651 (format!("expected one of {}, found `{}`", expect, actual),
652 (self.prev_span.next_point(), format!("expected one of {} here", short_expect)))
653 } else if expected.is_empty() {
654 (format!("unexpected token: `{}`", actual),
655 (self.prev_span, "unexpected token after this".to_string()))
657 (format!("expected {}, found `{}`", expect, actual),
658 (self.prev_span.next_point(), format!("expected {} here", expect)))
660 let mut err = self.fatal(&msg_exp);
661 let sp = if self.token == token::Token::Eof {
662 // This is EOF, don't want to point at the following char, but rather the last token
667 if self.span.contains(sp) {
668 err.span_label(self.span, label_exp);
670 err.span_label(sp, label_exp);
671 err.span_label(self.span, "unexpected token");
677 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
678 fn interpolated_or_expr_span(&self,
679 expr: PResult<'a, P<Expr>>)
680 -> PResult<'a, (Span, P<Expr>)> {
682 if self.prev_token_kind == PrevTokenKind::Interpolated {
690 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
693 if self.token.is_reserved_ident() {
694 self.span_err(self.span, &format!("expected identifier, found {}",
695 self.this_token_descr()));
701 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
702 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
704 let mut err = self.fatal(&format!("expected identifier, found `{}`",
705 self.this_token_to_string()));
706 if self.token == token::Underscore {
707 err.note("`_` is a wildcard pattern, not an identifier");
715 /// Check if the next token is `tok`, and return `true` if so.
717 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
719 pub fn check(&mut self, tok: &token::Token) -> bool {
720 let is_present = self.token == *tok;
721 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
725 /// Consume token 'tok' if it exists. Returns true if the given
726 /// token was present, false otherwise.
727 pub fn eat(&mut self, tok: &token::Token) -> bool {
728 let is_present = self.check(tok);
729 if is_present { self.bump() }
733 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
734 self.expected_tokens.push(TokenType::Keyword(kw));
735 self.token.is_keyword(kw)
738 /// If the next token is the given keyword, eat it and return
739 /// true. Otherwise, return false.
740 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
741 if self.check_keyword(kw) {
749 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
750 if self.token.is_keyword(kw) {
758 /// If the given word is not a keyword, signal an error.
759 /// If the next token is not the given word, signal an error.
760 /// Otherwise, eat it.
761 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
762 if !self.eat_keyword(kw) {
769 fn check_ident(&mut self) -> bool {
770 if self.token.is_ident() {
773 self.expected_tokens.push(TokenType::Ident);
778 fn check_path(&mut self) -> bool {
779 if self.token.is_path_start() {
782 self.expected_tokens.push(TokenType::Path);
787 fn check_type(&mut self) -> bool {
788 if self.token.can_begin_type() {
791 self.expected_tokens.push(TokenType::Type);
796 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
797 /// `&` and continue. If an `&` is not seen, signal an error.
798 fn expect_and(&mut self) -> PResult<'a, ()> {
799 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
801 token::BinOp(token::And) => {
806 let span = self.span.with_lo(self.span.lo() + BytePos(1));
807 Ok(self.bump_with(token::BinOp(token::And), span))
809 _ => self.unexpected()
813 /// Expect and consume an `|`. If `||` is seen, replace it with a single
814 /// `|` and continue. If an `|` is not seen, signal an error.
815 fn expect_or(&mut self) -> PResult<'a, ()> {
816 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
818 token::BinOp(token::Or) => {
823 let span = self.span.with_lo(self.span.lo() + BytePos(1));
824 Ok(self.bump_with(token::BinOp(token::Or), span))
826 _ => self.unexpected()
830 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
832 None => {/* everything ok */}
834 let text = suf.as_str();
836 self.span_bug(sp, "found empty literal suffix in Some")
838 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
843 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
844 /// `<` and continue. If a `<` is not seen, return false.
846 /// This is meant to be used when parsing generics on a path to get the
848 fn eat_lt(&mut self) -> bool {
849 self.expected_tokens.push(TokenType::Token(token::Lt));
855 token::BinOp(token::Shl) => {
856 let span = self.span.with_lo(self.span.lo() + BytePos(1));
857 self.bump_with(token::Lt, span);
864 fn expect_lt(&mut self) -> PResult<'a, ()> {
872 /// Expect and consume a GT. if a >> is seen, replace it
873 /// with a single > and continue. If a GT is not seen,
875 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
876 self.expected_tokens.push(TokenType::Token(token::Gt));
882 token::BinOp(token::Shr) => {
883 let span = self.span.with_lo(self.span.lo() + BytePos(1));
884 Ok(self.bump_with(token::Gt, span))
886 token::BinOpEq(token::Shr) => {
887 let span = self.span.with_lo(self.span.lo() + BytePos(1));
888 Ok(self.bump_with(token::Ge, span))
891 let span = self.span.with_lo(self.span.lo() + BytePos(1));
892 Ok(self.bump_with(token::Eq, span))
894 _ => self.unexpected()
898 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
899 sep: Option<token::Token>,
901 -> PResult<'a, (Vec<T>, bool)>
902 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
904 let mut v = Vec::new();
905 // This loop works by alternating back and forth between parsing types
906 // and commas. For example, given a string `A, B,>`, the parser would
907 // first parse `A`, then a comma, then `B`, then a comma. After that it
908 // would encounter a `>` and stop. This lets the parser handle trailing
909 // commas in generic parameters, because it can stop either after
910 // parsing a type or after parsing a comma.
912 if self.check(&token::Gt)
913 || self.token == token::BinOp(token::Shr)
914 || self.token == token::Ge
915 || self.token == token::BinOpEq(token::Shr) {
921 Some(result) => v.push(result),
922 None => return Ok((v, true))
925 if let Some(t) = sep.as_ref() {
931 return Ok((v, false));
934 /// Parse a sequence bracketed by '<' and '>', stopping
936 pub fn parse_seq_to_before_gt<T, F>(&mut self,
937 sep: Option<token::Token>,
939 -> PResult<'a, Vec<T>> where
940 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
942 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
943 |p| Ok(Some(f(p)?)))?;
948 pub fn parse_seq_to_gt<T, F>(&mut self,
949 sep: Option<token::Token>,
951 -> PResult<'a, Vec<T>> where
952 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
954 let v = self.parse_seq_to_before_gt(sep, f)?;
959 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
960 sep: Option<token::Token>,
962 -> PResult<'a, (Vec<T>, bool)> where
963 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
965 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
969 return Ok((v, returned));
972 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
973 /// passes through any errors encountered. Used for error recovery.
974 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
975 let handler = self.diagnostic();
977 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
979 TokenExpectType::Expect,
980 |p| Ok(p.parse_token_tree())) {
985 /// Parse a sequence, including the closing delimiter. The function
986 /// f must consume tokens until reaching the next separator or
988 pub fn parse_seq_to_end<T, F>(&mut self,
992 -> PResult<'a, Vec<T>> where
993 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
995 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1000 /// Parse a sequence, not including the closing delimiter. The function
1001 /// f must consume tokens until reaching the next separator or
1002 /// closing bracket.
1003 pub fn parse_seq_to_before_end<T, F>(&mut self,
1007 -> PResult<'a, Vec<T>>
1008 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1010 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1013 fn parse_seq_to_before_tokens<T, F>(&mut self,
1014 kets: &[&token::Token],
1016 expect: TokenExpectType,
1018 -> PResult<'a, Vec<T>>
1019 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1021 let mut first: bool = true;
1023 while !kets.contains(&&self.token) {
1025 token::CloseDelim(..) | token::Eof => break,
1028 if let Some(ref t) = sep.sep {
1032 if let Err(mut e) = self.expect(t) {
1033 // Attempt to keep parsing if it was a similar separator
1034 if let Some(ref tokens) = t.similar_tokens() {
1035 if tokens.contains(&self.token) {
1040 // Attempt to keep parsing if it was an omitted separator
1054 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1056 TokenExpectType::Expect => self.check(k),
1057 TokenExpectType::NoExpect => self.token == **k,
1070 /// Parse a sequence, including the closing delimiter. The function
1071 /// f must consume tokens until reaching the next separator or
1072 /// closing bracket.
1073 pub fn parse_unspanned_seq<T, F>(&mut self,
1078 -> PResult<'a, Vec<T>> where
1079 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1082 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1083 if self.token == *ket {
1089 // NB: Do not use this function unless you actually plan to place the
1090 // spanned list in the AST.
1091 pub fn parse_seq<T, F>(&mut self,
1096 -> PResult<'a, Spanned<Vec<T>>> where
1097 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1101 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1104 Ok(respan(lo.to(hi), result))
1107 /// Advance the parser by one token
1108 pub fn bump(&mut self) {
1109 if self.prev_token_kind == PrevTokenKind::Eof {
1110 // Bumping after EOF is a bad sign, usually an infinite loop.
1111 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1114 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1116 // Record last token kind for possible error recovery.
1117 self.prev_token_kind = match self.token {
1118 token::DocComment(..) => PrevTokenKind::DocComment,
1119 token::Comma => PrevTokenKind::Comma,
1120 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1121 token::Interpolated(..) => PrevTokenKind::Interpolated,
1122 token::Eof => PrevTokenKind::Eof,
1123 token::Ident(..) => PrevTokenKind::Ident,
1124 _ => PrevTokenKind::Other,
1127 let next = self.next_tok();
1128 self.span = next.sp;
1129 self.token = next.tok;
1130 self.expected_tokens.clear();
1131 // check after each token
1132 self.process_potential_macro_variable();
1135 /// Advance the parser using provided token as a next one. Use this when
1136 /// consuming a part of a token. For example a single `<` from `<<`.
1137 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1138 self.prev_span = self.span.with_hi(span.lo());
1139 // It would be incorrect to record the kind of the current token, but
1140 // fortunately for tokens currently using `bump_with`, the
1141 // prev_token_kind will be of no use anyway.
1142 self.prev_token_kind = PrevTokenKind::Other;
1145 self.expected_tokens.clear();
1148 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1149 F: FnOnce(&token::Token) -> R,
1152 return f(&self.token)
1155 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1156 Some(tree) => match tree {
1157 TokenTree::Token(_, tok) => tok,
1158 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1160 None => token::CloseDelim(self.token_cursor.frame.delim),
1163 fn look_ahead_span(&self, dist: usize) -> Span {
1168 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1169 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1170 None => self.look_ahead_span(dist - 1),
1173 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1174 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1176 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1177 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1179 pub fn span_fatal_err(&self, sp: Span, err: Error) -> DiagnosticBuilder<'a> {
1180 err.span_err(sp, self.diagnostic())
1182 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1183 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1187 pub fn bug(&self, m: &str) -> ! {
1188 self.sess.span_diagnostic.span_bug(self.span, m)
1190 pub fn warn(&self, m: &str) {
1191 self.sess.span_diagnostic.span_warn(self.span, m)
1193 pub fn span_warn(&self, sp: Span, m: &str) {
1194 self.sess.span_diagnostic.span_warn(sp, m)
1196 pub fn span_err(&self, sp: Span, m: &str) {
1197 self.sess.span_diagnostic.span_err(sp, m)
1199 pub fn span_err_help(&self, sp: Span, m: &str, h: &str) {
1200 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1204 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1205 self.sess.span_diagnostic.span_bug(sp, m)
1207 pub fn abort_if_errors(&self) {
1208 self.sess.span_diagnostic.abort_if_errors();
1211 fn cancel(&self, err: &mut DiagnosticBuilder) {
1212 self.sess.span_diagnostic.cancel(err)
1215 pub fn diagnostic(&self) -> &'a errors::Handler {
1216 &self.sess.span_diagnostic
1219 /// Is the current token one of the keywords that signals a bare function
1221 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1222 self.check_keyword(keywords::Fn) ||
1223 self.check_keyword(keywords::Unsafe) ||
1224 self.check_keyword(keywords::Extern)
1227 fn get_label(&mut self) -> ast::Ident {
1229 token::Lifetime(ref ident) => *ident,
1230 _ => self.bug("not a lifetime"),
1234 /// parse a TyKind::BareFn type:
1235 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<LifetimeDef>)
1236 -> PResult<'a, TyKind> {
1239 [unsafe] [extern "ABI"] fn (S) -> T
1249 let unsafety = self.parse_unsafety()?;
1250 let abi = if self.eat_keyword(keywords::Extern) {
1251 self.parse_opt_abi()?.unwrap_or(Abi::C)
1256 self.expect_keyword(keywords::Fn)?;
1257 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1258 let ret_ty = self.parse_ret_ty()?;
1259 let decl = P(FnDecl {
1264 Ok(TyKind::BareFn(P(BareFnTy {
1267 lifetimes: lifetime_defs,
1272 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1273 if self.eat_keyword(keywords::Unsafe) {
1274 return Ok(Unsafety::Unsafe);
1276 return Ok(Unsafety::Normal);
1280 /// Parse the items in a trait declaration
1281 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1282 maybe_whole!(self, NtTraitItem, |x| x);
1283 let attrs = self.parse_outer_attributes()?;
1284 let (mut item, tokens) = self.collect_tokens(|this| {
1285 this.parse_trait_item_(at_end, attrs)
1287 // See `parse_item` for why this clause is here.
1288 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1289 item.tokens = Some(tokens);
1294 fn parse_trait_item_(&mut self,
1296 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1299 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1300 let TyParam {ident, bounds, default, ..} = self.parse_ty_param(vec![])?;
1301 self.expect(&token::Semi)?;
1302 (ident, TraitItemKind::Type(bounds, default), ast::Generics::default())
1303 } else if self.is_const_item() {
1304 self.expect_keyword(keywords::Const)?;
1305 let ident = self.parse_ident()?;
1306 self.expect(&token::Colon)?;
1307 let ty = self.parse_ty()?;
1308 let default = if self.check(&token::Eq) {
1310 let expr = self.parse_expr()?;
1311 self.expect(&token::Semi)?;
1314 self.expect(&token::Semi)?;
1317 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1318 } else if self.token.is_path_start() {
1319 // trait item macro.
1320 // code copied from parse_macro_use_or_failure... abstraction!
1321 let prev_span = self.prev_span;
1323 let pth = self.parse_path(PathStyle::Mod)?;
1325 if pth.segments.len() == 1 {
1326 if !self.eat(&token::Not) {
1327 return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1330 self.expect(&token::Not)?;
1333 // eat a matched-delimiter token tree:
1334 let (delim, tts) = self.expect_delimited_token_tree()?;
1335 if delim != token::Brace {
1336 self.expect(&token::Semi)?
1339 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1340 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1342 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
1344 let ident = self.parse_ident()?;
1345 let mut generics = self.parse_generics()?;
1347 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1348 // This is somewhat dubious; We don't want to allow
1349 // argument names to be left off if there is a
1351 p.parse_arg_general(false)
1353 generics.where_clause = self.parse_where_clause()?;
1355 let sig = ast::MethodSig {
1362 let body = match self.token {
1366 debug!("parse_trait_methods(): parsing required method");
1369 token::OpenDelim(token::Brace) => {
1370 debug!("parse_trait_methods(): parsing provided method");
1372 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1373 attrs.extend(inner_attrs.iter().cloned());
1377 let token_str = self.this_token_to_string();
1378 return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1381 (ident, ast::TraitItemKind::Method(sig, body), generics)
1385 id: ast::DUMMY_NODE_ID,
1390 span: lo.to(self.prev_span),
1395 /// Parse optional return type [ -> TY ] in function decl
1396 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1397 if self.eat(&token::RArrow) {
1398 Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
1400 Ok(FunctionRetTy::Default(self.span.with_hi(self.span.lo())))
1405 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1406 self.parse_ty_common(true)
1409 /// Parse a type in restricted contexts where `+` is not permitted.
1410 /// Example 1: `&'a TYPE`
1411 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1412 /// Example 2: `value1 as TYPE + value2`
1413 /// `+` is prohibited to avoid interactions with expression grammar.
1414 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1415 self.parse_ty_common(false)
1418 fn parse_ty_common(&mut self, allow_plus: bool) -> PResult<'a, P<Ty>> {
1419 maybe_whole!(self, NtTy, |x| x);
1422 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1423 // `(TYPE)` is a parenthesized type.
1424 // `(TYPE,)` is a tuple with a single field of type TYPE.
1425 let mut ts = vec![];
1426 let mut last_comma = false;
1427 while self.token != token::CloseDelim(token::Paren) {
1428 ts.push(self.parse_ty()?);
1429 if self.eat(&token::Comma) {
1436 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1437 self.expect(&token::CloseDelim(token::Paren))?;
1439 if ts.len() == 1 && !last_comma {
1440 let ty = ts.into_iter().nth(0).unwrap().unwrap();
1441 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1443 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1444 TyKind::Path(None, ref path) if maybe_bounds => {
1445 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1447 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1448 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1449 let path = match bounds[0] {
1450 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1451 _ => self.bug("unexpected lifetime bound"),
1453 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1456 _ => TyKind::Paren(P(ty))
1461 } else if self.eat(&token::Not) {
1464 } else if self.eat(&token::BinOp(token::Star)) {
1466 TyKind::Ptr(self.parse_ptr()?)
1467 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1469 let t = self.parse_ty()?;
1470 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1471 let t = match self.maybe_parse_fixed_length_of_vec()? {
1472 None => TyKind::Slice(t),
1473 Some(suffix) => TyKind::Array(t, suffix),
1475 self.expect(&token::CloseDelim(token::Bracket))?;
1477 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1480 self.parse_borrowed_pointee()?
1481 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1483 // In order to not be ambiguous, the type must be surrounded by parens.
1484 self.expect(&token::OpenDelim(token::Paren))?;
1485 let e = self.parse_expr()?;
1486 self.expect(&token::CloseDelim(token::Paren))?;
1488 } else if self.eat(&token::Underscore) {
1489 // A type to be inferred `_`
1491 } else if self.token_is_bare_fn_keyword() {
1492 // Function pointer type
1493 self.parse_ty_bare_fn(Vec::new())?
1494 } else if self.check_keyword(keywords::For) {
1495 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1496 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1497 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1499 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1500 if self.token_is_bare_fn_keyword() {
1501 self.parse_ty_bare_fn(lifetime_defs)?
1503 let path = self.parse_path(PathStyle::Type)?;
1504 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1505 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1507 } else if self.eat_keyword(keywords::Impl) {
1508 // FIXME: figure out priority of `+` in `impl Trait1 + Trait2` (#34511).
1509 TyKind::ImplTrait(self.parse_ty_param_bounds()?)
1510 } else if self.check_keyword(keywords::Dyn) &&
1511 self.look_ahead(1, |t| t.can_begin_bound() && !can_continue_type_after_ident(t)) {
1512 // FIXME: figure out priority of `+` in `dyn Trait1 + Trait2` (#34511).
1513 self.bump(); // `dyn`
1514 TyKind::TraitObject(self.parse_ty_param_bounds()?, TraitObjectSyntax::Dyn)
1515 } else if self.check(&token::Question) ||
1516 self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)) {
1517 // Bound list (trait object type)
1518 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?,
1519 TraitObjectSyntax::None)
1520 } else if self.eat_lt() {
1522 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1523 TyKind::Path(Some(qself), path)
1524 } else if self.token.is_path_start() {
1526 let path = self.parse_path(PathStyle::Type)?;
1527 if self.eat(&token::Not) {
1528 // Macro invocation in type position
1529 let (_, tts) = self.expect_delimited_token_tree()?;
1530 TyKind::Mac(respan(lo.to(self.span), Mac_ { path: path, tts: tts }))
1532 // Just a type path or bound list (trait object type) starting with a trait.
1534 // `Trait1 + Trait2 + 'a`
1535 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1536 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1538 TyKind::Path(None, path)
1542 let msg = format!("expected type, found {}", self.this_token_descr());
1543 return Err(self.fatal(&msg));
1546 let span = lo.to(self.prev_span);
1547 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1549 // Try to recover from use of `+` with incorrect priority.
1550 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1555 fn parse_remaining_bounds(&mut self, lifetime_defs: Vec<LifetimeDef>, path: ast::Path,
1556 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1557 let poly_trait_ref = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
1558 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1561 bounds.append(&mut self.parse_ty_param_bounds()?);
1563 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1566 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1567 // Do not add `+` to expected tokens.
1568 if !allow_plus || self.token != token::BinOp(token::Plus) {
1573 let bounds = self.parse_ty_param_bounds()?;
1574 let sum_span = ty.span.to(self.prev_span);
1576 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1577 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1580 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1581 let sum_with_parens = pprust::to_string(|s| {
1582 use print::pprust::PrintState;
1585 s.print_opt_lifetime(lifetime)?;
1586 s.print_mutability(mut_ty.mutbl)?;
1588 s.print_type(&mut_ty.ty)?;
1589 s.print_bounds(" +", &bounds)?;
1592 err.span_suggestion(sum_span, "try adding parentheses", sum_with_parens);
1594 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1595 err.span_label(sum_span, "perhaps you forgot parentheses?");
1598 err.span_label(sum_span, "expected a path");
1605 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1606 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1607 let mutbl = self.parse_mutability();
1608 let ty = self.parse_ty_no_plus()?;
1609 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1612 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1613 let mutbl = if self.eat_keyword(keywords::Mut) {
1615 } else if self.eat_keyword(keywords::Const) {
1616 Mutability::Immutable
1618 let span = self.prev_span;
1620 "expected mut or const in raw pointer type (use \
1621 `*mut T` or `*const T` as appropriate)");
1622 Mutability::Immutable
1624 let t = self.parse_ty_no_plus()?;
1625 Ok(MutTy { ty: t, mutbl: mutbl })
1628 pub fn is_named_argument(&mut self) -> bool {
1629 let offset = match self.token {
1630 token::BinOp(token::And) |
1632 _ if self.token.is_keyword(keywords::Mut) => 1,
1636 debug!("parser is_named_argument offset:{}", offset);
1639 is_ident_or_underscore(&self.token)
1640 && self.look_ahead(1, |t| *t == token::Colon)
1642 self.look_ahead(offset, |t| is_ident_or_underscore(t))
1643 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1647 /// This version of parse arg doesn't necessarily require
1648 /// identifier names.
1649 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1650 maybe_whole!(self, NtArg, |x| x);
1652 let pat = if require_name || self.is_named_argument() {
1653 debug!("parse_arg_general parse_pat (require_name:{})",
1655 let pat = self.parse_pat()?;
1657 self.expect(&token::Colon)?;
1660 debug!("parse_arg_general ident_to_pat");
1661 let sp = self.prev_span;
1662 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1664 id: ast::DUMMY_NODE_ID,
1665 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1671 let t = self.parse_ty()?;
1676 id: ast::DUMMY_NODE_ID,
1680 /// Parse a single function argument
1681 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1682 self.parse_arg_general(true)
1685 /// Parse an argument in a lambda header e.g. |arg, arg|
1686 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1687 let pat = self.parse_pat()?;
1688 let t = if self.eat(&token::Colon) {
1692 id: ast::DUMMY_NODE_ID,
1693 node: TyKind::Infer,
1700 id: ast::DUMMY_NODE_ID
1704 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1705 if self.eat(&token::Semi) {
1706 Ok(Some(self.parse_expr()?))
1712 /// Matches token_lit = LIT_INTEGER | ...
1713 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1714 let out = match self.token {
1715 token::Interpolated(ref nt) => match nt.0 {
1716 token::NtExpr(ref v) => match v.node {
1717 ExprKind::Lit(ref lit) => { lit.node.clone() }
1718 _ => { return self.unexpected_last(&self.token); }
1720 _ => { return self.unexpected_last(&self.token); }
1722 token::Literal(lit, suf) => {
1723 let diag = Some((self.span, &self.sess.span_diagnostic));
1724 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1728 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1733 _ => { return self.unexpected_last(&self.token); }
1740 /// Matches lit = true | false | token_lit
1741 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1743 let lit = if self.eat_keyword(keywords::True) {
1745 } else if self.eat_keyword(keywords::False) {
1746 LitKind::Bool(false)
1748 let lit = self.parse_lit_token()?;
1751 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1754 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1755 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1756 maybe_whole_expr!(self);
1758 let minus_lo = self.span;
1759 let minus_present = self.eat(&token::BinOp(token::Minus));
1761 let literal = P(self.parse_lit()?);
1762 let hi = self.prev_span;
1763 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1766 let minus_hi = self.prev_span;
1767 let unary = self.mk_unary(UnOp::Neg, expr);
1768 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1774 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1776 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1780 _ => self.parse_ident(),
1784 /// Parses qualified path.
1785 /// Assumes that the leading `<` has been parsed already.
1787 /// `qualified_path = <type [as trait_ref]>::path`
1791 /// `<T as U>::F::a<S>` (without disambiguator)
1792 /// `<T as U>::F::a::<S>` (with disambiguator)
1793 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1794 let lo = self.prev_span;
1795 let ty = self.parse_ty()?;
1796 let mut path = if self.eat_keyword(keywords::As) {
1797 self.parse_path(PathStyle::Type)?
1799 ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP }
1801 self.expect(&token::Gt)?;
1802 self.expect(&token::ModSep)?;
1804 let qself = QSelf { ty, position: path.segments.len() };
1805 self.parse_path_segments(&mut path.segments, style, true)?;
1807 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1810 /// Parses simple paths.
1812 /// `path = [::] segment+`
1813 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1816 /// `a::b::C<D>` (without disambiguator)
1817 /// `a::b::C::<D>` (with disambiguator)
1818 /// `Fn(Args)` (without disambiguator)
1819 /// `Fn::(Args)` (with disambiguator)
1820 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1821 self.parse_path_common(style, true)
1824 pub fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1825 -> PResult<'a, ast::Path> {
1826 maybe_whole!(self, NtPath, |path| {
1827 if style == PathStyle::Mod &&
1828 path.segments.iter().any(|segment| segment.parameters.is_some()) {
1829 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1834 let lo = self.meta_var_span.unwrap_or(self.span);
1835 let mut segments = Vec::new();
1836 if self.eat(&token::ModSep) {
1837 segments.push(PathSegment::crate_root(lo));
1839 self.parse_path_segments(&mut segments, style, enable_warning)?;
1841 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1844 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1845 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1846 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1847 let meta_ident = match self.token {
1848 token::Interpolated(ref nt) => match nt.0 {
1849 token::NtMeta(ref meta) => match meta.node {
1850 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
1857 if let Some(ident) = meta_ident {
1859 return Ok(ast::Path::from_ident(self.prev_span, ident));
1861 self.parse_path(style)
1864 fn parse_path_segments(&mut self,
1865 segments: &mut Vec<PathSegment>,
1867 enable_warning: bool)
1868 -> PResult<'a, ()> {
1870 segments.push(self.parse_path_segment(style, enable_warning)?);
1872 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1878 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
1879 -> PResult<'a, PathSegment> {
1880 let ident_span = self.span;
1881 let ident = self.parse_path_segment_ident()?;
1883 let is_args_start = |token: &token::Token| match *token {
1884 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
1887 let check_args_start = |this: &mut Self| {
1888 this.expected_tokens.extend_from_slice(
1889 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1891 is_args_start(&this.token)
1894 Ok(if style == PathStyle::Type && check_args_start(self) ||
1895 style != PathStyle::Mod && self.check(&token::ModSep)
1896 && self.look_ahead(1, |t| is_args_start(t)) {
1897 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1899 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
1900 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
1901 .span_label(self.prev_span, "try removing `::`").emit();
1904 let parameters = if self.eat_lt() {
1906 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1908 let span = lo.to(self.prev_span);
1909 AngleBracketedParameterData { lifetimes, types, bindings, span }.into()
1913 let inputs = self.parse_seq_to_before_tokens(
1914 &[&token::CloseDelim(token::Paren)],
1915 SeqSep::trailing_allowed(token::Comma),
1916 TokenExpectType::Expect,
1919 let output = if self.eat(&token::RArrow) {
1920 Some(self.parse_ty_no_plus()?)
1924 let span = lo.to(self.prev_span);
1925 ParenthesizedParameterData { inputs, output, span }.into()
1928 PathSegment { identifier: ident, span: ident_span, parameters }
1930 // Generic arguments are not found.
1931 PathSegment::from_ident(ident, ident_span)
1935 fn check_lifetime(&mut self) -> bool {
1936 self.expected_tokens.push(TokenType::Lifetime);
1937 self.token.is_lifetime()
1940 /// Parse single lifetime 'a or panic.
1941 fn expect_lifetime(&mut self) -> Lifetime {
1943 token::Lifetime(ident) => {
1944 let ident_span = self.span;
1946 Lifetime { ident: ident, span: ident_span, id: ast::DUMMY_NODE_ID }
1948 _ => self.span_bug(self.span, "not a lifetime")
1952 /// Parse mutability (`mut` or nothing).
1953 fn parse_mutability(&mut self) -> Mutability {
1954 if self.eat_keyword(keywords::Mut) {
1957 Mutability::Immutable
1961 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1962 if let token::Literal(token::Integer(name), None) = self.token {
1964 Ok(Ident::with_empty_ctxt(name))
1970 /// Parse ident (COLON expr)?
1971 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1972 let attrs = self.parse_outer_attributes()?;
1976 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1977 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1978 let fieldname = self.parse_field_name()?;
1980 hi = self.prev_span;
1981 (fieldname, self.parse_expr()?, false)
1983 let fieldname = self.parse_ident()?;
1984 hi = self.prev_span;
1986 // Mimic `x: x` for the `x` field shorthand.
1987 let path = ast::Path::from_ident(lo.to(hi), fieldname);
1988 (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
1991 ident: respan(lo.to(hi), fieldname),
1992 span: lo.to(expr.span),
1995 attrs: attrs.into(),
1999 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2001 id: ast::DUMMY_NODE_ID,
2004 attrs: attrs.into(),
2008 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2009 ExprKind::Unary(unop, expr)
2012 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2013 ExprKind::Binary(binop, lhs, rhs)
2016 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2017 ExprKind::Call(f, args)
2020 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2021 ExprKind::Index(expr, idx)
2024 pub fn mk_range(&mut self,
2025 start: Option<P<Expr>>,
2026 end: Option<P<Expr>>,
2027 limits: RangeLimits)
2028 -> PResult<'a, ast::ExprKind> {
2029 if end.is_none() && limits == RangeLimits::Closed {
2030 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2032 Ok(ExprKind::Range(start, end, limits))
2036 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2037 ExprKind::TupField(expr, idx)
2040 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2041 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2042 ExprKind::AssignOp(binop, lhs, rhs)
2045 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2047 id: ast::DUMMY_NODE_ID,
2048 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2054 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2055 let span = &self.span;
2056 let lv_lit = P(codemap::Spanned {
2057 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2062 id: ast::DUMMY_NODE_ID,
2063 node: ExprKind::Lit(lv_lit),
2069 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2071 token::OpenDelim(delim) => match self.parse_token_tree() {
2072 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2073 _ => unreachable!(),
2075 _ => Err(self.fatal("expected open delimiter")),
2079 /// At the bottom (top?) of the precedence hierarchy,
2080 /// parse things like parenthesized exprs,
2081 /// macros, return, etc.
2083 /// NB: This does not parse outer attributes,
2084 /// and is private because it only works
2085 /// correctly if called from parse_dot_or_call_expr().
2086 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2087 maybe_whole_expr!(self);
2089 // Outer attributes are already parsed and will be
2090 // added to the return value after the fact.
2092 // Therefore, prevent sub-parser from parsing
2093 // attributes by giving them a empty "already parsed" list.
2094 let mut attrs = ThinVec::new();
2097 let mut hi = self.span;
2101 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2103 token::OpenDelim(token::Paren) => {
2106 attrs.extend(self.parse_inner_attributes()?);
2108 // (e) is parenthesized e
2109 // (e,) is a tuple with only one field, e
2110 let mut es = vec![];
2111 let mut trailing_comma = false;
2112 while self.token != token::CloseDelim(token::Paren) {
2113 es.push(self.parse_expr()?);
2114 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2115 if self.check(&token::Comma) {
2116 trailing_comma = true;
2120 trailing_comma = false;
2126 hi = self.prev_span;
2127 let span = lo.to(hi);
2128 return if es.len() == 1 && !trailing_comma {
2129 Ok(self.mk_expr(span, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2131 Ok(self.mk_expr(span, ExprKind::Tup(es), attrs))
2134 token::OpenDelim(token::Brace) => {
2135 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2137 token::BinOp(token::Or) | token::OrOr => {
2139 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2141 token::OpenDelim(token::Bracket) => {
2144 attrs.extend(self.parse_inner_attributes()?);
2146 if self.check(&token::CloseDelim(token::Bracket)) {
2149 ex = ExprKind::Array(Vec::new());
2152 let first_expr = self.parse_expr()?;
2153 if self.check(&token::Semi) {
2154 // Repeating array syntax: [ 0; 512 ]
2156 let count = self.parse_expr()?;
2157 self.expect(&token::CloseDelim(token::Bracket))?;
2158 ex = ExprKind::Repeat(first_expr, count);
2159 } else if self.check(&token::Comma) {
2160 // Vector with two or more elements.
2162 let remaining_exprs = self.parse_seq_to_end(
2163 &token::CloseDelim(token::Bracket),
2164 SeqSep::trailing_allowed(token::Comma),
2165 |p| Ok(p.parse_expr()?)
2167 let mut exprs = vec![first_expr];
2168 exprs.extend(remaining_exprs);
2169 ex = ExprKind::Array(exprs);
2171 // Vector with one element.
2172 self.expect(&token::CloseDelim(token::Bracket))?;
2173 ex = ExprKind::Array(vec![first_expr]);
2176 hi = self.prev_span;
2180 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2182 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2184 if self.eat_keyword(keywords::Move) {
2185 let lo = self.prev_span;
2186 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2188 if self.eat_keyword(keywords::If) {
2189 return self.parse_if_expr(attrs);
2191 if self.eat_keyword(keywords::For) {
2192 let lo = self.prev_span;
2193 return self.parse_for_expr(None, lo, attrs);
2195 if self.eat_keyword(keywords::While) {
2196 let lo = self.prev_span;
2197 return self.parse_while_expr(None, lo, attrs);
2199 if self.token.is_lifetime() {
2200 let label = Spanned { node: self.get_label(),
2204 self.expect(&token::Colon)?;
2205 if self.eat_keyword(keywords::While) {
2206 return self.parse_while_expr(Some(label), lo, attrs)
2208 if self.eat_keyword(keywords::For) {
2209 return self.parse_for_expr(Some(label), lo, attrs)
2211 if self.eat_keyword(keywords::Loop) {
2212 return self.parse_loop_expr(Some(label), lo, attrs)
2214 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2216 if self.eat_keyword(keywords::Loop) {
2217 let lo = self.prev_span;
2218 return self.parse_loop_expr(None, lo, attrs);
2220 if self.eat_keyword(keywords::Continue) {
2221 let ex = if self.token.is_lifetime() {
2222 let ex = ExprKind::Continue(Some(Spanned{
2223 node: self.get_label(),
2229 ExprKind::Continue(None)
2231 let hi = self.prev_span;
2232 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2234 if self.eat_keyword(keywords::Match) {
2235 return self.parse_match_expr(attrs);
2237 if self.eat_keyword(keywords::Unsafe) {
2238 return self.parse_block_expr(
2240 BlockCheckMode::Unsafe(ast::UserProvided),
2243 if self.is_catch_expr() {
2245 assert!(self.eat_keyword(keywords::Do));
2246 assert!(self.eat_keyword(keywords::Catch));
2247 return self.parse_catch_expr(lo, attrs);
2249 if self.eat_keyword(keywords::Return) {
2250 if self.token.can_begin_expr() {
2251 let e = self.parse_expr()?;
2253 ex = ExprKind::Ret(Some(e));
2255 ex = ExprKind::Ret(None);
2257 } else if self.eat_keyword(keywords::Break) {
2258 let lt = if self.token.is_lifetime() {
2259 let spanned_lt = Spanned {
2260 node: self.get_label(),
2268 let e = if self.token.can_begin_expr()
2269 && !(self.token == token::OpenDelim(token::Brace)
2270 && self.restrictions.contains(
2271 Restrictions::NO_STRUCT_LITERAL)) {
2272 Some(self.parse_expr()?)
2276 ex = ExprKind::Break(lt, e);
2277 hi = self.prev_span;
2278 } else if self.eat_keyword(keywords::Yield) {
2279 if self.token.can_begin_expr() {
2280 let e = self.parse_expr()?;
2282 ex = ExprKind::Yield(Some(e));
2284 ex = ExprKind::Yield(None);
2286 } else if self.token.is_keyword(keywords::Let) {
2287 // Catch this syntax error here, instead of in `parse_ident`, so
2288 // that we can explicitly mention that let is not to be used as an expression
2289 let mut db = self.fatal("expected expression, found statement (`let`)");
2290 db.note("variable declaration using `let` is a statement");
2292 } else if self.token.is_path_start() {
2293 let pth = self.parse_path(PathStyle::Expr)?;
2295 // `!`, as an operator, is prefix, so we know this isn't that
2296 if self.eat(&token::Not) {
2297 // MACRO INVOCATION expression
2298 let (_, tts) = self.expect_delimited_token_tree()?;
2299 let hi = self.prev_span;
2300 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2302 if self.check(&token::OpenDelim(token::Brace)) {
2303 // This is a struct literal, unless we're prohibited
2304 // from parsing struct literals here.
2305 let prohibited = self.restrictions.contains(
2306 Restrictions::NO_STRUCT_LITERAL
2309 return self.parse_struct_expr(lo, pth, attrs);
2314 ex = ExprKind::Path(None, pth);
2316 match self.parse_lit() {
2319 ex = ExprKind::Lit(P(lit));
2322 self.cancel(&mut err);
2323 let msg = format!("expected expression, found {}",
2324 self.this_token_descr());
2325 return Err(self.fatal(&msg));
2332 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2335 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2336 -> PResult<'a, P<Expr>> {
2338 let mut fields = Vec::new();
2339 let mut base = None;
2341 attrs.extend(self.parse_inner_attributes()?);
2343 while self.token != token::CloseDelim(token::Brace) {
2344 if self.eat(&token::DotDot) {
2345 let exp_span = self.prev_span;
2346 match self.parse_expr() {
2352 self.recover_stmt();
2355 if self.token == token::Comma {
2356 let mut err = self.sess.span_diagnostic.mut_span_err(
2357 exp_span.to(self.prev_span),
2358 "cannot use a comma after the base struct",
2360 err.span_suggestion_short(self.span, "remove this comma", "".to_owned());
2361 err.note("the base struct must always be the last field");
2363 self.recover_stmt();
2368 match self.parse_field() {
2369 Ok(f) => fields.push(f),
2372 self.recover_stmt();
2377 match self.expect_one_of(&[token::Comma],
2378 &[token::CloseDelim(token::Brace)]) {
2382 self.recover_stmt();
2388 let span = lo.to(self.span);
2389 self.expect(&token::CloseDelim(token::Brace))?;
2390 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2393 fn parse_or_use_outer_attributes(&mut self,
2394 already_parsed_attrs: Option<ThinVec<Attribute>>)
2395 -> PResult<'a, ThinVec<Attribute>> {
2396 if let Some(attrs) = already_parsed_attrs {
2399 self.parse_outer_attributes().map(|a| a.into())
2403 /// Parse a block or unsafe block
2404 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2405 outer_attrs: ThinVec<Attribute>)
2406 -> PResult<'a, P<Expr>> {
2407 self.expect(&token::OpenDelim(token::Brace))?;
2409 let mut attrs = outer_attrs;
2410 attrs.extend(self.parse_inner_attributes()?);
2412 let blk = self.parse_block_tail(lo, blk_mode)?;
2413 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2416 /// parse a.b or a(13) or a[4] or just a
2417 pub fn parse_dot_or_call_expr(&mut self,
2418 already_parsed_attrs: Option<ThinVec<Attribute>>)
2419 -> PResult<'a, P<Expr>> {
2420 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2422 let b = self.parse_bottom_expr();
2423 let (span, b) = self.interpolated_or_expr_span(b)?;
2424 self.parse_dot_or_call_expr_with(b, span, attrs)
2427 pub fn parse_dot_or_call_expr_with(&mut self,
2430 mut attrs: ThinVec<Attribute>)
2431 -> PResult<'a, P<Expr>> {
2432 // Stitch the list of outer attributes onto the return value.
2433 // A little bit ugly, but the best way given the current code
2435 self.parse_dot_or_call_expr_with_(e0, lo)
2437 expr.map(|mut expr| {
2438 attrs.extend::<Vec<_>>(expr.attrs.into());
2441 ExprKind::If(..) | ExprKind::IfLet(..) => {
2442 if !expr.attrs.is_empty() {
2443 // Just point to the first attribute in there...
2444 let span = expr.attrs[0].span;
2447 "attributes are not yet allowed on `if` \
2458 // Assuming we have just parsed `.`, continue parsing into an expression.
2459 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2460 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2461 Ok(match self.token {
2462 token::OpenDelim(token::Paren) => {
2463 // Method call `expr.f()`
2464 let mut args = self.parse_unspanned_seq(
2465 &token::OpenDelim(token::Paren),
2466 &token::CloseDelim(token::Paren),
2467 SeqSep::trailing_allowed(token::Comma),
2468 |p| Ok(p.parse_expr()?)
2470 args.insert(0, self_arg);
2472 let span = lo.to(self.prev_span);
2473 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2476 // Field access `expr.f`
2477 if let Some(parameters) = segment.parameters {
2478 self.span_err(parameters.span(),
2479 "field expressions may not have generic arguments");
2482 let span = lo.to(self.prev_span);
2483 let ident = respan(segment.span, segment.identifier);
2484 self.mk_expr(span, ExprKind::Field(self_arg, ident), ThinVec::new())
2489 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2494 while self.eat(&token::Question) {
2495 let hi = self.prev_span;
2496 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2500 if self.eat(&token::Dot) {
2502 token::Ident(..) => {
2503 e = self.parse_dot_suffix(e, lo)?;
2505 token::Literal(token::Integer(n), suf) => {
2508 // A tuple index may not have a suffix
2509 self.expect_no_suffix(sp, "tuple index", suf);
2511 let dot_span = self.prev_span;
2515 let index = n.as_str().parse::<usize>().ok();
2518 let id = respan(dot_span.to(hi), n);
2519 let field = self.mk_tup_field(e, id);
2520 e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2523 let prev_span = self.prev_span;
2524 self.span_err(prev_span, "invalid tuple or tuple struct index");
2528 token::Literal(token::Float(n), _suf) => {
2530 let fstr = n.as_str();
2531 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2532 &format!("unexpected token: `{}`", n));
2533 err.span_label(self.prev_span, "unexpected token");
2534 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2535 let float = match fstr.parse::<f64>().ok() {
2539 let sugg = pprust::to_string(|s| {
2540 use print::pprust::PrintState;
2544 s.print_usize(float.trunc() as usize)?;
2547 s.s.word(fstr.splitn(2, ".").last().unwrap())
2549 err.span_suggestion(
2550 lo.to(self.prev_span),
2551 "try parenthesizing the first index",
2558 // FIXME Could factor this out into non_fatal_unexpected or something.
2559 let actual = self.this_token_to_string();
2560 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2565 if self.expr_is_complete(&e) { break; }
2568 token::OpenDelim(token::Paren) => {
2569 let es = self.parse_unspanned_seq(
2570 &token::OpenDelim(token::Paren),
2571 &token::CloseDelim(token::Paren),
2572 SeqSep::trailing_allowed(token::Comma),
2573 |p| Ok(p.parse_expr()?)
2575 hi = self.prev_span;
2577 let nd = self.mk_call(e, es);
2578 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2582 // Could be either an index expression or a slicing expression.
2583 token::OpenDelim(token::Bracket) => {
2585 let ix = self.parse_expr()?;
2587 self.expect(&token::CloseDelim(token::Bracket))?;
2588 let index = self.mk_index(e, ix);
2589 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2597 pub fn process_potential_macro_variable(&mut self) {
2598 let ident = match self.token {
2599 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2600 self.look_ahead(1, |t| t.is_ident()) => {
2602 let name = match self.token { token::Ident(ident) => ident, _ => unreachable!() };
2603 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2606 token::Interpolated(ref nt) => {
2607 self.meta_var_span = Some(self.span);
2609 token::NtIdent(ident) => ident,
2615 self.token = token::Ident(ident.node);
2616 self.span = ident.span;
2619 /// parse a single token tree from the input.
2620 pub fn parse_token_tree(&mut self) -> TokenTree {
2622 token::OpenDelim(..) => {
2623 let frame = mem::replace(&mut self.token_cursor.frame,
2624 self.token_cursor.stack.pop().unwrap());
2625 self.span = frame.span;
2627 TokenTree::Delimited(frame.span, Delimited {
2629 tts: frame.tree_cursor.original_stream().into(),
2632 token::CloseDelim(_) | token::Eof => unreachable!(),
2634 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2636 TokenTree::Token(span, token)
2641 // parse a stream of tokens into a list of TokenTree's,
2643 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2644 let mut tts = Vec::new();
2645 while self.token != token::Eof {
2646 tts.push(self.parse_token_tree());
2651 pub fn parse_tokens(&mut self) -> TokenStream {
2652 let mut result = Vec::new();
2655 token::Eof | token::CloseDelim(..) => break,
2656 _ => result.push(self.parse_token_tree().into()),
2659 TokenStream::concat(result)
2662 /// Parse a prefix-unary-operator expr
2663 pub fn parse_prefix_expr(&mut self,
2664 already_parsed_attrs: Option<ThinVec<Attribute>>)
2665 -> PResult<'a, P<Expr>> {
2666 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2668 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2669 let (hi, ex) = match self.token {
2672 let e = self.parse_prefix_expr(None);
2673 let (span, e) = self.interpolated_or_expr_span(e)?;
2674 (lo.to(span), self.mk_unary(UnOp::Not, e))
2676 // Suggest `!` for bitwise negation when encountering a `~`
2679 let e = self.parse_prefix_expr(None);
2680 let (span, e) = self.interpolated_or_expr_span(e)?;
2681 let span_of_tilde = lo;
2682 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2683 "`~` can not be used as a unary operator");
2684 err.span_label(span_of_tilde, "did you mean `!`?");
2685 err.help("use `!` instead of `~` if you meant to perform bitwise negation");
2687 (lo.to(span), self.mk_unary(UnOp::Not, e))
2689 token::BinOp(token::Minus) => {
2691 let e = self.parse_prefix_expr(None);
2692 let (span, e) = self.interpolated_or_expr_span(e)?;
2693 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2695 token::BinOp(token::Star) => {
2697 let e = self.parse_prefix_expr(None);
2698 let (span, e) = self.interpolated_or_expr_span(e)?;
2699 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2701 token::BinOp(token::And) | token::AndAnd => {
2703 let m = self.parse_mutability();
2704 let e = self.parse_prefix_expr(None);
2705 let (span, e) = self.interpolated_or_expr_span(e)?;
2706 (lo.to(span), ExprKind::AddrOf(m, e))
2708 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2710 let place = self.parse_expr_res(
2711 Restrictions::NO_STRUCT_LITERAL,
2714 let blk = self.parse_block()?;
2715 let span = blk.span;
2716 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2717 (lo.to(span), ExprKind::InPlace(place, blk_expr))
2719 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2721 let e = self.parse_prefix_expr(None);
2722 let (span, e) = self.interpolated_or_expr_span(e)?;
2723 (lo.to(span), ExprKind::Box(e))
2725 _ => return self.parse_dot_or_call_expr(Some(attrs))
2727 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2730 /// Parse an associative expression
2732 /// This parses an expression accounting for associativity and precedence of the operators in
2734 pub fn parse_assoc_expr(&mut self,
2735 already_parsed_attrs: Option<ThinVec<Attribute>>)
2736 -> PResult<'a, P<Expr>> {
2737 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2740 /// Parse an associative expression with operators of at least `min_prec` precedence
2741 pub fn parse_assoc_expr_with(&mut self,
2744 -> PResult<'a, P<Expr>> {
2745 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2748 let attrs = match lhs {
2749 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2752 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2753 return self.parse_prefix_range_expr(attrs);
2755 self.parse_prefix_expr(attrs)?
2759 if self.expr_is_complete(&lhs) {
2760 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2763 self.expected_tokens.push(TokenType::Operator);
2764 while let Some(op) = AssocOp::from_token(&self.token) {
2766 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2767 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2768 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2769 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2770 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2771 (PrevTokenKind::Interpolated, _) => self.prev_span,
2772 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2773 if path.segments.len() == 1 => self.prev_span,
2777 let cur_op_span = self.span;
2778 let restrictions = if op.is_assign_like() {
2779 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2783 if op.precedence() < min_prec {
2786 // Warn about deprecated ... syntax (until SNAP)
2787 if self.token == token::DotDotDot {
2788 self.warn_dotdoteq(self.span);
2791 if op.is_comparison() {
2792 self.check_no_chained_comparison(&lhs, &op);
2795 if op == AssocOp::As {
2796 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2798 } else if op == AssocOp::Colon {
2799 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2802 err.span_label(self.span,
2803 "expecting a type here because of type ascription");
2804 let cm = self.sess.codemap();
2805 let cur_pos = cm.lookup_char_pos(self.span.lo());
2806 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
2807 if cur_pos.line != op_pos.line {
2808 err.span_suggestion_short(cur_op_span,
2809 "did you mean to use `;` here?",
2816 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2817 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2818 // generalise it to the Fixity::None code.
2820 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2821 // two variants are handled with `parse_prefix_range_expr` call above.
2822 // (and `x...y`/`x...` until SNAP)
2823 let rhs = if self.is_at_start_of_range_notation_rhs() {
2824 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2825 LhsExpr::NotYetParsed)?)
2829 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2834 let limits = if op == AssocOp::DotDot {
2835 RangeLimits::HalfOpen
2840 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2841 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2845 let rhs = match op.fixity() {
2846 Fixity::Right => self.with_res(
2847 restrictions - Restrictions::STMT_EXPR,
2849 this.parse_assoc_expr_with(op.precedence(),
2850 LhsExpr::NotYetParsed)
2852 Fixity::Left => self.with_res(
2853 restrictions - Restrictions::STMT_EXPR,
2855 this.parse_assoc_expr_with(op.precedence() + 1,
2856 LhsExpr::NotYetParsed)
2858 // We currently have no non-associative operators that are not handled above by
2859 // the special cases. The code is here only for future convenience.
2860 Fixity::None => self.with_res(
2861 restrictions - Restrictions::STMT_EXPR,
2863 this.parse_assoc_expr_with(op.precedence() + 1,
2864 LhsExpr::NotYetParsed)
2868 let span = lhs_span.to(rhs.span);
2870 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2871 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2872 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2873 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2874 AssocOp::Greater | AssocOp::GreaterEqual => {
2875 let ast_op = op.to_ast_binop().unwrap();
2876 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2877 self.mk_expr(span, binary, ThinVec::new())
2880 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2882 self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
2883 AssocOp::AssignOp(k) => {
2885 token::Plus => BinOpKind::Add,
2886 token::Minus => BinOpKind::Sub,
2887 token::Star => BinOpKind::Mul,
2888 token::Slash => BinOpKind::Div,
2889 token::Percent => BinOpKind::Rem,
2890 token::Caret => BinOpKind::BitXor,
2891 token::And => BinOpKind::BitAnd,
2892 token::Or => BinOpKind::BitOr,
2893 token::Shl => BinOpKind::Shl,
2894 token::Shr => BinOpKind::Shr,
2896 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2897 self.mk_expr(span, aopexpr, ThinVec::new())
2899 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
2900 self.bug("AssocOp should have been handled by special case")
2904 if op.fixity() == Fixity::None { break }
2909 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
2910 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
2911 -> PResult<'a, P<Expr>> {
2912 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
2913 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
2916 // Save the state of the parser before parsing type normally, in case there is a
2917 // LessThan comparison after this cast.
2918 let parser_snapshot_before_type = self.clone();
2919 match self.parse_ty_no_plus() {
2921 Ok(mk_expr(self, rhs))
2923 Err(mut type_err) => {
2924 // Rewind to before attempting to parse the type with generics, to recover
2925 // from situations like `x as usize < y` in which we first tried to parse
2926 // `usize < y` as a type with generic arguments.
2927 let parser_snapshot_after_type = self.clone();
2928 mem::replace(self, parser_snapshot_before_type);
2930 match self.parse_path(PathStyle::Expr) {
2932 let (op_noun, op_verb) = match self.token {
2933 token::Lt => ("comparison", "comparing"),
2934 token::BinOp(token::Shl) => ("shift", "shifting"),
2936 // We can end up here even without `<` being the next token, for
2937 // example because `parse_ty_no_plus` returns `Err` on keywords,
2938 // but `parse_path` returns `Ok` on them due to error recovery.
2939 // Return original error and parser state.
2940 mem::replace(self, parser_snapshot_after_type);
2941 return Err(type_err);
2945 // Successfully parsed the type path leaving a `<` yet to parse.
2948 // Report non-fatal diagnostics, keep `x as usize` as an expression
2949 // in AST and continue parsing.
2950 let msg = format!("`<` is interpreted as a start of generic \
2951 arguments for `{}`, not a {}", path, op_noun);
2952 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
2953 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
2954 "interpreted as generic arguments");
2955 err.span_label(self.span, format!("not interpreted as {}", op_noun));
2957 let expr = mk_expr(self, P(Ty {
2959 node: TyKind::Path(None, path),
2960 id: ast::DUMMY_NODE_ID
2963 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
2964 .unwrap_or(pprust::expr_to_string(&expr));
2965 err.span_suggestion(expr.span,
2966 &format!("try {} the casted value", op_verb),
2967 format!("({})", expr_str));
2972 Err(mut path_err) => {
2973 // Couldn't parse as a path, return original error and parser state.
2975 mem::replace(self, parser_snapshot_after_type);
2983 /// Produce an error if comparison operators are chained (RFC #558).
2984 /// We only need to check lhs, not rhs, because all comparison ops
2985 /// have same precedence and are left-associative
2986 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2987 debug_assert!(outer_op.is_comparison(),
2988 "check_no_chained_comparison: {:?} is not comparison",
2991 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2992 // respan to include both operators
2993 let op_span = op.span.to(self.span);
2994 let mut err = self.diagnostic().struct_span_err(op_span,
2995 "chained comparison operators require parentheses");
2996 if op.node == BinOpKind::Lt &&
2997 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
2998 *outer_op == AssocOp::Greater // even in a case like the following:
2999 { // Foo<Bar<Baz<Qux, ()>>>
3001 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3002 err.help("or use `(...)` if you meant to specify fn arguments");
3010 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr` (and `...expr` until SNAP)
3011 fn parse_prefix_range_expr(&mut self,
3012 already_parsed_attrs: Option<ThinVec<Attribute>>)
3013 -> PResult<'a, P<Expr>> {
3014 // SNAP remove DotDotDot
3015 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3016 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotDot/DotDotEq",
3018 let tok = self.token.clone();
3019 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3021 let mut hi = self.span;
3022 // Warn about deprecated ... syntax (until SNAP)
3023 if tok == token::DotDotDot {
3024 self.warn_dotdoteq(self.span);
3027 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3028 // RHS must be parsed with more associativity than the dots.
3029 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3030 Some(self.parse_assoc_expr_with(next_prec,
3031 LhsExpr::NotYetParsed)
3039 let limits = if tok == token::DotDot {
3040 RangeLimits::HalfOpen
3045 let r = try!(self.mk_range(None,
3048 Ok(self.mk_expr(lo.to(hi), r, attrs))
3051 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3052 if self.token.can_begin_expr() {
3053 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3054 if self.token == token::OpenDelim(token::Brace) {
3055 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3063 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3064 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3065 if self.check_keyword(keywords::Let) {
3066 return self.parse_if_let_expr(attrs);
3068 let lo = self.prev_span;
3069 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3071 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3072 // verify that the last statement is either an implicit return (no `;`) or an explicit
3073 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3074 // the dead code lint.
3075 if self.eat_keyword(keywords::Else) || !cond.returns() {
3076 let sp = lo.next_point();
3077 let mut err = self.diagnostic()
3078 .struct_span_err(sp, "missing condition for `if` statemement");
3079 err.span_label(sp, "expected if condition here");
3082 let thn = self.parse_block()?;
3083 let mut els: Option<P<Expr>> = None;
3084 let mut hi = thn.span;
3085 if self.eat_keyword(keywords::Else) {
3086 let elexpr = self.parse_else_expr()?;
3090 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3093 /// Parse an 'if let' expression ('if' token already eaten)
3094 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3095 -> PResult<'a, P<Expr>> {
3096 let lo = self.prev_span;
3097 self.expect_keyword(keywords::Let)?;
3098 let pat = self.parse_pat()?;
3099 self.expect(&token::Eq)?;
3100 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3101 let thn = self.parse_block()?;
3102 let (hi, els) = if self.eat_keyword(keywords::Else) {
3103 let expr = self.parse_else_expr()?;
3104 (expr.span, Some(expr))
3108 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
3111 // `move |args| expr`
3112 pub fn parse_lambda_expr(&mut self,
3114 capture_clause: CaptureBy,
3115 attrs: ThinVec<Attribute>)
3116 -> PResult<'a, P<Expr>>
3118 let decl = self.parse_fn_block_decl()?;
3119 let decl_hi = self.prev_span;
3120 let body = match decl.output {
3121 FunctionRetTy::Default(_) => {
3122 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3123 self.parse_expr_res(restrictions, None)?
3126 // If an explicit return type is given, require a
3127 // block to appear (RFC 968).
3128 let body_lo = self.span;
3129 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3135 ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3139 // `else` token already eaten
3140 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3141 if self.eat_keyword(keywords::If) {
3142 return self.parse_if_expr(ThinVec::new());
3144 let blk = self.parse_block()?;
3145 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3149 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3150 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3152 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3153 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3155 let pat = self.parse_pat()?;
3156 if !self.eat_keyword(keywords::In) {
3157 let in_span = self.prev_span.between(self.span);
3158 let mut err = self.sess.span_diagnostic
3159 .struct_span_err(in_span, "missing `in` in `for` loop");
3160 err.span_suggestion_short(in_span, "try adding `in` here", " in ".into());
3163 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3164 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3165 attrs.extend(iattrs);
3167 let hi = self.prev_span;
3168 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3171 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3172 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3174 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3175 if self.token.is_keyword(keywords::Let) {
3176 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3178 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3179 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3180 attrs.extend(iattrs);
3181 let span = span_lo.to(body.span);
3182 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3185 /// Parse a 'while let' expression ('while' token already eaten)
3186 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3188 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3189 self.expect_keyword(keywords::Let)?;
3190 let pat = self.parse_pat()?;
3191 self.expect(&token::Eq)?;
3192 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3193 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3194 attrs.extend(iattrs);
3195 let span = span_lo.to(body.span);
3196 return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3199 // parse `loop {...}`, `loop` token already eaten
3200 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3202 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3203 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3204 attrs.extend(iattrs);
3205 let span = span_lo.to(body.span);
3206 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3209 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3210 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3211 -> PResult<'a, P<Expr>>
3213 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3214 attrs.extend(iattrs);
3215 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3218 // `match` token already eaten
3219 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3220 let match_span = self.prev_span;
3221 let lo = self.prev_span;
3222 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3224 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3225 if self.token == token::Token::Semi {
3226 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3230 attrs.extend(self.parse_inner_attributes()?);
3232 let mut arms: Vec<Arm> = Vec::new();
3233 while self.token != token::CloseDelim(token::Brace) {
3234 match self.parse_arm() {
3235 Ok(arm) => arms.push(arm),
3237 // Recover by skipping to the end of the block.
3239 self.recover_stmt();
3240 let span = lo.to(self.span);
3241 if self.token == token::CloseDelim(token::Brace) {
3244 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3250 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3253 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3254 maybe_whole!(self, NtArm, |x| x);
3256 let attrs = self.parse_outer_attributes()?;
3257 // Allow a '|' before the pats (RFC 1925)
3258 let beginning_vert = if self.eat(&token::BinOp(token::Or)) {
3259 Some(self.prev_span)
3263 let pats = self.parse_pats()?;
3264 let guard = if self.eat_keyword(keywords::If) {
3265 Some(self.parse_expr()?)
3269 self.expect(&token::FatArrow)?;
3270 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)?;
3272 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3273 && self.token != token::CloseDelim(token::Brace);
3276 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3278 self.eat(&token::Comma);
3290 /// Parse an expression
3291 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3292 self.parse_expr_res(Restrictions::empty(), None)
3295 /// Evaluate the closure with restrictions in place.
3297 /// After the closure is evaluated, restrictions are reset.
3298 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3299 where F: FnOnce(&mut Self) -> T
3301 let old = self.restrictions;
3302 self.restrictions = r;
3304 self.restrictions = old;
3309 /// Parse an expression, subject to the given restrictions
3310 pub fn parse_expr_res(&mut self, r: Restrictions,
3311 already_parsed_attrs: Option<ThinVec<Attribute>>)
3312 -> PResult<'a, P<Expr>> {
3313 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3316 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3317 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3318 if self.check(&token::Eq) {
3320 Ok(Some(self.parse_expr()?))
3322 Ok(Some(self.parse_expr()?))
3328 /// Parse patterns, separated by '|' s
3329 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3330 let mut pats = Vec::new();
3332 pats.push(self.parse_pat()?);
3333 if self.check(&token::BinOp(token::Or)) { self.bump();}
3334 else { return Ok(pats); }
3338 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3339 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3340 let mut fields = vec![];
3341 let mut ddpos = None;
3343 while !self.check(&token::CloseDelim(token::Paren)) {
3344 if ddpos.is_none() && self.eat(&token::DotDot) {
3345 ddpos = Some(fields.len());
3346 if self.eat(&token::Comma) {
3347 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3348 fields.push(self.parse_pat()?);
3350 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3351 // Emit a friendly error, ignore `..` and continue parsing
3352 self.span_err(self.prev_span, "`..` can only be used once per \
3353 tuple or tuple struct pattern");
3355 fields.push(self.parse_pat()?);
3358 if !self.check(&token::CloseDelim(token::Paren)) ||
3359 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3360 self.expect(&token::Comma)?;
3367 fn parse_pat_vec_elements(
3369 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3370 let mut before = Vec::new();
3371 let mut slice = None;
3372 let mut after = Vec::new();
3373 let mut first = true;
3374 let mut before_slice = true;
3376 while self.token != token::CloseDelim(token::Bracket) {
3380 self.expect(&token::Comma)?;
3382 if self.token == token::CloseDelim(token::Bracket)
3383 && (before_slice || !after.is_empty()) {
3389 if self.eat(&token::DotDot) {
3391 if self.check(&token::Comma) ||
3392 self.check(&token::CloseDelim(token::Bracket)) {
3393 slice = Some(P(ast::Pat {
3394 id: ast::DUMMY_NODE_ID,
3395 node: PatKind::Wild,
3398 before_slice = false;
3404 let subpat = self.parse_pat()?;
3405 if before_slice && self.eat(&token::DotDot) {
3406 slice = Some(subpat);
3407 before_slice = false;
3408 } else if before_slice {
3409 before.push(subpat);
3415 Ok((before, slice, after))
3418 /// Parse the fields of a struct-like pattern
3419 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3420 let mut fields = Vec::new();
3421 let mut etc = false;
3422 let mut first = true;
3423 while self.token != token::CloseDelim(token::Brace) {
3427 self.expect(&token::Comma)?;
3428 // accept trailing commas
3429 if self.check(&token::CloseDelim(token::Brace)) { break }
3432 let attrs = self.parse_outer_attributes()?;
3436 if self.check(&token::DotDot) {
3438 if self.token != token::CloseDelim(token::Brace) {
3439 let token_str = self.this_token_to_string();
3440 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3447 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3448 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3449 // Parsing a pattern of the form "fieldname: pat"
3450 let fieldname = self.parse_field_name()?;
3452 let pat = self.parse_pat()?;
3454 (pat, fieldname, false)
3456 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3457 let is_box = self.eat_keyword(keywords::Box);
3458 let boxed_span = self.span;
3459 let is_ref = self.eat_keyword(keywords::Ref);
3460 let is_mut = self.eat_keyword(keywords::Mut);
3461 let fieldname = self.parse_ident()?;
3462 hi = self.prev_span;
3464 let bind_type = match (is_ref, is_mut) {
3465 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3466 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3467 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3468 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3470 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3471 let fieldpat = P(ast::Pat{
3472 id: ast::DUMMY_NODE_ID,
3473 node: PatKind::Ident(bind_type, fieldpath, None),
3474 span: boxed_span.to(hi),
3477 let subpat = if is_box {
3479 id: ast::DUMMY_NODE_ID,
3480 node: PatKind::Box(fieldpat),
3486 (subpat, fieldname, true)
3489 fields.push(codemap::Spanned { span: lo.to(hi),
3490 node: ast::FieldPat {
3494 attrs: attrs.into(),
3498 return Ok((fields, etc));
3501 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3502 if self.token.is_path_start() {
3504 let (qself, path) = if self.eat_lt() {
3505 // Parse a qualified path
3506 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3509 // Parse an unqualified path
3510 (None, self.parse_path(PathStyle::Expr)?)
3512 let hi = self.prev_span;
3513 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3515 self.parse_pat_literal_maybe_minus()
3519 // helper function to decide whether to parse as ident binding or to try to do
3520 // something more complex like range patterns
3521 fn parse_as_ident(&mut self) -> bool {
3522 self.look_ahead(1, |t| match *t {
3523 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3524 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3525 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3526 // range pattern branch
3527 token::DotDot => None,
3529 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3530 token::Comma | token::CloseDelim(token::Bracket) => true,
3535 /// Parse a pattern.
3536 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3537 maybe_whole!(self, NtPat, |x| x);
3542 token::Underscore => {
3545 pat = PatKind::Wild;
3547 token::BinOp(token::And) | token::AndAnd => {
3548 // Parse &pat / &mut pat
3550 let mutbl = self.parse_mutability();
3551 if let token::Lifetime(ident) = self.token {
3552 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3554 let subpat = self.parse_pat()?;
3555 pat = PatKind::Ref(subpat, mutbl);
3557 token::OpenDelim(token::Paren) => {
3558 // Parse (pat,pat,pat,...) as tuple pattern
3560 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3561 self.expect(&token::CloseDelim(token::Paren))?;
3562 pat = PatKind::Tuple(fields, ddpos);
3564 token::OpenDelim(token::Bracket) => {
3565 // Parse [pat,pat,...] as slice pattern
3567 let (before, slice, after) = self.parse_pat_vec_elements()?;
3568 self.expect(&token::CloseDelim(token::Bracket))?;
3569 pat = PatKind::Slice(before, slice, after);
3571 // At this point, token != _, &, &&, (, [
3572 _ => if self.eat_keyword(keywords::Mut) {
3573 // Parse mut ident @ pat / mut ref ident @ pat
3574 let mutref_span = self.prev_span.to(self.span);
3575 let binding_mode = if self.eat_keyword(keywords::Ref) {
3577 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3578 .span_suggestion(mutref_span, "try switching the order", "ref mut".into())
3580 BindingMode::ByRef(Mutability::Mutable)
3582 BindingMode::ByValue(Mutability::Mutable)
3584 pat = self.parse_pat_ident(binding_mode)?;
3585 } else if self.eat_keyword(keywords::Ref) {
3586 // Parse ref ident @ pat / ref mut ident @ pat
3587 let mutbl = self.parse_mutability();
3588 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3589 } else if self.eat_keyword(keywords::Box) {
3591 let subpat = self.parse_pat()?;
3592 pat = PatKind::Box(subpat);
3593 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3594 self.parse_as_ident() {
3595 // Parse ident @ pat
3596 // This can give false positives and parse nullary enums,
3597 // they are dealt with later in resolve
3598 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3599 pat = self.parse_pat_ident(binding_mode)?;
3600 } else if self.token.is_path_start() {
3601 // Parse pattern starting with a path
3602 let (qself, path) = if self.eat_lt() {
3603 // Parse a qualified path
3604 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3607 // Parse an unqualified path
3608 (None, self.parse_path(PathStyle::Expr)?)
3611 token::Not if qself.is_none() => {
3612 // Parse macro invocation
3614 let (_, tts) = self.expect_delimited_token_tree()?;
3615 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3616 pat = PatKind::Mac(mac);
3618 token::DotDotDot | token::DotDotEq | token::DotDot => {
3619 let end_kind = match self.token {
3620 token::DotDot => RangeEnd::Excluded,
3621 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
3622 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
3623 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
3627 let span = lo.to(self.prev_span);
3628 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3630 let end = self.parse_pat_range_end()?;
3631 pat = PatKind::Range(begin, end, end_kind);
3633 token::OpenDelim(token::Brace) => {
3634 if qself.is_some() {
3635 return Err(self.fatal("unexpected `{` after qualified path"));
3637 // Parse struct pattern
3639 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3641 self.recover_stmt();
3645 pat = PatKind::Struct(path, fields, etc);
3647 token::OpenDelim(token::Paren) => {
3648 if qself.is_some() {
3649 return Err(self.fatal("unexpected `(` after qualified path"));
3651 // Parse tuple struct or enum pattern
3653 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3654 self.expect(&token::CloseDelim(token::Paren))?;
3655 pat = PatKind::TupleStruct(path, fields, ddpos)
3657 _ => pat = PatKind::Path(qself, path),
3660 // Try to parse everything else as literal with optional minus
3661 match self.parse_pat_literal_maybe_minus() {
3663 if self.eat(&token::DotDotDot) {
3664 let end = self.parse_pat_range_end()?;
3665 pat = PatKind::Range(begin, end,
3666 RangeEnd::Included(RangeSyntax::DotDotDot));
3667 } else if self.eat(&token::DotDotEq) {
3668 let end = self.parse_pat_range_end()?;
3669 pat = PatKind::Range(begin, end,
3670 RangeEnd::Included(RangeSyntax::DotDotEq));
3671 } else if self.eat(&token::DotDot) {
3672 let end = self.parse_pat_range_end()?;
3673 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3675 pat = PatKind::Lit(begin);
3679 self.cancel(&mut err);
3680 let msg = format!("expected pattern, found {}", self.this_token_descr());
3681 return Err(self.fatal(&msg));
3688 id: ast::DUMMY_NODE_ID,
3690 span: lo.to(self.prev_span),
3694 /// Parse ident or ident @ pat
3695 /// used by the copy foo and ref foo patterns to give a good
3696 /// error message when parsing mistakes like ref foo(a,b)
3697 fn parse_pat_ident(&mut self,
3698 binding_mode: ast::BindingMode)
3699 -> PResult<'a, PatKind> {
3700 let ident_span = self.span;
3701 let ident = self.parse_ident()?;
3702 let name = codemap::Spanned{span: ident_span, node: ident};
3703 let sub = if self.eat(&token::At) {
3704 Some(self.parse_pat()?)
3709 // just to be friendly, if they write something like
3711 // we end up here with ( as the current token. This shortly
3712 // leads to a parse error. Note that if there is no explicit
3713 // binding mode then we do not end up here, because the lookahead
3714 // will direct us over to parse_enum_variant()
3715 if self.token == token::OpenDelim(token::Paren) {
3716 return Err(self.span_fatal(
3718 "expected identifier, found enum pattern"))
3721 Ok(PatKind::Ident(binding_mode, name, sub))
3724 /// Parse a local variable declaration
3725 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3726 let lo = self.prev_span;
3727 let pat = self.parse_pat()?;
3729 let (err, ty) = if self.eat(&token::Colon) {
3730 // Save the state of the parser before parsing type normally, in case there is a `:`
3731 // instead of an `=` typo.
3732 let parser_snapshot_before_type = self.clone();
3733 let colon_sp = self.prev_span;
3734 match self.parse_ty() {
3735 Ok(ty) => (None, Some(ty)),
3737 // Rewind to before attempting to parse the type and continue parsing
3738 let parser_snapshot_after_type = self.clone();
3739 mem::replace(self, parser_snapshot_before_type);
3741 let snippet = self.sess.codemap().span_to_snippet(pat.span).unwrap();
3742 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
3743 (Some((parser_snapshot_after_type, colon_sp, err)), None)
3749 let init = match (self.parse_initializer(err.is_some()), err) {
3750 (Ok(init), None) => { // init parsed, ty parsed
3753 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
3754 // Could parse the type as if it were the initializer, it is likely there was a
3755 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
3756 err.span_suggestion_short(colon_sp,
3757 "use `=` if you meant to assign",
3760 // As this was parsed successfuly, continue as if the code has been fixed for the
3761 // rest of the file. It will still fail due to the emitted error, but we avoid
3765 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
3767 // Couldn't parse the type nor the initializer, only raise the type error and
3768 // return to the parser state before parsing the type as the initializer.
3769 // let x: <parse_error>;
3770 mem::replace(self, snapshot);
3773 (Err(err), None) => { // init error, ty parsed
3774 // Couldn't parse the initializer and we're not attempting to recover a failed
3775 // parse of the type, return the error.
3779 let hi = if self.token == token::Semi {
3788 id: ast::DUMMY_NODE_ID,
3794 /// Parse a structure field
3795 fn parse_name_and_ty(&mut self,
3798 attrs: Vec<Attribute>)
3799 -> PResult<'a, StructField> {
3800 let name = self.parse_ident()?;
3801 self.expect(&token::Colon)?;
3802 let ty = self.parse_ty()?;
3804 span: lo.to(self.prev_span),
3807 id: ast::DUMMY_NODE_ID,
3813 /// Emit an expected item after attributes error.
3814 fn expected_item_err(&self, attrs: &[Attribute]) {
3815 let message = match attrs.last() {
3816 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3817 _ => "expected item after attributes",
3820 self.span_err(self.prev_span, message);
3823 /// Parse a statement. This stops just before trailing semicolons on everything but items.
3824 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3825 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3826 Ok(self.parse_stmt_(true))
3829 // Eat tokens until we can be relatively sure we reached the end of the
3830 // statement. This is something of a best-effort heuristic.
3832 // We terminate when we find an unmatched `}` (without consuming it).
3833 fn recover_stmt(&mut self) {
3834 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
3837 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3838 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3839 // approximate - it can mean we break too early due to macros, but that
3840 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3842 // If `break_on_block` is `Break`, then we will stop consuming tokens
3843 // after finding (and consuming) a brace-delimited block.
3844 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
3845 let mut brace_depth = 0;
3846 let mut bracket_depth = 0;
3847 let mut in_block = false;
3848 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
3849 break_on_semi, break_on_block);
3851 debug!("recover_stmt_ loop {:?}", self.token);
3853 token::OpenDelim(token::DelimToken::Brace) => {
3856 if break_on_block == BlockMode::Break &&
3858 bracket_depth == 0 {
3862 token::OpenDelim(token::DelimToken::Bracket) => {
3866 token::CloseDelim(token::DelimToken::Brace) => {
3867 if brace_depth == 0 {
3868 debug!("recover_stmt_ return - close delim {:?}", self.token);
3873 if in_block && bracket_depth == 0 && brace_depth == 0 {
3874 debug!("recover_stmt_ return - block end {:?}", self.token);
3878 token::CloseDelim(token::DelimToken::Bracket) => {
3880 if bracket_depth < 0 {
3886 debug!("recover_stmt_ return - Eof");
3891 if break_on_semi == SemiColonMode::Break &&
3893 bracket_depth == 0 {
3894 debug!("recover_stmt_ return - Semi");
3905 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
3906 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
3908 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
3913 fn is_catch_expr(&mut self) -> bool {
3914 self.token.is_keyword(keywords::Do) &&
3915 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
3916 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
3918 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3919 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
3922 fn is_union_item(&self) -> bool {
3923 self.token.is_keyword(keywords::Union) &&
3924 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
3927 fn eat_auto_trait(&mut self) -> bool {
3928 if self.token.is_keyword(keywords::Auto)
3929 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
3931 self.eat_keyword(keywords::Auto) && self.eat_keyword(keywords::Trait)
3937 fn is_defaultness(&self) -> bool {
3938 // `pub` is included for better error messages
3939 self.token.is_keyword(keywords::Default) &&
3940 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
3941 t.is_keyword(keywords::Const) ||
3942 t.is_keyword(keywords::Fn) ||
3943 t.is_keyword(keywords::Unsafe) ||
3944 t.is_keyword(keywords::Extern) ||
3945 t.is_keyword(keywords::Type) ||
3946 t.is_keyword(keywords::Pub))
3949 fn eat_defaultness(&mut self) -> bool {
3950 let is_defaultness = self.is_defaultness();
3954 self.expected_tokens.push(TokenType::Keyword(keywords::Default));
3959 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
3960 -> PResult<'a, Option<P<Item>>> {
3961 let token_lo = self.span;
3962 let (ident, def) = match self.token {
3963 token::Ident(ident) if ident.name == keywords::Macro.name() => {
3965 let ident = self.parse_ident()?;
3966 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
3967 match self.parse_token_tree() {
3968 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
3969 _ => unreachable!(),
3971 } else if self.check(&token::OpenDelim(token::Paren)) {
3972 let args = self.parse_token_tree();
3973 let body = if self.check(&token::OpenDelim(token::Brace)) {
3974 self.parse_token_tree()
3979 TokenStream::concat(vec![
3981 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
3989 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
3991 token::Ident(ident) if ident.name == "macro_rules" &&
3992 self.look_ahead(1, |t| *t == token::Not) => {
3993 let prev_span = self.prev_span;
3994 self.complain_if_pub_macro(vis, prev_span);
3998 let ident = self.parse_ident()?;
3999 let (delim, tokens) = self.expect_delimited_token_tree()?;
4000 if delim != token::Brace {
4001 if !self.eat(&token::Semi) {
4002 let msg = "macros that expand to items must either \
4003 be surrounded with braces or followed by a semicolon";
4004 self.span_err(self.prev_span, msg);
4008 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4010 _ => return Ok(None),
4013 let span = lo.to(self.prev_span);
4014 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4017 fn parse_stmt_without_recovery(&mut self,
4018 macro_legacy_warnings: bool)
4019 -> PResult<'a, Option<Stmt>> {
4020 maybe_whole!(self, NtStmt, |x| Some(x));
4022 let attrs = self.parse_outer_attributes()?;
4025 Ok(Some(if self.eat_keyword(keywords::Let) {
4027 id: ast::DUMMY_NODE_ID,
4028 node: StmtKind::Local(self.parse_local(attrs.into())?),
4029 span: lo.to(self.prev_span),
4031 } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited, lo)? {
4033 id: ast::DUMMY_NODE_ID,
4034 node: StmtKind::Item(macro_def),
4035 span: lo.to(self.prev_span),
4037 // Starts like a simple path, but not a union item.
4038 } else if self.token.is_path_start() &&
4039 !self.token.is_qpath_start() &&
4040 !self.is_union_item() {
4041 let pth = self.parse_path(PathStyle::Expr)?;
4043 if !self.eat(&token::Not) {
4044 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4045 self.parse_struct_expr(lo, pth, ThinVec::new())?
4047 let hi = self.prev_span;
4048 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4051 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4052 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4053 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4056 return Ok(Some(Stmt {
4057 id: ast::DUMMY_NODE_ID,
4058 node: StmtKind::Expr(expr),
4059 span: lo.to(self.prev_span),
4063 // it's a macro invocation
4064 let id = match self.token {
4065 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4066 _ => self.parse_ident()?,
4069 // check that we're pointing at delimiters (need to check
4070 // again after the `if`, because of `parse_ident`
4071 // consuming more tokens).
4072 let delim = match self.token {
4073 token::OpenDelim(delim) => delim,
4075 // we only expect an ident if we didn't parse one
4077 let ident_str = if id.name == keywords::Invalid.name() {
4082 let tok_str = self.this_token_to_string();
4083 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4089 let (_, tts) = self.expect_delimited_token_tree()?;
4090 let hi = self.prev_span;
4092 let style = if delim == token::Brace {
4093 MacStmtStyle::Braces
4095 MacStmtStyle::NoBraces
4098 if id.name == keywords::Invalid.name() {
4099 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
4100 let node = if delim == token::Brace ||
4101 self.token == token::Semi || self.token == token::Eof {
4102 StmtKind::Mac(P((mac, style, attrs.into())))
4104 // We used to incorrectly stop parsing macro-expanded statements here.
4105 // If the next token will be an error anyway but could have parsed with the
4106 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4107 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4108 // These can continue an expression, so we can't stop parsing and warn.
4109 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4110 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4111 token::BinOp(token::And) | token::BinOp(token::Or) |
4112 token::AndAnd | token::OrOr |
4113 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4116 self.warn_missing_semicolon();
4117 StmtKind::Mac(P((mac, style, attrs.into())))
4119 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4120 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4121 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4125 id: ast::DUMMY_NODE_ID,
4130 // if it has a special ident, it's definitely an item
4132 // Require a semicolon or braces.
4133 if style != MacStmtStyle::Braces {
4134 if !self.eat(&token::Semi) {
4135 self.span_err(self.prev_span,
4136 "macros that expand to items must \
4137 either be surrounded with braces or \
4138 followed by a semicolon");
4141 let span = lo.to(hi);
4143 id: ast::DUMMY_NODE_ID,
4145 node: StmtKind::Item({
4147 span, id /*id is good here*/,
4148 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
4149 Visibility::Inherited,
4155 // FIXME: Bad copy of attrs
4156 let old_directory_ownership =
4157 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4158 let item = self.parse_item_(attrs.clone(), false, true)?;
4159 self.directory.ownership = old_directory_ownership;
4163 id: ast::DUMMY_NODE_ID,
4164 span: lo.to(i.span),
4165 node: StmtKind::Item(i),
4168 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4169 if !attrs.is_empty() {
4170 if s.prev_token_kind == PrevTokenKind::DocComment {
4171 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4172 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4173 s.span_err(s.span, "expected statement after outer attribute");
4178 // Do not attempt to parse an expression if we're done here.
4179 if self.token == token::Semi {
4180 unused_attrs(&attrs, self);
4185 if self.token == token::CloseDelim(token::Brace) {
4186 unused_attrs(&attrs, self);
4190 // Remainder are line-expr stmts.
4191 let e = self.parse_expr_res(
4192 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4194 id: ast::DUMMY_NODE_ID,
4195 span: lo.to(e.span),
4196 node: StmtKind::Expr(e),
4203 /// Is this expression a successfully-parsed statement?
4204 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4205 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4206 !classify::expr_requires_semi_to_be_stmt(e)
4209 /// Parse a block. No inner attrs are allowed.
4210 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4211 maybe_whole!(self, NtBlock, |x| x);
4215 if !self.eat(&token::OpenDelim(token::Brace)) {
4217 let tok = self.this_token_to_string();
4218 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4220 // Check to see if the user has written something like
4225 // Which is valid in other languages, but not Rust.
4226 match self.parse_stmt_without_recovery(false) {
4228 let mut stmt_span = stmt.span;
4229 // expand the span to include the semicolon, if it exists
4230 if self.eat(&token::Semi) {
4231 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4233 let sugg = pprust::to_string(|s| {
4234 use print::pprust::{PrintState, INDENT_UNIT};
4235 s.ibox(INDENT_UNIT)?;
4237 s.print_stmt(&stmt)?;
4238 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4240 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4243 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4244 self.cancel(&mut e);
4251 self.parse_block_tail(lo, BlockCheckMode::Default)
4254 /// Parse a block. Inner attrs are allowed.
4255 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4256 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4259 self.expect(&token::OpenDelim(token::Brace))?;
4260 Ok((self.parse_inner_attributes()?,
4261 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4264 /// Parse the rest of a block expression or function body
4265 /// Precondition: already parsed the '{'.
4266 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4267 let mut stmts = vec![];
4269 while !self.eat(&token::CloseDelim(token::Brace)) {
4270 if let Some(stmt) = self.parse_full_stmt(false)? {
4272 } else if self.token == token::Eof {
4275 // Found only `;` or `}`.
4282 id: ast::DUMMY_NODE_ID,
4284 span: lo.to(self.prev_span),
4288 /// Parse a statement, including the trailing semicolon.
4289 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4290 let mut stmt = match self.parse_stmt_(macro_legacy_warnings) {
4292 None => return Ok(None),
4296 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4297 // expression without semicolon
4298 if classify::expr_requires_semi_to_be_stmt(expr) {
4299 // Just check for errors and recover; do not eat semicolon yet.
4301 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4304 self.recover_stmt();
4308 StmtKind::Local(..) => {
4309 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4310 if macro_legacy_warnings && self.token != token::Semi {
4311 self.warn_missing_semicolon();
4313 self.expect_one_of(&[token::Semi], &[])?;
4319 if self.eat(&token::Semi) {
4320 stmt = stmt.add_trailing_semicolon();
4323 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4327 fn warn_missing_semicolon(&self) {
4328 self.diagnostic().struct_span_warn(self.span, {
4329 &format!("expected `;`, found `{}`", self.this_token_to_string())
4331 "This was erroneously allowed and will become a hard error in a future release"
4335 fn warn_dotdoteq(&self, span: Span) {
4336 self.diagnostic().struct_span_warn(span, {
4337 "`...` is being replaced by `..=`"
4341 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4342 // BOUND = TY_BOUND | LT_BOUND
4343 // LT_BOUND = LIFETIME (e.g. `'a`)
4344 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4345 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4346 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4347 let mut bounds = Vec::new();
4349 // This needs to be syncronized with `Token::can_begin_bound`.
4350 let is_bound_start = self.check_path() || self.check_lifetime() ||
4351 self.check(&token::Question) ||
4352 self.check_keyword(keywords::For) ||
4353 self.check(&token::OpenDelim(token::Paren));
4355 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4356 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4357 if self.token.is_lifetime() {
4358 if let Some(question_span) = question {
4359 self.span_err(question_span,
4360 "`?` may only modify trait bounds, not lifetime bounds");
4362 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4365 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4366 let path = self.parse_path(PathStyle::Type)?;
4367 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4368 let modifier = if question.is_some() {
4369 TraitBoundModifier::Maybe
4371 TraitBoundModifier::None
4373 bounds.push(TraitTyParamBound(poly_trait, modifier));
4376 self.expect(&token::CloseDelim(token::Paren))?;
4377 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4378 self.span_err(self.prev_span,
4379 "parenthesized lifetime bounds are not supported");
4386 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4394 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4395 self.parse_ty_param_bounds_common(true)
4398 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4399 // BOUND = LT_BOUND (e.g. `'a`)
4400 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4401 let mut lifetimes = Vec::new();
4402 while self.check_lifetime() {
4403 lifetimes.push(self.expect_lifetime());
4405 if !self.eat(&token::BinOp(token::Plus)) {
4412 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4413 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4414 let span = self.span;
4415 let ident = self.parse_ident()?;
4417 // Parse optional colon and param bounds.
4418 let bounds = if self.eat(&token::Colon) {
4419 self.parse_ty_param_bounds()?
4424 let default = if self.eat(&token::Eq) {
4425 Some(self.parse_ty()?)
4431 attrs: preceding_attrs.into(),
4433 id: ast::DUMMY_NODE_ID,
4440 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4441 /// trailing comma and erroneous trailing attributes.
4442 pub fn parse_generic_params(&mut self) -> PResult<'a, (Vec<LifetimeDef>, Vec<TyParam>)> {
4443 let mut lifetime_defs = Vec::new();
4444 let mut ty_params = Vec::new();
4445 let mut seen_ty_param = false;
4447 let attrs = self.parse_outer_attributes()?;
4448 if self.check_lifetime() {
4449 let lifetime = self.expect_lifetime();
4450 // Parse lifetime parameter.
4451 let bounds = if self.eat(&token::Colon) {
4452 self.parse_lt_param_bounds()
4456 lifetime_defs.push(LifetimeDef {
4457 attrs: attrs.into(),
4462 self.span_err(self.prev_span,
4463 "lifetime parameters must be declared prior to type parameters");
4465 } else if self.check_ident() {
4466 // Parse type parameter.
4467 ty_params.push(self.parse_ty_param(attrs)?);
4468 seen_ty_param = true;
4470 // Check for trailing attributes and stop parsing.
4471 if !attrs.is_empty() {
4472 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4473 self.span_err(attrs[0].span,
4474 &format!("trailing attribute after {} parameters", param_kind));
4479 if !self.eat(&token::Comma) {
4483 Ok((lifetime_defs, ty_params))
4486 /// Parse a set of optional generic type parameter declarations. Where
4487 /// clauses are not parsed here, and must be added later via
4488 /// `parse_where_clause()`.
4490 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4491 /// | ( < lifetimes , typaramseq ( , )? > )
4492 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4493 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4494 maybe_whole!(self, NtGenerics, |x| x);
4496 let span_lo = self.span;
4498 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4501 lifetimes: lifetime_defs,
4503 where_clause: WhereClause {
4504 id: ast::DUMMY_NODE_ID,
4505 predicates: Vec::new(),
4506 span: syntax_pos::DUMMY_SP,
4508 span: span_lo.to(self.prev_span),
4511 Ok(ast::Generics::default())
4515 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4516 /// possibly including trailing comma.
4517 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4518 let mut lifetimes = Vec::new();
4519 let mut types = Vec::new();
4520 let mut bindings = Vec::new();
4521 let mut seen_type = false;
4522 let mut seen_binding = false;
4524 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4525 // Parse lifetime argument.
4526 lifetimes.push(self.expect_lifetime());
4527 if seen_type || seen_binding {
4528 self.span_err(self.prev_span,
4529 "lifetime parameters must be declared prior to type parameters");
4531 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4532 // Parse associated type binding.
4534 let ident = self.parse_ident()?;
4536 let ty = self.parse_ty()?;
4537 bindings.push(TypeBinding {
4538 id: ast::DUMMY_NODE_ID,
4541 span: lo.to(self.prev_span),
4543 seen_binding = true;
4544 } else if self.check_type() {
4545 // Parse type argument.
4546 types.push(self.parse_ty()?);
4548 self.span_err(types[types.len() - 1].span,
4549 "type parameters must be declared prior to associated type bindings");
4556 if !self.eat(&token::Comma) {
4560 Ok((lifetimes, types, bindings))
4563 /// Parses an optional `where` clause and places it in `generics`.
4565 /// ```ignore (only-for-syntax-highlight)
4566 /// where T : Trait<U, V> + 'b, 'a : 'b
4568 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4569 maybe_whole!(self, NtWhereClause, |x| x);
4571 let mut where_clause = WhereClause {
4572 id: ast::DUMMY_NODE_ID,
4573 predicates: Vec::new(),
4574 span: syntax_pos::DUMMY_SP,
4577 if !self.eat_keyword(keywords::Where) {
4578 return Ok(where_clause);
4580 let lo = self.prev_span;
4582 // This is a temporary future proofing.
4584 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4585 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4586 // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4587 if token::Lt == self.token {
4588 let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4589 if ident_or_lifetime {
4590 let gt_comma_or_colon = self.look_ahead(2, |t| {
4591 *t == token::Gt || *t == token::Comma || *t == token::Colon
4593 if gt_comma_or_colon {
4594 self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4601 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4602 let lifetime = self.expect_lifetime();
4603 // Bounds starting with a colon are mandatory, but possibly empty.
4604 self.expect(&token::Colon)?;
4605 let bounds = self.parse_lt_param_bounds();
4606 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4607 ast::WhereRegionPredicate {
4608 span: lo.to(self.prev_span),
4613 } else if self.check_type() {
4614 // Parse optional `for<'a, 'b>`.
4615 // This `for` is parsed greedily and applies to the whole predicate,
4616 // the bounded type can have its own `for` applying only to it.
4617 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4618 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4619 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4620 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4622 // Parse type with mandatory colon and (possibly empty) bounds,
4623 // or with mandatory equality sign and the second type.
4624 let ty = self.parse_ty()?;
4625 if self.eat(&token::Colon) {
4626 let bounds = self.parse_ty_param_bounds()?;
4627 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4628 ast::WhereBoundPredicate {
4629 span: lo.to(self.prev_span),
4630 bound_lifetimes: lifetime_defs,
4635 // FIXME: Decide what should be used here, `=` or `==`.
4636 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4637 let rhs_ty = self.parse_ty()?;
4638 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4639 ast::WhereEqPredicate {
4640 span: lo.to(self.prev_span),
4643 id: ast::DUMMY_NODE_ID,
4647 return self.unexpected();
4653 if !self.eat(&token::Comma) {
4658 where_clause.span = lo.to(self.prev_span);
4662 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4663 -> PResult<'a, (Vec<Arg> , bool)> {
4665 let mut variadic = false;
4666 let args: Vec<Option<Arg>> =
4667 self.parse_unspanned_seq(
4668 &token::OpenDelim(token::Paren),
4669 &token::CloseDelim(token::Paren),
4670 SeqSep::trailing_allowed(token::Comma),
4672 if p.token == token::DotDotDot {
4675 if p.token != token::CloseDelim(token::Paren) {
4678 "`...` must be last in argument list for variadic function");
4683 "only foreign functions are allowed to be variadic");
4688 match p.parse_arg_general(named_args) {
4689 Ok(arg) => Ok(Some(arg)),
4692 let lo = p.prev_span;
4693 // Skip every token until next possible arg or end.
4694 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4695 // Create a placeholder argument for proper arg count (#34264).
4696 let span = lo.to(p.prev_span);
4697 Ok(Some(dummy_arg(span)))
4704 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4706 if variadic && args.is_empty() {
4708 "variadic function must be declared with at least one named argument");
4711 Ok((args, variadic))
4714 /// Parse the argument list and result type of a function declaration
4715 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4717 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4718 let ret_ty = self.parse_ret_ty()?;
4727 /// Returns the parsed optional self argument and whether a self shortcut was used.
4728 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4729 let expect_ident = |this: &mut Self| match this.token {
4730 // Preserve hygienic context.
4731 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4734 let isolated_self = |this: &mut Self, n| {
4735 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4736 this.look_ahead(n + 1, |t| t != &token::ModSep)
4739 // Parse optional self parameter of a method.
4740 // Only a limited set of initial token sequences is considered self parameters, anything
4741 // else is parsed as a normal function parameter list, so some lookahead is required.
4742 let eself_lo = self.span;
4743 let (eself, eself_ident) = match self.token {
4744 token::BinOp(token::And) => {
4750 if isolated_self(self, 1) {
4752 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4753 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4754 isolated_self(self, 2) {
4757 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4758 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4759 isolated_self(self, 2) {
4761 let lt = self.expect_lifetime();
4762 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4763 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4764 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4765 isolated_self(self, 3) {
4767 let lt = self.expect_lifetime();
4769 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4774 token::BinOp(token::Star) => {
4779 // Emit special error for `self` cases.
4780 if isolated_self(self, 1) {
4782 self.span_err(self.span, "cannot pass `self` by raw pointer");
4783 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4784 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4785 isolated_self(self, 2) {
4788 self.span_err(self.span, "cannot pass `self` by raw pointer");
4789 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4794 token::Ident(..) => {
4795 if isolated_self(self, 0) {
4798 let eself_ident = expect_ident(self);
4799 if self.eat(&token::Colon) {
4800 let ty = self.parse_ty()?;
4801 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4803 (SelfKind::Value(Mutability::Immutable), eself_ident)
4805 } else if self.token.is_keyword(keywords::Mut) &&
4806 isolated_self(self, 1) {
4810 let eself_ident = expect_ident(self);
4811 if self.eat(&token::Colon) {
4812 let ty = self.parse_ty()?;
4813 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4815 (SelfKind::Value(Mutability::Mutable), eself_ident)
4821 _ => return Ok(None),
4824 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
4825 Ok(Some(Arg::from_self(eself, eself_ident)))
4828 /// Parse the parameter list and result type of a function that may have a `self` parameter.
4829 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
4830 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4832 self.expect(&token::OpenDelim(token::Paren))?;
4834 // Parse optional self argument
4835 let self_arg = self.parse_self_arg()?;
4837 // Parse the rest of the function parameter list.
4838 let sep = SeqSep::trailing_allowed(token::Comma);
4839 let fn_inputs = if let Some(self_arg) = self_arg {
4840 if self.check(&token::CloseDelim(token::Paren)) {
4842 } else if self.eat(&token::Comma) {
4843 let mut fn_inputs = vec![self_arg];
4844 fn_inputs.append(&mut self.parse_seq_to_before_end(
4845 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
4849 return self.unexpected();
4852 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
4855 // Parse closing paren and return type.
4856 self.expect(&token::CloseDelim(token::Paren))?;
4859 output: self.parse_ret_ty()?,
4864 // parse the |arg, arg| header on a lambda
4865 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4866 let inputs_captures = {
4867 if self.eat(&token::OrOr) {
4870 self.expect(&token::BinOp(token::Or))?;
4871 let args = self.parse_seq_to_before_tokens(
4872 &[&token::BinOp(token::Or), &token::OrOr],
4873 SeqSep::trailing_allowed(token::Comma),
4874 TokenExpectType::NoExpect,
4875 |p| p.parse_fn_block_arg()
4881 let output = self.parse_ret_ty()?;
4884 inputs: inputs_captures,
4890 /// Parse the name and optional generic types of a function header.
4891 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4892 let id = self.parse_ident()?;
4893 let generics = self.parse_generics()?;
4897 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
4898 attrs: Vec<Attribute>) -> P<Item> {
4902 id: ast::DUMMY_NODE_ID,
4910 /// Parse an item-position function declaration.
4911 fn parse_item_fn(&mut self,
4913 constness: Spanned<Constness>,
4915 -> PResult<'a, ItemInfo> {
4916 let (ident, mut generics) = self.parse_fn_header()?;
4917 let decl = self.parse_fn_decl(false)?;
4918 generics.where_clause = self.parse_where_clause()?;
4919 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4920 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4923 /// true if we are looking at `const ID`, false for things like `const fn` etc
4924 pub fn is_const_item(&mut self) -> bool {
4925 self.token.is_keyword(keywords::Const) &&
4926 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4927 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4930 /// parses all the "front matter" for a `fn` declaration, up to
4931 /// and including the `fn` keyword:
4935 /// - `const unsafe fn`
4938 pub fn parse_fn_front_matter(&mut self)
4939 -> PResult<'a, (Spanned<ast::Constness>,
4942 let is_const_fn = self.eat_keyword(keywords::Const);
4943 let const_span = self.prev_span;
4944 let unsafety = self.parse_unsafety()?;
4945 let (constness, unsafety, abi) = if is_const_fn {
4946 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
4948 let abi = if self.eat_keyword(keywords::Extern) {
4949 self.parse_opt_abi()?.unwrap_or(Abi::C)
4953 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
4955 self.expect_keyword(keywords::Fn)?;
4956 Ok((constness, unsafety, abi))
4959 /// Parse an impl item.
4960 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
4961 maybe_whole!(self, NtImplItem, |x| x);
4962 let attrs = self.parse_outer_attributes()?;
4963 let (mut item, tokens) = self.collect_tokens(|this| {
4964 this.parse_impl_item_(at_end, attrs)
4967 // See `parse_item` for why this clause is here.
4968 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
4969 item.tokens = Some(tokens);
4974 fn parse_impl_item_(&mut self,
4976 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
4978 let vis = self.parse_visibility(false)?;
4979 let defaultness = self.parse_defaultness()?;
4980 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
4981 let name = self.parse_ident()?;
4982 self.expect(&token::Eq)?;
4983 let typ = self.parse_ty()?;
4984 self.expect(&token::Semi)?;
4985 (name, ast::ImplItemKind::Type(typ), ast::Generics::default())
4986 } else if self.is_const_item() {
4987 self.expect_keyword(keywords::Const)?;
4988 let name = self.parse_ident()?;
4989 self.expect(&token::Colon)?;
4990 let typ = self.parse_ty()?;
4991 self.expect(&token::Eq)?;
4992 let expr = self.parse_expr()?;
4993 self.expect(&token::Semi)?;
4994 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
4996 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
4997 attrs.extend(inner_attrs);
4998 (name, node, generics)
5002 id: ast::DUMMY_NODE_ID,
5003 span: lo.to(self.prev_span),
5014 fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
5015 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5020 fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
5022 Visibility::Inherited => Ok(()),
5024 let is_macro_rules: bool = match self.token {
5025 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
5029 let mut err = self.diagnostic()
5030 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5031 err.help("did you mean #[macro_export]?");
5034 let mut err = self.diagnostic()
5035 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5036 err.help("try adjusting the macro to put `pub` inside the invocation");
5043 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5044 -> DiagnosticBuilder<'a>
5046 // Given this code `path(`, it seems like this is not
5047 // setting the visibility of a macro invocation, but rather
5048 // a mistyped method declaration.
5049 // Create a diagnostic pointing out that `fn` is missing.
5051 // x | pub path(&self) {
5052 // | ^ missing `fn`, `type`, or `const`
5054 // ^^ `sp` below will point to this
5055 let sp = prev_span.between(self.prev_span);
5056 let mut err = self.diagnostic().struct_span_err(
5058 &format!("missing `fn`, `type`, or `const` for {}-item declaration",
5060 err.span_label(sp, "missing `fn`, `type`, or `const`");
5064 /// Parse a method or a macro invocation in a trait impl.
5065 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5066 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::Generics,
5067 ast::ImplItemKind)> {
5068 // code copied from parse_macro_use_or_failure... abstraction!
5069 if self.token.is_path_start() {
5072 let prev_span = self.prev_span;
5075 let pth = self.parse_path(PathStyle::Mod)?;
5076 if pth.segments.len() == 1 {
5077 if !self.eat(&token::Not) {
5078 return Err(self.missing_assoc_item_kind_err("impl", prev_span));
5081 self.expect(&token::Not)?;
5084 self.complain_if_pub_macro(vis, prev_span);
5086 // eat a matched-delimiter token tree:
5088 let (delim, tts) = self.expect_delimited_token_tree()?;
5089 if delim != token::Brace {
5090 self.expect(&token::Semi)?
5093 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
5094 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5095 ast::ImplItemKind::Macro(mac)))
5097 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
5098 let ident = self.parse_ident()?;
5099 let mut generics = self.parse_generics()?;
5100 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5101 generics.where_clause = self.parse_where_clause()?;
5103 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5104 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(ast::MethodSig {
5113 /// Parse trait Foo { ... }
5114 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5115 let ident = self.parse_ident()?;
5116 let mut tps = self.parse_generics()?;
5118 // Parse optional colon and supertrait bounds.
5119 let bounds = if self.eat(&token::Colon) {
5120 self.parse_ty_param_bounds()?
5125 tps.where_clause = self.parse_where_clause()?;
5127 self.expect(&token::OpenDelim(token::Brace))?;
5128 let mut trait_items = vec![];
5129 while !self.eat(&token::CloseDelim(token::Brace)) {
5130 let mut at_end = false;
5131 match self.parse_trait_item(&mut at_end) {
5132 Ok(item) => trait_items.push(item),
5136 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5141 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5144 /// Parses items implementations variants
5145 /// impl<T> Foo { ... }
5146 /// impl<T> ToString for &'static T { ... }
5147 /// impl Send for .. {}
5148 fn parse_item_impl(&mut self,
5149 unsafety: ast::Unsafety,
5150 defaultness: Defaultness) -> PResult<'a, ItemInfo> {
5151 let impl_span = self.span;
5153 // First, parse type parameters if necessary.
5154 let mut generics = self.parse_generics()?;
5156 // Special case: if the next identifier that follows is '(', don't
5157 // allow this to be parsed as a trait.
5158 let could_be_trait = self.token != token::OpenDelim(token::Paren);
5160 let neg_span = self.span;
5161 let polarity = if self.eat(&token::Not) {
5162 ast::ImplPolarity::Negative
5164 ast::ImplPolarity::Positive
5168 let mut ty = self.parse_ty()?;
5170 // Parse traits, if necessary.
5171 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
5172 // New-style trait. Reinterpret the type as a trait.
5174 TyKind::Path(None, ref path) => {
5176 path: (*path).clone(),
5181 self.span_err(ty.span, "not a trait");
5186 if polarity == ast::ImplPolarity::Negative {
5187 // This is a negated type implementation
5188 // `impl !MyType {}`, which is not allowed.
5189 self.span_err(neg_span, "inherent implementation can't be negated");
5194 if opt_trait.is_some() && self.eat(&token::DotDot) {
5195 if generics.is_parameterized() {
5196 self.span_err(impl_span, "auto trait implementations are not \
5197 allowed to have generics");
5200 if let ast::Defaultness::Default = defaultness {
5201 self.span_err(impl_span, "`default impl` is not allowed for \
5202 auto trait implementations");
5205 self.expect(&token::OpenDelim(token::Brace))?;
5206 self.expect(&token::CloseDelim(token::Brace))?;
5207 Ok((keywords::Invalid.ident(),
5208 ItemKind::AutoImpl(unsafety, opt_trait.unwrap()), None))
5210 if opt_trait.is_some() {
5211 ty = self.parse_ty()?;
5213 generics.where_clause = self.parse_where_clause()?;
5215 self.expect(&token::OpenDelim(token::Brace))?;
5216 let attrs = self.parse_inner_attributes()?;
5218 let mut impl_items = vec![];
5219 while !self.eat(&token::CloseDelim(token::Brace)) {
5220 let mut at_end = false;
5221 match self.parse_impl_item(&mut at_end) {
5222 Ok(item) => impl_items.push(item),
5226 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5232 Ok((keywords::Invalid.ident(),
5233 ItemKind::Impl(unsafety, polarity, defaultness, generics, opt_trait, ty, impl_items),
5238 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<LifetimeDef>> {
5239 if self.eat_keyword(keywords::For) {
5241 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
5243 if !ty_params.is_empty() {
5244 self.span_err(ty_params[0].span,
5245 "only lifetime parameters can be used in this context");
5253 /// Parse struct Foo { ... }
5254 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5255 let class_name = self.parse_ident()?;
5257 let mut generics = self.parse_generics()?;
5259 // There is a special case worth noting here, as reported in issue #17904.
5260 // If we are parsing a tuple struct it is the case that the where clause
5261 // should follow the field list. Like so:
5263 // struct Foo<T>(T) where T: Copy;
5265 // If we are parsing a normal record-style struct it is the case
5266 // that the where clause comes before the body, and after the generics.
5267 // So if we look ahead and see a brace or a where-clause we begin
5268 // parsing a record style struct.
5270 // Otherwise if we look ahead and see a paren we parse a tuple-style
5273 let vdata = if self.token.is_keyword(keywords::Where) {
5274 generics.where_clause = self.parse_where_clause()?;
5275 if self.eat(&token::Semi) {
5276 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5277 VariantData::Unit(ast::DUMMY_NODE_ID)
5279 // If we see: `struct Foo<T> where T: Copy { ... }`
5280 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5282 // No `where` so: `struct Foo<T>;`
5283 } else if self.eat(&token::Semi) {
5284 VariantData::Unit(ast::DUMMY_NODE_ID)
5285 // Record-style struct definition
5286 } else if self.token == token::OpenDelim(token::Brace) {
5287 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5288 // Tuple-style struct definition with optional where-clause.
5289 } else if self.token == token::OpenDelim(token::Paren) {
5290 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5291 generics.where_clause = self.parse_where_clause()?;
5292 self.expect(&token::Semi)?;
5295 let token_str = self.this_token_to_string();
5296 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5297 name, found `{}`", token_str)))
5300 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5303 /// Parse union Foo { ... }
5304 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5305 let class_name = self.parse_ident()?;
5307 let mut generics = self.parse_generics()?;
5309 let vdata = if self.token.is_keyword(keywords::Where) {
5310 generics.where_clause = self.parse_where_clause()?;
5311 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5312 } else if self.token == token::OpenDelim(token::Brace) {
5313 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5315 let token_str = self.this_token_to_string();
5316 return Err(self.fatal(&format!("expected `where` or `{{` after union \
5317 name, found `{}`", token_str)))
5320 Ok((class_name, ItemKind::Union(vdata, generics), None))
5323 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5324 let mut fields = Vec::new();
5325 if self.eat(&token::OpenDelim(token::Brace)) {
5326 while self.token != token::CloseDelim(token::Brace) {
5327 fields.push(self.parse_struct_decl_field().map_err(|e| {
5328 self.recover_stmt();
5329 self.eat(&token::CloseDelim(token::Brace));
5336 let token_str = self.this_token_to_string();
5337 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5345 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5346 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5347 // Unit like structs are handled in parse_item_struct function
5348 let fields = self.parse_unspanned_seq(
5349 &token::OpenDelim(token::Paren),
5350 &token::CloseDelim(token::Paren),
5351 SeqSep::trailing_allowed(token::Comma),
5353 let attrs = p.parse_outer_attributes()?;
5355 let vis = p.parse_visibility(true)?;
5356 let ty = p.parse_ty()?;
5358 span: lo.to(p.span),
5361 id: ast::DUMMY_NODE_ID,
5370 /// Parse a structure field declaration
5371 pub fn parse_single_struct_field(&mut self,
5374 attrs: Vec<Attribute> )
5375 -> PResult<'a, StructField> {
5376 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5381 token::CloseDelim(token::Brace) => {}
5382 token::DocComment(_) => return Err(self.span_fatal_err(self.span,
5383 Error::UselessDocComment)),
5384 _ => return Err(self.span_fatal_help(self.span,
5385 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5386 "struct fields should be separated by commas")),
5391 /// Parse an element of a struct definition
5392 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5393 let attrs = self.parse_outer_attributes()?;
5395 let vis = self.parse_visibility(false)?;
5396 self.parse_single_struct_field(lo, vis, attrs)
5399 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5400 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5401 /// a function definition, it's not a tuple struct field) and the contents within the parens
5402 /// isn't valid, emit a proper diagnostic.
5403 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5404 maybe_whole!(self, NtVis, |x| x);
5406 if self.eat_keyword(keywords::Crate) {
5407 return Ok(Visibility::Crate(self.prev_span, CrateSugar::JustCrate));
5410 if !self.eat_keyword(keywords::Pub) {
5411 return Ok(Visibility::Inherited)
5414 if self.check(&token::OpenDelim(token::Paren)) {
5415 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5416 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5417 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5418 // by the following tokens.
5419 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5422 self.bump(); // `crate`
5423 let vis = Visibility::Crate(self.prev_span, CrateSugar::PubCrate);
5424 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5426 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5429 self.bump(); // `in`
5430 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5431 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5432 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5434 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5435 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5436 t.is_keyword(keywords::SelfValue)) {
5437 // `pub(self)` or `pub(super)`
5439 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5440 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5441 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5443 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5444 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5446 let msg = "incorrect visibility restriction";
5447 let suggestion = r##"some possible visibility restrictions are:
5448 `pub(crate)`: visible only on the current crate
5449 `pub(super)`: visible only in the current module's parent
5450 `pub(in path::to::module)`: visible only on the specified path"##;
5451 let path = self.parse_path(PathStyle::Mod)?;
5452 let path_span = self.prev_span;
5453 let help_msg = format!("make this visible only to module `{}` with `in`", path);
5454 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5455 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5456 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5457 err.emit(); // emit diagnostic, but continue with public visibility
5461 Ok(Visibility::Public)
5464 /// Parse defaultness: DEFAULT or nothing
5465 fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5466 if self.eat_defaultness() {
5467 Ok(Defaultness::Default)
5469 Ok(Defaultness::Final)
5473 /// Given a termination token, parse all of the items in a module
5474 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5475 let mut items = vec![];
5476 while let Some(item) = self.parse_item()? {
5480 if !self.eat(term) {
5481 let token_str = self.this_token_to_string();
5482 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5485 let hi = if self.span == syntax_pos::DUMMY_SP {
5492 inner: inner_lo.to(hi),
5497 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5498 let id = self.parse_ident()?;
5499 self.expect(&token::Colon)?;
5500 let ty = self.parse_ty()?;
5501 self.expect(&token::Eq)?;
5502 let e = self.parse_expr()?;
5503 self.expect(&token::Semi)?;
5504 let item = match m {
5505 Some(m) => ItemKind::Static(ty, m, e),
5506 None => ItemKind::Const(ty, e),
5508 Ok((id, item, None))
5511 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5512 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5513 let (in_cfg, outer_attrs) = {
5514 let mut strip_unconfigured = ::config::StripUnconfigured {
5516 should_test: false, // irrelevant
5517 features: None, // don't perform gated feature checking
5519 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5520 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5523 let id_span = self.span;
5524 let id = self.parse_ident()?;
5525 if self.check(&token::Semi) {
5527 if in_cfg && self.recurse_into_file_modules {
5528 // This mod is in an external file. Let's go get it!
5529 let ModulePathSuccess { path, directory_ownership, warn } =
5530 self.submod_path(id, &outer_attrs, id_span)?;
5531 let (module, mut attrs) =
5532 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5534 let attr = ast::Attribute {
5535 id: attr::mk_attr_id(),
5536 style: ast::AttrStyle::Outer,
5537 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5538 Ident::from_str("warn_directory_ownership")),
5539 tokens: TokenStream::empty(),
5540 is_sugared_doc: false,
5541 span: syntax_pos::DUMMY_SP,
5543 attr::mark_known(&attr);
5546 Ok((id, module, Some(attrs)))
5548 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5549 Ok((id, ItemKind::Mod(placeholder), None))
5552 let old_directory = self.directory.clone();
5553 self.push_directory(id, &outer_attrs);
5555 self.expect(&token::OpenDelim(token::Brace))?;
5556 let mod_inner_lo = self.span;
5557 let attrs = self.parse_inner_attributes()?;
5558 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5560 self.directory = old_directory;
5561 Ok((id, ItemKind::Mod(module), Some(attrs)))
5565 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5566 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5567 self.directory.path.push(&path.as_str());
5568 self.directory.ownership = DirectoryOwnership::Owned;
5570 self.directory.path.push(&id.name.as_str());
5574 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5575 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5578 /// Returns either a path to a module, or .
5579 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5580 let mod_name = id.to_string();
5581 let default_path_str = format!("{}.rs", mod_name);
5582 let secondary_path_str = format!("{}{}mod.rs", mod_name, path::MAIN_SEPARATOR);
5583 let default_path = dir_path.join(&default_path_str);
5584 let secondary_path = dir_path.join(&secondary_path_str);
5585 let default_exists = codemap.file_exists(&default_path);
5586 let secondary_exists = codemap.file_exists(&secondary_path);
5588 let result = match (default_exists, secondary_exists) {
5589 (true, false) => Ok(ModulePathSuccess {
5591 directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5594 (false, true) => Ok(ModulePathSuccess {
5595 path: secondary_path,
5596 directory_ownership: DirectoryOwnership::Owned,
5599 (false, false) => Err(Error::FileNotFoundForModule {
5600 mod_name: mod_name.clone(),
5601 default_path: default_path_str,
5602 secondary_path: secondary_path_str,
5603 dir_path: format!("{}", dir_path.display()),
5605 (true, true) => Err(Error::DuplicatePaths {
5606 mod_name: mod_name.clone(),
5607 default_path: default_path_str,
5608 secondary_path: secondary_path_str,
5614 path_exists: default_exists || secondary_exists,
5619 fn submod_path(&mut self,
5621 outer_attrs: &[ast::Attribute],
5623 -> PResult<'a, ModulePathSuccess> {
5624 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5625 return Ok(ModulePathSuccess {
5626 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5627 Some("mod.rs") => DirectoryOwnership::Owned,
5628 _ => DirectoryOwnership::UnownedViaMod(true),
5635 let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5637 if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5639 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5640 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5641 if paths.path_exists {
5642 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5644 err.span_note(id_sp, &msg);
5647 } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5649 if let Ok(result) = paths.result {
5650 return Ok(ModulePathSuccess { warn: true, ..result });
5653 let mut err = self.diagnostic().struct_span_err(id_sp,
5654 "cannot declare a new module at this location");
5655 if id_sp != syntax_pos::DUMMY_SP {
5656 let src_path = PathBuf::from(self.sess.codemap().span_to_filename(id_sp));
5657 if let Some(stem) = src_path.file_stem() {
5658 let mut dest_path = src_path.clone();
5659 dest_path.set_file_name(stem);
5660 dest_path.push("mod.rs");
5661 err.span_note(id_sp,
5662 &format!("maybe move this module `{}` to its own \
5663 directory via `{}`", src_path.to_string_lossy(),
5664 dest_path.to_string_lossy()));
5667 if paths.path_exists {
5668 err.span_note(id_sp,
5669 &format!("... or maybe `use` the module `{}` instead \
5670 of possibly redeclaring it",
5675 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5679 /// Read a module from a source file.
5680 fn eval_src_mod(&mut self,
5682 directory_ownership: DirectoryOwnership,
5685 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5686 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5687 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5688 let mut err = String::from("circular modules: ");
5689 let len = included_mod_stack.len();
5690 for p in &included_mod_stack[i.. len] {
5691 err.push_str(&p.to_string_lossy());
5692 err.push_str(" -> ");
5694 err.push_str(&path.to_string_lossy());
5695 return Err(self.span_fatal(id_sp, &err[..]));
5697 included_mod_stack.push(path.clone());
5698 drop(included_mod_stack);
5701 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5702 p0.cfg_mods = self.cfg_mods;
5703 let mod_inner_lo = p0.span;
5704 let mod_attrs = p0.parse_inner_attributes()?;
5705 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5706 self.sess.included_mod_stack.borrow_mut().pop();
5707 Ok((ast::ItemKind::Mod(m0), mod_attrs))
5710 /// Parse a function declaration from a foreign module
5711 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5712 -> PResult<'a, ForeignItem> {
5713 self.expect_keyword(keywords::Fn)?;
5715 let (ident, mut generics) = self.parse_fn_header()?;
5716 let decl = self.parse_fn_decl(true)?;
5717 generics.where_clause = self.parse_where_clause()?;
5719 self.expect(&token::Semi)?;
5720 Ok(ast::ForeignItem {
5723 node: ForeignItemKind::Fn(decl, generics),
5724 id: ast::DUMMY_NODE_ID,
5730 /// Parse a static item from a foreign module.
5731 /// Assumes that the `static` keyword is already parsed.
5732 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5733 -> PResult<'a, ForeignItem> {
5734 let mutbl = self.eat_keyword(keywords::Mut);
5735 let ident = self.parse_ident()?;
5736 self.expect(&token::Colon)?;
5737 let ty = self.parse_ty()?;
5739 self.expect(&token::Semi)?;
5743 node: ForeignItemKind::Static(ty, mutbl),
5744 id: ast::DUMMY_NODE_ID,
5750 /// Parse a type from a foreign module
5751 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5752 -> PResult<'a, ForeignItem> {
5753 self.expect_keyword(keywords::Type)?;
5755 let ident = self.parse_ident()?;
5757 self.expect(&token::Semi)?;
5758 Ok(ast::ForeignItem {
5761 node: ForeignItemKind::Ty,
5762 id: ast::DUMMY_NODE_ID,
5768 /// Parse extern crate links
5772 /// extern crate foo;
5773 /// extern crate bar as foo;
5774 fn parse_item_extern_crate(&mut self,
5776 visibility: Visibility,
5777 attrs: Vec<Attribute>)
5778 -> PResult<'a, P<Item>> {
5780 let crate_name = self.parse_ident()?;
5781 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
5782 (Some(crate_name.name), ident)
5786 self.expect(&token::Semi)?;
5788 let prev_span = self.prev_span;
5789 Ok(self.mk_item(lo.to(prev_span),
5791 ItemKind::ExternCrate(maybe_path),
5796 /// Parse `extern` for foreign ABIs
5799 /// `extern` is expected to have been
5800 /// consumed before calling this method
5806 fn parse_item_foreign_mod(&mut self,
5808 opt_abi: Option<abi::Abi>,
5809 visibility: Visibility,
5810 mut attrs: Vec<Attribute>)
5811 -> PResult<'a, P<Item>> {
5812 self.expect(&token::OpenDelim(token::Brace))?;
5814 let abi = opt_abi.unwrap_or(Abi::C);
5816 attrs.extend(self.parse_inner_attributes()?);
5818 let mut foreign_items = vec![];
5819 while let Some(item) = self.parse_foreign_item()? {
5820 foreign_items.push(item);
5822 self.expect(&token::CloseDelim(token::Brace))?;
5824 let prev_span = self.prev_span;
5825 let m = ast::ForeignMod {
5827 items: foreign_items
5829 let invalid = keywords::Invalid.ident();
5830 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
5833 /// Parse type Foo = Bar;
5834 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5835 let ident = self.parse_ident()?;
5836 let mut tps = self.parse_generics()?;
5837 tps.where_clause = self.parse_where_clause()?;
5838 self.expect(&token::Eq)?;
5839 let ty = self.parse_ty()?;
5840 self.expect(&token::Semi)?;
5841 Ok((ident, ItemKind::Ty(ty, tps), None))
5844 /// Parse the part of an "enum" decl following the '{'
5845 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5846 let mut variants = Vec::new();
5847 let mut all_nullary = true;
5848 let mut any_disr = None;
5849 while self.token != token::CloseDelim(token::Brace) {
5850 let variant_attrs = self.parse_outer_attributes()?;
5851 let vlo = self.span;
5854 let mut disr_expr = None;
5855 let ident = self.parse_ident()?;
5856 if self.check(&token::OpenDelim(token::Brace)) {
5857 // Parse a struct variant.
5858 all_nullary = false;
5859 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
5860 ast::DUMMY_NODE_ID);
5861 } else if self.check(&token::OpenDelim(token::Paren)) {
5862 all_nullary = false;
5863 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
5864 ast::DUMMY_NODE_ID);
5865 } else if self.eat(&token::Eq) {
5866 disr_expr = Some(self.parse_expr()?);
5867 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5868 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5870 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5873 let vr = ast::Variant_ {
5875 attrs: variant_attrs,
5879 variants.push(respan(vlo.to(self.prev_span), vr));
5881 if !self.eat(&token::Comma) { break; }
5883 self.expect(&token::CloseDelim(token::Brace))?;
5885 Some(disr_span) if !all_nullary =>
5886 self.span_err(disr_span,
5887 "discriminator values can only be used with a c-like enum"),
5891 Ok(ast::EnumDef { variants: variants })
5894 /// Parse an "enum" declaration
5895 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5896 let id = self.parse_ident()?;
5897 let mut generics = self.parse_generics()?;
5898 generics.where_clause = self.parse_where_clause()?;
5899 self.expect(&token::OpenDelim(token::Brace))?;
5901 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
5902 self.recover_stmt();
5903 self.eat(&token::CloseDelim(token::Brace));
5906 Ok((id, ItemKind::Enum(enum_definition, generics), None))
5909 /// Parses a string as an ABI spec on an extern type or module. Consumes
5910 /// the `extern` keyword, if one is found.
5911 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5913 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5915 self.expect_no_suffix(sp, "ABI spec", suf);
5917 match abi::lookup(&s.as_str()) {
5918 Some(abi) => Ok(Some(abi)),
5920 let prev_span = self.prev_span;
5923 &format!("invalid ABI: expected one of [{}], \
5925 abi::all_names().join(", "),
5936 /// Parse one of the items allowed by the flags.
5937 /// NB: this function no longer parses the items inside an
5939 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5940 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5941 maybe_whole!(self, NtItem, |item| {
5942 let mut item = item.unwrap();
5943 let mut attrs = attrs;
5944 mem::swap(&mut item.attrs, &mut attrs);
5945 item.attrs.extend(attrs);
5951 let visibility = self.parse_visibility(false)?;
5953 if self.eat_keyword(keywords::Use) {
5955 let item_ = ItemKind::Use(self.parse_view_path()?);
5956 self.expect(&token::Semi)?;
5958 let prev_span = self.prev_span;
5959 let invalid = keywords::Invalid.ident();
5960 let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
5961 return Ok(Some(item));
5964 if self.eat_keyword(keywords::Extern) {
5965 if self.eat_keyword(keywords::Crate) {
5966 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
5969 let opt_abi = self.parse_opt_abi()?;
5971 if self.eat_keyword(keywords::Fn) {
5972 // EXTERN FUNCTION ITEM
5973 let fn_span = self.prev_span;
5974 let abi = opt_abi.unwrap_or(Abi::C);
5975 let (ident, item_, extra_attrs) =
5976 self.parse_item_fn(Unsafety::Normal,
5977 respan(fn_span, Constness::NotConst),
5979 let prev_span = self.prev_span;
5980 let item = self.mk_item(lo.to(prev_span),
5984 maybe_append(attrs, extra_attrs));
5985 return Ok(Some(item));
5986 } else if self.check(&token::OpenDelim(token::Brace)) {
5987 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
5993 if self.eat_keyword(keywords::Static) {
5995 let m = if self.eat_keyword(keywords::Mut) {
5998 Mutability::Immutable
6000 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6001 let prev_span = self.prev_span;
6002 let item = self.mk_item(lo.to(prev_span),
6006 maybe_append(attrs, extra_attrs));
6007 return Ok(Some(item));
6009 if self.eat_keyword(keywords::Const) {
6010 let const_span = self.prev_span;
6011 if self.check_keyword(keywords::Fn)
6012 || (self.check_keyword(keywords::Unsafe)
6013 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6014 // CONST FUNCTION ITEM
6015 let unsafety = if self.eat_keyword(keywords::Unsafe) {
6021 let (ident, item_, extra_attrs) =
6022 self.parse_item_fn(unsafety,
6023 respan(const_span, Constness::Const),
6025 let prev_span = self.prev_span;
6026 let item = self.mk_item(lo.to(prev_span),
6030 maybe_append(attrs, extra_attrs));
6031 return Ok(Some(item));
6035 if self.eat_keyword(keywords::Mut) {
6036 let prev_span = self.prev_span;
6037 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6038 .help("did you mean to declare a static?")
6041 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6042 let prev_span = self.prev_span;
6043 let item = self.mk_item(lo.to(prev_span),
6047 maybe_append(attrs, extra_attrs));
6048 return Ok(Some(item));
6050 if self.check_keyword(keywords::Unsafe) &&
6051 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
6052 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
6054 // UNSAFE TRAIT ITEM
6055 self.expect_keyword(keywords::Unsafe)?;
6056 let is_auto = if self.eat_keyword(keywords::Trait) {
6059 self.eat_auto_trait();
6062 let (ident, item_, extra_attrs) =
6063 self.parse_item_trait(is_auto, ast::Unsafety::Unsafe)?;
6064 let prev_span = self.prev_span;
6065 let item = self.mk_item(lo.to(prev_span),
6069 maybe_append(attrs, extra_attrs));
6070 return Ok(Some(item));
6072 if (self.check_keyword(keywords::Unsafe) &&
6073 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))) ||
6074 (self.check_keyword(keywords::Default) &&
6075 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) &&
6076 self.look_ahead(2, |t| t.is_keyword(keywords::Impl)))
6079 let defaultness = self.parse_defaultness()?;
6080 self.expect_keyword(keywords::Unsafe)?;
6081 self.expect_keyword(keywords::Impl)?;
6084 extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe, defaultness)?;
6085 let prev_span = self.prev_span;
6086 let item = self.mk_item(lo.to(prev_span),
6090 maybe_append(attrs, extra_attrs));
6091 return Ok(Some(item));
6093 if self.check_keyword(keywords::Fn) {
6096 let fn_span = self.prev_span;
6097 let (ident, item_, extra_attrs) =
6098 self.parse_item_fn(Unsafety::Normal,
6099 respan(fn_span, Constness::NotConst),
6101 let prev_span = self.prev_span;
6102 let item = self.mk_item(lo.to(prev_span),
6106 maybe_append(attrs, extra_attrs));
6107 return Ok(Some(item));
6109 if self.check_keyword(keywords::Unsafe)
6110 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
6111 // UNSAFE FUNCTION ITEM
6113 let abi = if self.eat_keyword(keywords::Extern) {
6114 self.parse_opt_abi()?.unwrap_or(Abi::C)
6118 self.expect_keyword(keywords::Fn)?;
6119 let fn_span = self.prev_span;
6120 let (ident, item_, extra_attrs) =
6121 self.parse_item_fn(Unsafety::Unsafe,
6122 respan(fn_span, Constness::NotConst),
6124 let prev_span = self.prev_span;
6125 let item = self.mk_item(lo.to(prev_span),
6129 maybe_append(attrs, extra_attrs));
6130 return Ok(Some(item));
6132 if self.eat_keyword(keywords::Mod) {
6134 let (ident, item_, extra_attrs) =
6135 self.parse_item_mod(&attrs[..])?;
6136 let prev_span = self.prev_span;
6137 let item = self.mk_item(lo.to(prev_span),
6141 maybe_append(attrs, extra_attrs));
6142 return Ok(Some(item));
6144 if self.eat_keyword(keywords::Type) {
6146 let (ident, item_, extra_attrs) = self.parse_item_type()?;
6147 let prev_span = self.prev_span;
6148 let item = self.mk_item(lo.to(prev_span),
6152 maybe_append(attrs, extra_attrs));
6153 return Ok(Some(item));
6155 if self.eat_keyword(keywords::Enum) {
6157 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
6158 let prev_span = self.prev_span;
6159 let item = self.mk_item(lo.to(prev_span),
6163 maybe_append(attrs, extra_attrs));
6164 return Ok(Some(item));
6166 if self.check_keyword(keywords::Trait)
6167 || (self.check_keyword(keywords::Auto)
6168 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
6170 let is_auto = if self.eat_keyword(keywords::Trait) {
6173 self.eat_auto_trait();
6177 let (ident, item_, extra_attrs) =
6178 self.parse_item_trait(is_auto, ast::Unsafety::Normal)?;
6179 let prev_span = self.prev_span;
6180 let item = self.mk_item(lo.to(prev_span),
6184 maybe_append(attrs, extra_attrs));
6185 return Ok(Some(item));
6187 if (self.check_keyword(keywords::Impl)) ||
6188 (self.check_keyword(keywords::Default) &&
6189 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)))
6192 let defaultness = self.parse_defaultness()?;
6193 self.expect_keyword(keywords::Impl)?;
6196 extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal, defaultness)?;
6197 let prev_span = self.prev_span;
6198 let item = self.mk_item(lo.to(prev_span),
6202 maybe_append(attrs, extra_attrs));
6203 return Ok(Some(item));
6205 if self.eat_keyword(keywords::Struct) {
6207 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6208 let prev_span = self.prev_span;
6209 let item = self.mk_item(lo.to(prev_span),
6213 maybe_append(attrs, extra_attrs));
6214 return Ok(Some(item));
6216 if self.is_union_item() {
6219 let (ident, item_, extra_attrs) = self.parse_item_union()?;
6220 let prev_span = self.prev_span;
6221 let item = self.mk_item(lo.to(prev_span),
6225 maybe_append(attrs, extra_attrs));
6226 return Ok(Some(item));
6228 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
6229 return Ok(Some(macro_def));
6232 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
6235 /// Parse a foreign item.
6236 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
6237 let attrs = self.parse_outer_attributes()?;
6239 let visibility = self.parse_visibility(false)?;
6241 // FOREIGN STATIC ITEM
6242 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
6243 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
6244 if self.token.is_keyword(keywords::Const) {
6246 .struct_span_err(self.span, "extern items cannot be `const`")
6247 .span_suggestion(self.span, "instead try using", "static".to_owned())
6250 self.bump(); // `static` or `const`
6251 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6253 // FOREIGN FUNCTION ITEM
6254 if self.check_keyword(keywords::Fn) {
6255 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6257 // FOREIGN TYPE ITEM
6258 if self.check_keyword(keywords::Type) {
6259 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
6262 // FIXME #5668: this will occur for a macro invocation:
6263 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
6265 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
6271 /// This is the fall-through for parsing items.
6272 fn parse_macro_use_or_failure(
6274 attrs: Vec<Attribute> ,
6275 macros_allowed: bool,
6276 attributes_allowed: bool,
6278 visibility: Visibility
6279 ) -> PResult<'a, Option<P<Item>>> {
6280 if macros_allowed && self.token.is_path_start() {
6281 // MACRO INVOCATION ITEM
6283 let prev_span = self.prev_span;
6284 self.complain_if_pub_macro(&visibility, prev_span);
6286 let mac_lo = self.span;
6289 let pth = self.parse_path(PathStyle::Mod)?;
6290 self.expect(&token::Not)?;
6292 // a 'special' identifier (like what `macro_rules!` uses)
6293 // is optional. We should eventually unify invoc syntax
6295 let id = if self.token.is_ident() {
6298 keywords::Invalid.ident() // no special identifier
6300 // eat a matched-delimiter token tree:
6301 let (delim, tts) = self.expect_delimited_token_tree()?;
6302 if delim != token::Brace {
6303 if !self.eat(&token::Semi) {
6304 self.span_err(self.prev_span,
6305 "macros that expand to items must either \
6306 be surrounded with braces or followed by \
6311 let hi = self.prev_span;
6312 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6313 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6314 return Ok(Some(item));
6317 // FAILURE TO PARSE ITEM
6319 Visibility::Inherited => {}
6321 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
6325 if !attributes_allowed && !attrs.is_empty() {
6326 self.expected_item_err(&attrs);
6331 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
6332 where F: FnOnce(&mut Self) -> PResult<'a, R>
6334 // Record all tokens we parse when parsing this item.
6335 let mut tokens = Vec::new();
6336 match self.token_cursor.frame.last_token {
6337 LastToken::Collecting(_) => {
6338 panic!("cannot collect tokens recursively yet")
6340 LastToken::Was(ref mut last) => tokens.extend(last.take()),
6342 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
6343 let prev = self.token_cursor.stack.len();
6345 let last_token = if self.token_cursor.stack.len() == prev {
6346 &mut self.token_cursor.frame.last_token
6348 &mut self.token_cursor.stack[prev].last_token
6350 let mut tokens = match *last_token {
6351 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
6352 LastToken::Was(_) => panic!("our vector went away?"),
6355 // If we're not at EOF our current token wasn't actually consumed by
6356 // `f`, but it'll still be in our list that we pulled out. In that case
6358 if self.token == token::Eof {
6359 *last_token = LastToken::Was(None);
6361 *last_token = LastToken::Was(tokens.pop());
6364 Ok((ret?, tokens.into_iter().collect()))
6367 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6368 let attrs = self.parse_outer_attributes()?;
6370 let (ret, tokens) = self.collect_tokens(|this| {
6371 this.parse_item_(attrs, true, false)
6374 // Once we've parsed an item and recorded the tokens we got while
6375 // parsing we may want to store `tokens` into the item we're about to
6376 // return. Note, though, that we specifically didn't capture tokens
6377 // related to outer attributes. The `tokens` field here may later be
6378 // used with procedural macros to convert this item back into a token
6379 // stream, but during expansion we may be removing attributes as we go
6382 // If we've got inner attributes then the `tokens` we've got above holds
6383 // these inner attributes. If an inner attribute is expanded we won't
6384 // actually remove it from the token stream, so we'll just keep yielding
6385 // it (bad!). To work around this case for now we just avoid recording
6386 // `tokens` if we detect any inner attributes. This should help keep
6387 // expansion correct, but we should fix this bug one day!
6390 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6391 i.tokens = Some(tokens);
6398 fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> {
6399 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
6400 &token::CloseDelim(token::Brace),
6401 SeqSep::trailing_allowed(token::Comma), |this| {
6403 let ident = if this.eat_keyword(keywords::SelfValue) {
6404 keywords::SelfValue.ident()
6408 let rename = this.parse_rename()?;
6409 let node = ast::PathListItem_ {
6412 id: ast::DUMMY_NODE_ID
6414 Ok(respan(lo.to(this.prev_span), node))
6419 fn is_import_coupler(&mut self) -> bool {
6420 self.check(&token::ModSep) &&
6421 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6422 *t == token::BinOp(token::Star))
6425 /// Matches ViewPath:
6426 /// MOD_SEP? non_global_path
6427 /// MOD_SEP? non_global_path as IDENT
6428 /// MOD_SEP? non_global_path MOD_SEP STAR
6429 /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE
6430 /// MOD_SEP? LBRACE item_seq RBRACE
6431 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
6433 if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) ||
6434 self.is_import_coupler() {
6435 // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`.
6436 self.eat(&token::ModSep);
6437 let prefix = ast::Path {
6438 segments: vec![PathSegment::crate_root(lo)],
6439 span: lo.to(self.span),
6441 let view_path_kind = if self.eat(&token::BinOp(token::Star)) {
6442 ViewPathGlob(prefix)
6444 ViewPathList(prefix, self.parse_path_list_items()?)
6446 Ok(P(respan(lo.to(self.span), view_path_kind)))
6448 let prefix = self.parse_path(PathStyle::Mod)?.default_to_global();
6449 if self.is_import_coupler() {
6450 // `foo::bar::{a, b}` or `foo::bar::*`
6452 if self.check(&token::BinOp(token::Star)) {
6454 Ok(P(respan(lo.to(self.span), ViewPathGlob(prefix))))
6456 let items = self.parse_path_list_items()?;
6457 Ok(P(respan(lo.to(self.span), ViewPathList(prefix, items))))
6460 // `foo::bar` or `foo::bar as baz`
6461 let rename = self.parse_rename()?.
6462 unwrap_or(prefix.segments.last().unwrap().identifier);
6463 Ok(P(respan(lo.to(self.prev_span), ViewPathSimple(rename, prefix))))
6468 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6469 if self.eat_keyword(keywords::As) {
6470 self.parse_ident().map(Some)
6476 /// Parses a source module as a crate. This is the main
6477 /// entry point for the parser.
6478 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6481 attrs: self.parse_inner_attributes()?,
6482 module: self.parse_mod_items(&token::Eof, lo)?,
6483 span: lo.to(self.span),
6487 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6488 let ret = match self.token {
6489 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6490 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6497 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6498 match self.parse_optional_str() {
6499 Some((s, style, suf)) => {
6500 let sp = self.prev_span;
6501 self.expect_no_suffix(sp, "string literal", suf);
6504 _ => Err(self.fatal("expected string literal"))