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::{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, 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};
37 use ast::{Ty, TyKind, TypeBinding, TyParam, TyParamBounds};
38 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
39 use ast::{Visibility, WhereClause};
40 use ast::{BinOpKind, UnOp};
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 flags Restrictions: u8 {
68 const RESTRICTION_STMT_EXPR = 1 << 0,
69 const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1,
73 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute> >);
75 /// How to parse a path. There are three different kinds of paths, all of which
76 /// are parsed somewhat differently.
77 #[derive(Copy, Clone, PartialEq)]
79 /// A path with no type parameters, e.g. `foo::bar::Baz`, used in imports or visibilities.
81 /// A path with a lifetime and type parameters, with no double colons
82 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`, used in types.
83 /// Paths using this style can be passed into macros expecting `path` nonterminals.
85 /// A path with a lifetime and type parameters with double colons before
86 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`, used in expressions or patterns.
90 #[derive(Clone, Copy, Debug, PartialEq)]
91 pub enum SemiColonMode {
96 #[derive(Clone, Copy, Debug, PartialEq)]
102 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
103 /// dropped into the token stream, which happens while parsing the result of
104 /// macro expansion). Placement of these is not as complex as I feared it would
105 /// be. The important thing is to make sure that lookahead doesn't balk at
106 /// `token::Interpolated` tokens.
107 macro_rules! maybe_whole_expr {
109 if let token::Interpolated(nt) = $p.token.clone() {
111 token::NtExpr(ref e) => {
113 return Ok((*e).clone());
115 token::NtPath(ref path) => {
118 let kind = ExprKind::Path(None, (*path).clone());
119 return Ok($p.mk_expr(span, kind, ThinVec::new()));
121 token::NtBlock(ref block) => {
124 let kind = ExprKind::Block((*block).clone());
125 return Ok($p.mk_expr(span, kind, ThinVec::new()));
133 /// As maybe_whole_expr, but for things other than expressions
134 macro_rules! maybe_whole {
135 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
136 if let token::Interpolated(nt) = $p.token.clone() {
137 if let token::$constructor($x) = (*nt).clone() {
145 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
147 if let Some(ref attrs) = rhs {
148 lhs.extend(attrs.iter().cloned())
163 /* ident is handled by common.rs */
165 pub struct Parser<'a> {
166 pub sess: &'a ParseSess,
167 /// the current token:
168 pub token: token::Token,
169 /// the span of the current token:
171 /// the span of the previous token:
172 pub meta_var_span: Option<Span>,
174 /// the previous token kind
175 prev_token_kind: PrevTokenKind,
176 pub restrictions: Restrictions,
177 /// The set of seen errors about obsolete syntax. Used to suppress
178 /// extra detail when the same error is seen twice
179 pub obsolete_set: HashSet<ObsoleteSyntax>,
180 /// Used to determine the path to externally loaded source files
181 pub directory: Directory,
182 /// Name of the root module this parser originated from. If `None`, then the
183 /// name is not known. This does not change while the parser is descending
184 /// into modules, and sub-parsers have new values for this name.
185 pub root_module_name: Option<String>,
186 pub expected_tokens: Vec<TokenType>,
187 token_cursor: TokenCursor,
188 pub desugar_doc_comments: bool,
189 /// Whether we should configure out of line modules as we parse.
194 frame: TokenCursorFrame,
195 stack: Vec<TokenCursorFrame>,
198 struct TokenCursorFrame {
199 delim: token::DelimToken,
202 tree_cursor: tokenstream::Cursor,
206 impl TokenCursorFrame {
207 fn new(sp: Span, delimited: &Delimited) -> Self {
209 delim: delimited.delim,
211 open_delim: delimited.delim == token::NoDelim,
212 tree_cursor: delimited.stream().into_trees(),
213 close_delim: delimited.delim == token::NoDelim,
219 fn next(&mut self) -> TokenAndSpan {
221 let tree = if !self.frame.open_delim {
222 self.frame.open_delim = true;
223 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
224 .open_tt(self.frame.span)
225 } else if let Some(tree) = self.frame.tree_cursor.next() {
227 } else if !self.frame.close_delim {
228 self.frame.close_delim = true;
229 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
230 .close_tt(self.frame.span)
231 } else if let Some(frame) = self.stack.pop() {
235 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
239 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
240 TokenTree::Delimited(sp, ref delimited) => {
241 let frame = TokenCursorFrame::new(sp, delimited);
242 self.stack.push(mem::replace(&mut self.frame, frame));
248 fn next_desugared(&mut self) -> TokenAndSpan {
249 let (sp, name) = match self.next() {
250 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
251 tok @ _ => return tok,
254 let stripped = strip_doc_comment_decoration(&name.as_str());
256 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
257 // required to wrap the text.
258 let mut num_of_hashes = 0;
260 for ch in stripped.chars() {
263 '#' if count > 0 => count + 1,
266 num_of_hashes = cmp::max(num_of_hashes, count);
269 let body = TokenTree::Delimited(sp, Delimited {
270 delim: token::Bracket,
271 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"))),
272 TokenTree::Token(sp, token::Eq),
273 TokenTree::Token(sp, token::Literal(
274 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
275 .iter().cloned().collect::<TokenStream>().into(),
278 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
279 delim: token::NoDelim,
280 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
281 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
282 .iter().cloned().collect::<TokenStream>().into()
284 [TokenTree::Token(sp, token::Pound), body]
285 .iter().cloned().collect::<TokenStream>().into()
293 #[derive(PartialEq, Eq, Clone)]
296 Keyword(keywords::Keyword),
305 fn to_string(&self) -> String {
307 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
308 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
309 TokenType::Operator => "an operator".to_string(),
310 TokenType::Lifetime => "lifetime".to_string(),
311 TokenType::Ident => "identifier".to_string(),
312 TokenType::Path => "path".to_string(),
313 TokenType::Type => "type".to_string(),
318 fn is_ident_or_underscore(t: &token::Token) -> bool {
319 t.is_ident() || *t == token::Underscore
322 /// Information about the path to a module.
323 pub struct ModulePath {
325 pub path_exists: bool,
326 pub result: Result<ModulePathSuccess, Error>,
329 pub struct ModulePathSuccess {
331 pub directory_ownership: DirectoryOwnership,
335 pub struct ModulePathError {
337 pub help_msg: String,
341 FileNotFoundForModule {
343 default_path: String,
344 secondary_path: String,
349 default_path: String,
350 secondary_path: String,
353 InclusiveRangeWithNoEnd,
357 pub fn span_err<'a>(self, sp: Span, handler: &'a errors::Handler) -> DiagnosticBuilder<'a> {
359 Error::FileNotFoundForModule { ref mod_name,
363 let mut err = struct_span_err!(handler, sp, E0583,
364 "file not found for module `{}`", mod_name);
365 err.help(&format!("name the file either {} or {} inside the directory {:?}",
371 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
372 let mut err = struct_span_err!(handler, sp, E0584,
373 "file for module `{}` found at both {} and {}",
377 err.help("delete or rename one of them to remove the ambiguity");
380 Error::UselessDocComment => {
381 let mut err = struct_span_err!(handler, sp, E0585,
382 "found a documentation comment that doesn't document anything");
383 err.help("doc comments must come before what they document, maybe a comment was \
384 intended with `//`?");
387 Error::InclusiveRangeWithNoEnd => {
388 let mut err = struct_span_err!(handler, sp, E0586,
389 "inclusive range with no end");
390 err.help("inclusive ranges must be bounded at the end (`...b` or `a...b`)");
399 AttributesParsed(ThinVec<Attribute>),
400 AlreadyParsed(P<Expr>),
403 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
404 fn from(o: Option<ThinVec<Attribute>>) -> Self {
405 if let Some(attrs) = o {
406 LhsExpr::AttributesParsed(attrs)
408 LhsExpr::NotYetParsed
413 impl From<P<Expr>> for LhsExpr {
414 fn from(expr: P<Expr>) -> Self {
415 LhsExpr::AlreadyParsed(expr)
419 /// Create a placeholder argument.
420 fn dummy_arg(span: Span) -> Arg {
421 let spanned = Spanned {
423 node: keywords::Invalid.ident()
426 id: ast::DUMMY_NODE_ID,
427 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), spanned, None),
433 id: ast::DUMMY_NODE_ID
435 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
438 impl<'a> Parser<'a> {
439 pub fn new(sess: &'a ParseSess,
441 directory: Option<Directory>,
442 desugar_doc_comments: bool)
444 let mut parser = Parser {
446 token: token::Underscore,
447 span: syntax_pos::DUMMY_SP,
448 prev_span: syntax_pos::DUMMY_SP,
450 prev_token_kind: PrevTokenKind::Other,
451 restrictions: Restrictions::empty(),
452 obsolete_set: HashSet::new(),
453 directory: Directory { path: PathBuf::new(), ownership: DirectoryOwnership::Owned },
454 root_module_name: None,
455 expected_tokens: Vec::new(),
456 token_cursor: TokenCursor {
457 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
458 delim: token::NoDelim,
463 desugar_doc_comments: desugar_doc_comments,
467 let tok = parser.next_tok();
468 parser.token = tok.tok;
469 parser.span = tok.sp;
470 if let Some(directory) = directory {
471 parser.directory = directory;
472 } else if parser.span != syntax_pos::DUMMY_SP {
473 parser.directory.path = PathBuf::from(sess.codemap().span_to_filename(parser.span));
474 parser.directory.path.pop();
476 parser.process_potential_macro_variable();
480 fn next_tok(&mut self) -> TokenAndSpan {
481 let mut next = match self.desugar_doc_comments {
482 true => self.token_cursor.next_desugared(),
483 false => self.token_cursor.next(),
485 if next.sp == syntax_pos::DUMMY_SP {
486 next.sp = self.prev_span;
491 /// Convert a token to a string using self's reader
492 pub fn token_to_string(token: &token::Token) -> String {
493 pprust::token_to_string(token)
496 /// Convert the current token to a string using self's reader
497 pub fn this_token_to_string(&self) -> String {
498 Parser::token_to_string(&self.token)
501 pub fn this_token_descr(&self) -> String {
502 let s = self.this_token_to_string();
503 if self.token.is_strict_keyword() {
504 format!("keyword `{}`", s)
505 } else if self.token.is_reserved_keyword() {
506 format!("reserved keyword `{}`", s)
512 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
513 let token_str = Parser::token_to_string(t);
514 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
517 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
518 match self.expect_one_of(&[], &[]) {
520 Ok(_) => unreachable!(),
524 /// Expect and consume the token t. Signal an error if
525 /// the next token is not t.
526 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
527 if self.expected_tokens.is_empty() {
528 if self.token == *t {
532 let token_str = Parser::token_to_string(t);
533 let this_token_str = self.this_token_to_string();
534 Err(self.fatal(&format!("expected `{}`, found `{}`",
539 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
543 /// Expect next token to be edible or inedible token. If edible,
544 /// then consume it; if inedible, then return without consuming
545 /// anything. Signal a fatal error if next token is unexpected.
546 pub fn expect_one_of(&mut self,
547 edible: &[token::Token],
548 inedible: &[token::Token]) -> PResult<'a, ()>{
549 fn tokens_to_string(tokens: &[TokenType]) -> String {
550 let mut i = tokens.iter();
551 // This might be a sign we need a connect method on Iterator.
553 .map_or("".to_string(), |t| t.to_string());
554 i.enumerate().fold(b, |mut b, (i, ref a)| {
555 if tokens.len() > 2 && i == tokens.len() - 2 {
557 } else if tokens.len() == 2 && i == tokens.len() - 2 {
562 b.push_str(&a.to_string());
566 if edible.contains(&self.token) {
569 } else if inedible.contains(&self.token) {
570 // leave it in the input
573 let mut expected = edible.iter()
574 .map(|x| TokenType::Token(x.clone()))
575 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
576 .chain(self.expected_tokens.iter().cloned())
577 .collect::<Vec<_>>();
578 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
580 let expect = tokens_to_string(&expected[..]);
581 let actual = self.this_token_to_string();
582 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
583 let short_expect = if expected.len() > 6 {
584 format!("{} possible tokens", expected.len())
588 (format!("expected one of {}, found `{}`", expect, actual),
589 (self.prev_span.next_point(), format!("expected one of {} here", short_expect)))
590 } else if expected.is_empty() {
591 (format!("unexpected token: `{}`", actual),
592 (self.prev_span, "unexpected token after this".to_string()))
594 (format!("expected {}, found `{}`", expect, actual),
595 (self.prev_span.next_point(), format!("expected {} here", expect)))
597 let mut err = self.fatal(&msg_exp);
598 let sp = if self.token == token::Token::Eof {
599 // This is EOF, don't want to point at the following char, but rather the last token
604 if self.span.contains(sp) {
605 err.span_label(self.span, label_exp);
607 err.span_label(sp, label_exp);
608 err.span_label(self.span, "unexpected token");
614 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
615 fn interpolated_or_expr_span(&self,
616 expr: PResult<'a, P<Expr>>)
617 -> PResult<'a, (Span, P<Expr>)> {
619 if self.prev_token_kind == PrevTokenKind::Interpolated {
627 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
628 self.check_strict_keywords();
629 self.check_reserved_keywords();
636 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
637 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
639 let mut err = self.fatal(&format!("expected identifier, found `{}`",
640 self.this_token_to_string()));
641 if self.token == token::Underscore {
642 err.note("`_` is a wildcard pattern, not an identifier");
650 /// Check if the next token is `tok`, and return `true` if so.
652 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
654 pub fn check(&mut self, tok: &token::Token) -> bool {
655 let is_present = self.token == *tok;
656 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
660 /// Consume token 'tok' if it exists. Returns true if the given
661 /// token was present, false otherwise.
662 pub fn eat(&mut self, tok: &token::Token) -> bool {
663 let is_present = self.check(tok);
664 if is_present { self.bump() }
668 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
669 self.expected_tokens.push(TokenType::Keyword(kw));
670 self.token.is_keyword(kw)
673 /// If the next token is the given keyword, eat it and return
674 /// true. Otherwise, return false.
675 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
676 if self.check_keyword(kw) {
684 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
685 if self.token.is_keyword(kw) {
693 pub fn check_contextual_keyword(&mut self, ident: Ident) -> bool {
694 self.expected_tokens.push(TokenType::Token(token::Ident(ident)));
695 if let token::Ident(ref cur_ident) = self.token {
696 cur_ident.name == ident.name
702 pub fn eat_contextual_keyword(&mut self, ident: Ident) -> bool {
703 if self.check_contextual_keyword(ident) {
711 /// If the given word is not a keyword, signal an error.
712 /// If the next token is not the given word, signal an error.
713 /// Otherwise, eat it.
714 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
715 if !self.eat_keyword(kw) {
722 /// Signal an error if the given string is a strict keyword
723 pub fn check_strict_keywords(&mut self) {
724 if self.token.is_strict_keyword() {
725 let token_str = self.this_token_to_string();
726 let span = self.span;
728 &format!("expected identifier, found keyword `{}`",
733 /// Signal an error if the current token is a reserved keyword
734 pub fn check_reserved_keywords(&mut self) {
735 if self.token.is_reserved_keyword() {
736 let token_str = self.this_token_to_string();
737 self.fatal(&format!("`{}` is a reserved keyword", token_str)).emit()
741 fn check_ident(&mut self) -> bool {
742 if self.token.is_ident() {
745 self.expected_tokens.push(TokenType::Ident);
750 fn check_path(&mut self) -> bool {
751 if self.token.is_path_start() {
754 self.expected_tokens.push(TokenType::Path);
759 fn check_type(&mut self) -> bool {
760 if self.token.can_begin_type() {
763 self.expected_tokens.push(TokenType::Type);
768 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
769 /// `&` and continue. If an `&` is not seen, signal an error.
770 fn expect_and(&mut self) -> PResult<'a, ()> {
771 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
773 token::BinOp(token::And) => {
778 let span = self.span;
779 let lo = span.lo + BytePos(1);
780 Ok(self.bump_with(token::BinOp(token::And), Span { lo: lo, ..span }))
782 _ => self.unexpected()
786 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
788 None => {/* everything ok */}
790 let text = suf.as_str();
792 self.span_bug(sp, "found empty literal suffix in Some")
794 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
799 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
800 /// `<` and continue. If a `<` is not seen, return false.
802 /// This is meant to be used when parsing generics on a path to get the
804 fn eat_lt(&mut self) -> bool {
805 self.expected_tokens.push(TokenType::Token(token::Lt));
811 token::BinOp(token::Shl) => {
812 let span = self.span;
813 let lo = span.lo + BytePos(1);
814 self.bump_with(token::Lt, Span { lo: lo, ..span });
821 fn expect_lt(&mut self) -> PResult<'a, ()> {
829 /// Expect and consume a GT. if a >> is seen, replace it
830 /// with a single > and continue. If a GT is not seen,
832 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
833 self.expected_tokens.push(TokenType::Token(token::Gt));
839 token::BinOp(token::Shr) => {
840 let span = self.span;
841 let lo = span.lo + BytePos(1);
842 Ok(self.bump_with(token::Gt, Span { lo: lo, ..span }))
844 token::BinOpEq(token::Shr) => {
845 let span = self.span;
846 let lo = span.lo + BytePos(1);
847 Ok(self.bump_with(token::Ge, Span { lo: lo, ..span }))
850 let span = self.span;
851 let lo = span.lo + BytePos(1);
852 Ok(self.bump_with(token::Eq, Span { lo: lo, ..span }))
854 _ => self.unexpected()
858 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
859 sep: Option<token::Token>,
861 -> PResult<'a, (Vec<T>, bool)>
862 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
864 let mut v = Vec::new();
865 // This loop works by alternating back and forth between parsing types
866 // and commas. For example, given a string `A, B,>`, the parser would
867 // first parse `A`, then a comma, then `B`, then a comma. After that it
868 // would encounter a `>` and stop. This lets the parser handle trailing
869 // commas in generic parameters, because it can stop either after
870 // parsing a type or after parsing a comma.
872 if self.check(&token::Gt)
873 || self.token == token::BinOp(token::Shr)
874 || self.token == token::Ge
875 || self.token == token::BinOpEq(token::Shr) {
881 Some(result) => v.push(result),
882 None => return Ok((v, true))
885 if let Some(t) = sep.as_ref() {
891 return Ok((v, false));
894 /// Parse a sequence bracketed by '<' and '>', stopping
896 pub fn parse_seq_to_before_gt<T, F>(&mut self,
897 sep: Option<token::Token>,
899 -> PResult<'a, Vec<T>> where
900 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
902 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
903 |p| Ok(Some(f(p)?)))?;
908 pub fn parse_seq_to_gt<T, F>(&mut self,
909 sep: Option<token::Token>,
911 -> PResult<'a, Vec<T>> where
912 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
914 let v = self.parse_seq_to_before_gt(sep, f)?;
919 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
920 sep: Option<token::Token>,
922 -> PResult<'a, (Vec<T>, bool)> where
923 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
925 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
929 return Ok((v, returned));
932 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
933 /// passes through any errors encountered. Used for error recovery.
934 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
935 let handler = self.diagnostic();
937 self.parse_seq_to_before_tokens(kets,
939 |p| Ok(p.parse_token_tree()),
940 |mut e| handler.cancel(&mut e));
943 /// Parse a sequence, including the closing delimiter. The function
944 /// f must consume tokens until reaching the next separator or
946 pub fn parse_seq_to_end<T, F>(&mut self,
950 -> PResult<'a, Vec<T>> where
951 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
953 let val = self.parse_seq_to_before_end(ket, sep, f);
958 /// Parse a sequence, not including the closing delimiter. The function
959 /// f must consume tokens until reaching the next separator or
961 pub fn parse_seq_to_before_end<T, F>(&mut self,
966 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
968 self.parse_seq_to_before_tokens(&[ket], sep, f, |mut e| e.emit())
971 // `fe` is an error handler.
972 fn parse_seq_to_before_tokens<T, F, Fe>(&mut self,
973 kets: &[&token::Token],
978 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
979 Fe: FnMut(DiagnosticBuilder)
981 let mut first: bool = true;
983 while !kets.contains(&&self.token) {
985 token::CloseDelim(..) | token::Eof => break,
993 if let Err(e) = self.expect(t) {
1001 if sep.trailing_sep_allowed && kets.iter().any(|k| self.check(k)) {
1017 /// Parse a sequence, including the closing delimiter. The function
1018 /// f must consume tokens until reaching the next separator or
1019 /// closing bracket.
1020 pub fn parse_unspanned_seq<T, F>(&mut self,
1025 -> PResult<'a, Vec<T>> where
1026 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1029 let result = self.parse_seq_to_before_end(ket, sep, f);
1030 if self.token == *ket {
1036 // NB: Do not use this function unless you actually plan to place the
1037 // spanned list in the AST.
1038 pub fn parse_seq<T, F>(&mut self,
1043 -> PResult<'a, Spanned<Vec<T>>> where
1044 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1048 let result = self.parse_seq_to_before_end(ket, sep, f);
1051 Ok(respan(lo.to(hi), result))
1054 /// Advance the parser by one token
1055 pub fn bump(&mut self) {
1056 if self.prev_token_kind == PrevTokenKind::Eof {
1057 // Bumping after EOF is a bad sign, usually an infinite loop.
1058 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1061 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1063 // Record last token kind for possible error recovery.
1064 self.prev_token_kind = match self.token {
1065 token::DocComment(..) => PrevTokenKind::DocComment,
1066 token::Comma => PrevTokenKind::Comma,
1067 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1068 token::Interpolated(..) => PrevTokenKind::Interpolated,
1069 token::Eof => PrevTokenKind::Eof,
1070 _ => PrevTokenKind::Other,
1073 let next = self.next_tok();
1074 self.span = next.sp;
1075 self.token = next.tok;
1076 self.expected_tokens.clear();
1077 // check after each token
1078 self.process_potential_macro_variable();
1081 /// Advance the parser using provided token as a next one. Use this when
1082 /// consuming a part of a token. For example a single `<` from `<<`.
1083 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1084 self.prev_span = Span { hi: span.lo, ..self.span };
1085 // It would be incorrect to record the kind of the current token, but
1086 // fortunately for tokens currently using `bump_with`, the
1087 // prev_token_kind will be of no use anyway.
1088 self.prev_token_kind = PrevTokenKind::Other;
1091 self.expected_tokens.clear();
1094 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1095 F: FnOnce(&token::Token) -> R,
1098 return f(&self.token)
1101 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1102 Some(tree) => match tree {
1103 TokenTree::Token(_, tok) => tok,
1104 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1106 None => token::CloseDelim(self.token_cursor.frame.delim),
1109 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1110 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1112 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1113 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1115 pub fn span_fatal_err(&self, sp: Span, err: Error) -> DiagnosticBuilder<'a> {
1116 err.span_err(sp, self.diagnostic())
1118 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1119 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1123 pub fn bug(&self, m: &str) -> ! {
1124 self.sess.span_diagnostic.span_bug(self.span, m)
1126 pub fn warn(&self, m: &str) {
1127 self.sess.span_diagnostic.span_warn(self.span, m)
1129 pub fn span_warn(&self, sp: Span, m: &str) {
1130 self.sess.span_diagnostic.span_warn(sp, m)
1132 pub fn span_err(&self, sp: Span, m: &str) {
1133 self.sess.span_diagnostic.span_err(sp, m)
1135 pub fn span_err_help(&self, sp: Span, m: &str, h: &str) {
1136 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1140 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1141 self.sess.span_diagnostic.span_bug(sp, m)
1143 pub fn abort_if_errors(&self) {
1144 self.sess.span_diagnostic.abort_if_errors();
1147 fn cancel(&self, err: &mut DiagnosticBuilder) {
1148 self.sess.span_diagnostic.cancel(err)
1151 pub fn diagnostic(&self) -> &'a errors::Handler {
1152 &self.sess.span_diagnostic
1155 /// Is the current token one of the keywords that signals a bare function
1157 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1158 self.check_keyword(keywords::Fn) ||
1159 self.check_keyword(keywords::Unsafe) ||
1160 self.check_keyword(keywords::Extern)
1163 fn get_label(&mut self) -> ast::Ident {
1165 token::Lifetime(ref ident) => *ident,
1166 _ => self.bug("not a lifetime"),
1170 /// parse a TyKind::BareFn type:
1171 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<LifetimeDef>)
1172 -> PResult<'a, TyKind> {
1175 [unsafe] [extern "ABI"] fn (S) -> T
1185 let unsafety = self.parse_unsafety()?;
1186 let abi = if self.eat_keyword(keywords::Extern) {
1187 self.parse_opt_abi()?.unwrap_or(Abi::C)
1192 self.expect_keyword(keywords::Fn)?;
1193 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1194 let ret_ty = self.parse_ret_ty()?;
1195 let decl = P(FnDecl {
1200 Ok(TyKind::BareFn(P(BareFnTy {
1203 lifetimes: lifetime_defs,
1208 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1209 if self.eat_keyword(keywords::Unsafe) {
1210 return Ok(Unsafety::Unsafe);
1212 return Ok(Unsafety::Normal);
1216 /// Parse the items in a trait declaration
1217 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1218 maybe_whole!(self, NtTraitItem, |x| x);
1219 let mut attrs = self.parse_outer_attributes()?;
1222 let (name, node) = if self.eat_keyword(keywords::Type) {
1223 let TyParam {ident, bounds, default, ..} = self.parse_ty_param(vec![])?;
1224 self.expect(&token::Semi)?;
1225 (ident, TraitItemKind::Type(bounds, default))
1226 } else if self.is_const_item() {
1227 self.expect_keyword(keywords::Const)?;
1228 let ident = self.parse_ident()?;
1229 self.expect(&token::Colon)?;
1230 let ty = self.parse_ty()?;
1231 let default = if self.check(&token::Eq) {
1233 let expr = self.parse_expr()?;
1234 self.expect(&token::Semi)?;
1237 self.expect(&token::Semi)?;
1240 (ident, TraitItemKind::Const(ty, default))
1241 } else if self.token.is_path_start() {
1242 // trait item macro.
1243 // code copied from parse_macro_use_or_failure... abstraction!
1244 let prev_span = self.prev_span;
1246 let pth = self.parse_path(PathStyle::Mod)?;
1248 if pth.segments.len() == 1 {
1249 if !self.eat(&token::Not) {
1250 return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1253 self.expect(&token::Not)?;
1256 // eat a matched-delimiter token tree:
1257 let (delim, tts) = self.expect_delimited_token_tree()?;
1258 if delim != token::Brace {
1259 self.expect(&token::Semi)?
1262 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1263 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac))
1265 let (constness, unsafety, abi) = match self.parse_fn_front_matter() {
1267 Err(e) => return Err(e),
1270 let ident = self.parse_ident()?;
1271 let mut generics = self.parse_generics()?;
1273 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1274 // This is somewhat dubious; We don't want to allow
1275 // argument names to be left off if there is a
1277 p.parse_arg_general(false)
1280 generics.where_clause = self.parse_where_clause()?;
1281 let sig = ast::MethodSig {
1283 constness: constness,
1289 let body = match self.token {
1293 debug!("parse_trait_methods(): parsing required method");
1296 token::OpenDelim(token::Brace) => {
1297 debug!("parse_trait_methods(): parsing provided method");
1299 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1300 attrs.extend(inner_attrs.iter().cloned());
1304 let token_str = self.this_token_to_string();
1305 return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1308 (ident, ast::TraitItemKind::Method(sig, body))
1312 id: ast::DUMMY_NODE_ID,
1316 span: lo.to(self.prev_span),
1320 /// Parse optional return type [ -> TY ] in function decl
1321 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1322 if self.eat(&token::RArrow) {
1323 Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
1325 Ok(FunctionRetTy::Default(Span { hi: self.span.lo, ..self.span }))
1330 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1331 self.parse_ty_common(true)
1334 /// Parse a type in restricted contexts where `+` is not permitted.
1335 /// Example 1: `&'a TYPE`
1336 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1337 /// Example 2: `value1 as TYPE + value2`
1338 /// `+` is prohibited to avoid interactions with expression grammar.
1339 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1340 self.parse_ty_common(false)
1343 fn parse_ty_common(&mut self, allow_plus: bool) -> PResult<'a, P<Ty>> {
1344 maybe_whole!(self, NtTy, |x| x);
1347 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1348 // `(TYPE)` is a parenthesized type.
1349 // `(TYPE,)` is a tuple with a single field of type TYPE.
1350 let mut ts = vec![];
1351 let mut last_comma = false;
1352 while self.token != token::CloseDelim(token::Paren) {
1353 ts.push(self.parse_ty()?);
1354 if self.eat(&token::Comma) {
1361 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1362 self.expect(&token::CloseDelim(token::Paren))?;
1364 if ts.len() == 1 && !last_comma {
1365 let ty = ts.into_iter().nth(0).unwrap().unwrap();
1366 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1368 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1369 TyKind::Path(None, ref path) if maybe_bounds => {
1370 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1372 TyKind::TraitObject(ref bounds)
1373 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1374 let path = match bounds[0] {
1375 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1376 _ => self.bug("unexpected lifetime bound"),
1378 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1381 _ => TyKind::Paren(P(ty))
1386 } else if self.eat(&token::Not) {
1389 } else if self.eat(&token::BinOp(token::Star)) {
1391 TyKind::Ptr(self.parse_ptr()?)
1392 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1394 let t = self.parse_ty()?;
1395 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1396 let t = match self.maybe_parse_fixed_length_of_vec()? {
1397 None => TyKind::Slice(t),
1398 Some(suffix) => TyKind::Array(t, suffix),
1400 self.expect(&token::CloseDelim(token::Bracket))?;
1402 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1405 self.parse_borrowed_pointee()?
1406 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1408 // In order to not be ambiguous, the type must be surrounded by parens.
1409 self.expect(&token::OpenDelim(token::Paren))?;
1410 let e = self.parse_expr()?;
1411 self.expect(&token::CloseDelim(token::Paren))?;
1413 } else if self.eat(&token::Underscore) {
1414 // A type to be inferred `_`
1416 } else if self.eat_lt() {
1418 let (qself, path) = self.parse_qualified_path(PathStyle::Type)?;
1419 TyKind::Path(Some(qself), path)
1420 } else if self.token.is_path_start() {
1422 let path = self.parse_path(PathStyle::Type)?;
1423 if self.eat(&token::Not) {
1424 // Macro invocation in type position
1425 let (_, tts) = self.expect_delimited_token_tree()?;
1426 TyKind::Mac(respan(lo.to(self.span), Mac_ { path: path, tts: tts }))
1428 // Just a type path or bound list (trait object type) starting with a trait.
1430 // `Trait1 + Trait2 + 'a`
1431 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1432 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1434 TyKind::Path(None, path)
1437 } else if self.token_is_bare_fn_keyword() {
1438 // Function pointer type
1439 self.parse_ty_bare_fn(Vec::new())?
1440 } else if self.check_keyword(keywords::For) {
1441 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1442 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1443 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1445 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1446 if self.token_is_bare_fn_keyword() {
1447 self.parse_ty_bare_fn(lifetime_defs)?
1449 let path = self.parse_path(PathStyle::Type)?;
1450 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1451 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1453 } else if self.eat_keyword(keywords::Impl) {
1454 // FIXME: figure out priority of `+` in `impl Trait1 + Trait2` (#34511).
1455 TyKind::ImplTrait(self.parse_ty_param_bounds()?)
1456 } else if self.check(&token::Question) ||
1457 self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)){
1458 // Bound list (trait object type)
1459 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?)
1461 let msg = format!("expected type, found {}", self.this_token_descr());
1462 return Err(self.fatal(&msg));
1465 let span = lo.to(self.prev_span);
1466 let ty = Ty { node: node, span: span, id: ast::DUMMY_NODE_ID };
1468 // Try to recover from use of `+` with incorrect priority.
1469 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1474 fn parse_remaining_bounds(&mut self, lifetime_defs: Vec<LifetimeDef>, path: ast::Path,
1475 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1476 let poly_trait_ref = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
1477 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1480 bounds.append(&mut self.parse_ty_param_bounds()?);
1482 Ok(TyKind::TraitObject(bounds))
1485 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1486 // Do not add `+` to expected tokens.
1487 if !allow_plus || self.token != token::BinOp(token::Plus) {
1492 let bounds = self.parse_ty_param_bounds()?;
1493 let sum_span = ty.span.to(self.prev_span);
1495 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1496 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(&ty));
1499 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1500 let sum_with_parens = pprust::to_string(|s| {
1501 use print::pp::word;
1502 use print::pprust::PrintState;
1504 word(&mut s.s, "&")?;
1505 s.print_opt_lifetime(lifetime)?;
1506 s.print_mutability(mut_ty.mutbl)?;
1508 s.print_type(&mut_ty.ty)?;
1509 s.print_bounds(" +", &bounds)?;
1512 err.span_suggestion(sum_span, "try adding parentheses:", sum_with_parens);
1514 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1515 err.span_label(sum_span, "perhaps you forgot parentheses?");
1518 err.span_label(sum_span, "expected a path");
1525 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1526 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1527 let mutbl = self.parse_mutability();
1528 let ty = self.parse_ty_no_plus()?;
1529 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1532 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1533 let mutbl = if self.eat_keyword(keywords::Mut) {
1535 } else if self.eat_keyword(keywords::Const) {
1536 Mutability::Immutable
1538 let span = self.prev_span;
1540 "expected mut or const in raw pointer type (use \
1541 `*mut T` or `*const T` as appropriate)");
1542 Mutability::Immutable
1544 let t = self.parse_ty_no_plus()?;
1545 Ok(MutTy { ty: t, mutbl: mutbl })
1548 pub fn is_named_argument(&mut self) -> bool {
1549 let offset = match self.token {
1550 token::BinOp(token::And) => 1,
1552 _ if self.token.is_keyword(keywords::Mut) => 1,
1556 debug!("parser is_named_argument offset:{}", offset);
1559 is_ident_or_underscore(&self.token)
1560 && self.look_ahead(1, |t| *t == token::Colon)
1562 self.look_ahead(offset, |t| is_ident_or_underscore(t))
1563 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1567 /// This version of parse arg doesn't necessarily require
1568 /// identifier names.
1569 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1570 maybe_whole!(self, NtArg, |x| x);
1572 let pat = if require_name || self.is_named_argument() {
1573 debug!("parse_arg_general parse_pat (require_name:{})",
1575 let pat = self.parse_pat()?;
1577 self.expect(&token::Colon)?;
1580 debug!("parse_arg_general ident_to_pat");
1581 let sp = self.prev_span;
1582 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1584 id: ast::DUMMY_NODE_ID,
1585 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1591 let t = self.parse_ty()?;
1596 id: ast::DUMMY_NODE_ID,
1600 /// Parse a single function argument
1601 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1602 self.parse_arg_general(true)
1605 /// Parse an argument in a lambda header e.g. |arg, arg|
1606 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1607 let pat = self.parse_pat()?;
1608 let t = if self.eat(&token::Colon) {
1612 id: ast::DUMMY_NODE_ID,
1613 node: TyKind::Infer,
1620 id: ast::DUMMY_NODE_ID
1624 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1625 if self.eat(&token::Semi) {
1626 Ok(Some(self.parse_expr()?))
1632 /// Matches token_lit = LIT_INTEGER | ...
1633 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1634 let out = match self.token {
1635 token::Interpolated(ref nt) => match **nt {
1636 token::NtExpr(ref v) => match v.node {
1637 ExprKind::Lit(ref lit) => { lit.node.clone() }
1638 _ => { return self.unexpected_last(&self.token); }
1640 _ => { return self.unexpected_last(&self.token); }
1642 token::Literal(lit, suf) => {
1643 let diag = Some((self.span, &self.sess.span_diagnostic));
1644 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1648 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1653 _ => { return self.unexpected_last(&self.token); }
1660 /// Matches lit = true | false | token_lit
1661 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1663 let lit = if self.eat_keyword(keywords::True) {
1665 } else if self.eat_keyword(keywords::False) {
1666 LitKind::Bool(false)
1668 let lit = self.parse_lit_token()?;
1671 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1674 /// matches '-' lit | lit
1675 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1676 let minus_lo = self.span;
1677 let minus_present = self.eat(&token::BinOp(token::Minus));
1679 let literal = P(self.parse_lit()?);
1680 let hi = self.prev_span;
1681 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1684 let minus_hi = self.prev_span;
1685 let unary = self.mk_unary(UnOp::Neg, expr);
1686 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1692 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1694 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1698 _ => self.parse_ident(),
1702 /// Parses qualified path.
1704 /// Assumes that the leading `<` has been parsed already.
1706 /// Qualifed paths are a part of the universal function call
1709 /// `qualified_path = <type [as trait_ref]>::path`
1711 /// See `parse_path` for `mode` meaning.
1716 /// `<T as U>::F::a::<S>`
1717 pub fn parse_qualified_path(&mut self, mode: PathStyle)
1718 -> PResult<'a, (QSelf, ast::Path)> {
1719 let span = self.prev_span;
1720 let self_type = self.parse_ty()?;
1721 let mut path = if self.eat_keyword(keywords::As) {
1722 self.parse_path(PathStyle::Type)?
1732 position: path.segments.len()
1735 self.expect(&token::Gt)?;
1736 self.expect(&token::ModSep)?;
1738 let segments = match mode {
1739 PathStyle::Type => {
1740 self.parse_path_segments_without_colons()?
1742 PathStyle::Expr => {
1743 self.parse_path_segments_with_colons()?
1746 self.parse_path_segments_without_types()?
1749 path.segments.extend(segments);
1751 path.span.hi = self.prev_span.hi;
1756 /// Parses a path and optional type parameter bounds, depending on the
1757 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1758 /// bounds are permitted and whether `::` must precede type parameter
1760 pub fn parse_path(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1761 maybe_whole!(self, NtPath, |x| x);
1763 let lo = self.meta_var_span.unwrap_or(self.span);
1764 let is_global = self.eat(&token::ModSep);
1766 // Parse any number of segments and bound sets. A segment is an
1767 // identifier followed by an optional lifetime and a set of types.
1768 // A bound set is a set of type parameter bounds.
1769 let mut segments = match mode {
1770 PathStyle::Type => {
1771 self.parse_path_segments_without_colons()?
1773 PathStyle::Expr => {
1774 self.parse_path_segments_with_colons()?
1777 self.parse_path_segments_without_types()?
1782 segments.insert(0, PathSegment::crate_root());
1785 // Assemble the result.
1787 span: lo.to(self.prev_span),
1792 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1793 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1794 pub fn parse_path_allowing_meta(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1795 let meta_ident = match self.token {
1796 token::Interpolated(ref nt) => match **nt {
1797 token::NtMeta(ref meta) => match meta.node {
1798 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
1805 if let Some(ident) = meta_ident {
1807 return Ok(ast::Path::from_ident(self.prev_span, ident));
1809 self.parse_path(mode)
1813 /// - `a::b<T,U>::c<V,W>`
1814 /// - `a::b<T,U>::c(V) -> W`
1815 /// - `a::b<T,U>::c(V)`
1816 pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1817 let mut segments = Vec::new();
1819 // First, parse an identifier.
1820 let ident_span = self.span;
1821 let identifier = self.parse_path_segment_ident()?;
1823 if self.check(&token::ModSep) && self.look_ahead(1, |t| *t == token::Lt) {
1825 let prev_span = self.prev_span;
1827 let mut err = self.diagnostic().struct_span_err(prev_span,
1828 "unexpected token: `::`");
1830 "use `<...>` instead of `::<...>` if you meant to specify type arguments");
1834 // Parse types, optionally.
1835 let parameters = if self.eat_lt() {
1836 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1838 ast::AngleBracketedParameterData {
1839 lifetimes: lifetimes,
1843 } else if self.eat(&token::OpenDelim(token::Paren)) {
1844 let lo = self.prev_span;
1846 let inputs = self.parse_seq_to_end(
1847 &token::CloseDelim(token::Paren),
1848 SeqSep::trailing_allowed(token::Comma),
1851 let output_ty = if self.eat(&token::RArrow) {
1852 Some(self.parse_ty_no_plus()?)
1857 let hi = self.prev_span;
1859 Some(P(ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData {
1868 // Assemble and push the result.
1869 segments.push(PathSegment {
1870 identifier: identifier,
1872 parameters: parameters
1875 // Continue only if we see a `::`
1876 if !self.eat(&token::ModSep) {
1877 return Ok(segments);
1883 /// - `a::b::<T,U>::c`
1884 pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1885 let mut segments = Vec::new();
1887 // First, parse an identifier.
1888 let ident_span = self.span;
1889 let identifier = self.parse_path_segment_ident()?;
1891 // If we do not see a `::`, stop.
1892 if !self.eat(&token::ModSep) {
1893 segments.push(PathSegment::from_ident(identifier, ident_span));
1894 return Ok(segments);
1897 // Check for a type segment.
1899 // Consumed `a::b::<`, go look for types
1900 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1902 segments.push(PathSegment {
1903 identifier: identifier,
1905 parameters: ast::AngleBracketedParameterData {
1906 lifetimes: lifetimes,
1912 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1913 if !self.eat(&token::ModSep) {
1914 return Ok(segments);
1917 // Consumed `a::`, go look for `b`
1918 segments.push(PathSegment::from_ident(identifier, ident_span));
1925 pub fn parse_path_segments_without_types(&mut self)
1926 -> PResult<'a, Vec<PathSegment>> {
1927 let mut segments = Vec::new();
1929 // First, parse an identifier.
1930 let ident_span = self.span;
1931 let identifier = self.parse_path_segment_ident()?;
1933 // Assemble and push the result.
1934 segments.push(PathSegment::from_ident(identifier, ident_span));
1936 // If we do not see a `::` or see `::{`/`::*`, stop.
1937 if !self.check(&token::ModSep) || self.is_import_coupler() {
1938 return Ok(segments);
1945 fn check_lifetime(&mut self) -> bool {
1946 self.expected_tokens.push(TokenType::Lifetime);
1947 self.token.is_lifetime()
1950 /// Parse single lifetime 'a or panic.
1951 fn expect_lifetime(&mut self) -> Lifetime {
1953 token::Lifetime(ident) => {
1954 let ident_span = self.span;
1956 Lifetime { name: ident.name, span: ident_span, id: ast::DUMMY_NODE_ID }
1958 _ => self.span_bug(self.span, "not a lifetime")
1962 /// Parse mutability (`mut` or nothing).
1963 fn parse_mutability(&mut self) -> Mutability {
1964 if self.eat_keyword(keywords::Mut) {
1967 Mutability::Immutable
1971 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1972 if let token::Literal(token::Integer(name), None) = self.token {
1974 Ok(Ident::with_empty_ctxt(name))
1980 /// Parse ident (COLON expr)?
1981 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1982 let attrs = self.parse_outer_attributes()?;
1986 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1987 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1988 let fieldname = self.parse_field_name()?;
1990 hi = self.prev_span;
1991 (fieldname, self.parse_expr()?, false)
1993 let fieldname = self.parse_ident()?;
1994 hi = self.prev_span;
1996 // Mimic `x: x` for the `x` field shorthand.
1997 let path = ast::Path::from_ident(lo.to(hi), fieldname);
1998 (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
2001 ident: respan(lo.to(hi), fieldname),
2002 span: lo.to(expr.span),
2004 is_shorthand: is_shorthand,
2005 attrs: attrs.into(),
2009 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2011 id: ast::DUMMY_NODE_ID,
2014 attrs: attrs.into(),
2018 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2019 ExprKind::Unary(unop, expr)
2022 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2023 ExprKind::Binary(binop, lhs, rhs)
2026 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2027 ExprKind::Call(f, args)
2030 fn mk_method_call(&mut self,
2031 ident: ast::SpannedIdent,
2035 ExprKind::MethodCall(ident, tps, args)
2038 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2039 ExprKind::Index(expr, idx)
2042 pub fn mk_range(&mut self,
2043 start: Option<P<Expr>>,
2044 end: Option<P<Expr>>,
2045 limits: RangeLimits)
2046 -> PResult<'a, ast::ExprKind> {
2047 if end.is_none() && limits == RangeLimits::Closed {
2048 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2050 Ok(ExprKind::Range(start, end, limits))
2054 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::ExprKind {
2055 ExprKind::Field(expr, ident)
2058 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2059 ExprKind::TupField(expr, idx)
2062 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2063 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2064 ExprKind::AssignOp(binop, lhs, rhs)
2067 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2069 id: ast::DUMMY_NODE_ID,
2070 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2076 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2077 let span = &self.span;
2078 let lv_lit = P(codemap::Spanned {
2079 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2084 id: ast::DUMMY_NODE_ID,
2085 node: ExprKind::Lit(lv_lit),
2091 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2093 token::OpenDelim(delim) => match self.parse_token_tree() {
2094 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2095 _ => unreachable!(),
2097 _ => Err(self.fatal("expected open delimiter")),
2101 /// At the bottom (top?) of the precedence hierarchy,
2102 /// parse things like parenthesized exprs,
2103 /// macros, return, etc.
2105 /// NB: This does not parse outer attributes,
2106 /// and is private because it only works
2107 /// correctly if called from parse_dot_or_call_expr().
2108 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2109 maybe_whole_expr!(self);
2111 // Outer attributes are already parsed and will be
2112 // added to the return value after the fact.
2114 // Therefore, prevent sub-parser from parsing
2115 // attributes by giving them a empty "already parsed" list.
2116 let mut attrs = ThinVec::new();
2119 let mut hi = self.span;
2123 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2125 token::OpenDelim(token::Paren) => {
2128 attrs.extend(self.parse_inner_attributes()?);
2130 // (e) is parenthesized e
2131 // (e,) is a tuple with only one field, e
2132 let mut es = vec![];
2133 let mut trailing_comma = false;
2134 while self.token != token::CloseDelim(token::Paren) {
2135 es.push(self.parse_expr()?);
2136 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2137 if self.check(&token::Comma) {
2138 trailing_comma = true;
2142 trailing_comma = false;
2148 hi = self.prev_span;
2149 let span = lo.to(hi);
2150 return if es.len() == 1 && !trailing_comma {
2151 Ok(self.mk_expr(span, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2153 Ok(self.mk_expr(span, ExprKind::Tup(es), attrs))
2156 token::OpenDelim(token::Brace) => {
2157 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2159 token::BinOp(token::Or) | token::OrOr => {
2161 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2163 token::OpenDelim(token::Bracket) => {
2166 attrs.extend(self.parse_inner_attributes()?);
2168 if self.check(&token::CloseDelim(token::Bracket)) {
2171 ex = ExprKind::Array(Vec::new());
2174 let first_expr = self.parse_expr()?;
2175 if self.check(&token::Semi) {
2176 // Repeating array syntax: [ 0; 512 ]
2178 let count = self.parse_expr()?;
2179 self.expect(&token::CloseDelim(token::Bracket))?;
2180 ex = ExprKind::Repeat(first_expr, count);
2181 } else if self.check(&token::Comma) {
2182 // Vector with two or more elements.
2184 let remaining_exprs = self.parse_seq_to_end(
2185 &token::CloseDelim(token::Bracket),
2186 SeqSep::trailing_allowed(token::Comma),
2187 |p| Ok(p.parse_expr()?)
2189 let mut exprs = vec![first_expr];
2190 exprs.extend(remaining_exprs);
2191 ex = ExprKind::Array(exprs);
2193 // Vector with one element.
2194 self.expect(&token::CloseDelim(token::Bracket))?;
2195 ex = ExprKind::Array(vec![first_expr]);
2198 hi = self.prev_span;
2203 self.parse_qualified_path(PathStyle::Expr)?;
2205 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2207 if self.eat_keyword(keywords::Move) {
2208 let lo = self.prev_span;
2209 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2211 if self.eat_keyword(keywords::If) {
2212 return self.parse_if_expr(attrs);
2214 if self.eat_keyword(keywords::For) {
2215 let lo = self.prev_span;
2216 return self.parse_for_expr(None, lo, attrs);
2218 if self.eat_keyword(keywords::While) {
2219 let lo = self.prev_span;
2220 return self.parse_while_expr(None, lo, attrs);
2222 if self.token.is_lifetime() {
2223 let label = Spanned { node: self.get_label(),
2227 self.expect(&token::Colon)?;
2228 if self.eat_keyword(keywords::While) {
2229 return self.parse_while_expr(Some(label), lo, attrs)
2231 if self.eat_keyword(keywords::For) {
2232 return self.parse_for_expr(Some(label), lo, attrs)
2234 if self.eat_keyword(keywords::Loop) {
2235 return self.parse_loop_expr(Some(label), lo, attrs)
2237 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2239 if self.eat_keyword(keywords::Loop) {
2240 let lo = self.prev_span;
2241 return self.parse_loop_expr(None, lo, attrs);
2243 if self.eat_keyword(keywords::Continue) {
2244 let ex = if self.token.is_lifetime() {
2245 let ex = ExprKind::Continue(Some(Spanned{
2246 node: self.get_label(),
2252 ExprKind::Continue(None)
2254 let hi = self.prev_span;
2255 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2257 if self.eat_keyword(keywords::Match) {
2258 return self.parse_match_expr(attrs);
2260 if self.eat_keyword(keywords::Unsafe) {
2261 return self.parse_block_expr(
2263 BlockCheckMode::Unsafe(ast::UserProvided),
2266 if self.is_catch_expr() {
2267 assert!(self.eat_keyword(keywords::Do));
2268 assert!(self.eat_keyword(keywords::Catch));
2269 let lo = self.prev_span;
2270 return self.parse_catch_expr(lo, attrs);
2272 if self.eat_keyword(keywords::Return) {
2273 if self.token.can_begin_expr() {
2274 let e = self.parse_expr()?;
2276 ex = ExprKind::Ret(Some(e));
2278 ex = ExprKind::Ret(None);
2280 } else if self.eat_keyword(keywords::Break) {
2281 let lt = if self.token.is_lifetime() {
2282 let spanned_lt = Spanned {
2283 node: self.get_label(),
2291 let e = if self.token.can_begin_expr()
2292 && !(self.token == token::OpenDelim(token::Brace)
2293 && self.restrictions.contains(
2294 RESTRICTION_NO_STRUCT_LITERAL)) {
2295 Some(self.parse_expr()?)
2299 ex = ExprKind::Break(lt, e);
2300 hi = self.prev_span;
2301 } else if self.token.is_keyword(keywords::Let) {
2302 // Catch this syntax error here, instead of in `check_strict_keywords`, so
2303 // that we can explicitly mention that let is not to be used as an expression
2304 let mut db = self.fatal("expected expression, found statement (`let`)");
2305 db.note("variable declaration using `let` is a statement");
2307 } else if self.token.is_path_start() {
2308 let pth = self.parse_path(PathStyle::Expr)?;
2310 // `!`, as an operator, is prefix, so we know this isn't that
2311 if self.eat(&token::Not) {
2312 // MACRO INVOCATION expression
2313 let (_, tts) = self.expect_delimited_token_tree()?;
2314 let hi = self.prev_span;
2315 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2317 if self.check(&token::OpenDelim(token::Brace)) {
2318 // This is a struct literal, unless we're prohibited
2319 // from parsing struct literals here.
2320 let prohibited = self.restrictions.contains(
2321 RESTRICTION_NO_STRUCT_LITERAL
2324 return self.parse_struct_expr(lo, pth, attrs);
2329 ex = ExprKind::Path(None, pth);
2331 match self.parse_lit() {
2334 ex = ExprKind::Lit(P(lit));
2337 self.cancel(&mut err);
2338 let msg = format!("expected expression, found {}",
2339 self.this_token_descr());
2340 return Err(self.fatal(&msg));
2347 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2350 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2351 -> PResult<'a, P<Expr>> {
2353 let mut fields = Vec::new();
2354 let mut base = None;
2356 attrs.extend(self.parse_inner_attributes()?);
2358 while self.token != token::CloseDelim(token::Brace) {
2359 if self.eat(&token::DotDot) {
2360 match self.parse_expr() {
2366 self.recover_stmt();
2372 match self.parse_field() {
2373 Ok(f) => fields.push(f),
2376 self.recover_stmt();
2381 match self.expect_one_of(&[token::Comma],
2382 &[token::CloseDelim(token::Brace)]) {
2386 self.recover_stmt();
2392 let span = lo.to(self.span);
2393 self.expect(&token::CloseDelim(token::Brace))?;
2394 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2397 fn parse_or_use_outer_attributes(&mut self,
2398 already_parsed_attrs: Option<ThinVec<Attribute>>)
2399 -> PResult<'a, ThinVec<Attribute>> {
2400 if let Some(attrs) = already_parsed_attrs {
2403 self.parse_outer_attributes().map(|a| a.into())
2407 /// Parse a block or unsafe block
2408 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2409 outer_attrs: ThinVec<Attribute>)
2410 -> PResult<'a, P<Expr>> {
2412 self.expect(&token::OpenDelim(token::Brace))?;
2414 let mut attrs = outer_attrs;
2415 attrs.extend(self.parse_inner_attributes()?);
2417 let blk = self.parse_block_tail(lo, blk_mode)?;
2418 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2421 /// parse a.b or a(13) or a[4] or just a
2422 pub fn parse_dot_or_call_expr(&mut self,
2423 already_parsed_attrs: Option<ThinVec<Attribute>>)
2424 -> PResult<'a, P<Expr>> {
2425 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2427 let b = self.parse_bottom_expr();
2428 let (span, b) = self.interpolated_or_expr_span(b)?;
2429 self.parse_dot_or_call_expr_with(b, span, attrs)
2432 pub fn parse_dot_or_call_expr_with(&mut self,
2435 mut attrs: ThinVec<Attribute>)
2436 -> PResult<'a, P<Expr>> {
2437 // Stitch the list of outer attributes onto the return value.
2438 // A little bit ugly, but the best way given the current code
2440 self.parse_dot_or_call_expr_with_(e0, lo)
2442 expr.map(|mut expr| {
2443 attrs.extend::<Vec<_>>(expr.attrs.into());
2446 ExprKind::If(..) | ExprKind::IfLet(..) => {
2447 if !expr.attrs.is_empty() {
2448 // Just point to the first attribute in there...
2449 let span = expr.attrs[0].span;
2452 "attributes are not yet allowed on `if` \
2463 // Assuming we have just parsed `.foo` (i.e., a dot and an ident), continue
2464 // parsing into an expression.
2465 fn parse_dot_suffix(&mut self, ident: Ident, ident_span: Span, self_value: P<Expr>, lo: Span)
2466 -> PResult<'a, P<Expr>> {
2467 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2469 let args = self.parse_generic_args()?;
2473 (Vec::new(), Vec::new(), Vec::new())
2476 if !bindings.is_empty() {
2477 let prev_span = self.prev_span;
2478 self.span_err(prev_span, "type bindings are only permitted on trait paths");
2481 Ok(match self.token {
2482 // expr.f() method call.
2483 token::OpenDelim(token::Paren) => {
2484 let mut es = self.parse_unspanned_seq(
2485 &token::OpenDelim(token::Paren),
2486 &token::CloseDelim(token::Paren),
2487 SeqSep::trailing_allowed(token::Comma),
2488 |p| Ok(p.parse_expr()?)
2490 let hi = self.prev_span;
2492 es.insert(0, self_value);
2493 let id = respan(ident_span.to(ident_span), ident);
2494 let nd = self.mk_method_call(id, tys, es);
2495 self.mk_expr(lo.to(hi), nd, ThinVec::new())
2499 if !tys.is_empty() {
2500 let prev_span = self.prev_span;
2501 self.span_err(prev_span,
2502 "field expressions may not \
2503 have type parameters");
2506 let id = respan(ident_span.to(ident_span), ident);
2507 let field = self.mk_field(self_value, id);
2508 self.mk_expr(lo.to(ident_span), field, ThinVec::new())
2513 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2518 while self.eat(&token::Question) {
2519 let hi = self.prev_span;
2520 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2524 if self.eat(&token::Dot) {
2526 token::Ident(i) => {
2527 let ident_span = self.span;
2529 e = self.parse_dot_suffix(i, ident_span, e, lo)?;
2531 token::Literal(token::Integer(n), suf) => {
2534 // A tuple index may not have a suffix
2535 self.expect_no_suffix(sp, "tuple index", suf);
2537 let dot_span = self.prev_span;
2541 let index = n.as_str().parse::<usize>().ok();
2544 let id = respan(dot_span.to(hi), n);
2545 let field = self.mk_tup_field(e, id);
2546 e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2549 let prev_span = self.prev_span;
2550 self.span_err(prev_span, "invalid tuple or tuple struct index");
2554 token::Literal(token::Float(n), _suf) => {
2556 let fstr = n.as_str();
2557 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2558 &format!("unexpected token: `{}`", n));
2559 err.span_label(self.prev_span, "unexpected token");
2560 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2561 let float = match fstr.parse::<f64>().ok() {
2565 let sugg = pprust::to_string(|s| {
2566 use print::pprust::PrintState;
2567 use print::pp::word;
2570 word(&mut s.s, ".")?;
2571 s.print_usize(float.trunc() as usize)?;
2573 word(&mut s.s, ".")?;
2574 word(&mut s.s, fstr.splitn(2, ".").last().unwrap())
2576 err.span_suggestion(
2577 lo.to(self.prev_span),
2578 "try parenthesizing the first index",
2585 // FIXME Could factor this out into non_fatal_unexpected or something.
2586 let actual = self.this_token_to_string();
2587 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2589 let dot_span = self.prev_span;
2590 e = self.parse_dot_suffix(keywords::Invalid.ident(), dot_span, e, lo)?;
2595 if self.expr_is_complete(&e) { break; }
2598 token::OpenDelim(token::Paren) => {
2599 let es = self.parse_unspanned_seq(
2600 &token::OpenDelim(token::Paren),
2601 &token::CloseDelim(token::Paren),
2602 SeqSep::trailing_allowed(token::Comma),
2603 |p| Ok(p.parse_expr()?)
2605 hi = self.prev_span;
2607 let nd = self.mk_call(e, es);
2608 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2612 // Could be either an index expression or a slicing expression.
2613 token::OpenDelim(token::Bracket) => {
2615 let ix = self.parse_expr()?;
2617 self.expect(&token::CloseDelim(token::Bracket))?;
2618 let index = self.mk_index(e, ix);
2619 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2627 pub fn process_potential_macro_variable(&mut self) {
2628 let ident = match self.token {
2629 token::SubstNt(name) => {
2630 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2633 token::Interpolated(ref nt) => {
2634 self.meta_var_span = Some(self.span);
2636 token::NtIdent(ident) => ident,
2642 self.token = token::Ident(ident.node);
2643 self.span = ident.span;
2646 /// parse a single token tree from the input.
2647 pub fn parse_token_tree(&mut self) -> TokenTree {
2649 token::OpenDelim(..) => {
2650 let frame = mem::replace(&mut self.token_cursor.frame,
2651 self.token_cursor.stack.pop().unwrap());
2652 self.span = frame.span;
2654 TokenTree::Delimited(frame.span, Delimited {
2656 tts: frame.tree_cursor.original_stream().into(),
2659 token::CloseDelim(_) | token::Eof => unreachable!(),
2661 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2663 TokenTree::Token(span, token)
2668 // parse a stream of tokens into a list of TokenTree's,
2670 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2671 let mut tts = Vec::new();
2672 while self.token != token::Eof {
2673 tts.push(self.parse_token_tree());
2678 pub fn parse_tokens(&mut self) -> TokenStream {
2679 let mut result = Vec::new();
2682 token::Eof | token::CloseDelim(..) => break,
2683 _ => result.push(self.parse_token_tree().into()),
2686 TokenStream::concat(result)
2689 /// Parse a prefix-unary-operator expr
2690 pub fn parse_prefix_expr(&mut self,
2691 already_parsed_attrs: Option<ThinVec<Attribute>>)
2692 -> PResult<'a, P<Expr>> {
2693 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2695 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2696 let (hi, ex) = match self.token {
2699 let e = self.parse_prefix_expr(None);
2700 let (span, e) = self.interpolated_or_expr_span(e)?;
2701 (span, self.mk_unary(UnOp::Not, e))
2703 // Suggest `!` for bitwise negation when encountering a `~`
2706 let e = self.parse_prefix_expr(None);
2707 let (span, e) = self.interpolated_or_expr_span(e)?;
2708 let span_of_tilde = lo;
2709 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2710 "`~` can not be used as a unary operator");
2711 err.span_label(span_of_tilde, "did you mean `!`?");
2712 err.help("use `!` instead of `~` if you meant to perform bitwise negation");
2714 (span, self.mk_unary(UnOp::Not, e))
2716 token::BinOp(token::Minus) => {
2718 let e = self.parse_prefix_expr(None);
2719 let (span, e) = self.interpolated_or_expr_span(e)?;
2720 (span, self.mk_unary(UnOp::Neg, e))
2722 token::BinOp(token::Star) => {
2724 let e = self.parse_prefix_expr(None);
2725 let (span, e) = self.interpolated_or_expr_span(e)?;
2726 (span, self.mk_unary(UnOp::Deref, e))
2728 token::BinOp(token::And) | token::AndAnd => {
2730 let m = self.parse_mutability();
2731 let e = self.parse_prefix_expr(None);
2732 let (span, e) = self.interpolated_or_expr_span(e)?;
2733 (span, ExprKind::AddrOf(m, e))
2735 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2737 let place = self.parse_expr_res(
2738 RESTRICTION_NO_STRUCT_LITERAL,
2741 let blk = self.parse_block()?;
2742 let span = blk.span;
2743 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2744 (span, ExprKind::InPlace(place, blk_expr))
2746 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2748 let e = self.parse_prefix_expr(None);
2749 let (span, e) = self.interpolated_or_expr_span(e)?;
2750 (span, ExprKind::Box(e))
2752 _ => return self.parse_dot_or_call_expr(Some(attrs))
2754 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2757 /// Parse an associative expression
2759 /// This parses an expression accounting for associativity and precedence of the operators in
2761 pub fn parse_assoc_expr(&mut self,
2762 already_parsed_attrs: Option<ThinVec<Attribute>>)
2763 -> PResult<'a, P<Expr>> {
2764 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2767 /// Parse an associative expression with operators of at least `min_prec` precedence
2768 pub fn parse_assoc_expr_with(&mut self,
2771 -> PResult<'a, P<Expr>> {
2772 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2775 let attrs = match lhs {
2776 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2779 if self.token == token::DotDot || self.token == token::DotDotDot {
2780 return self.parse_prefix_range_expr(attrs);
2782 self.parse_prefix_expr(attrs)?
2786 if self.expr_is_complete(&lhs) {
2787 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2790 self.expected_tokens.push(TokenType::Operator);
2791 while let Some(op) = AssocOp::from_token(&self.token) {
2793 let lhs_span = if self.prev_token_kind == PrevTokenKind::Interpolated {
2799 let cur_op_span = self.span;
2800 let restrictions = if op.is_assign_like() {
2801 self.restrictions & RESTRICTION_NO_STRUCT_LITERAL
2805 if op.precedence() < min_prec {
2809 if op.is_comparison() {
2810 self.check_no_chained_comparison(&lhs, &op);
2813 if op == AssocOp::As {
2814 let rhs = self.parse_ty_no_plus()?;
2815 lhs = self.mk_expr(lhs_span.to(rhs.span), ExprKind::Cast(lhs, rhs), ThinVec::new());
2817 } else if op == AssocOp::Colon {
2818 let rhs = self.parse_ty_no_plus()?;
2819 lhs = self.mk_expr(lhs_span.to(rhs.span), ExprKind::Type(lhs, rhs), ThinVec::new());
2821 } else if op == AssocOp::DotDot || op == AssocOp::DotDotDot {
2822 // If we didn’t have to handle `x..`/`x...`, it would be pretty easy to
2823 // generalise it to the Fixity::None code.
2825 // We have 2 alternatives here: `x..y`/`x...y` and `x..`/`x...` The other
2826 // two variants are handled with `parse_prefix_range_expr` call above.
2827 let rhs = if self.is_at_start_of_range_notation_rhs() {
2828 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2829 LhsExpr::NotYetParsed)?)
2833 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2838 let limits = if op == AssocOp::DotDot {
2839 RangeLimits::HalfOpen
2844 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2845 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2849 let rhs = match op.fixity() {
2850 Fixity::Right => self.with_res(
2851 restrictions - RESTRICTION_STMT_EXPR,
2853 this.parse_assoc_expr_with(op.precedence(),
2854 LhsExpr::NotYetParsed)
2856 Fixity::Left => self.with_res(
2857 restrictions - RESTRICTION_STMT_EXPR,
2859 this.parse_assoc_expr_with(op.precedence() + 1,
2860 LhsExpr::NotYetParsed)
2862 // We currently have no non-associative operators that are not handled above by
2863 // the special cases. The code is here only for future convenience.
2864 Fixity::None => self.with_res(
2865 restrictions - RESTRICTION_STMT_EXPR,
2867 this.parse_assoc_expr_with(op.precedence() + 1,
2868 LhsExpr::NotYetParsed)
2872 let span = lhs_span.to(rhs.span);
2874 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2875 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2876 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2877 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2878 AssocOp::Greater | AssocOp::GreaterEqual => {
2879 let ast_op = op.to_ast_binop().unwrap();
2880 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2881 self.mk_expr(span, binary, ThinVec::new())
2884 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2886 self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
2887 AssocOp::AssignOp(k) => {
2889 token::Plus => BinOpKind::Add,
2890 token::Minus => BinOpKind::Sub,
2891 token::Star => BinOpKind::Mul,
2892 token::Slash => BinOpKind::Div,
2893 token::Percent => BinOpKind::Rem,
2894 token::Caret => BinOpKind::BitXor,
2895 token::And => BinOpKind::BitAnd,
2896 token::Or => BinOpKind::BitOr,
2897 token::Shl => BinOpKind::Shl,
2898 token::Shr => BinOpKind::Shr,
2900 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2901 self.mk_expr(span, aopexpr, ThinVec::new())
2903 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotDot => {
2904 self.bug("As, Colon, DotDot or DotDotDot branch reached")
2908 if op.fixity() == Fixity::None { break }
2913 /// Produce an error if comparison operators are chained (RFC #558).
2914 /// We only need to check lhs, not rhs, because all comparison ops
2915 /// have same precedence and are left-associative
2916 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2917 debug_assert!(outer_op.is_comparison());
2919 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2920 // respan to include both operators
2921 let op_span = op.span.to(self.span);
2922 let mut err = self.diagnostic().struct_span_err(op_span,
2923 "chained comparison operators require parentheses");
2924 if op.node == BinOpKind::Lt &&
2925 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
2926 *outer_op == AssocOp::Greater // even in a case like the following:
2927 { // Foo<Bar<Baz<Qux, ()>>>
2929 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2937 /// Parse prefix-forms of range notation: `..expr`, `..`, `...expr`
2938 fn parse_prefix_range_expr(&mut self,
2939 already_parsed_attrs: Option<ThinVec<Attribute>>)
2940 -> PResult<'a, P<Expr>> {
2941 debug_assert!(self.token == token::DotDot || self.token == token::DotDotDot);
2942 let tok = self.token.clone();
2943 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2945 let mut hi = self.span;
2947 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2948 // RHS must be parsed with more associativity than the dots.
2949 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
2950 Some(self.parse_assoc_expr_with(next_prec,
2951 LhsExpr::NotYetParsed)
2959 let limits = if tok == token::DotDot {
2960 RangeLimits::HalfOpen
2965 let r = try!(self.mk_range(None,
2968 Ok(self.mk_expr(lo.to(hi), r, attrs))
2971 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2972 if self.token.can_begin_expr() {
2973 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2974 if self.token == token::OpenDelim(token::Brace) {
2975 return !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL);
2983 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2984 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
2985 if self.check_keyword(keywords::Let) {
2986 return self.parse_if_let_expr(attrs);
2988 let lo = self.prev_span;
2989 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
2990 let thn = self.parse_block()?;
2991 let mut els: Option<P<Expr>> = None;
2992 let mut hi = thn.span;
2993 if self.eat_keyword(keywords::Else) {
2994 let elexpr = self.parse_else_expr()?;
2998 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3001 /// Parse an 'if let' expression ('if' token already eaten)
3002 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3003 -> PResult<'a, P<Expr>> {
3004 let lo = self.prev_span;
3005 self.expect_keyword(keywords::Let)?;
3006 let pat = self.parse_pat()?;
3007 self.expect(&token::Eq)?;
3008 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3009 let thn = self.parse_block()?;
3010 let (hi, els) = if self.eat_keyword(keywords::Else) {
3011 let expr = self.parse_else_expr()?;
3012 (expr.span, Some(expr))
3016 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
3019 // `move |args| expr`
3020 pub fn parse_lambda_expr(&mut self,
3022 capture_clause: CaptureBy,
3023 attrs: ThinVec<Attribute>)
3024 -> PResult<'a, P<Expr>>
3026 let decl = self.parse_fn_block_decl()?;
3027 let decl_hi = self.prev_span;
3028 let body = match decl.output {
3029 FunctionRetTy::Default(_) => self.parse_expr()?,
3031 // If an explicit return type is given, require a
3032 // block to appear (RFC 968).
3033 let body_lo = self.span;
3034 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3040 ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3044 // `else` token already eaten
3045 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3046 if self.eat_keyword(keywords::If) {
3047 return self.parse_if_expr(ThinVec::new());
3049 let blk = self.parse_block()?;
3050 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3054 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3055 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3057 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3058 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3060 let pat = self.parse_pat()?;
3061 self.expect_keyword(keywords::In)?;
3062 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3063 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3064 attrs.extend(iattrs);
3066 let hi = self.prev_span;
3067 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3070 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3071 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3073 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3074 if self.token.is_keyword(keywords::Let) {
3075 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3077 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3078 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3079 attrs.extend(iattrs);
3080 let span = span_lo.to(body.span);
3081 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3084 /// Parse a 'while let' expression ('while' token already eaten)
3085 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3087 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3088 self.expect_keyword(keywords::Let)?;
3089 let pat = self.parse_pat()?;
3090 self.expect(&token::Eq)?;
3091 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3092 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3093 attrs.extend(iattrs);
3094 let span = span_lo.to(body.span);
3095 return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3098 // parse `loop {...}`, `loop` token already eaten
3099 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3101 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3102 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3103 attrs.extend(iattrs);
3104 let span = span_lo.to(body.span);
3105 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3108 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3109 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3110 -> PResult<'a, P<Expr>>
3112 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3113 attrs.extend(iattrs);
3114 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3117 // `match` token already eaten
3118 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3119 let match_span = self.prev_span;
3120 let lo = self.prev_span;
3121 let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL,
3123 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3124 if self.token == token::Token::Semi {
3125 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3129 attrs.extend(self.parse_inner_attributes()?);
3131 let mut arms: Vec<Arm> = Vec::new();
3132 while self.token != token::CloseDelim(token::Brace) {
3133 match self.parse_arm() {
3134 Ok(arm) => arms.push(arm),
3136 // Recover by skipping to the end of the block.
3138 self.recover_stmt();
3139 let span = lo.to(self.span);
3140 if self.token == token::CloseDelim(token::Brace) {
3143 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3149 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3152 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3153 maybe_whole!(self, NtArm, |x| x);
3155 let attrs = self.parse_outer_attributes()?;
3156 let pats = self.parse_pats()?;
3157 let mut guard = None;
3158 if self.eat_keyword(keywords::If) {
3159 guard = Some(self.parse_expr()?);
3161 self.expect(&token::FatArrow)?;
3162 let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR, None)?;
3165 !classify::expr_is_simple_block(&expr)
3166 && self.token != token::CloseDelim(token::Brace);
3169 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3171 self.eat(&token::Comma);
3182 /// Parse an expression
3183 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3184 self.parse_expr_res(Restrictions::empty(), None)
3187 /// Evaluate the closure with restrictions in place.
3189 /// After the closure is evaluated, restrictions are reset.
3190 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3191 where F: FnOnce(&mut Self) -> T
3193 let old = self.restrictions;
3194 self.restrictions = r;
3196 self.restrictions = old;
3201 /// Parse an expression, subject to the given restrictions
3202 pub fn parse_expr_res(&mut self, r: Restrictions,
3203 already_parsed_attrs: Option<ThinVec<Attribute>>)
3204 -> PResult<'a, P<Expr>> {
3205 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3208 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3209 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3210 if self.check(&token::Eq) {
3212 Ok(Some(self.parse_expr()?))
3218 /// Parse patterns, separated by '|' s
3219 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3220 let mut pats = Vec::new();
3222 pats.push(self.parse_pat()?);
3223 if self.check(&token::BinOp(token::Or)) { self.bump();}
3224 else { return Ok(pats); }
3228 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3229 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3230 let mut fields = vec![];
3231 let mut ddpos = None;
3233 while !self.check(&token::CloseDelim(token::Paren)) {
3234 if ddpos.is_none() && self.eat(&token::DotDot) {
3235 ddpos = Some(fields.len());
3236 if self.eat(&token::Comma) {
3237 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3238 fields.push(self.parse_pat()?);
3240 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3241 // Emit a friendly error, ignore `..` and continue parsing
3242 self.span_err(self.prev_span, "`..` can only be used once per \
3243 tuple or tuple struct pattern");
3245 fields.push(self.parse_pat()?);
3248 if !self.check(&token::CloseDelim(token::Paren)) ||
3249 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3250 self.expect(&token::Comma)?;
3257 fn parse_pat_vec_elements(
3259 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3260 let mut before = Vec::new();
3261 let mut slice = None;
3262 let mut after = Vec::new();
3263 let mut first = true;
3264 let mut before_slice = true;
3266 while self.token != token::CloseDelim(token::Bracket) {
3270 self.expect(&token::Comma)?;
3272 if self.token == token::CloseDelim(token::Bracket)
3273 && (before_slice || !after.is_empty()) {
3279 if self.eat(&token::DotDot) {
3281 if self.check(&token::Comma) ||
3282 self.check(&token::CloseDelim(token::Bracket)) {
3283 slice = Some(P(ast::Pat {
3284 id: ast::DUMMY_NODE_ID,
3285 node: PatKind::Wild,
3288 before_slice = false;
3294 let subpat = self.parse_pat()?;
3295 if before_slice && self.eat(&token::DotDot) {
3296 slice = Some(subpat);
3297 before_slice = false;
3298 } else if before_slice {
3299 before.push(subpat);
3305 Ok((before, slice, after))
3308 /// Parse the fields of a struct-like pattern
3309 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3310 let mut fields = Vec::new();
3311 let mut etc = false;
3312 let mut first = true;
3313 while self.token != token::CloseDelim(token::Brace) {
3317 self.expect(&token::Comma)?;
3318 // accept trailing commas
3319 if self.check(&token::CloseDelim(token::Brace)) { break }
3322 let attrs = self.parse_outer_attributes()?;
3326 if self.check(&token::DotDot) {
3328 if self.token != token::CloseDelim(token::Brace) {
3329 let token_str = self.this_token_to_string();
3330 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3337 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3338 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3339 // Parsing a pattern of the form "fieldname: pat"
3340 let fieldname = self.parse_field_name()?;
3342 let pat = self.parse_pat()?;
3344 (pat, fieldname, false)
3346 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3347 let is_box = self.eat_keyword(keywords::Box);
3348 let boxed_span = self.span;
3349 let is_ref = self.eat_keyword(keywords::Ref);
3350 let is_mut = self.eat_keyword(keywords::Mut);
3351 let fieldname = self.parse_ident()?;
3352 hi = self.prev_span;
3354 let bind_type = match (is_ref, is_mut) {
3355 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3356 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3357 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3358 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3360 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3361 let fieldpat = P(ast::Pat{
3362 id: ast::DUMMY_NODE_ID,
3363 node: PatKind::Ident(bind_type, fieldpath, None),
3364 span: boxed_span.to(hi),
3367 let subpat = if is_box {
3369 id: ast::DUMMY_NODE_ID,
3370 node: PatKind::Box(fieldpat),
3376 (subpat, fieldname, true)
3379 fields.push(codemap::Spanned { span: lo.to(hi),
3380 node: ast::FieldPat {
3383 is_shorthand: is_shorthand,
3384 attrs: attrs.into(),
3388 return Ok((fields, etc));
3391 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3392 if self.token.is_path_start() {
3394 let (qself, path) = if self.eat_lt() {
3395 // Parse a qualified path
3397 self.parse_qualified_path(PathStyle::Expr)?;
3400 // Parse an unqualified path
3401 (None, self.parse_path(PathStyle::Expr)?)
3403 let hi = self.prev_span;
3404 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3406 self.parse_pat_literal_maybe_minus()
3410 // helper function to decide whether to parse as ident binding or to try to do
3411 // something more complex like range patterns
3412 fn parse_as_ident(&mut self) -> bool {
3413 self.look_ahead(1, |t| match *t {
3414 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3415 token::DotDotDot | token::ModSep | token::Not => Some(false),
3416 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3417 // range pattern branch
3418 token::DotDot => None,
3420 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3421 token::Comma | token::CloseDelim(token::Bracket) => true,
3426 /// Parse a pattern.
3427 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3428 maybe_whole!(self, NtPat, |x| x);
3433 token::Underscore => {
3436 pat = PatKind::Wild;
3438 token::BinOp(token::And) | token::AndAnd => {
3439 // Parse &pat / &mut pat
3441 let mutbl = self.parse_mutability();
3442 if let token::Lifetime(ident) = self.token {
3443 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3445 let subpat = self.parse_pat()?;
3446 pat = PatKind::Ref(subpat, mutbl);
3448 token::OpenDelim(token::Paren) => {
3449 // Parse (pat,pat,pat,...) as tuple pattern
3451 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3452 self.expect(&token::CloseDelim(token::Paren))?;
3453 pat = PatKind::Tuple(fields, ddpos);
3455 token::OpenDelim(token::Bracket) => {
3456 // Parse [pat,pat,...] as slice pattern
3458 let (before, slice, after) = self.parse_pat_vec_elements()?;
3459 self.expect(&token::CloseDelim(token::Bracket))?;
3460 pat = PatKind::Slice(before, slice, after);
3462 // At this point, token != _, &, &&, (, [
3463 _ => if self.eat_keyword(keywords::Mut) {
3464 // Parse mut ident @ pat
3465 pat = self.parse_pat_ident(BindingMode::ByValue(Mutability::Mutable))?;
3466 } else if self.eat_keyword(keywords::Ref) {
3467 // Parse ref ident @ pat / ref mut ident @ pat
3468 let mutbl = self.parse_mutability();
3469 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3470 } else if self.eat_keyword(keywords::Box) {
3472 let subpat = self.parse_pat()?;
3473 pat = PatKind::Box(subpat);
3474 } else if self.token.is_ident() && !self.token.is_any_keyword() &&
3475 self.parse_as_ident() {
3476 // Parse ident @ pat
3477 // This can give false positives and parse nullary enums,
3478 // they are dealt with later in resolve
3479 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3480 pat = self.parse_pat_ident(binding_mode)?;
3481 } else if self.token.is_path_start() {
3482 // Parse pattern starting with a path
3483 let (qself, path) = if self.eat_lt() {
3484 // Parse a qualified path
3485 let (qself, path) = self.parse_qualified_path(PathStyle::Expr)?;
3488 // Parse an unqualified path
3489 (None, self.parse_path(PathStyle::Expr)?)
3492 token::Not if qself.is_none() => {
3493 // Parse macro invocation
3495 let (_, tts) = self.expect_delimited_token_tree()?;
3496 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3497 pat = PatKind::Mac(mac);
3499 token::DotDotDot | token::DotDot => {
3500 let end_kind = match self.token {
3501 token::DotDot => RangeEnd::Excluded,
3502 token::DotDotDot => RangeEnd::Included,
3503 _ => panic!("can only parse `..` or `...` for ranges (checked above)"),
3506 let span = lo.to(self.prev_span);
3507 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3509 let end = self.parse_pat_range_end()?;
3510 pat = PatKind::Range(begin, end, end_kind);
3512 token::OpenDelim(token::Brace) => {
3513 if qself.is_some() {
3514 return Err(self.fatal("unexpected `{` after qualified path"));
3516 // Parse struct pattern
3518 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3520 self.recover_stmt();
3524 pat = PatKind::Struct(path, fields, etc);
3526 token::OpenDelim(token::Paren) => {
3527 if qself.is_some() {
3528 return Err(self.fatal("unexpected `(` after qualified path"));
3530 // Parse tuple struct or enum pattern
3532 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3533 self.expect(&token::CloseDelim(token::Paren))?;
3534 pat = PatKind::TupleStruct(path, fields, ddpos)
3536 _ => pat = PatKind::Path(qself, path),
3539 // Try to parse everything else as literal with optional minus
3540 match self.parse_pat_literal_maybe_minus() {
3542 if self.eat(&token::DotDotDot) {
3543 let end = self.parse_pat_range_end()?;
3544 pat = PatKind::Range(begin, end, RangeEnd::Included);
3545 } else if self.eat(&token::DotDot) {
3546 let end = self.parse_pat_range_end()?;
3547 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3549 pat = PatKind::Lit(begin);
3553 self.cancel(&mut err);
3554 let msg = format!("expected pattern, found {}", self.this_token_descr());
3555 return Err(self.fatal(&msg));
3562 id: ast::DUMMY_NODE_ID,
3564 span: lo.to(self.prev_span),
3568 /// Parse ident or ident @ pat
3569 /// used by the copy foo and ref foo patterns to give a good
3570 /// error message when parsing mistakes like ref foo(a,b)
3571 fn parse_pat_ident(&mut self,
3572 binding_mode: ast::BindingMode)
3573 -> PResult<'a, PatKind> {
3574 let ident_span = self.span;
3575 let ident = self.parse_ident()?;
3576 let name = codemap::Spanned{span: ident_span, node: ident};
3577 let sub = if self.eat(&token::At) {
3578 Some(self.parse_pat()?)
3583 // just to be friendly, if they write something like
3585 // we end up here with ( as the current token. This shortly
3586 // leads to a parse error. Note that if there is no explicit
3587 // binding mode then we do not end up here, because the lookahead
3588 // will direct us over to parse_enum_variant()
3589 if self.token == token::OpenDelim(token::Paren) {
3590 return Err(self.span_fatal(
3592 "expected identifier, found enum pattern"))
3595 Ok(PatKind::Ident(binding_mode, name, sub))
3598 /// Parse a local variable declaration
3599 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3601 let pat = self.parse_pat()?;
3604 if self.eat(&token::Colon) {
3605 ty = Some(self.parse_ty()?);
3607 let init = self.parse_initializer()?;
3612 id: ast::DUMMY_NODE_ID,
3613 span: lo.to(self.prev_span),
3618 /// Parse a structure field
3619 fn parse_name_and_ty(&mut self,
3622 attrs: Vec<Attribute>)
3623 -> PResult<'a, StructField> {
3624 let name = self.parse_ident()?;
3625 self.expect(&token::Colon)?;
3626 let ty = self.parse_ty()?;
3628 span: lo.to(self.prev_span),
3631 id: ast::DUMMY_NODE_ID,
3637 /// Emit an expected item after attributes error.
3638 fn expected_item_err(&self, attrs: &[Attribute]) {
3639 let message = match attrs.last() {
3640 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3641 _ => "expected item after attributes",
3644 self.span_err(self.prev_span, message);
3647 /// Parse a statement. This stops just before trailing semicolons on everything but items.
3648 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3649 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3650 Ok(self.parse_stmt_(true))
3653 // Eat tokens until we can be relatively sure we reached the end of the
3654 // statement. This is something of a best-effort heuristic.
3656 // We terminate when we find an unmatched `}` (without consuming it).
3657 fn recover_stmt(&mut self) {
3658 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
3661 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3662 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3663 // approximate - it can mean we break too early due to macros, but that
3664 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3666 // If `break_on_block` is `Break`, then we will stop consuming tokens
3667 // after finding (and consuming) a brace-delimited block.
3668 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
3669 let mut brace_depth = 0;
3670 let mut bracket_depth = 0;
3671 let mut in_block = false;
3672 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
3673 break_on_semi, break_on_block);
3675 debug!("recover_stmt_ loop {:?}", self.token);
3677 token::OpenDelim(token::DelimToken::Brace) => {
3680 if break_on_block == BlockMode::Break &&
3682 bracket_depth == 0 {
3686 token::OpenDelim(token::DelimToken::Bracket) => {
3690 token::CloseDelim(token::DelimToken::Brace) => {
3691 if brace_depth == 0 {
3692 debug!("recover_stmt_ return - close delim {:?}", self.token);
3697 if in_block && bracket_depth == 0 && brace_depth == 0 {
3698 debug!("recover_stmt_ return - block end {:?}", self.token);
3702 token::CloseDelim(token::DelimToken::Bracket) => {
3704 if bracket_depth < 0 {
3710 debug!("recover_stmt_ return - Eof");
3715 if break_on_semi == SemiColonMode::Break &&
3717 bracket_depth == 0 {
3718 debug!("recover_stmt_ return - Semi");
3729 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
3730 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
3732 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
3737 fn is_catch_expr(&mut self) -> bool {
3738 self.token.is_keyword(keywords::Do) &&
3739 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
3740 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
3742 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3743 !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL)
3746 fn is_union_item(&self) -> bool {
3747 self.token.is_keyword(keywords::Union) &&
3748 self.look_ahead(1, |t| t.is_ident() && !t.is_any_keyword())
3751 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility)
3752 -> PResult<'a, Option<P<Item>>> {
3755 token::Ident(ident) if ident.name == "macro_rules" => {
3756 if self.look_ahead(1, |t| *t == token::Not) {
3757 let prev_span = self.prev_span;
3758 self.complain_if_pub_macro(vis, prev_span);
3763 _ => return Ok(None),
3766 let id = self.parse_ident()?;
3767 let (delim, tts) = self.expect_delimited_token_tree()?;
3768 if delim != token::Brace {
3769 if !self.eat(&token::Semi) {
3770 let msg = "macros that expand to items must either be surrounded with braces \
3771 or followed by a semicolon";
3772 self.span_err(self.prev_span, msg);
3776 let span = lo.to(self.prev_span);
3777 let kind = ItemKind::MacroDef(tts);
3778 Ok(Some(self.mk_item(span, id, kind, Visibility::Inherited, attrs.to_owned())))
3781 fn parse_stmt_without_recovery(&mut self,
3782 macro_legacy_warnings: bool)
3783 -> PResult<'a, Option<Stmt>> {
3784 maybe_whole!(self, NtStmt, |x| Some(x));
3786 let attrs = self.parse_outer_attributes()?;
3789 Ok(Some(if self.eat_keyword(keywords::Let) {
3791 id: ast::DUMMY_NODE_ID,
3792 node: StmtKind::Local(self.parse_local(attrs.into())?),
3793 span: lo.to(self.prev_span),
3795 } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited)? {
3797 id: ast::DUMMY_NODE_ID,
3798 node: StmtKind::Item(macro_def),
3799 span: lo.to(self.prev_span),
3801 // Starts like a simple path, but not a union item.
3802 } else if self.token.is_path_start() &&
3803 !self.token.is_qpath_start() &&
3804 !self.is_union_item() {
3805 let pth = self.parse_path(PathStyle::Expr)?;
3807 if !self.eat(&token::Not) {
3808 let expr = if self.check(&token::OpenDelim(token::Brace)) {
3809 self.parse_struct_expr(lo, pth, ThinVec::new())?
3811 let hi = self.prev_span;
3812 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
3815 let expr = self.with_res(RESTRICTION_STMT_EXPR, |this| {
3816 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
3817 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
3820 return Ok(Some(Stmt {
3821 id: ast::DUMMY_NODE_ID,
3822 node: StmtKind::Expr(expr),
3823 span: lo.to(self.prev_span),
3827 // it's a macro invocation
3828 let id = match self.token {
3829 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
3830 _ => self.parse_ident()?,
3833 // check that we're pointing at delimiters (need to check
3834 // again after the `if`, because of `parse_ident`
3835 // consuming more tokens).
3836 let delim = match self.token {
3837 token::OpenDelim(delim) => delim,
3839 // we only expect an ident if we didn't parse one
3841 let ident_str = if id.name == keywords::Invalid.name() {
3846 let tok_str = self.this_token_to_string();
3847 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3853 let (_, tts) = self.expect_delimited_token_tree()?;
3854 let hi = self.prev_span;
3856 let style = if delim == token::Brace {
3857 MacStmtStyle::Braces
3859 MacStmtStyle::NoBraces
3862 if id.name == keywords::Invalid.name() {
3863 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
3864 let node = if delim == token::Brace ||
3865 self.token == token::Semi || self.token == token::Eof {
3866 StmtKind::Mac(P((mac, style, attrs.into())))
3868 // We used to incorrectly stop parsing macro-expanded statements here.
3869 // If the next token will be an error anyway but could have parsed with the
3870 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
3871 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
3872 // These can continue an expression, so we can't stop parsing and warn.
3873 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
3874 token::BinOp(token::Minus) | token::BinOp(token::Star) |
3875 token::BinOp(token::And) | token::BinOp(token::Or) |
3876 token::AndAnd | token::OrOr |
3877 token::DotDot | token::DotDotDot => false,
3880 self.warn_missing_semicolon();
3881 StmtKind::Mac(P((mac, style, attrs.into())))
3883 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
3884 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
3885 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
3889 id: ast::DUMMY_NODE_ID,
3894 // if it has a special ident, it's definitely an item
3896 // Require a semicolon or braces.
3897 if style != MacStmtStyle::Braces {
3898 if !self.eat(&token::Semi) {
3899 self.span_err(self.prev_span,
3900 "macros that expand to items must \
3901 either be surrounded with braces or \
3902 followed by a semicolon");
3905 let span = lo.to(hi);
3907 id: ast::DUMMY_NODE_ID,
3909 node: StmtKind::Item({
3911 span, id /*id is good here*/,
3912 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
3913 Visibility::Inherited,
3919 // FIXME: Bad copy of attrs
3920 let old_directory_ownership =
3921 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
3922 let item = self.parse_item_(attrs.clone(), false, true)?;
3923 self.directory.ownership = old_directory_ownership;
3926 id: ast::DUMMY_NODE_ID,
3927 span: lo.to(i.span),
3928 node: StmtKind::Item(i),
3931 let unused_attrs = |attrs: &[_], s: &mut Self| {
3932 if attrs.len() > 0 {
3933 if s.prev_token_kind == PrevTokenKind::DocComment {
3934 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
3936 s.span_err(s.span, "expected statement after outer attribute");
3941 // Do not attempt to parse an expression if we're done here.
3942 if self.token == token::Semi {
3943 unused_attrs(&attrs, self);
3948 if self.token == token::CloseDelim(token::Brace) {
3949 unused_attrs(&attrs, self);
3953 // Remainder are line-expr stmts.
3954 let e = self.parse_expr_res(
3955 RESTRICTION_STMT_EXPR, Some(attrs.into()))?;
3957 id: ast::DUMMY_NODE_ID,
3958 span: lo.to(e.span),
3959 node: StmtKind::Expr(e),
3966 /// Is this expression a successfully-parsed statement?
3967 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3968 self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
3969 !classify::expr_requires_semi_to_be_stmt(e)
3972 /// Parse a block. No inner attrs are allowed.
3973 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
3974 maybe_whole!(self, NtBlock, |x| x);
3978 if !self.eat(&token::OpenDelim(token::Brace)) {
3980 let tok = self.this_token_to_string();
3981 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
3983 // Check to see if the user has written something like
3988 // Which is valid in other languages, but not Rust.
3989 match self.parse_stmt_without_recovery(false) {
3991 let mut stmt_span = stmt.span;
3992 // expand the span to include the semicolon, if it exists
3993 if self.eat(&token::Semi) {
3994 stmt_span.hi = self.prev_span.hi;
3996 let sugg = pprust::to_string(|s| {
3997 use print::pprust::{PrintState, INDENT_UNIT};
3998 s.ibox(INDENT_UNIT)?;
4000 s.print_stmt(&stmt)?;
4001 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4003 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4006 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4007 self.cancel(&mut e);
4014 self.parse_block_tail(lo, BlockCheckMode::Default)
4017 /// Parse a block. Inner attrs are allowed.
4018 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4019 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4022 self.expect(&token::OpenDelim(token::Brace))?;
4023 Ok((self.parse_inner_attributes()?,
4024 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4027 /// Parse the rest of a block expression or function body
4028 /// Precondition: already parsed the '{'.
4029 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4030 let mut stmts = vec![];
4032 while !self.eat(&token::CloseDelim(token::Brace)) {
4033 if let Some(stmt) = self.parse_full_stmt(false)? {
4035 } else if self.token == token::Eof {
4038 // Found only `;` or `}`.
4045 id: ast::DUMMY_NODE_ID,
4047 span: lo.to(self.prev_span),
4051 /// Parse a statement, including the trailing semicolon.
4052 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4053 let mut stmt = match self.parse_stmt_(macro_legacy_warnings) {
4055 None => return Ok(None),
4059 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4060 // expression without semicolon
4061 if classify::expr_requires_semi_to_be_stmt(expr) {
4062 // Just check for errors and recover; do not eat semicolon yet.
4064 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4067 self.recover_stmt();
4071 StmtKind::Local(..) => {
4072 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4073 if macro_legacy_warnings && self.token != token::Semi {
4074 self.warn_missing_semicolon();
4076 self.expect_one_of(&[token::Semi], &[])?;
4082 if self.eat(&token::Semi) {
4083 stmt = stmt.add_trailing_semicolon();
4086 stmt.span.hi = self.prev_span.hi;
4090 fn warn_missing_semicolon(&self) {
4091 self.diagnostic().struct_span_warn(self.span, {
4092 &format!("expected `;`, found `{}`", self.this_token_to_string())
4094 "This was erroneously allowed and will become a hard error in a future release"
4098 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4099 // BOUND = TY_BOUND | LT_BOUND
4100 // LT_BOUND = LIFETIME (e.g. `'a`)
4101 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4102 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4103 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4104 let mut bounds = Vec::new();
4106 let is_bound_start = self.check_path() || self.check_lifetime() ||
4107 self.check(&token::Question) ||
4108 self.check_keyword(keywords::For) ||
4109 self.check(&token::OpenDelim(token::Paren));
4111 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4112 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4113 if self.token.is_lifetime() {
4114 if let Some(question_span) = question {
4115 self.span_err(question_span,
4116 "`?` may only modify trait bounds, not lifetime bounds");
4118 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4121 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4122 let path = self.parse_path(PathStyle::Type)?;
4123 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4124 let modifier = if question.is_some() {
4125 TraitBoundModifier::Maybe
4127 TraitBoundModifier::None
4129 bounds.push(TraitTyParamBound(poly_trait, modifier));
4132 self.expect(&token::CloseDelim(token::Paren))?;
4133 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4134 self.span_err(self.prev_span,
4135 "parenthesized lifetime bounds are not supported");
4142 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4150 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4151 self.parse_ty_param_bounds_common(true)
4154 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4155 // BOUND = LT_BOUND (e.g. `'a`)
4156 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4157 let mut lifetimes = Vec::new();
4158 while self.check_lifetime() {
4159 lifetimes.push(self.expect_lifetime());
4161 if !self.eat(&token::BinOp(token::Plus)) {
4168 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4169 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4170 let span = self.span;
4171 let ident = self.parse_ident()?;
4173 // Parse optional colon and param bounds.
4174 let bounds = if self.eat(&token::Colon) {
4175 self.parse_ty_param_bounds()?
4180 let default = if self.eat(&token::Eq) {
4181 Some(self.parse_ty()?)
4187 attrs: preceding_attrs.into(),
4189 id: ast::DUMMY_NODE_ID,
4196 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4197 /// trailing comma and erroneous trailing attributes.
4198 pub fn parse_generic_params(&mut self) -> PResult<'a, (Vec<LifetimeDef>, Vec<TyParam>)> {
4199 let mut lifetime_defs = Vec::new();
4200 let mut ty_params = Vec::new();
4201 let mut seen_ty_param = false;
4203 let attrs = self.parse_outer_attributes()?;
4204 if self.check_lifetime() {
4205 let lifetime = self.expect_lifetime();
4206 // Parse lifetime parameter.
4207 let bounds = if self.eat(&token::Colon) {
4208 self.parse_lt_param_bounds()
4212 lifetime_defs.push(LifetimeDef {
4213 attrs: attrs.into(),
4218 self.span_err(self.prev_span,
4219 "lifetime parameters must be declared prior to type parameters");
4221 } else if self.check_ident() {
4222 // Parse type parameter.
4223 ty_params.push(self.parse_ty_param(attrs)?);
4224 seen_ty_param = true;
4226 // Check for trailing attributes and stop parsing.
4227 if !attrs.is_empty() {
4228 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4229 self.span_err(attrs[0].span,
4230 &format!("trailing attribute after {} parameters", param_kind));
4235 if !self.eat(&token::Comma) {
4239 Ok((lifetime_defs, ty_params))
4242 /// Parse a set of optional generic type parameter declarations. Where
4243 /// clauses are not parsed here, and must be added later via
4244 /// `parse_where_clause()`.
4246 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4247 /// | ( < lifetimes , typaramseq ( , )? > )
4248 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4249 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4250 maybe_whole!(self, NtGenerics, |x| x);
4252 let span_lo = self.span;
4254 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4257 lifetimes: lifetime_defs,
4258 ty_params: ty_params,
4259 where_clause: WhereClause {
4260 id: ast::DUMMY_NODE_ID,
4261 predicates: Vec::new(),
4263 span: span_lo.to(self.prev_span),
4266 Ok(ast::Generics::default())
4270 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4271 /// possibly including trailing comma.
4272 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4273 let mut lifetimes = Vec::new();
4274 let mut types = Vec::new();
4275 let mut bindings = Vec::new();
4276 let mut seen_type = false;
4277 let mut seen_binding = false;
4279 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4280 // Parse lifetime argument.
4281 lifetimes.push(self.expect_lifetime());
4282 if seen_type || seen_binding {
4283 self.span_err(self.prev_span,
4284 "lifetime parameters must be declared prior to type parameters");
4286 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4287 // Parse associated type binding.
4289 let ident = self.parse_ident()?;
4291 let ty = self.parse_ty()?;
4292 bindings.push(TypeBinding {
4293 id: ast::DUMMY_NODE_ID,
4296 span: lo.to(self.prev_span),
4298 seen_binding = true;
4299 } else if self.check_type() {
4300 // Parse type argument.
4301 types.push(self.parse_ty()?);
4303 self.span_err(types[types.len() - 1].span,
4304 "type parameters must be declared prior to associated type bindings");
4311 if !self.eat(&token::Comma) {
4315 Ok((lifetimes, types, bindings))
4318 /// Parses an optional `where` clause and places it in `generics`.
4321 /// where T : Trait<U, V> + 'b, 'a : 'b
4323 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4324 maybe_whole!(self, NtWhereClause, |x| x);
4326 let mut where_clause = WhereClause {
4327 id: ast::DUMMY_NODE_ID,
4328 predicates: Vec::new(),
4331 if !self.eat_keyword(keywords::Where) {
4332 return Ok(where_clause);
4335 // This is a temporary future proofing.
4337 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4338 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4339 // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4340 if token::Lt == self.token {
4341 let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4342 if ident_or_lifetime {
4343 let gt_comma_or_colon = self.look_ahead(2, |t| {
4344 *t == token::Gt || *t == token::Comma || *t == token::Colon
4346 if gt_comma_or_colon {
4347 self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4354 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4355 let lifetime = self.expect_lifetime();
4356 // Bounds starting with a colon are mandatory, but possibly empty.
4357 self.expect(&token::Colon)?;
4358 let bounds = self.parse_lt_param_bounds();
4359 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4360 ast::WhereRegionPredicate {
4361 span: lo.to(self.prev_span),
4366 } else if self.check_type() {
4367 // Parse optional `for<'a, 'b>`.
4368 // This `for` is parsed greedily and applies to the whole predicate,
4369 // the bounded type can have its own `for` applying only to it.
4370 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4371 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4372 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4373 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4375 // Parse type with mandatory colon and (possibly empty) bounds,
4376 // or with mandatory equality sign and the second type.
4377 let ty = self.parse_ty()?;
4378 if self.eat(&token::Colon) {
4379 let bounds = self.parse_ty_param_bounds()?;
4380 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4381 ast::WhereBoundPredicate {
4382 span: lo.to(self.prev_span),
4383 bound_lifetimes: lifetime_defs,
4388 // FIXME: Decide what should be used here, `=` or `==`.
4389 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4390 let rhs_ty = self.parse_ty()?;
4391 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4392 ast::WhereEqPredicate {
4393 span: lo.to(self.prev_span),
4396 id: ast::DUMMY_NODE_ID,
4400 return self.unexpected();
4406 if !self.eat(&token::Comma) {
4414 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4415 -> PResult<'a, (Vec<Arg> , bool)> {
4417 let mut variadic = false;
4418 let args: Vec<Option<Arg>> =
4419 self.parse_unspanned_seq(
4420 &token::OpenDelim(token::Paren),
4421 &token::CloseDelim(token::Paren),
4422 SeqSep::trailing_allowed(token::Comma),
4424 if p.token == token::DotDotDot {
4427 if p.token != token::CloseDelim(token::Paren) {
4430 "`...` must be last in argument list for variadic function");
4435 "only foreign functions are allowed to be variadic");
4440 match p.parse_arg_general(named_args) {
4441 Ok(arg) => Ok(Some(arg)),
4444 let lo = p.prev_span;
4445 // Skip every token until next possible arg or end.
4446 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4447 // Create a placeholder argument for proper arg count (#34264).
4448 let span = lo.to(p.prev_span);
4449 Ok(Some(dummy_arg(span)))
4456 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4458 if variadic && args.is_empty() {
4460 "variadic function must be declared with at least one named argument");
4463 Ok((args, variadic))
4466 /// Parse the argument list and result type of a function declaration
4467 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4469 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4470 let ret_ty = self.parse_ret_ty()?;
4479 /// Returns the parsed optional self argument and whether a self shortcut was used.
4480 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4481 let expect_ident = |this: &mut Self| match this.token {
4482 // Preserve hygienic context.
4483 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4486 let isolated_self = |this: &mut Self, n| {
4487 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4488 this.look_ahead(n + 1, |t| t != &token::ModSep)
4491 // Parse optional self parameter of a method.
4492 // Only a limited set of initial token sequences is considered self parameters, anything
4493 // else is parsed as a normal function parameter list, so some lookahead is required.
4494 let eself_lo = self.span;
4495 let (eself, eself_ident) = match self.token {
4496 token::BinOp(token::And) => {
4502 if isolated_self(self, 1) {
4504 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4505 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4506 isolated_self(self, 2) {
4509 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4510 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4511 isolated_self(self, 2) {
4513 let lt = self.expect_lifetime();
4514 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4515 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4516 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4517 isolated_self(self, 3) {
4519 let lt = self.expect_lifetime();
4521 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4526 token::BinOp(token::Star) => {
4531 // Emit special error for `self` cases.
4532 if isolated_self(self, 1) {
4534 self.span_err(self.span, "cannot pass `self` by raw pointer");
4535 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4536 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4537 isolated_self(self, 2) {
4540 self.span_err(self.span, "cannot pass `self` by raw pointer");
4541 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4546 token::Ident(..) => {
4547 if isolated_self(self, 0) {
4550 let eself_ident = expect_ident(self);
4551 if self.eat(&token::Colon) {
4552 let ty = self.parse_ty()?;
4553 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4555 (SelfKind::Value(Mutability::Immutable), eself_ident)
4557 } else if self.token.is_keyword(keywords::Mut) &&
4558 isolated_self(self, 1) {
4562 let eself_ident = expect_ident(self);
4563 if self.eat(&token::Colon) {
4564 let ty = self.parse_ty()?;
4565 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4567 (SelfKind::Value(Mutability::Mutable), eself_ident)
4573 _ => return Ok(None),
4576 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
4577 Ok(Some(Arg::from_self(eself, eself_ident)))
4580 /// Parse the parameter list and result type of a function that may have a `self` parameter.
4581 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
4582 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4584 self.expect(&token::OpenDelim(token::Paren))?;
4586 // Parse optional self argument
4587 let self_arg = self.parse_self_arg()?;
4589 // Parse the rest of the function parameter list.
4590 let sep = SeqSep::trailing_allowed(token::Comma);
4591 let fn_inputs = if let Some(self_arg) = self_arg {
4592 if self.check(&token::CloseDelim(token::Paren)) {
4594 } else if self.eat(&token::Comma) {
4595 let mut fn_inputs = vec![self_arg];
4596 fn_inputs.append(&mut self.parse_seq_to_before_end(
4597 &token::CloseDelim(token::Paren), sep, parse_arg_fn)
4601 return self.unexpected();
4604 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4607 // Parse closing paren and return type.
4608 self.expect(&token::CloseDelim(token::Paren))?;
4611 output: self.parse_ret_ty()?,
4616 // parse the |arg, arg| header on a lambda
4617 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4618 let inputs_captures = {
4619 if self.eat(&token::OrOr) {
4622 self.expect(&token::BinOp(token::Or))?;
4623 let args = self.parse_seq_to_before_end(
4624 &token::BinOp(token::Or),
4625 SeqSep::trailing_allowed(token::Comma),
4626 |p| p.parse_fn_block_arg()
4632 let output = self.parse_ret_ty()?;
4635 inputs: inputs_captures,
4641 /// Parse the name and optional generic types of a function header.
4642 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4643 let id = self.parse_ident()?;
4644 let generics = self.parse_generics()?;
4648 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
4649 attrs: Vec<Attribute>) -> P<Item> {
4653 id: ast::DUMMY_NODE_ID,
4660 /// Parse an item-position function declaration.
4661 fn parse_item_fn(&mut self,
4663 constness: Spanned<Constness>,
4665 -> PResult<'a, ItemInfo> {
4666 let (ident, mut generics) = self.parse_fn_header()?;
4667 let decl = self.parse_fn_decl(false)?;
4668 generics.where_clause = self.parse_where_clause()?;
4669 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4670 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4673 /// true if we are looking at `const ID`, false for things like `const fn` etc
4674 pub fn is_const_item(&mut self) -> bool {
4675 self.token.is_keyword(keywords::Const) &&
4676 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4677 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4680 /// parses all the "front matter" for a `fn` declaration, up to
4681 /// and including the `fn` keyword:
4685 /// - `const unsafe fn`
4688 pub fn parse_fn_front_matter(&mut self)
4689 -> PResult<'a, (Spanned<ast::Constness>,
4692 let is_const_fn = self.eat_keyword(keywords::Const);
4693 let const_span = self.prev_span;
4694 let unsafety = self.parse_unsafety()?;
4695 let (constness, unsafety, abi) = if is_const_fn {
4696 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
4698 let abi = if self.eat_keyword(keywords::Extern) {
4699 self.parse_opt_abi()?.unwrap_or(Abi::C)
4703 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
4705 self.expect_keyword(keywords::Fn)?;
4706 Ok((constness, unsafety, abi))
4709 /// Parse an impl item.
4710 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
4711 maybe_whole!(self, NtImplItem, |x| x);
4713 let mut attrs = self.parse_outer_attributes()?;
4715 let vis = self.parse_visibility(false)?;
4716 let defaultness = self.parse_defaultness()?;
4717 let (name, node) = if self.eat_keyword(keywords::Type) {
4718 let name = self.parse_ident()?;
4719 self.expect(&token::Eq)?;
4720 let typ = self.parse_ty()?;
4721 self.expect(&token::Semi)?;
4722 (name, ast::ImplItemKind::Type(typ))
4723 } else if self.is_const_item() {
4724 self.expect_keyword(keywords::Const)?;
4725 let name = self.parse_ident()?;
4726 self.expect(&token::Colon)?;
4727 let typ = self.parse_ty()?;
4728 self.expect(&token::Eq)?;
4729 let expr = self.parse_expr()?;
4730 self.expect(&token::Semi)?;
4731 (name, ast::ImplItemKind::Const(typ, expr))
4733 let (name, inner_attrs, node) = self.parse_impl_method(&vis, at_end)?;
4734 attrs.extend(inner_attrs);
4739 id: ast::DUMMY_NODE_ID,
4740 span: lo.to(self.prev_span),
4743 defaultness: defaultness,
4749 fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
4750 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
4755 fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
4757 Visibility::Inherited => Ok(()),
4759 let is_macro_rules: bool = match self.token {
4760 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
4764 let mut err = self.diagnostic()
4765 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
4766 err.help("did you mean #[macro_export]?");
4769 let mut err = self.diagnostic()
4770 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
4771 err.help("try adjusting the macro to put `pub` inside the invocation");
4778 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
4779 -> DiagnosticBuilder<'a>
4781 // Given this code `path(`, it seems like this is not
4782 // setting the visibility of a macro invocation, but rather
4783 // a mistyped method declaration.
4784 // Create a diagnostic pointing out that `fn` is missing.
4786 // x | pub path(&self) {
4787 // | ^ missing `fn`, `type`, or `const`
4789 // ^^ `sp` below will point to this
4790 let sp = prev_span.between(self.prev_span);
4791 let mut err = self.diagnostic().struct_span_err(
4793 &format!("missing `fn`, `type`, or `const` for {}-item declaration",
4795 err.span_label(sp, "missing `fn`, `type`, or `const`");
4799 /// Parse a method or a macro invocation in a trait impl.
4800 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
4801 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4802 // code copied from parse_macro_use_or_failure... abstraction!
4803 if self.token.is_path_start() {
4806 let prev_span = self.prev_span;
4809 let pth = self.parse_path(PathStyle::Mod)?;
4810 if pth.segments.len() == 1 {
4811 if !self.eat(&token::Not) {
4812 return Err(self.missing_assoc_item_kind_err("impl", prev_span));
4815 self.expect(&token::Not)?;
4818 self.complain_if_pub_macro(&vis, prev_span);
4820 // eat a matched-delimiter token tree:
4822 let (delim, tts) = self.expect_delimited_token_tree()?;
4823 if delim != token::Brace {
4824 self.expect(&token::Semi)?
4827 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
4828 Ok((keywords::Invalid.ident(), vec![], ast::ImplItemKind::Macro(mac)))
4830 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
4831 let ident = self.parse_ident()?;
4832 let mut generics = self.parse_generics()?;
4833 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
4834 generics.where_clause = self.parse_where_clause()?;
4836 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4837 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4841 constness: constness,
4847 /// Parse trait Foo { ... }
4848 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4849 let ident = self.parse_ident()?;
4850 let mut tps = self.parse_generics()?;
4852 // Parse optional colon and supertrait bounds.
4853 let bounds = if self.eat(&token::Colon) {
4854 self.parse_ty_param_bounds()?
4859 tps.where_clause = self.parse_where_clause()?;
4861 self.expect(&token::OpenDelim(token::Brace))?;
4862 let mut trait_items = vec![];
4863 while !self.eat(&token::CloseDelim(token::Brace)) {
4864 let mut at_end = false;
4865 match self.parse_trait_item(&mut at_end) {
4866 Ok(item) => trait_items.push(item),
4870 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
4875 Ok((ident, ItemKind::Trait(unsafety, tps, bounds, trait_items), None))
4878 /// Parses items implementations variants
4879 /// impl<T> Foo { ... }
4880 /// impl<T> ToString for &'static T { ... }
4881 /// impl Send for .. {}
4882 fn parse_item_impl(&mut self,
4883 unsafety: ast::Unsafety,
4884 defaultness: Defaultness) -> PResult<'a, ItemInfo> {
4885 let impl_span = self.span;
4887 // First, parse type parameters if necessary.
4888 let mut generics = self.parse_generics()?;
4890 // Special case: if the next identifier that follows is '(', don't
4891 // allow this to be parsed as a trait.
4892 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4894 let neg_span = self.span;
4895 let polarity = if self.eat(&token::Not) {
4896 ast::ImplPolarity::Negative
4898 ast::ImplPolarity::Positive
4902 let mut ty = self.parse_ty()?;
4904 // Parse traits, if necessary.
4905 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4906 // New-style trait. Reinterpret the type as a trait.
4908 TyKind::Path(None, ref path) => {
4910 path: (*path).clone(),
4915 self.span_err(ty.span, "not a trait");
4921 ast::ImplPolarity::Negative => {
4922 // This is a negated type implementation
4923 // `impl !MyType {}`, which is not allowed.
4924 self.span_err(neg_span, "inherent implementation can't be negated");
4931 if opt_trait.is_some() && self.eat(&token::DotDot) {
4932 if generics.is_parameterized() {
4933 self.span_err(impl_span, "default trait implementations are not \
4934 allowed to have generics");
4937 if let ast::Defaultness::Default = defaultness {
4938 self.span_err(impl_span, "`default impl` is not allowed for \
4939 default trait implementations");
4942 self.expect(&token::OpenDelim(token::Brace))?;
4943 self.expect(&token::CloseDelim(token::Brace))?;
4944 Ok((keywords::Invalid.ident(),
4945 ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
4947 if opt_trait.is_some() {
4948 ty = self.parse_ty()?;
4950 generics.where_clause = self.parse_where_clause()?;
4952 self.expect(&token::OpenDelim(token::Brace))?;
4953 let attrs = self.parse_inner_attributes()?;
4955 let mut impl_items = vec![];
4956 while !self.eat(&token::CloseDelim(token::Brace)) {
4957 let mut at_end = false;
4958 match self.parse_impl_item(&mut at_end) {
4959 Ok(item) => impl_items.push(item),
4963 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
4969 Ok((keywords::Invalid.ident(),
4970 ItemKind::Impl(unsafety, polarity, defaultness, generics, opt_trait, ty, impl_items),
4975 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<LifetimeDef>> {
4976 if self.eat_keyword(keywords::For) {
4978 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4980 if !ty_params.is_empty() {
4981 self.span_err(ty_params[0].span,
4982 "only lifetime parameters can be used in this context");
4990 /// Parse struct Foo { ... }
4991 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
4992 let class_name = self.parse_ident()?;
4994 let mut generics = self.parse_generics()?;
4996 // There is a special case worth noting here, as reported in issue #17904.
4997 // If we are parsing a tuple struct it is the case that the where clause
4998 // should follow the field list. Like so:
5000 // struct Foo<T>(T) where T: Copy;
5002 // If we are parsing a normal record-style struct it is the case
5003 // that the where clause comes before the body, and after the generics.
5004 // So if we look ahead and see a brace or a where-clause we begin
5005 // parsing a record style struct.
5007 // Otherwise if we look ahead and see a paren we parse a tuple-style
5010 let vdata = if self.token.is_keyword(keywords::Where) {
5011 generics.where_clause = self.parse_where_clause()?;
5012 if self.eat(&token::Semi) {
5013 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5014 VariantData::Unit(ast::DUMMY_NODE_ID)
5016 // If we see: `struct Foo<T> where T: Copy { ... }`
5017 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5019 // No `where` so: `struct Foo<T>;`
5020 } else if self.eat(&token::Semi) {
5021 VariantData::Unit(ast::DUMMY_NODE_ID)
5022 // Record-style struct definition
5023 } else if self.token == token::OpenDelim(token::Brace) {
5024 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5025 // Tuple-style struct definition with optional where-clause.
5026 } else if self.token == token::OpenDelim(token::Paren) {
5027 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5028 generics.where_clause = self.parse_where_clause()?;
5029 self.expect(&token::Semi)?;
5032 let token_str = self.this_token_to_string();
5033 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5034 name, found `{}`", token_str)))
5037 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5040 /// Parse union Foo { ... }
5041 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5042 let class_name = self.parse_ident()?;
5044 let mut generics = self.parse_generics()?;
5046 let vdata = if self.token.is_keyword(keywords::Where) {
5047 generics.where_clause = self.parse_where_clause()?;
5048 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5049 } else if self.token == token::OpenDelim(token::Brace) {
5050 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5052 let token_str = self.this_token_to_string();
5053 return Err(self.fatal(&format!("expected `where` or `{{` after union \
5054 name, found `{}`", token_str)))
5057 Ok((class_name, ItemKind::Union(vdata, generics), None))
5060 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5061 let mut fields = Vec::new();
5062 if self.eat(&token::OpenDelim(token::Brace)) {
5063 while self.token != token::CloseDelim(token::Brace) {
5064 fields.push(self.parse_struct_decl_field().map_err(|e| {
5065 self.recover_stmt();
5066 self.eat(&token::CloseDelim(token::Brace));
5073 let token_str = self.this_token_to_string();
5074 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5082 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5083 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5084 // Unit like structs are handled in parse_item_struct function
5085 let fields = self.parse_unspanned_seq(
5086 &token::OpenDelim(token::Paren),
5087 &token::CloseDelim(token::Paren),
5088 SeqSep::trailing_allowed(token::Comma),
5090 let attrs = p.parse_outer_attributes()?;
5092 let vis = p.parse_visibility(true)?;
5093 let ty = p.parse_ty()?;
5095 span: lo.to(p.span),
5098 id: ast::DUMMY_NODE_ID,
5107 /// Parse a structure field declaration
5108 pub fn parse_single_struct_field(&mut self,
5111 attrs: Vec<Attribute> )
5112 -> PResult<'a, StructField> {
5113 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5118 token::CloseDelim(token::Brace) => {}
5119 token::DocComment(_) => return Err(self.span_fatal_err(self.span,
5120 Error::UselessDocComment)),
5121 _ => return Err(self.span_fatal_help(self.span,
5122 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5123 "struct fields should be separated by commas")),
5128 /// Parse an element of a struct definition
5129 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5130 let attrs = self.parse_outer_attributes()?;
5132 let vis = self.parse_visibility(false)?;
5133 self.parse_single_struct_field(lo, vis, attrs)
5136 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5137 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5138 /// a function definition, it's not a tuple struct field) and the contents within the parens
5139 /// isn't valid, emit a proper diagnostic.
5140 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5141 maybe_whole!(self, NtVis, |x| x);
5143 if !self.eat_keyword(keywords::Pub) {
5144 return Ok(Visibility::Inherited)
5147 if self.check(&token::OpenDelim(token::Paren)) {
5148 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5149 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5150 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5151 // by the following tokens.
5152 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5155 self.bump(); // `crate`
5156 let vis = Visibility::Crate(self.prev_span);
5157 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5159 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5162 self.bump(); // `in`
5163 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5164 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5165 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5167 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5168 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5169 t.is_keyword(keywords::SelfValue)) {
5170 // `pub(self)` or `pub(super)`
5172 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5173 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5174 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5176 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5177 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5179 let msg = "incorrect visibility restriction";
5180 let suggestion = r##"some possible visibility restrictions are:
5181 `pub(crate)`: visible only on the current crate
5182 `pub(super)`: visible only in the current module's parent
5183 `pub(in path::to::module)`: visible only on the specified path"##;
5184 let path = self.parse_path(PathStyle::Mod)?;
5185 let path_span = self.prev_span;
5186 let help_msg = format!("make this visible only to module `{}` with `in`:", path);
5187 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5188 let mut err = self.span_fatal_help(path_span, &msg, &suggestion);
5189 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5190 err.emit(); // emit diagnostic, but continue with public visibility
5194 Ok(Visibility::Public)
5197 /// Parse defaultness: DEFAULT or nothing
5198 fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5199 if self.eat_contextual_keyword(keywords::Default.ident()) {
5200 Ok(Defaultness::Default)
5202 Ok(Defaultness::Final)
5206 /// Given a termination token, parse all of the items in a module
5207 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5208 let mut items = vec![];
5209 while let Some(item) = self.parse_item()? {
5213 if !self.eat(term) {
5214 let token_str = self.this_token_to_string();
5215 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5218 let hi = if self.span == syntax_pos::DUMMY_SP {
5225 inner: inner_lo.to(hi),
5230 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5231 let id = self.parse_ident()?;
5232 self.expect(&token::Colon)?;
5233 let ty = self.parse_ty()?;
5234 self.expect(&token::Eq)?;
5235 let e = self.parse_expr()?;
5236 self.expect(&token::Semi)?;
5237 let item = match m {
5238 Some(m) => ItemKind::Static(ty, m, e),
5239 None => ItemKind::Const(ty, e),
5241 Ok((id, item, None))
5244 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5245 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5246 let (in_cfg, outer_attrs) = {
5247 let mut strip_unconfigured = ::config::StripUnconfigured {
5249 should_test: false, // irrelevant
5250 features: None, // don't perform gated feature checking
5252 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5253 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5256 let id_span = self.span;
5257 let id = self.parse_ident()?;
5258 if self.check(&token::Semi) {
5261 // This mod is in an external file. Let's go get it!
5262 let ModulePathSuccess { path, directory_ownership, warn } =
5263 self.submod_path(id, &outer_attrs, id_span)?;
5264 let (module, mut attrs) =
5265 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5267 let attr = ast::Attribute {
5268 id: attr::mk_attr_id(),
5269 style: ast::AttrStyle::Outer,
5270 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5271 Ident::from_str("warn_directory_ownership")),
5272 tokens: TokenStream::empty(),
5273 is_sugared_doc: false,
5274 span: syntax_pos::DUMMY_SP,
5276 attr::mark_known(&attr);
5279 Ok((id, module, Some(attrs)))
5281 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5282 Ok((id, ItemKind::Mod(placeholder), None))
5285 let old_directory = self.directory.clone();
5286 self.push_directory(id, &outer_attrs);
5287 self.expect(&token::OpenDelim(token::Brace))?;
5288 let mod_inner_lo = self.span;
5289 let attrs = self.parse_inner_attributes()?;
5290 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5291 self.directory = old_directory;
5292 Ok((id, ItemKind::Mod(module), Some(attrs)))
5296 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5297 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5298 self.directory.path.push(&path.as_str());
5299 self.directory.ownership = DirectoryOwnership::Owned;
5301 self.directory.path.push(&id.name.as_str());
5305 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5306 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5309 /// Returns either a path to a module, or .
5310 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5311 let mod_name = id.to_string();
5312 let default_path_str = format!("{}.rs", mod_name);
5313 let secondary_path_str = format!("{}{}mod.rs", mod_name, path::MAIN_SEPARATOR);
5314 let default_path = dir_path.join(&default_path_str);
5315 let secondary_path = dir_path.join(&secondary_path_str);
5316 let default_exists = codemap.file_exists(&default_path);
5317 let secondary_exists = codemap.file_exists(&secondary_path);
5319 let result = match (default_exists, secondary_exists) {
5320 (true, false) => Ok(ModulePathSuccess {
5322 directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5325 (false, true) => Ok(ModulePathSuccess {
5326 path: secondary_path,
5327 directory_ownership: DirectoryOwnership::Owned,
5330 (false, false) => Err(Error::FileNotFoundForModule {
5331 mod_name: mod_name.clone(),
5332 default_path: default_path_str,
5333 secondary_path: secondary_path_str,
5334 dir_path: format!("{}", dir_path.display()),
5336 (true, true) => Err(Error::DuplicatePaths {
5337 mod_name: mod_name.clone(),
5338 default_path: default_path_str,
5339 secondary_path: secondary_path_str,
5345 path_exists: default_exists || secondary_exists,
5350 fn submod_path(&mut self,
5352 outer_attrs: &[ast::Attribute],
5353 id_sp: Span) -> PResult<'a, ModulePathSuccess> {
5354 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5355 return Ok(ModulePathSuccess {
5356 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5357 Some("mod.rs") => DirectoryOwnership::Owned,
5358 _ => DirectoryOwnership::UnownedViaMod(true),
5365 let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5367 if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5369 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5370 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5371 if paths.path_exists {
5372 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5374 err.span_note(id_sp, &msg);
5377 } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5379 if let Ok(result) = paths.result {
5380 return Ok(ModulePathSuccess { warn: true, ..result });
5383 let mut err = self.diagnostic().struct_span_err(id_sp,
5384 "cannot declare a new module at this location");
5385 if id_sp != syntax_pos::DUMMY_SP {
5386 let src_path = PathBuf::from(self.sess.codemap().span_to_filename(id_sp));
5387 if let Some(stem) = src_path.file_stem() {
5388 let mut dest_path = src_path.clone();
5389 dest_path.set_file_name(stem);
5390 dest_path.push("mod.rs");
5391 err.span_note(id_sp,
5392 &format!("maybe move this module `{}` to its own \
5393 directory via `{}`", src_path.to_string_lossy(),
5394 dest_path.to_string_lossy()));
5397 if paths.path_exists {
5398 err.span_note(id_sp,
5399 &format!("... or maybe `use` the module `{}` instead \
5400 of possibly redeclaring it",
5405 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5409 /// Read a module from a source file.
5410 fn eval_src_mod(&mut self,
5412 directory_ownership: DirectoryOwnership,
5415 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5416 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5417 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5418 let mut err = String::from("circular modules: ");
5419 let len = included_mod_stack.len();
5420 for p in &included_mod_stack[i.. len] {
5421 err.push_str(&p.to_string_lossy());
5422 err.push_str(" -> ");
5424 err.push_str(&path.to_string_lossy());
5425 return Err(self.span_fatal(id_sp, &err[..]));
5427 included_mod_stack.push(path.clone());
5428 drop(included_mod_stack);
5431 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5432 p0.cfg_mods = self.cfg_mods;
5433 let mod_inner_lo = p0.span;
5434 let mod_attrs = p0.parse_inner_attributes()?;
5435 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5436 self.sess.included_mod_stack.borrow_mut().pop();
5437 Ok((ast::ItemKind::Mod(m0), mod_attrs))
5440 /// Parse a function declaration from a foreign module
5441 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5442 -> PResult<'a, ForeignItem> {
5443 self.expect_keyword(keywords::Fn)?;
5445 let (ident, mut generics) = self.parse_fn_header()?;
5446 let decl = self.parse_fn_decl(true)?;
5447 generics.where_clause = self.parse_where_clause()?;
5449 self.expect(&token::Semi)?;
5450 Ok(ast::ForeignItem {
5453 node: ForeignItemKind::Fn(decl, generics),
5454 id: ast::DUMMY_NODE_ID,
5460 /// Parse a static item from a foreign module
5461 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5462 -> PResult<'a, ForeignItem> {
5463 self.expect_keyword(keywords::Static)?;
5464 let mutbl = self.eat_keyword(keywords::Mut);
5466 let ident = self.parse_ident()?;
5467 self.expect(&token::Colon)?;
5468 let ty = self.parse_ty()?;
5470 self.expect(&token::Semi)?;
5474 node: ForeignItemKind::Static(ty, mutbl),
5475 id: ast::DUMMY_NODE_ID,
5481 /// Parse extern crate links
5485 /// extern crate foo;
5486 /// extern crate bar as foo;
5487 fn parse_item_extern_crate(&mut self,
5489 visibility: Visibility,
5490 attrs: Vec<Attribute>)
5491 -> PResult<'a, P<Item>> {
5493 let crate_name = self.parse_ident()?;
5494 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
5495 (Some(crate_name.name), ident)
5499 self.expect(&token::Semi)?;
5501 let prev_span = self.prev_span;
5502 Ok(self.mk_item(lo.to(prev_span),
5504 ItemKind::ExternCrate(maybe_path),
5509 /// Parse `extern` for foreign ABIs
5512 /// `extern` is expected to have been
5513 /// consumed before calling this method
5519 fn parse_item_foreign_mod(&mut self,
5521 opt_abi: Option<abi::Abi>,
5522 visibility: Visibility,
5523 mut attrs: Vec<Attribute>)
5524 -> PResult<'a, P<Item>> {
5525 self.expect(&token::OpenDelim(token::Brace))?;
5527 let abi = opt_abi.unwrap_or(Abi::C);
5529 attrs.extend(self.parse_inner_attributes()?);
5531 let mut foreign_items = vec![];
5532 while let Some(item) = self.parse_foreign_item()? {
5533 foreign_items.push(item);
5535 self.expect(&token::CloseDelim(token::Brace))?;
5537 let prev_span = self.prev_span;
5538 let m = ast::ForeignMod {
5540 items: foreign_items
5542 let invalid = keywords::Invalid.ident();
5543 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
5546 /// Parse type Foo = Bar;
5547 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5548 let ident = self.parse_ident()?;
5549 let mut tps = self.parse_generics()?;
5550 tps.where_clause = self.parse_where_clause()?;
5551 self.expect(&token::Eq)?;
5552 let ty = self.parse_ty()?;
5553 self.expect(&token::Semi)?;
5554 Ok((ident, ItemKind::Ty(ty, tps), None))
5557 /// Parse the part of an "enum" decl following the '{'
5558 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5559 let mut variants = Vec::new();
5560 let mut all_nullary = true;
5561 let mut any_disr = None;
5562 while self.token != token::CloseDelim(token::Brace) {
5563 let variant_attrs = self.parse_outer_attributes()?;
5564 let vlo = self.span;
5567 let mut disr_expr = None;
5568 let ident = self.parse_ident()?;
5569 if self.check(&token::OpenDelim(token::Brace)) {
5570 // Parse a struct variant.
5571 all_nullary = false;
5572 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
5573 ast::DUMMY_NODE_ID);
5574 } else if self.check(&token::OpenDelim(token::Paren)) {
5575 all_nullary = false;
5576 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
5577 ast::DUMMY_NODE_ID);
5578 } else if self.eat(&token::Eq) {
5579 disr_expr = Some(self.parse_expr()?);
5580 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5581 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5583 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5586 let vr = ast::Variant_ {
5588 attrs: variant_attrs,
5590 disr_expr: disr_expr,
5592 variants.push(respan(vlo.to(self.prev_span), vr));
5594 if !self.eat(&token::Comma) { break; }
5596 self.expect(&token::CloseDelim(token::Brace))?;
5598 Some(disr_span) if !all_nullary =>
5599 self.span_err(disr_span,
5600 "discriminator values can only be used with a c-like enum"),
5604 Ok(ast::EnumDef { variants: variants })
5607 /// Parse an "enum" declaration
5608 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5609 let id = self.parse_ident()?;
5610 let mut generics = self.parse_generics()?;
5611 generics.where_clause = self.parse_where_clause()?;
5612 self.expect(&token::OpenDelim(token::Brace))?;
5614 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
5615 self.recover_stmt();
5616 self.eat(&token::CloseDelim(token::Brace));
5619 Ok((id, ItemKind::Enum(enum_definition, generics), None))
5622 /// Parses a string as an ABI spec on an extern type or module. Consumes
5623 /// the `extern` keyword, if one is found.
5624 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5626 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5628 self.expect_no_suffix(sp, "ABI spec", suf);
5630 match abi::lookup(&s.as_str()) {
5631 Some(abi) => Ok(Some(abi)),
5633 let prev_span = self.prev_span;
5636 &format!("invalid ABI: expected one of [{}], \
5638 abi::all_names().join(", "),
5649 /// Parse one of the items allowed by the flags.
5650 /// NB: this function no longer parses the items inside an
5652 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5653 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5654 maybe_whole!(self, NtItem, |item| {
5655 let mut item = item.unwrap();
5656 let mut attrs = attrs;
5657 mem::swap(&mut item.attrs, &mut attrs);
5658 item.attrs.extend(attrs);
5664 let visibility = self.parse_visibility(false)?;
5666 if self.eat_keyword(keywords::Use) {
5668 let item_ = ItemKind::Use(self.parse_view_path()?);
5669 self.expect(&token::Semi)?;
5671 let prev_span = self.prev_span;
5672 let invalid = keywords::Invalid.ident();
5673 let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
5674 return Ok(Some(item));
5677 if self.eat_keyword(keywords::Extern) {
5678 if self.eat_keyword(keywords::Crate) {
5679 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
5682 let opt_abi = self.parse_opt_abi()?;
5684 if self.eat_keyword(keywords::Fn) {
5685 // EXTERN FUNCTION ITEM
5686 let fn_span = self.prev_span;
5687 let abi = opt_abi.unwrap_or(Abi::C);
5688 let (ident, item_, extra_attrs) =
5689 self.parse_item_fn(Unsafety::Normal,
5690 respan(fn_span, Constness::NotConst),
5692 let prev_span = self.prev_span;
5693 let item = self.mk_item(lo.to(prev_span),
5697 maybe_append(attrs, extra_attrs));
5698 return Ok(Some(item));
5699 } else if self.check(&token::OpenDelim(token::Brace)) {
5700 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
5706 if self.eat_keyword(keywords::Static) {
5708 let m = if self.eat_keyword(keywords::Mut) {
5711 Mutability::Immutable
5713 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
5714 let prev_span = self.prev_span;
5715 let item = self.mk_item(lo.to(prev_span),
5719 maybe_append(attrs, extra_attrs));
5720 return Ok(Some(item));
5722 if self.eat_keyword(keywords::Const) {
5723 let const_span = self.prev_span;
5724 if self.check_keyword(keywords::Fn)
5725 || (self.check_keyword(keywords::Unsafe)
5726 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5727 // CONST FUNCTION ITEM
5728 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5734 let (ident, item_, extra_attrs) =
5735 self.parse_item_fn(unsafety,
5736 respan(const_span, Constness::Const),
5738 let prev_span = self.prev_span;
5739 let item = self.mk_item(lo.to(prev_span),
5743 maybe_append(attrs, extra_attrs));
5744 return Ok(Some(item));
5748 if self.eat_keyword(keywords::Mut) {
5749 let prev_span = self.prev_span;
5750 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
5751 .help("did you mean to declare a static?")
5754 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
5755 let prev_span = self.prev_span;
5756 let item = self.mk_item(lo.to(prev_span),
5760 maybe_append(attrs, extra_attrs));
5761 return Ok(Some(item));
5763 if self.check_keyword(keywords::Unsafe) &&
5764 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5766 // UNSAFE TRAIT ITEM
5767 self.expect_keyword(keywords::Unsafe)?;
5768 self.expect_keyword(keywords::Trait)?;
5769 let (ident, item_, extra_attrs) =
5770 self.parse_item_trait(ast::Unsafety::Unsafe)?;
5771 let prev_span = self.prev_span;
5772 let item = self.mk_item(lo.to(prev_span),
5776 maybe_append(attrs, extra_attrs));
5777 return Ok(Some(item));
5779 if (self.check_keyword(keywords::Unsafe) &&
5780 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))) ||
5781 (self.check_keyword(keywords::Default) &&
5782 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) &&
5783 self.look_ahead(2, |t| t.is_keyword(keywords::Impl)))
5786 let defaultness = self.parse_defaultness()?;
5787 self.expect_keyword(keywords::Unsafe)?;
5788 self.expect_keyword(keywords::Impl)?;
5791 extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe, defaultness)?;
5792 let prev_span = self.prev_span;
5793 let item = self.mk_item(lo.to(prev_span),
5797 maybe_append(attrs, extra_attrs));
5798 return Ok(Some(item));
5800 if self.check_keyword(keywords::Fn) {
5803 let fn_span = self.prev_span;
5804 let (ident, item_, extra_attrs) =
5805 self.parse_item_fn(Unsafety::Normal,
5806 respan(fn_span, Constness::NotConst),
5808 let prev_span = self.prev_span;
5809 let item = self.mk_item(lo.to(prev_span),
5813 maybe_append(attrs, extra_attrs));
5814 return Ok(Some(item));
5816 if self.check_keyword(keywords::Unsafe)
5817 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5818 // UNSAFE FUNCTION ITEM
5820 let abi = if self.eat_keyword(keywords::Extern) {
5821 self.parse_opt_abi()?.unwrap_or(Abi::C)
5825 self.expect_keyword(keywords::Fn)?;
5826 let fn_span = self.prev_span;
5827 let (ident, item_, extra_attrs) =
5828 self.parse_item_fn(Unsafety::Unsafe,
5829 respan(fn_span, Constness::NotConst),
5831 let prev_span = self.prev_span;
5832 let item = self.mk_item(lo.to(prev_span),
5836 maybe_append(attrs, extra_attrs));
5837 return Ok(Some(item));
5839 if self.eat_keyword(keywords::Mod) {
5841 let (ident, item_, extra_attrs) =
5842 self.parse_item_mod(&attrs[..])?;
5843 let prev_span = self.prev_span;
5844 let item = self.mk_item(lo.to(prev_span),
5848 maybe_append(attrs, extra_attrs));
5849 return Ok(Some(item));
5851 if self.eat_keyword(keywords::Type) {
5853 let (ident, item_, extra_attrs) = self.parse_item_type()?;
5854 let prev_span = self.prev_span;
5855 let item = self.mk_item(lo.to(prev_span),
5859 maybe_append(attrs, extra_attrs));
5860 return Ok(Some(item));
5862 if self.eat_keyword(keywords::Enum) {
5864 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
5865 let prev_span = self.prev_span;
5866 let item = self.mk_item(lo.to(prev_span),
5870 maybe_append(attrs, extra_attrs));
5871 return Ok(Some(item));
5873 if self.eat_keyword(keywords::Trait) {
5875 let (ident, item_, extra_attrs) =
5876 self.parse_item_trait(ast::Unsafety::Normal)?;
5877 let prev_span = self.prev_span;
5878 let item = self.mk_item(lo.to(prev_span),
5882 maybe_append(attrs, extra_attrs));
5883 return Ok(Some(item));
5885 if (self.check_keyword(keywords::Impl)) ||
5886 (self.check_keyword(keywords::Default) &&
5887 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)))
5890 let defaultness = self.parse_defaultness()?;
5891 self.expect_keyword(keywords::Impl)?;
5894 extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal, defaultness)?;
5895 let prev_span = self.prev_span;
5896 let item = self.mk_item(lo.to(prev_span),
5900 maybe_append(attrs, extra_attrs));
5901 return Ok(Some(item));
5903 if self.eat_keyword(keywords::Struct) {
5905 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
5906 let prev_span = self.prev_span;
5907 let item = self.mk_item(lo.to(prev_span),
5911 maybe_append(attrs, extra_attrs));
5912 return Ok(Some(item));
5914 if self.is_union_item() {
5917 let (ident, item_, extra_attrs) = self.parse_item_union()?;
5918 let prev_span = self.prev_span;
5919 let item = self.mk_item(lo.to(prev_span),
5923 maybe_append(attrs, extra_attrs));
5924 return Ok(Some(item));
5926 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility)? {
5927 return Ok(Some(macro_def));
5930 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5933 /// Parse a foreign item.
5934 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
5935 let attrs = self.parse_outer_attributes()?;
5937 let visibility = self.parse_visibility(false)?;
5939 if self.check_keyword(keywords::Static) {
5940 // FOREIGN STATIC ITEM
5941 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
5943 if self.check_keyword(keywords::Fn) {
5944 // FOREIGN FUNCTION ITEM
5945 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
5948 // FIXME #5668: this will occur for a macro invocation:
5949 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
5951 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5957 /// This is the fall-through for parsing items.
5958 fn parse_macro_use_or_failure(
5960 attrs: Vec<Attribute> ,
5961 macros_allowed: bool,
5962 attributes_allowed: bool,
5964 visibility: Visibility
5965 ) -> PResult<'a, Option<P<Item>>> {
5966 if macros_allowed && self.token.is_path_start() {
5967 // MACRO INVOCATION ITEM
5969 let prev_span = self.prev_span;
5970 self.complain_if_pub_macro(&visibility, prev_span);
5972 let mac_lo = self.span;
5975 let pth = self.parse_path(PathStyle::Mod)?;
5976 self.expect(&token::Not)?;
5978 // a 'special' identifier (like what `macro_rules!` uses)
5979 // is optional. We should eventually unify invoc syntax
5981 let id = if self.token.is_ident() {
5984 keywords::Invalid.ident() // no special identifier
5986 // eat a matched-delimiter token tree:
5987 let (delim, tts) = self.expect_delimited_token_tree()?;
5988 if delim != token::Brace {
5989 if !self.eat(&token::Semi) {
5990 let prev_span = self.prev_span;
5991 self.span_err(prev_span,
5992 "macros that expand to items must either \
5993 be surrounded with braces or followed by \
5998 let hi = self.prev_span;
5999 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6000 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6001 return Ok(Some(item));
6004 // FAILURE TO PARSE ITEM
6006 Visibility::Inherited => {}
6008 let prev_span = self.prev_span;
6009 return Err(self.span_fatal(prev_span, "unmatched visibility `pub`"));
6013 if !attributes_allowed && !attrs.is_empty() {
6014 self.expected_item_err(&attrs);
6019 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6020 let attrs = self.parse_outer_attributes()?;
6021 self.parse_item_(attrs, true, false)
6024 fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> {
6025 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
6026 &token::CloseDelim(token::Brace),
6027 SeqSep::trailing_allowed(token::Comma), |this| {
6029 let ident = if this.eat_keyword(keywords::SelfValue) {
6030 keywords::SelfValue.ident()
6034 let rename = this.parse_rename()?;
6035 let node = ast::PathListItem_ {
6038 id: ast::DUMMY_NODE_ID
6040 Ok(respan(lo.to(this.prev_span), node))
6045 fn is_import_coupler(&mut self) -> bool {
6046 self.check(&token::ModSep) &&
6047 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6048 *t == token::BinOp(token::Star))
6051 /// Matches ViewPath:
6052 /// MOD_SEP? non_global_path
6053 /// MOD_SEP? non_global_path as IDENT
6054 /// MOD_SEP? non_global_path MOD_SEP STAR
6055 /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE
6056 /// MOD_SEP? LBRACE item_seq RBRACE
6057 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
6059 if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) ||
6060 self.is_import_coupler() {
6061 // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`.
6062 self.eat(&token::ModSep);
6063 let prefix = ast::Path {
6064 segments: vec![PathSegment::crate_root()],
6065 span: lo.to(self.span),
6067 let view_path_kind = if self.eat(&token::BinOp(token::Star)) {
6068 ViewPathGlob(prefix)
6070 ViewPathList(prefix, self.parse_path_list_items()?)
6072 Ok(P(respan(lo.to(self.span), view_path_kind)))
6074 let prefix = self.parse_path(PathStyle::Mod)?.default_to_global();
6075 if self.is_import_coupler() {
6076 // `foo::bar::{a, b}` or `foo::bar::*`
6078 if self.check(&token::BinOp(token::Star)) {
6080 Ok(P(respan(lo.to(self.span), ViewPathGlob(prefix))))
6082 let items = self.parse_path_list_items()?;
6083 Ok(P(respan(lo.to(self.span), ViewPathList(prefix, items))))
6086 // `foo::bar` or `foo::bar as baz`
6087 let rename = self.parse_rename()?.
6088 unwrap_or(prefix.segments.last().unwrap().identifier);
6089 Ok(P(respan(lo.to(self.prev_span), ViewPathSimple(rename, prefix))))
6094 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6095 if self.eat_keyword(keywords::As) {
6096 self.parse_ident().map(Some)
6102 /// Parses a source module as a crate. This is the main
6103 /// entry point for the parser.
6104 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6107 attrs: self.parse_inner_attributes()?,
6108 module: self.parse_mod_items(&token::Eof, lo)?,
6109 span: lo.to(self.span),
6113 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6114 let ret = match self.token {
6115 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6116 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6123 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6124 match self.parse_optional_str() {
6125 Some((s, style, suf)) => {
6126 let sp = self.prev_span;
6127 self.expect_no_suffix(sp, "string literal", suf);
6130 _ => Err(self.fatal("expected string literal"))