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 /// Whether to parse sub-modules in other files.
183 pub recurse_into_file_modules: bool,
184 /// Name of the root module this parser originated from. If `None`, then the
185 /// name is not known. This does not change while the parser is descending
186 /// into modules, and sub-parsers have new values for this name.
187 pub root_module_name: Option<String>,
188 pub expected_tokens: Vec<TokenType>,
189 token_cursor: TokenCursor,
190 pub desugar_doc_comments: bool,
191 /// Whether we should configure out of line modules as we parse.
197 frame: TokenCursorFrame,
198 stack: Vec<TokenCursorFrame>,
201 struct TokenCursorFrame {
202 delim: token::DelimToken,
205 tree_cursor: tokenstream::Cursor,
209 impl TokenCursorFrame {
210 fn new(sp: Span, delimited: &Delimited) -> Self {
212 delim: delimited.delim,
214 open_delim: delimited.delim == token::NoDelim,
215 tree_cursor: delimited.stream().into_trees(),
216 close_delim: delimited.delim == token::NoDelim,
222 fn next(&mut self) -> TokenAndSpan {
224 let tree = if !self.frame.open_delim {
225 self.frame.open_delim = true;
226 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
227 .open_tt(self.frame.span)
228 } else if let Some(tree) = self.frame.tree_cursor.next() {
230 } else if !self.frame.close_delim {
231 self.frame.close_delim = true;
232 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
233 .close_tt(self.frame.span)
234 } else if let Some(frame) = self.stack.pop() {
238 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
242 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
243 TokenTree::Delimited(sp, ref delimited) => {
244 let frame = TokenCursorFrame::new(sp, delimited);
245 self.stack.push(mem::replace(&mut self.frame, frame));
251 fn next_desugared(&mut self) -> TokenAndSpan {
252 let (sp, name) = match self.next() {
253 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
257 let stripped = strip_doc_comment_decoration(&name.as_str());
259 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
260 // required to wrap the text.
261 let mut num_of_hashes = 0;
263 for ch in stripped.chars() {
266 '#' if count > 0 => count + 1,
269 num_of_hashes = cmp::max(num_of_hashes, count);
272 let body = TokenTree::Delimited(sp, Delimited {
273 delim: token::Bracket,
274 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"))),
275 TokenTree::Token(sp, token::Eq),
276 TokenTree::Token(sp, token::Literal(
277 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
278 .iter().cloned().collect::<TokenStream>().into(),
281 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
282 delim: token::NoDelim,
283 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
284 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
285 .iter().cloned().collect::<TokenStream>().into()
287 [TokenTree::Token(sp, token::Pound), body]
288 .iter().cloned().collect::<TokenStream>().into()
296 #[derive(PartialEq, Eq, Clone)]
299 Keyword(keywords::Keyword),
308 fn to_string(&self) -> String {
310 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
311 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
312 TokenType::Operator => "an operator".to_string(),
313 TokenType::Lifetime => "lifetime".to_string(),
314 TokenType::Ident => "identifier".to_string(),
315 TokenType::Path => "path".to_string(),
316 TokenType::Type => "type".to_string(),
321 fn is_ident_or_underscore(t: &token::Token) -> bool {
322 t.is_ident() || *t == token::Underscore
325 /// Information about the path to a module.
326 pub struct ModulePath {
328 pub path_exists: bool,
329 pub result: Result<ModulePathSuccess, Error>,
332 pub struct ModulePathSuccess {
334 pub directory_ownership: DirectoryOwnership,
338 pub struct ModulePathError {
340 pub help_msg: String,
344 FileNotFoundForModule {
346 default_path: String,
347 secondary_path: String,
352 default_path: String,
353 secondary_path: String,
356 InclusiveRangeWithNoEnd,
360 pub fn span_err(self, sp: Span, handler: &errors::Handler) -> DiagnosticBuilder {
362 Error::FileNotFoundForModule { ref mod_name,
366 let mut err = struct_span_err!(handler, sp, E0583,
367 "file not found for module `{}`", mod_name);
368 err.help(&format!("name the file either {} or {} inside the directory {:?}",
374 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
375 let mut err = struct_span_err!(handler, sp, E0584,
376 "file for module `{}` found at both {} and {}",
380 err.help("delete or rename one of them to remove the ambiguity");
383 Error::UselessDocComment => {
384 let mut err = struct_span_err!(handler, sp, E0585,
385 "found a documentation comment that doesn't document anything");
386 err.help("doc comments must come before what they document, maybe a comment was \
387 intended with `//`?");
390 Error::InclusiveRangeWithNoEnd => {
391 let mut err = struct_span_err!(handler, sp, E0586,
392 "inclusive range with no end");
393 err.help("inclusive ranges must be bounded at the end (`...b` or `a...b`)");
402 AttributesParsed(ThinVec<Attribute>),
403 AlreadyParsed(P<Expr>),
406 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
407 fn from(o: Option<ThinVec<Attribute>>) -> Self {
408 if let Some(attrs) = o {
409 LhsExpr::AttributesParsed(attrs)
411 LhsExpr::NotYetParsed
416 impl From<P<Expr>> for LhsExpr {
417 fn from(expr: P<Expr>) -> Self {
418 LhsExpr::AlreadyParsed(expr)
422 /// Create a placeholder argument.
423 fn dummy_arg(span: Span) -> Arg {
424 let spanned = Spanned {
426 node: keywords::Invalid.ident()
429 id: ast::DUMMY_NODE_ID,
430 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), spanned, None),
436 id: ast::DUMMY_NODE_ID
438 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
441 impl<'a> Parser<'a> {
442 pub fn new(sess: &'a ParseSess,
444 directory: Option<Directory>,
445 recurse_into_file_modules: bool,
446 desugar_doc_comments: bool)
448 let mut parser = Parser {
450 token: token::Underscore,
451 span: syntax_pos::DUMMY_SP,
452 prev_span: syntax_pos::DUMMY_SP,
454 prev_token_kind: PrevTokenKind::Other,
455 restrictions: Restrictions::empty(),
456 obsolete_set: HashSet::new(),
457 recurse_into_file_modules: recurse_into_file_modules,
458 directory: Directory { path: PathBuf::new(), ownership: DirectoryOwnership::Owned },
459 root_module_name: None,
460 expected_tokens: Vec::new(),
461 token_cursor: TokenCursor {
462 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
463 delim: token::NoDelim,
468 desugar_doc_comments: desugar_doc_comments,
472 let tok = parser.next_tok();
473 parser.token = tok.tok;
474 parser.span = tok.sp;
476 if let Some(directory) = directory {
477 parser.directory = directory;
478 } else if parser.span != syntax_pos::DUMMY_SP {
479 parser.directory.path = PathBuf::from(sess.codemap().span_to_filename(parser.span));
480 parser.directory.path.pop();
483 parser.process_potential_macro_variable();
487 fn next_tok(&mut self) -> TokenAndSpan {
488 let mut next = if self.desugar_doc_comments {
489 self.token_cursor.next_desugared()
491 self.token_cursor.next()
493 if next.sp == syntax_pos::DUMMY_SP {
494 next.sp = self.prev_span;
499 /// Convert a token to a string using self's reader
500 pub fn token_to_string(token: &token::Token) -> String {
501 pprust::token_to_string(token)
504 /// Convert the current token to a string using self's reader
505 pub fn this_token_to_string(&self) -> String {
506 Parser::token_to_string(&self.token)
509 pub fn this_token_descr(&self) -> String {
510 let s = self.this_token_to_string();
511 if self.token.is_strict_keyword() {
512 format!("keyword `{}`", s)
513 } else if self.token.is_reserved_keyword() {
514 format!("reserved keyword `{}`", s)
520 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
521 let token_str = Parser::token_to_string(t);
522 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
525 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
526 match self.expect_one_of(&[], &[]) {
528 Ok(_) => unreachable!(),
532 /// Expect and consume the token t. Signal an error if
533 /// the next token is not t.
534 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
535 if self.expected_tokens.is_empty() {
536 if self.token == *t {
540 let token_str = Parser::token_to_string(t);
541 let this_token_str = self.this_token_to_string();
542 Err(self.fatal(&format!("expected `{}`, found `{}`",
547 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
551 /// Expect next token to be edible or inedible token. If edible,
552 /// then consume it; if inedible, then return without consuming
553 /// anything. Signal a fatal error if next token is unexpected.
554 pub fn expect_one_of(&mut self,
555 edible: &[token::Token],
556 inedible: &[token::Token]) -> PResult<'a, ()>{
557 fn tokens_to_string(tokens: &[TokenType]) -> String {
558 let mut i = tokens.iter();
559 // This might be a sign we need a connect method on Iterator.
561 .map_or("".to_string(), |t| t.to_string());
562 i.enumerate().fold(b, |mut b, (i, a)| {
563 if tokens.len() > 2 && i == tokens.len() - 2 {
565 } else if tokens.len() == 2 && i == tokens.len() - 2 {
570 b.push_str(&a.to_string());
574 if edible.contains(&self.token) {
577 } else if inedible.contains(&self.token) {
578 // leave it in the input
581 let mut expected = edible.iter()
582 .map(|x| TokenType::Token(x.clone()))
583 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
584 .chain(self.expected_tokens.iter().cloned())
585 .collect::<Vec<_>>();
586 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
588 let expect = tokens_to_string(&expected[..]);
589 let actual = self.this_token_to_string();
590 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
591 let short_expect = if expected.len() > 6 {
592 format!("{} possible tokens", expected.len())
596 (format!("expected one of {}, found `{}`", expect, actual),
597 (self.prev_span.next_point(), format!("expected one of {} here", short_expect)))
598 } else if expected.is_empty() {
599 (format!("unexpected token: `{}`", actual),
600 (self.prev_span, "unexpected token after this".to_string()))
602 (format!("expected {}, found `{}`", expect, actual),
603 (self.prev_span.next_point(), format!("expected {} here", expect)))
605 let mut err = self.fatal(&msg_exp);
606 let sp = if self.token == token::Token::Eof {
607 // This is EOF, don't want to point at the following char, but rather the last token
612 if self.span.contains(sp) {
613 err.span_label(self.span, label_exp);
615 err.span_label(sp, label_exp);
616 err.span_label(self.span, "unexpected token");
622 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
623 fn interpolated_or_expr_span(&self,
624 expr: PResult<'a, P<Expr>>)
625 -> PResult<'a, (Span, P<Expr>)> {
627 if self.prev_token_kind == PrevTokenKind::Interpolated {
635 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
636 self.check_strict_keywords();
637 self.check_reserved_keywords();
644 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
645 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
647 let mut err = self.fatal(&format!("expected identifier, found `{}`",
648 self.this_token_to_string()));
649 if self.token == token::Underscore {
650 err.note("`_` is a wildcard pattern, not an identifier");
658 /// Check if the next token is `tok`, and return `true` if so.
660 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
662 pub fn check(&mut self, tok: &token::Token) -> bool {
663 let is_present = self.token == *tok;
664 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
668 /// Consume token 'tok' if it exists. Returns true if the given
669 /// token was present, false otherwise.
670 pub fn eat(&mut self, tok: &token::Token) -> bool {
671 let is_present = self.check(tok);
672 if is_present { self.bump() }
676 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
677 self.expected_tokens.push(TokenType::Keyword(kw));
678 self.token.is_keyword(kw)
681 /// If the next token is the given keyword, eat it and return
682 /// true. Otherwise, return false.
683 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
684 if self.check_keyword(kw) {
692 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
693 if self.token.is_keyword(kw) {
701 /// If the given word is not a keyword, signal an error.
702 /// If the next token is not the given word, signal an error.
703 /// Otherwise, eat it.
704 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
705 if !self.eat_keyword(kw) {
712 /// Signal an error if the given string is a strict keyword
713 pub fn check_strict_keywords(&mut self) {
714 if self.token.is_strict_keyword() {
715 let token_str = self.this_token_to_string();
716 let span = self.span;
718 &format!("expected identifier, found keyword `{}`",
723 /// Signal an error if the current token is a reserved keyword
724 pub fn check_reserved_keywords(&mut self) {
725 if self.token.is_reserved_keyword() {
726 let token_str = self.this_token_to_string();
727 self.fatal(&format!("`{}` is a reserved keyword", token_str)).emit()
731 fn check_ident(&mut self) -> bool {
732 if self.token.is_ident() {
735 self.expected_tokens.push(TokenType::Ident);
740 fn check_path(&mut self) -> bool {
741 if self.token.is_path_start() {
744 self.expected_tokens.push(TokenType::Path);
749 fn check_type(&mut self) -> bool {
750 if self.token.can_begin_type() {
753 self.expected_tokens.push(TokenType::Type);
758 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
759 /// `&` and continue. If an `&` is not seen, signal an error.
760 fn expect_and(&mut self) -> PResult<'a, ()> {
761 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
763 token::BinOp(token::And) => {
768 let span = self.span;
769 let lo = span.lo + BytePos(1);
770 Ok(self.bump_with(token::BinOp(token::And), Span { lo: lo, ..span }))
772 _ => self.unexpected()
776 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
778 None => {/* everything ok */}
780 let text = suf.as_str();
782 self.span_bug(sp, "found empty literal suffix in Some")
784 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
789 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
790 /// `<` and continue. If a `<` is not seen, return false.
792 /// This is meant to be used when parsing generics on a path to get the
794 fn eat_lt(&mut self) -> bool {
795 self.expected_tokens.push(TokenType::Token(token::Lt));
801 token::BinOp(token::Shl) => {
802 let span = self.span;
803 let lo = span.lo + BytePos(1);
804 self.bump_with(token::Lt, Span { lo: lo, ..span });
811 fn expect_lt(&mut self) -> PResult<'a, ()> {
819 /// Expect and consume a GT. if a >> is seen, replace it
820 /// with a single > and continue. If a GT is not seen,
822 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
823 self.expected_tokens.push(TokenType::Token(token::Gt));
829 token::BinOp(token::Shr) => {
830 let span = self.span;
831 let lo = span.lo + BytePos(1);
832 Ok(self.bump_with(token::Gt, Span { lo: lo, ..span }))
834 token::BinOpEq(token::Shr) => {
835 let span = self.span;
836 let lo = span.lo + BytePos(1);
837 Ok(self.bump_with(token::Ge, Span { lo: lo, ..span }))
840 let span = self.span;
841 let lo = span.lo + BytePos(1);
842 Ok(self.bump_with(token::Eq, Span { lo: lo, ..span }))
844 _ => self.unexpected()
848 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
849 sep: Option<token::Token>,
851 -> PResult<'a, (Vec<T>, bool)>
852 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
854 let mut v = Vec::new();
855 // This loop works by alternating back and forth between parsing types
856 // and commas. For example, given a string `A, B,>`, the parser would
857 // first parse `A`, then a comma, then `B`, then a comma. After that it
858 // would encounter a `>` and stop. This lets the parser handle trailing
859 // commas in generic parameters, because it can stop either after
860 // parsing a type or after parsing a comma.
862 if self.check(&token::Gt)
863 || self.token == token::BinOp(token::Shr)
864 || self.token == token::Ge
865 || self.token == token::BinOpEq(token::Shr) {
871 Some(result) => v.push(result),
872 None => return Ok((v, true))
875 if let Some(t) = sep.as_ref() {
881 return Ok((v, false));
884 /// Parse a sequence bracketed by '<' and '>', stopping
886 pub fn parse_seq_to_before_gt<T, F>(&mut self,
887 sep: Option<token::Token>,
889 -> PResult<'a, Vec<T>> where
890 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
892 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
893 |p| Ok(Some(f(p)?)))?;
898 pub fn parse_seq_to_gt<T, F>(&mut self,
899 sep: Option<token::Token>,
901 -> PResult<'a, Vec<T>> where
902 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
904 let v = self.parse_seq_to_before_gt(sep, f)?;
909 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
910 sep: Option<token::Token>,
912 -> PResult<'a, (Vec<T>, bool)> where
913 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
915 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
919 return Ok((v, returned));
922 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
923 /// passes through any errors encountered. Used for error recovery.
924 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
925 let handler = self.diagnostic();
927 self.parse_seq_to_before_tokens(kets,
929 |p| Ok(p.parse_token_tree()),
930 |mut e| handler.cancel(&mut e));
933 /// Parse a sequence, including the closing delimiter. The function
934 /// f must consume tokens until reaching the next separator or
936 pub fn parse_seq_to_end<T, F>(&mut self,
940 -> PResult<'a, Vec<T>> where
941 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
943 let val = self.parse_seq_to_before_end(ket, sep, f);
948 /// Parse a sequence, not including the closing delimiter. The function
949 /// f must consume tokens until reaching the next separator or
951 pub fn parse_seq_to_before_end<T, F>(&mut self,
956 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
958 self.parse_seq_to_before_tokens(&[ket], sep, f, |mut e| e.emit())
961 // `fe` is an error handler.
962 fn parse_seq_to_before_tokens<T, F, Fe>(&mut self,
963 kets: &[&token::Token],
968 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
969 Fe: FnMut(DiagnosticBuilder)
971 let mut first: bool = true;
973 while !kets.contains(&&self.token) {
975 token::CloseDelim(..) | token::Eof => break,
978 if let Some(ref t) = sep.sep {
982 if let Err(e) = self.expect(t) {
988 if sep.trailing_sep_allowed && kets.iter().any(|k| self.check(k)) {
1004 /// Parse a sequence, including the closing delimiter. The function
1005 /// f must consume tokens until reaching the next separator or
1006 /// closing bracket.
1007 pub fn parse_unspanned_seq<T, F>(&mut self,
1012 -> PResult<'a, Vec<T>> where
1013 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1016 let result = self.parse_seq_to_before_end(ket, sep, f);
1017 if self.token == *ket {
1023 // NB: Do not use this function unless you actually plan to place the
1024 // spanned list in the AST.
1025 pub fn parse_seq<T, F>(&mut self,
1030 -> PResult<'a, Spanned<Vec<T>>> where
1031 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1035 let result = self.parse_seq_to_before_end(ket, sep, f);
1038 Ok(respan(lo.to(hi), result))
1041 /// Advance the parser by one token
1042 pub fn bump(&mut self) {
1043 if self.prev_token_kind == PrevTokenKind::Eof {
1044 // Bumping after EOF is a bad sign, usually an infinite loop.
1045 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1048 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1050 // Record last token kind for possible error recovery.
1051 self.prev_token_kind = match self.token {
1052 token::DocComment(..) => PrevTokenKind::DocComment,
1053 token::Comma => PrevTokenKind::Comma,
1054 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1055 token::Interpolated(..) => PrevTokenKind::Interpolated,
1056 token::Eof => PrevTokenKind::Eof,
1057 _ => PrevTokenKind::Other,
1060 let next = self.next_tok();
1061 self.span = next.sp;
1062 self.token = next.tok;
1063 self.expected_tokens.clear();
1064 // check after each token
1065 self.process_potential_macro_variable();
1068 /// Advance the parser using provided token as a next one. Use this when
1069 /// consuming a part of a token. For example a single `<` from `<<`.
1070 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1071 self.prev_span = Span { hi: span.lo, ..self.span };
1072 // It would be incorrect to record the kind of the current token, but
1073 // fortunately for tokens currently using `bump_with`, the
1074 // prev_token_kind will be of no use anyway.
1075 self.prev_token_kind = PrevTokenKind::Other;
1078 self.expected_tokens.clear();
1081 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1082 F: FnOnce(&token::Token) -> R,
1085 return f(&self.token)
1088 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1089 Some(tree) => match tree {
1090 TokenTree::Token(_, tok) => tok,
1091 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1093 None => token::CloseDelim(self.token_cursor.frame.delim),
1096 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1097 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1099 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1100 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1102 pub fn span_fatal_err(&self, sp: Span, err: Error) -> DiagnosticBuilder<'a> {
1103 err.span_err(sp, self.diagnostic())
1105 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1106 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1110 pub fn bug(&self, m: &str) -> ! {
1111 self.sess.span_diagnostic.span_bug(self.span, m)
1113 pub fn warn(&self, m: &str) {
1114 self.sess.span_diagnostic.span_warn(self.span, m)
1116 pub fn span_warn(&self, sp: Span, m: &str) {
1117 self.sess.span_diagnostic.span_warn(sp, m)
1119 pub fn span_err(&self, sp: Span, m: &str) {
1120 self.sess.span_diagnostic.span_err(sp, m)
1122 pub fn span_err_help(&self, sp: Span, m: &str, h: &str) {
1123 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1127 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1128 self.sess.span_diagnostic.span_bug(sp, m)
1130 pub fn abort_if_errors(&self) {
1131 self.sess.span_diagnostic.abort_if_errors();
1134 fn cancel(&self, err: &mut DiagnosticBuilder) {
1135 self.sess.span_diagnostic.cancel(err)
1138 pub fn diagnostic(&self) -> &'a errors::Handler {
1139 &self.sess.span_diagnostic
1142 /// Is the current token one of the keywords that signals a bare function
1144 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1145 self.check_keyword(keywords::Fn) ||
1146 self.check_keyword(keywords::Unsafe) ||
1147 self.check_keyword(keywords::Extern)
1150 fn get_label(&mut self) -> ast::Ident {
1152 token::Lifetime(ref ident) => *ident,
1153 _ => self.bug("not a lifetime"),
1157 /// parse a TyKind::BareFn type:
1158 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<LifetimeDef>)
1159 -> PResult<'a, TyKind> {
1162 [unsafe] [extern "ABI"] fn (S) -> T
1172 let unsafety = self.parse_unsafety()?;
1173 let abi = if self.eat_keyword(keywords::Extern) {
1174 self.parse_opt_abi()?.unwrap_or(Abi::C)
1179 self.expect_keyword(keywords::Fn)?;
1180 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1181 let ret_ty = self.parse_ret_ty()?;
1182 let decl = P(FnDecl {
1187 Ok(TyKind::BareFn(P(BareFnTy {
1190 lifetimes: lifetime_defs,
1195 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1196 if self.eat_keyword(keywords::Unsafe) {
1197 return Ok(Unsafety::Unsafe);
1199 return Ok(Unsafety::Normal);
1203 /// Parse the items in a trait declaration
1204 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1205 maybe_whole!(self, NtTraitItem, |x| x);
1206 let mut attrs = self.parse_outer_attributes()?;
1209 let (name, node) = if self.eat_keyword(keywords::Type) {
1210 let TyParam {ident, bounds, default, ..} = self.parse_ty_param(vec![])?;
1211 self.expect(&token::Semi)?;
1212 (ident, TraitItemKind::Type(bounds, default))
1213 } else if self.is_const_item() {
1214 self.expect_keyword(keywords::Const)?;
1215 let ident = self.parse_ident()?;
1216 self.expect(&token::Colon)?;
1217 let ty = self.parse_ty()?;
1218 let default = if self.check(&token::Eq) {
1220 let expr = self.parse_expr()?;
1221 self.expect(&token::Semi)?;
1224 self.expect(&token::Semi)?;
1227 (ident, TraitItemKind::Const(ty, default))
1228 } else if self.token.is_path_start() {
1229 // trait item macro.
1230 // code copied from parse_macro_use_or_failure... abstraction!
1231 let prev_span = self.prev_span;
1233 let pth = self.parse_path(PathStyle::Mod)?;
1235 if pth.segments.len() == 1 {
1236 if !self.eat(&token::Not) {
1237 return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1240 self.expect(&token::Not)?;
1243 // eat a matched-delimiter token tree:
1244 let (delim, tts) = self.expect_delimited_token_tree()?;
1245 if delim != token::Brace {
1246 self.expect(&token::Semi)?
1249 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1250 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac))
1252 let (constness, unsafety, abi) = match self.parse_fn_front_matter() {
1254 Err(e) => return Err(e),
1257 let ident = self.parse_ident()?;
1258 let mut generics = self.parse_generics()?;
1260 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1261 // This is somewhat dubious; We don't want to allow
1262 // argument names to be left off if there is a
1264 p.parse_arg_general(false)
1267 generics.where_clause = self.parse_where_clause()?;
1268 let sig = ast::MethodSig {
1270 constness: constness,
1276 let body = match self.token {
1280 debug!("parse_trait_methods(): parsing required method");
1283 token::OpenDelim(token::Brace) => {
1284 debug!("parse_trait_methods(): parsing provided method");
1286 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1287 attrs.extend(inner_attrs.iter().cloned());
1291 let token_str = self.this_token_to_string();
1292 return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1295 (ident, ast::TraitItemKind::Method(sig, body))
1299 id: ast::DUMMY_NODE_ID,
1303 span: lo.to(self.prev_span),
1307 /// Parse optional return type [ -> TY ] in function decl
1308 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1309 if self.eat(&token::RArrow) {
1310 Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
1312 Ok(FunctionRetTy::Default(Span { hi: self.span.lo, ..self.span }))
1317 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1318 self.parse_ty_common(true)
1321 /// Parse a type in restricted contexts where `+` is not permitted.
1322 /// Example 1: `&'a TYPE`
1323 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1324 /// Example 2: `value1 as TYPE + value2`
1325 /// `+` is prohibited to avoid interactions with expression grammar.
1326 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1327 self.parse_ty_common(false)
1330 fn parse_ty_common(&mut self, allow_plus: bool) -> PResult<'a, P<Ty>> {
1331 maybe_whole!(self, NtTy, |x| x);
1334 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1335 // `(TYPE)` is a parenthesized type.
1336 // `(TYPE,)` is a tuple with a single field of type TYPE.
1337 let mut ts = vec![];
1338 let mut last_comma = false;
1339 while self.token != token::CloseDelim(token::Paren) {
1340 ts.push(self.parse_ty()?);
1341 if self.eat(&token::Comma) {
1348 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1349 self.expect(&token::CloseDelim(token::Paren))?;
1351 if ts.len() == 1 && !last_comma {
1352 let ty = ts.into_iter().nth(0).unwrap().unwrap();
1353 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1355 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1356 TyKind::Path(None, ref path) if maybe_bounds => {
1357 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1359 TyKind::TraitObject(ref bounds)
1360 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1361 let path = match bounds[0] {
1362 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1363 _ => self.bug("unexpected lifetime bound"),
1365 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1368 _ => TyKind::Paren(P(ty))
1373 } else if self.eat(&token::Not) {
1376 } else if self.eat(&token::BinOp(token::Star)) {
1378 TyKind::Ptr(self.parse_ptr()?)
1379 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1381 let t = self.parse_ty()?;
1382 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1383 let t = match self.maybe_parse_fixed_length_of_vec()? {
1384 None => TyKind::Slice(t),
1385 Some(suffix) => TyKind::Array(t, suffix),
1387 self.expect(&token::CloseDelim(token::Bracket))?;
1389 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1392 self.parse_borrowed_pointee()?
1393 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1395 // In order to not be ambiguous, the type must be surrounded by parens.
1396 self.expect(&token::OpenDelim(token::Paren))?;
1397 let e = self.parse_expr()?;
1398 self.expect(&token::CloseDelim(token::Paren))?;
1400 } else if self.eat(&token::Underscore) {
1401 // A type to be inferred `_`
1403 } else if self.eat_lt() {
1405 let (qself, path) = self.parse_qualified_path(PathStyle::Type)?;
1406 TyKind::Path(Some(qself), path)
1407 } else if self.token.is_path_start() {
1409 let path = self.parse_path(PathStyle::Type)?;
1410 if self.eat(&token::Not) {
1411 // Macro invocation in type position
1412 let (_, tts) = self.expect_delimited_token_tree()?;
1413 TyKind::Mac(respan(lo.to(self.span), Mac_ { path: path, tts: tts }))
1415 // Just a type path or bound list (trait object type) starting with a trait.
1417 // `Trait1 + Trait2 + 'a`
1418 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1419 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1421 TyKind::Path(None, path)
1424 } else if self.token_is_bare_fn_keyword() {
1425 // Function pointer type
1426 self.parse_ty_bare_fn(Vec::new())?
1427 } else if self.check_keyword(keywords::For) {
1428 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1429 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1430 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1432 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1433 if self.token_is_bare_fn_keyword() {
1434 self.parse_ty_bare_fn(lifetime_defs)?
1436 let path = self.parse_path(PathStyle::Type)?;
1437 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1438 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1440 } else if self.eat_keyword(keywords::Impl) {
1441 // FIXME: figure out priority of `+` in `impl Trait1 + Trait2` (#34511).
1442 TyKind::ImplTrait(self.parse_ty_param_bounds()?)
1443 } else if self.check(&token::Question) ||
1444 self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)){
1445 // Bound list (trait object type)
1446 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?)
1448 let msg = format!("expected type, found {}", self.this_token_descr());
1449 return Err(self.fatal(&msg));
1452 let span = lo.to(self.prev_span);
1453 let ty = Ty { node: node, span: span, id: ast::DUMMY_NODE_ID };
1455 // Try to recover from use of `+` with incorrect priority.
1456 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1461 fn parse_remaining_bounds(&mut self, lifetime_defs: Vec<LifetimeDef>, path: ast::Path,
1462 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1463 let poly_trait_ref = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
1464 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1467 bounds.append(&mut self.parse_ty_param_bounds()?);
1469 Ok(TyKind::TraitObject(bounds))
1472 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1473 // Do not add `+` to expected tokens.
1474 if !allow_plus || self.token != token::BinOp(token::Plus) {
1479 let bounds = self.parse_ty_param_bounds()?;
1480 let sum_span = ty.span.to(self.prev_span);
1482 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1483 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1486 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1487 let sum_with_parens = pprust::to_string(|s| {
1488 use print::pp::word;
1489 use print::pprust::PrintState;
1491 word(&mut s.s, "&")?;
1492 s.print_opt_lifetime(lifetime)?;
1493 s.print_mutability(mut_ty.mutbl)?;
1495 s.print_type(&mut_ty.ty)?;
1496 s.print_bounds(" +", &bounds)?;
1499 err.span_suggestion(sum_span, "try adding parentheses:", sum_with_parens);
1501 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1502 err.span_label(sum_span, "perhaps you forgot parentheses?");
1505 err.span_label(sum_span, "expected a path");
1512 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1513 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1514 let mutbl = self.parse_mutability();
1515 let ty = self.parse_ty_no_plus()?;
1516 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1519 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1520 let mutbl = if self.eat_keyword(keywords::Mut) {
1522 } else if self.eat_keyword(keywords::Const) {
1523 Mutability::Immutable
1525 let span = self.prev_span;
1527 "expected mut or const in raw pointer type (use \
1528 `*mut T` or `*const T` as appropriate)");
1529 Mutability::Immutable
1531 let t = self.parse_ty_no_plus()?;
1532 Ok(MutTy { ty: t, mutbl: mutbl })
1535 pub fn is_named_argument(&mut self) -> bool {
1536 let offset = match self.token {
1537 token::BinOp(token::And) |
1539 _ if self.token.is_keyword(keywords::Mut) => 1,
1543 debug!("parser is_named_argument offset:{}", offset);
1546 is_ident_or_underscore(&self.token)
1547 && self.look_ahead(1, |t| *t == token::Colon)
1549 self.look_ahead(offset, |t| is_ident_or_underscore(t))
1550 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1554 /// This version of parse arg doesn't necessarily require
1555 /// identifier names.
1556 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1557 maybe_whole!(self, NtArg, |x| x);
1559 let pat = if require_name || self.is_named_argument() {
1560 debug!("parse_arg_general parse_pat (require_name:{})",
1562 let pat = self.parse_pat()?;
1564 self.expect(&token::Colon)?;
1567 debug!("parse_arg_general ident_to_pat");
1568 let sp = self.prev_span;
1569 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1571 id: ast::DUMMY_NODE_ID,
1572 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1578 let t = self.parse_ty()?;
1583 id: ast::DUMMY_NODE_ID,
1587 /// Parse a single function argument
1588 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1589 self.parse_arg_general(true)
1592 /// Parse an argument in a lambda header e.g. |arg, arg|
1593 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1594 let pat = self.parse_pat()?;
1595 let t = if self.eat(&token::Colon) {
1599 id: ast::DUMMY_NODE_ID,
1600 node: TyKind::Infer,
1607 id: ast::DUMMY_NODE_ID
1611 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1612 if self.eat(&token::Semi) {
1613 Ok(Some(self.parse_expr()?))
1619 /// Matches token_lit = LIT_INTEGER | ...
1620 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1621 let out = match self.token {
1622 token::Interpolated(ref nt) => match **nt {
1623 token::NtExpr(ref v) => match v.node {
1624 ExprKind::Lit(ref lit) => { lit.node.clone() }
1625 _ => { return self.unexpected_last(&self.token); }
1627 _ => { return self.unexpected_last(&self.token); }
1629 token::Literal(lit, suf) => {
1630 let diag = Some((self.span, &self.sess.span_diagnostic));
1631 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1635 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1640 _ => { return self.unexpected_last(&self.token); }
1647 /// Matches lit = true | false | token_lit
1648 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1650 let lit = if self.eat_keyword(keywords::True) {
1652 } else if self.eat_keyword(keywords::False) {
1653 LitKind::Bool(false)
1655 let lit = self.parse_lit_token()?;
1658 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1661 /// matches '-' lit | lit
1662 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1663 let minus_lo = self.span;
1664 let minus_present = self.eat(&token::BinOp(token::Minus));
1666 let literal = P(self.parse_lit()?);
1667 let hi = self.prev_span;
1668 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1671 let minus_hi = self.prev_span;
1672 let unary = self.mk_unary(UnOp::Neg, expr);
1673 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1679 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1681 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1685 _ => self.parse_ident(),
1689 /// Parses qualified path.
1691 /// Assumes that the leading `<` has been parsed already.
1693 /// Qualifed paths are a part of the universal function call
1696 /// `qualified_path = <type [as trait_ref]>::path`
1698 /// See `parse_path` for `mode` meaning.
1703 /// `<T as U>::F::a::<S>`
1704 pub fn parse_qualified_path(&mut self, mode: PathStyle)
1705 -> PResult<'a, (QSelf, ast::Path)> {
1706 let span = self.prev_span;
1707 let self_type = self.parse_ty()?;
1708 let mut path = if self.eat_keyword(keywords::As) {
1709 self.parse_path(PathStyle::Type)?
1719 position: path.segments.len()
1722 self.expect(&token::Gt)?;
1723 self.expect(&token::ModSep)?;
1725 let segments = match mode {
1726 PathStyle::Type => {
1727 self.parse_path_segments_without_colons()?
1729 PathStyle::Expr => {
1730 self.parse_path_segments_with_colons()?
1733 self.parse_path_segments_without_types()?
1736 path.segments.extend(segments);
1738 path.span.hi = self.prev_span.hi;
1743 /// Parses a path and optional type parameter bounds, depending on the
1744 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1745 /// bounds are permitted and whether `::` must precede type parameter
1747 pub fn parse_path(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1748 maybe_whole!(self, NtPath, |x| x);
1750 let lo = self.meta_var_span.unwrap_or(self.span);
1751 let is_global = self.eat(&token::ModSep);
1753 // Parse any number of segments and bound sets. A segment is an
1754 // identifier followed by an optional lifetime and a set of types.
1755 // A bound set is a set of type parameter bounds.
1756 let mut segments = match mode {
1757 PathStyle::Type => {
1758 self.parse_path_segments_without_colons()?
1760 PathStyle::Expr => {
1761 self.parse_path_segments_with_colons()?
1764 self.parse_path_segments_without_types()?
1769 segments.insert(0, PathSegment::crate_root());
1772 // Assemble the result.
1774 span: lo.to(self.prev_span),
1779 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1780 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1781 pub fn parse_path_allowing_meta(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1782 let meta_ident = match self.token {
1783 token::Interpolated(ref nt) => match **nt {
1784 token::NtMeta(ref meta) => match meta.node {
1785 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
1792 if let Some(ident) = meta_ident {
1794 return Ok(ast::Path::from_ident(self.prev_span, ident));
1796 self.parse_path(mode)
1800 /// - `a::b<T,U>::c<V,W>`
1801 /// - `a::b<T,U>::c(V) -> W`
1802 /// - `a::b<T,U>::c(V)`
1803 pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1804 let mut segments = Vec::new();
1806 // First, parse an identifier.
1807 let ident_span = self.span;
1808 let identifier = self.parse_path_segment_ident()?;
1810 if self.check(&token::ModSep) && self.look_ahead(1, |t| *t == token::Lt) {
1812 let prev_span = self.prev_span;
1814 let mut err = self.diagnostic().struct_span_err(prev_span,
1815 "unexpected token: `::`");
1817 "use `<...>` instead of `::<...>` if you meant to specify type arguments");
1821 // Parse types, optionally.
1822 let parameters = if self.eat_lt() {
1823 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1825 ast::AngleBracketedParameterData {
1826 lifetimes: lifetimes,
1830 } else if self.eat(&token::OpenDelim(token::Paren)) {
1831 let lo = self.prev_span;
1833 let inputs = self.parse_seq_to_end(
1834 &token::CloseDelim(token::Paren),
1835 SeqSep::trailing_allowed(token::Comma),
1838 let output_ty = if self.eat(&token::RArrow) {
1839 Some(self.parse_ty_no_plus()?)
1844 let hi = self.prev_span;
1846 Some(P(ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData {
1855 // Assemble and push the result.
1856 segments.push(PathSegment {
1857 identifier: identifier,
1859 parameters: parameters
1862 // Continue only if we see a `::`
1863 if !self.eat(&token::ModSep) {
1864 return Ok(segments);
1870 /// - `a::b::<T,U>::c`
1871 pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1872 let mut segments = Vec::new();
1874 // First, parse an identifier.
1875 let ident_span = self.span;
1876 let identifier = self.parse_path_segment_ident()?;
1878 // If we do not see a `::`, stop.
1879 if !self.eat(&token::ModSep) {
1880 segments.push(PathSegment::from_ident(identifier, ident_span));
1881 return Ok(segments);
1884 // Check for a type segment.
1886 // Consumed `a::b::<`, go look for types
1887 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1889 segments.push(PathSegment {
1890 identifier: identifier,
1892 parameters: ast::AngleBracketedParameterData {
1893 lifetimes: lifetimes,
1899 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1900 if !self.eat(&token::ModSep) {
1901 return Ok(segments);
1904 // Consumed `a::`, go look for `b`
1905 segments.push(PathSegment::from_ident(identifier, ident_span));
1912 pub fn parse_path_segments_without_types(&mut self)
1913 -> PResult<'a, Vec<PathSegment>> {
1914 let mut segments = Vec::new();
1916 // First, parse an identifier.
1917 let ident_span = self.span;
1918 let identifier = self.parse_path_segment_ident()?;
1920 // Assemble and push the result.
1921 segments.push(PathSegment::from_ident(identifier, ident_span));
1923 // If we do not see a `::` or see `::{`/`::*`, stop.
1924 if !self.check(&token::ModSep) || self.is_import_coupler() {
1925 return Ok(segments);
1932 fn check_lifetime(&mut self) -> bool {
1933 self.expected_tokens.push(TokenType::Lifetime);
1934 self.token.is_lifetime()
1937 /// Parse single lifetime 'a or panic.
1938 fn expect_lifetime(&mut self) -> Lifetime {
1940 token::Lifetime(ident) => {
1941 let ident_span = self.span;
1943 Lifetime { ident: ident, span: ident_span, id: ast::DUMMY_NODE_ID }
1945 _ => self.span_bug(self.span, "not a lifetime")
1949 /// Parse mutability (`mut` or nothing).
1950 fn parse_mutability(&mut self) -> Mutability {
1951 if self.eat_keyword(keywords::Mut) {
1954 Mutability::Immutable
1958 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1959 if let token::Literal(token::Integer(name), None) = self.token {
1961 Ok(Ident::with_empty_ctxt(name))
1967 /// Parse ident (COLON expr)?
1968 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1969 let attrs = self.parse_outer_attributes()?;
1973 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1974 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1975 let fieldname = self.parse_field_name()?;
1977 hi = self.prev_span;
1978 (fieldname, self.parse_expr()?, false)
1980 let fieldname = self.parse_ident()?;
1981 hi = self.prev_span;
1983 // Mimic `x: x` for the `x` field shorthand.
1984 let path = ast::Path::from_ident(lo.to(hi), fieldname);
1985 (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
1988 ident: respan(lo.to(hi), fieldname),
1989 span: lo.to(expr.span),
1991 is_shorthand: is_shorthand,
1992 attrs: attrs.into(),
1996 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1998 id: ast::DUMMY_NODE_ID,
2001 attrs: attrs.into(),
2005 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2006 ExprKind::Unary(unop, expr)
2009 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2010 ExprKind::Binary(binop, lhs, rhs)
2013 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2014 ExprKind::Call(f, args)
2017 fn mk_method_call(&mut self,
2018 ident: ast::SpannedIdent,
2022 ExprKind::MethodCall(ident, tps, args)
2025 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2026 ExprKind::Index(expr, idx)
2029 pub fn mk_range(&mut self,
2030 start: Option<P<Expr>>,
2031 end: Option<P<Expr>>,
2032 limits: RangeLimits)
2033 -> PResult<'a, ast::ExprKind> {
2034 if end.is_none() && limits == RangeLimits::Closed {
2035 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2037 Ok(ExprKind::Range(start, end, limits))
2041 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::ExprKind {
2042 ExprKind::Field(expr, ident)
2045 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2046 ExprKind::TupField(expr, idx)
2049 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2050 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2051 ExprKind::AssignOp(binop, lhs, rhs)
2054 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2056 id: ast::DUMMY_NODE_ID,
2057 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2063 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2064 let span = &self.span;
2065 let lv_lit = P(codemap::Spanned {
2066 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2071 id: ast::DUMMY_NODE_ID,
2072 node: ExprKind::Lit(lv_lit),
2078 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2080 token::OpenDelim(delim) => match self.parse_token_tree() {
2081 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2082 _ => unreachable!(),
2084 _ => Err(self.fatal("expected open delimiter")),
2088 /// At the bottom (top?) of the precedence hierarchy,
2089 /// parse things like parenthesized exprs,
2090 /// macros, return, etc.
2092 /// NB: This does not parse outer attributes,
2093 /// and is private because it only works
2094 /// correctly if called from parse_dot_or_call_expr().
2095 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2096 maybe_whole_expr!(self);
2098 // Outer attributes are already parsed and will be
2099 // added to the return value after the fact.
2101 // Therefore, prevent sub-parser from parsing
2102 // attributes by giving them a empty "already parsed" list.
2103 let mut attrs = ThinVec::new();
2106 let mut hi = self.span;
2110 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2112 token::OpenDelim(token::Paren) => {
2115 attrs.extend(self.parse_inner_attributes()?);
2117 // (e) is parenthesized e
2118 // (e,) is a tuple with only one field, e
2119 let mut es = vec![];
2120 let mut trailing_comma = false;
2121 while self.token != token::CloseDelim(token::Paren) {
2122 es.push(self.parse_expr()?);
2123 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2124 if self.check(&token::Comma) {
2125 trailing_comma = true;
2129 trailing_comma = false;
2135 hi = self.prev_span;
2136 let span = lo.to(hi);
2137 return if es.len() == 1 && !trailing_comma {
2138 Ok(self.mk_expr(span, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2140 Ok(self.mk_expr(span, ExprKind::Tup(es), attrs))
2143 token::OpenDelim(token::Brace) => {
2144 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2146 token::BinOp(token::Or) | token::OrOr => {
2148 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2150 token::OpenDelim(token::Bracket) => {
2153 attrs.extend(self.parse_inner_attributes()?);
2155 if self.check(&token::CloseDelim(token::Bracket)) {
2158 ex = ExprKind::Array(Vec::new());
2161 let first_expr = self.parse_expr()?;
2162 if self.check(&token::Semi) {
2163 // Repeating array syntax: [ 0; 512 ]
2165 let count = self.parse_expr()?;
2166 self.expect(&token::CloseDelim(token::Bracket))?;
2167 ex = ExprKind::Repeat(first_expr, count);
2168 } else if self.check(&token::Comma) {
2169 // Vector with two or more elements.
2171 let remaining_exprs = self.parse_seq_to_end(
2172 &token::CloseDelim(token::Bracket),
2173 SeqSep::trailing_allowed(token::Comma),
2174 |p| Ok(p.parse_expr()?)
2176 let mut exprs = vec![first_expr];
2177 exprs.extend(remaining_exprs);
2178 ex = ExprKind::Array(exprs);
2180 // Vector with one element.
2181 self.expect(&token::CloseDelim(token::Bracket))?;
2182 ex = ExprKind::Array(vec![first_expr]);
2185 hi = self.prev_span;
2190 self.parse_qualified_path(PathStyle::Expr)?;
2192 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2194 if self.eat_keyword(keywords::Move) {
2195 let lo = self.prev_span;
2196 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2198 if self.eat_keyword(keywords::If) {
2199 return self.parse_if_expr(attrs);
2201 if self.eat_keyword(keywords::For) {
2202 let lo = self.prev_span;
2203 return self.parse_for_expr(None, lo, attrs);
2205 if self.eat_keyword(keywords::While) {
2206 let lo = self.prev_span;
2207 return self.parse_while_expr(None, lo, attrs);
2209 if self.token.is_lifetime() {
2210 let label = Spanned { node: self.get_label(),
2214 self.expect(&token::Colon)?;
2215 if self.eat_keyword(keywords::While) {
2216 return self.parse_while_expr(Some(label), lo, attrs)
2218 if self.eat_keyword(keywords::For) {
2219 return self.parse_for_expr(Some(label), lo, attrs)
2221 if self.eat_keyword(keywords::Loop) {
2222 return self.parse_loop_expr(Some(label), lo, attrs)
2224 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2226 if self.eat_keyword(keywords::Loop) {
2227 let lo = self.prev_span;
2228 return self.parse_loop_expr(None, lo, attrs);
2230 if self.eat_keyword(keywords::Continue) {
2231 let ex = if self.token.is_lifetime() {
2232 let ex = ExprKind::Continue(Some(Spanned{
2233 node: self.get_label(),
2239 ExprKind::Continue(None)
2241 let hi = self.prev_span;
2242 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2244 if self.eat_keyword(keywords::Match) {
2245 return self.parse_match_expr(attrs);
2247 if self.eat_keyword(keywords::Unsafe) {
2248 return self.parse_block_expr(
2250 BlockCheckMode::Unsafe(ast::UserProvided),
2253 if self.is_catch_expr() {
2254 assert!(self.eat_keyword(keywords::Do));
2255 assert!(self.eat_keyword(keywords::Catch));
2256 let lo = self.prev_span;
2257 return self.parse_catch_expr(lo, attrs);
2259 if self.eat_keyword(keywords::Return) {
2260 if self.token.can_begin_expr() {
2261 let e = self.parse_expr()?;
2263 ex = ExprKind::Ret(Some(e));
2265 ex = ExprKind::Ret(None);
2267 } else if self.eat_keyword(keywords::Break) {
2268 let lt = if self.token.is_lifetime() {
2269 let spanned_lt = Spanned {
2270 node: self.get_label(),
2278 let e = if self.token.can_begin_expr()
2279 && !(self.token == token::OpenDelim(token::Brace)
2280 && self.restrictions.contains(
2281 RESTRICTION_NO_STRUCT_LITERAL)) {
2282 Some(self.parse_expr()?)
2286 ex = ExprKind::Break(lt, e);
2287 hi = self.prev_span;
2288 } else if self.token.is_keyword(keywords::Let) {
2289 // Catch this syntax error here, instead of in `check_strict_keywords`, so
2290 // that we can explicitly mention that let is not to be used as an expression
2291 let mut db = self.fatal("expected expression, found statement (`let`)");
2292 db.note("variable declaration using `let` is a statement");
2294 } else if self.token.is_path_start() {
2295 let pth = self.parse_path(PathStyle::Expr)?;
2297 // `!`, as an operator, is prefix, so we know this isn't that
2298 if self.eat(&token::Not) {
2299 // MACRO INVOCATION expression
2300 let (_, tts) = self.expect_delimited_token_tree()?;
2301 let hi = self.prev_span;
2302 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2304 if self.check(&token::OpenDelim(token::Brace)) {
2305 // This is a struct literal, unless we're prohibited
2306 // from parsing struct literals here.
2307 let prohibited = self.restrictions.contains(
2308 RESTRICTION_NO_STRUCT_LITERAL
2311 return self.parse_struct_expr(lo, pth, attrs);
2316 ex = ExprKind::Path(None, pth);
2318 match self.parse_lit() {
2321 ex = ExprKind::Lit(P(lit));
2324 self.cancel(&mut err);
2325 let msg = format!("expected expression, found {}",
2326 self.this_token_descr());
2327 return Err(self.fatal(&msg));
2334 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2337 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2338 -> PResult<'a, P<Expr>> {
2340 let mut fields = Vec::new();
2341 let mut base = None;
2343 attrs.extend(self.parse_inner_attributes()?);
2345 while self.token != token::CloseDelim(token::Brace) {
2346 if self.eat(&token::DotDot) {
2347 match self.parse_expr() {
2353 self.recover_stmt();
2359 match self.parse_field() {
2360 Ok(f) => fields.push(f),
2363 self.recover_stmt();
2368 match self.expect_one_of(&[token::Comma],
2369 &[token::CloseDelim(token::Brace)]) {
2373 self.recover_stmt();
2379 let span = lo.to(self.span);
2380 self.expect(&token::CloseDelim(token::Brace))?;
2381 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2384 fn parse_or_use_outer_attributes(&mut self,
2385 already_parsed_attrs: Option<ThinVec<Attribute>>)
2386 -> PResult<'a, ThinVec<Attribute>> {
2387 if let Some(attrs) = already_parsed_attrs {
2390 self.parse_outer_attributes().map(|a| a.into())
2394 /// Parse a block or unsafe block
2395 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2396 outer_attrs: ThinVec<Attribute>)
2397 -> PResult<'a, P<Expr>> {
2399 self.expect(&token::OpenDelim(token::Brace))?;
2401 let mut attrs = outer_attrs;
2402 attrs.extend(self.parse_inner_attributes()?);
2404 let blk = self.parse_block_tail(lo, blk_mode)?;
2405 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2408 /// parse a.b or a(13) or a[4] or just a
2409 pub fn parse_dot_or_call_expr(&mut self,
2410 already_parsed_attrs: Option<ThinVec<Attribute>>)
2411 -> PResult<'a, P<Expr>> {
2412 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2414 let b = self.parse_bottom_expr();
2415 let (span, b) = self.interpolated_or_expr_span(b)?;
2416 self.parse_dot_or_call_expr_with(b, span, attrs)
2419 pub fn parse_dot_or_call_expr_with(&mut self,
2422 mut attrs: ThinVec<Attribute>)
2423 -> PResult<'a, P<Expr>> {
2424 // Stitch the list of outer attributes onto the return value.
2425 // A little bit ugly, but the best way given the current code
2427 self.parse_dot_or_call_expr_with_(e0, lo)
2429 expr.map(|mut expr| {
2430 attrs.extend::<Vec<_>>(expr.attrs.into());
2433 ExprKind::If(..) | ExprKind::IfLet(..) => {
2434 if !expr.attrs.is_empty() {
2435 // Just point to the first attribute in there...
2436 let span = expr.attrs[0].span;
2439 "attributes are not yet allowed on `if` \
2450 // Assuming we have just parsed `.foo` (i.e., a dot and an ident), continue
2451 // parsing into an expression.
2452 fn parse_dot_suffix(&mut self, ident: Ident, ident_span: Span, self_value: P<Expr>, lo: Span)
2453 -> PResult<'a, P<Expr>> {
2454 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2456 let args = self.parse_generic_args()?;
2460 (Vec::new(), Vec::new(), Vec::new())
2463 if !bindings.is_empty() {
2464 let prev_span = self.prev_span;
2465 self.span_err(prev_span, "type bindings are only permitted on trait paths");
2468 Ok(match self.token {
2469 // expr.f() method call.
2470 token::OpenDelim(token::Paren) => {
2471 let mut es = self.parse_unspanned_seq(
2472 &token::OpenDelim(token::Paren),
2473 &token::CloseDelim(token::Paren),
2474 SeqSep::trailing_allowed(token::Comma),
2475 |p| Ok(p.parse_expr()?)
2477 let hi = self.prev_span;
2479 es.insert(0, self_value);
2480 let id = respan(ident_span.to(ident_span), ident);
2481 let nd = self.mk_method_call(id, tys, es);
2482 self.mk_expr(lo.to(hi), nd, ThinVec::new())
2486 if !tys.is_empty() {
2487 let prev_span = self.prev_span;
2488 self.span_err(prev_span,
2489 "field expressions may not \
2490 have type parameters");
2493 let id = respan(ident_span.to(ident_span), ident);
2494 let field = self.mk_field(self_value, id);
2495 self.mk_expr(lo.to(ident_span), field, ThinVec::new())
2500 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2505 while self.eat(&token::Question) {
2506 let hi = self.prev_span;
2507 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2511 if self.eat(&token::Dot) {
2513 token::Ident(i) => {
2514 let ident_span = self.span;
2516 e = self.parse_dot_suffix(i, ident_span, e, lo)?;
2518 token::Literal(token::Integer(n), suf) => {
2521 // A tuple index may not have a suffix
2522 self.expect_no_suffix(sp, "tuple index", suf);
2524 let dot_span = self.prev_span;
2528 let index = n.as_str().parse::<usize>().ok();
2531 let id = respan(dot_span.to(hi), n);
2532 let field = self.mk_tup_field(e, id);
2533 e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2536 let prev_span = self.prev_span;
2537 self.span_err(prev_span, "invalid tuple or tuple struct index");
2541 token::Literal(token::Float(n), _suf) => {
2543 let fstr = n.as_str();
2544 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2545 &format!("unexpected token: `{}`", n));
2546 err.span_label(self.prev_span, "unexpected token");
2547 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2548 let float = match fstr.parse::<f64>().ok() {
2552 let sugg = pprust::to_string(|s| {
2553 use print::pprust::PrintState;
2554 use print::pp::word;
2557 word(&mut s.s, ".")?;
2558 s.print_usize(float.trunc() as usize)?;
2560 word(&mut s.s, ".")?;
2561 word(&mut s.s, fstr.splitn(2, ".").last().unwrap())
2563 err.span_suggestion(
2564 lo.to(self.prev_span),
2565 "try parenthesizing the first index",
2572 // FIXME Could factor this out into non_fatal_unexpected or something.
2573 let actual = self.this_token_to_string();
2574 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2576 let dot_span = self.prev_span;
2577 e = self.parse_dot_suffix(keywords::Invalid.ident(), dot_span, e, lo)?;
2582 if self.expr_is_complete(&e) { break; }
2585 token::OpenDelim(token::Paren) => {
2586 let es = self.parse_unspanned_seq(
2587 &token::OpenDelim(token::Paren),
2588 &token::CloseDelim(token::Paren),
2589 SeqSep::trailing_allowed(token::Comma),
2590 |p| Ok(p.parse_expr()?)
2592 hi = self.prev_span;
2594 let nd = self.mk_call(e, es);
2595 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2599 // Could be either an index expression or a slicing expression.
2600 token::OpenDelim(token::Bracket) => {
2602 let ix = self.parse_expr()?;
2604 self.expect(&token::CloseDelim(token::Bracket))?;
2605 let index = self.mk_index(e, ix);
2606 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2614 pub fn process_potential_macro_variable(&mut self) {
2615 let ident = match self.token {
2616 token::SubstNt(name) => {
2617 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2620 token::Interpolated(ref nt) => {
2621 self.meta_var_span = Some(self.span);
2623 token::NtIdent(ident) => ident,
2629 self.token = token::Ident(ident.node);
2630 self.span = ident.span;
2633 /// parse a single token tree from the input.
2634 pub fn parse_token_tree(&mut self) -> TokenTree {
2636 token::OpenDelim(..) => {
2637 let frame = mem::replace(&mut self.token_cursor.frame,
2638 self.token_cursor.stack.pop().unwrap());
2639 self.span = frame.span;
2641 TokenTree::Delimited(frame.span, Delimited {
2643 tts: frame.tree_cursor.original_stream().into(),
2646 token::CloseDelim(_) | token::Eof => unreachable!(),
2648 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2650 TokenTree::Token(span, token)
2655 // parse a stream of tokens into a list of TokenTree's,
2657 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2658 let mut tts = Vec::new();
2659 while self.token != token::Eof {
2660 tts.push(self.parse_token_tree());
2665 pub fn parse_tokens(&mut self) -> TokenStream {
2666 let mut result = Vec::new();
2669 token::Eof | token::CloseDelim(..) => break,
2670 _ => result.push(self.parse_token_tree().into()),
2673 TokenStream::concat(result)
2676 /// Parse a prefix-unary-operator expr
2677 pub fn parse_prefix_expr(&mut self,
2678 already_parsed_attrs: Option<ThinVec<Attribute>>)
2679 -> PResult<'a, P<Expr>> {
2680 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2682 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2683 let (hi, ex) = match self.token {
2686 let e = self.parse_prefix_expr(None);
2687 let (span, e) = self.interpolated_or_expr_span(e)?;
2688 (span, self.mk_unary(UnOp::Not, e))
2690 // Suggest `!` for bitwise negation when encountering a `~`
2693 let e = self.parse_prefix_expr(None);
2694 let (span, e) = self.interpolated_or_expr_span(e)?;
2695 let span_of_tilde = lo;
2696 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2697 "`~` can not be used as a unary operator");
2698 err.span_label(span_of_tilde, "did you mean `!`?");
2699 err.help("use `!` instead of `~` if you meant to perform bitwise negation");
2701 (span, self.mk_unary(UnOp::Not, e))
2703 token::BinOp(token::Minus) => {
2705 let e = self.parse_prefix_expr(None);
2706 let (span, e) = self.interpolated_or_expr_span(e)?;
2707 (span, self.mk_unary(UnOp::Neg, e))
2709 token::BinOp(token::Star) => {
2711 let e = self.parse_prefix_expr(None);
2712 let (span, e) = self.interpolated_or_expr_span(e)?;
2713 (span, self.mk_unary(UnOp::Deref, e))
2715 token::BinOp(token::And) | token::AndAnd => {
2717 let m = self.parse_mutability();
2718 let e = self.parse_prefix_expr(None);
2719 let (span, e) = self.interpolated_or_expr_span(e)?;
2720 (span, ExprKind::AddrOf(m, e))
2722 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2724 let place = self.parse_expr_res(
2725 RESTRICTION_NO_STRUCT_LITERAL,
2728 let blk = self.parse_block()?;
2729 let span = blk.span;
2730 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2731 (span, ExprKind::InPlace(place, blk_expr))
2733 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2735 let e = self.parse_prefix_expr(None);
2736 let (span, e) = self.interpolated_or_expr_span(e)?;
2737 (span, ExprKind::Box(e))
2739 _ => return self.parse_dot_or_call_expr(Some(attrs))
2741 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2744 /// Parse an associative expression
2746 /// This parses an expression accounting for associativity and precedence of the operators in
2748 pub fn parse_assoc_expr(&mut self,
2749 already_parsed_attrs: Option<ThinVec<Attribute>>)
2750 -> PResult<'a, P<Expr>> {
2751 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2754 /// Parse an associative expression with operators of at least `min_prec` precedence
2755 pub fn parse_assoc_expr_with(&mut self,
2758 -> PResult<'a, P<Expr>> {
2759 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2762 let attrs = match lhs {
2763 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2766 if self.token == token::DotDot || self.token == token::DotDotDot {
2767 return self.parse_prefix_range_expr(attrs);
2769 self.parse_prefix_expr(attrs)?
2773 if self.expr_is_complete(&lhs) {
2774 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2777 self.expected_tokens.push(TokenType::Operator);
2778 while let Some(op) = AssocOp::from_token(&self.token) {
2780 let lhs_span = if self.prev_token_kind == PrevTokenKind::Interpolated {
2786 let cur_op_span = self.span;
2787 let restrictions = if op.is_assign_like() {
2788 self.restrictions & RESTRICTION_NO_STRUCT_LITERAL
2792 if op.precedence() < min_prec {
2796 if op.is_comparison() {
2797 self.check_no_chained_comparison(&lhs, &op);
2800 if op == AssocOp::As {
2801 let rhs = self.parse_ty_no_plus()?;
2802 lhs = self.mk_expr(lhs_span.to(rhs.span), ExprKind::Cast(lhs, rhs), ThinVec::new());
2804 } else if op == AssocOp::Colon {
2805 let rhs = self.parse_ty_no_plus()?;
2806 lhs = self.mk_expr(lhs_span.to(rhs.span), ExprKind::Type(lhs, rhs), ThinVec::new());
2808 } else if op == AssocOp::DotDot || op == AssocOp::DotDotDot {
2809 // If we didn’t have to handle `x..`/`x...`, it would be pretty easy to
2810 // generalise it to the Fixity::None code.
2812 // We have 2 alternatives here: `x..y`/`x...y` and `x..`/`x...` The other
2813 // two variants are handled with `parse_prefix_range_expr` call above.
2814 let rhs = if self.is_at_start_of_range_notation_rhs() {
2815 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2816 LhsExpr::NotYetParsed)?)
2820 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2825 let limits = if op == AssocOp::DotDot {
2826 RangeLimits::HalfOpen
2831 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2832 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2836 let rhs = match op.fixity() {
2837 Fixity::Right => self.with_res(
2838 restrictions - RESTRICTION_STMT_EXPR,
2840 this.parse_assoc_expr_with(op.precedence(),
2841 LhsExpr::NotYetParsed)
2843 Fixity::Left => self.with_res(
2844 restrictions - RESTRICTION_STMT_EXPR,
2846 this.parse_assoc_expr_with(op.precedence() + 1,
2847 LhsExpr::NotYetParsed)
2849 // We currently have no non-associative operators that are not handled above by
2850 // the special cases. The code is here only for future convenience.
2851 Fixity::None => self.with_res(
2852 restrictions - RESTRICTION_STMT_EXPR,
2854 this.parse_assoc_expr_with(op.precedence() + 1,
2855 LhsExpr::NotYetParsed)
2859 let span = lhs_span.to(rhs.span);
2861 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2862 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2863 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2864 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2865 AssocOp::Greater | AssocOp::GreaterEqual => {
2866 let ast_op = op.to_ast_binop().unwrap();
2867 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2868 self.mk_expr(span, binary, ThinVec::new())
2871 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2873 self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
2874 AssocOp::AssignOp(k) => {
2876 token::Plus => BinOpKind::Add,
2877 token::Minus => BinOpKind::Sub,
2878 token::Star => BinOpKind::Mul,
2879 token::Slash => BinOpKind::Div,
2880 token::Percent => BinOpKind::Rem,
2881 token::Caret => BinOpKind::BitXor,
2882 token::And => BinOpKind::BitAnd,
2883 token::Or => BinOpKind::BitOr,
2884 token::Shl => BinOpKind::Shl,
2885 token::Shr => BinOpKind::Shr,
2887 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2888 self.mk_expr(span, aopexpr, ThinVec::new())
2890 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotDot => {
2891 self.bug("As, Colon, DotDot or DotDotDot branch reached")
2895 if op.fixity() == Fixity::None { break }
2900 /// Produce an error if comparison operators are chained (RFC #558).
2901 /// We only need to check lhs, not rhs, because all comparison ops
2902 /// have same precedence and are left-associative
2903 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2904 debug_assert!(outer_op.is_comparison());
2906 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2907 // respan to include both operators
2908 let op_span = op.span.to(self.span);
2909 let mut err = self.diagnostic().struct_span_err(op_span,
2910 "chained comparison operators require parentheses");
2911 if op.node == BinOpKind::Lt &&
2912 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
2913 *outer_op == AssocOp::Greater // even in a case like the following:
2914 { // Foo<Bar<Baz<Qux, ()>>>
2916 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2924 /// Parse prefix-forms of range notation: `..expr`, `..`, `...expr`
2925 fn parse_prefix_range_expr(&mut self,
2926 already_parsed_attrs: Option<ThinVec<Attribute>>)
2927 -> PResult<'a, P<Expr>> {
2928 debug_assert!(self.token == token::DotDot || self.token == token::DotDotDot);
2929 let tok = self.token.clone();
2930 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2932 let mut hi = self.span;
2934 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2935 // RHS must be parsed with more associativity than the dots.
2936 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
2937 Some(self.parse_assoc_expr_with(next_prec,
2938 LhsExpr::NotYetParsed)
2946 let limits = if tok == token::DotDot {
2947 RangeLimits::HalfOpen
2952 let r = try!(self.mk_range(None,
2955 Ok(self.mk_expr(lo.to(hi), r, attrs))
2958 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2959 if self.token.can_begin_expr() {
2960 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2961 if self.token == token::OpenDelim(token::Brace) {
2962 return !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL);
2970 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2971 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
2972 if self.check_keyword(keywords::Let) {
2973 return self.parse_if_let_expr(attrs);
2975 let lo = self.prev_span;
2976 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
2977 let thn = self.parse_block()?;
2978 let mut els: Option<P<Expr>> = None;
2979 let mut hi = thn.span;
2980 if self.eat_keyword(keywords::Else) {
2981 let elexpr = self.parse_else_expr()?;
2985 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
2988 /// Parse an 'if let' expression ('if' token already eaten)
2989 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
2990 -> PResult<'a, P<Expr>> {
2991 let lo = self.prev_span;
2992 self.expect_keyword(keywords::Let)?;
2993 let pat = self.parse_pat()?;
2994 self.expect(&token::Eq)?;
2995 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
2996 let thn = self.parse_block()?;
2997 let (hi, els) = if self.eat_keyword(keywords::Else) {
2998 let expr = self.parse_else_expr()?;
2999 (expr.span, Some(expr))
3003 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
3006 // `move |args| expr`
3007 pub fn parse_lambda_expr(&mut self,
3009 capture_clause: CaptureBy,
3010 attrs: ThinVec<Attribute>)
3011 -> PResult<'a, P<Expr>>
3013 let decl = self.parse_fn_block_decl()?;
3014 let decl_hi = self.prev_span;
3015 let body = match decl.output {
3016 FunctionRetTy::Default(_) => self.parse_expr()?,
3018 // If an explicit return type is given, require a
3019 // block to appear (RFC 968).
3020 let body_lo = self.span;
3021 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3027 ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3031 // `else` token already eaten
3032 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3033 if self.eat_keyword(keywords::If) {
3034 return self.parse_if_expr(ThinVec::new());
3036 let blk = self.parse_block()?;
3037 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3041 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3042 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3044 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3045 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3047 let pat = self.parse_pat()?;
3048 self.expect_keyword(keywords::In)?;
3049 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3050 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3051 attrs.extend(iattrs);
3053 let hi = self.prev_span;
3054 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3057 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3058 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3060 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3061 if self.token.is_keyword(keywords::Let) {
3062 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3064 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3065 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3066 attrs.extend(iattrs);
3067 let span = span_lo.to(body.span);
3068 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3071 /// Parse a 'while let' expression ('while' token already eaten)
3072 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3074 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3075 self.expect_keyword(keywords::Let)?;
3076 let pat = self.parse_pat()?;
3077 self.expect(&token::Eq)?;
3078 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3079 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3080 attrs.extend(iattrs);
3081 let span = span_lo.to(body.span);
3082 return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3085 // parse `loop {...}`, `loop` token already eaten
3086 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3088 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3089 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3090 attrs.extend(iattrs);
3091 let span = span_lo.to(body.span);
3092 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3095 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3096 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3097 -> PResult<'a, P<Expr>>
3099 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3100 attrs.extend(iattrs);
3101 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3104 // `match` token already eaten
3105 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3106 let match_span = self.prev_span;
3107 let lo = self.prev_span;
3108 let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL,
3110 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3111 if self.token == token::Token::Semi {
3112 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3116 attrs.extend(self.parse_inner_attributes()?);
3118 let mut arms: Vec<Arm> = Vec::new();
3119 while self.token != token::CloseDelim(token::Brace) {
3120 match self.parse_arm() {
3121 Ok(arm) => arms.push(arm),
3123 // Recover by skipping to the end of the block.
3125 self.recover_stmt();
3126 let span = lo.to(self.span);
3127 if self.token == token::CloseDelim(token::Brace) {
3130 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3136 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3139 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3140 maybe_whole!(self, NtArm, |x| x);
3142 let attrs = self.parse_outer_attributes()?;
3143 let pats = self.parse_pats()?;
3144 let guard = if self.eat_keyword(keywords::If) {
3145 Some(self.parse_expr()?)
3149 self.expect(&token::FatArrow)?;
3150 let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR, None)?;
3153 !classify::expr_is_simple_block(&expr)
3154 && self.token != token::CloseDelim(token::Brace);
3157 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3159 self.eat(&token::Comma);
3170 /// Parse an expression
3171 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3172 self.parse_expr_res(Restrictions::empty(), None)
3175 /// Evaluate the closure with restrictions in place.
3177 /// After the closure is evaluated, restrictions are reset.
3178 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3179 where F: FnOnce(&mut Self) -> T
3181 let old = self.restrictions;
3182 self.restrictions = r;
3184 self.restrictions = old;
3189 /// Parse an expression, subject to the given restrictions
3190 pub fn parse_expr_res(&mut self, r: Restrictions,
3191 already_parsed_attrs: Option<ThinVec<Attribute>>)
3192 -> PResult<'a, P<Expr>> {
3193 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3196 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3197 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3198 if self.check(&token::Eq) {
3200 Ok(Some(self.parse_expr()?))
3206 /// Parse patterns, separated by '|' s
3207 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3208 let mut pats = Vec::new();
3210 pats.push(self.parse_pat()?);
3211 if self.check(&token::BinOp(token::Or)) { self.bump();}
3212 else { return Ok(pats); }
3216 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3217 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3218 let mut fields = vec![];
3219 let mut ddpos = None;
3221 while !self.check(&token::CloseDelim(token::Paren)) {
3222 if ddpos.is_none() && self.eat(&token::DotDot) {
3223 ddpos = Some(fields.len());
3224 if self.eat(&token::Comma) {
3225 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3226 fields.push(self.parse_pat()?);
3228 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3229 // Emit a friendly error, ignore `..` and continue parsing
3230 self.span_err(self.prev_span, "`..` can only be used once per \
3231 tuple or tuple struct pattern");
3233 fields.push(self.parse_pat()?);
3236 if !self.check(&token::CloseDelim(token::Paren)) ||
3237 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3238 self.expect(&token::Comma)?;
3245 fn parse_pat_vec_elements(
3247 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3248 let mut before = Vec::new();
3249 let mut slice = None;
3250 let mut after = Vec::new();
3251 let mut first = true;
3252 let mut before_slice = true;
3254 while self.token != token::CloseDelim(token::Bracket) {
3258 self.expect(&token::Comma)?;
3260 if self.token == token::CloseDelim(token::Bracket)
3261 && (before_slice || !after.is_empty()) {
3267 if self.eat(&token::DotDot) {
3269 if self.check(&token::Comma) ||
3270 self.check(&token::CloseDelim(token::Bracket)) {
3271 slice = Some(P(ast::Pat {
3272 id: ast::DUMMY_NODE_ID,
3273 node: PatKind::Wild,
3276 before_slice = false;
3282 let subpat = self.parse_pat()?;
3283 if before_slice && self.eat(&token::DotDot) {
3284 slice = Some(subpat);
3285 before_slice = false;
3286 } else if before_slice {
3287 before.push(subpat);
3293 Ok((before, slice, after))
3296 /// Parse the fields of a struct-like pattern
3297 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3298 let mut fields = Vec::new();
3299 let mut etc = false;
3300 let mut first = true;
3301 while self.token != token::CloseDelim(token::Brace) {
3305 self.expect(&token::Comma)?;
3306 // accept trailing commas
3307 if self.check(&token::CloseDelim(token::Brace)) { break }
3310 let attrs = self.parse_outer_attributes()?;
3314 if self.check(&token::DotDot) {
3316 if self.token != token::CloseDelim(token::Brace) {
3317 let token_str = self.this_token_to_string();
3318 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3325 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3326 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3327 // Parsing a pattern of the form "fieldname: pat"
3328 let fieldname = self.parse_field_name()?;
3330 let pat = self.parse_pat()?;
3332 (pat, fieldname, false)
3334 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3335 let is_box = self.eat_keyword(keywords::Box);
3336 let boxed_span = self.span;
3337 let is_ref = self.eat_keyword(keywords::Ref);
3338 let is_mut = self.eat_keyword(keywords::Mut);
3339 let fieldname = self.parse_ident()?;
3340 hi = self.prev_span;
3342 let bind_type = match (is_ref, is_mut) {
3343 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3344 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3345 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3346 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3348 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3349 let fieldpat = P(ast::Pat{
3350 id: ast::DUMMY_NODE_ID,
3351 node: PatKind::Ident(bind_type, fieldpath, None),
3352 span: boxed_span.to(hi),
3355 let subpat = if is_box {
3357 id: ast::DUMMY_NODE_ID,
3358 node: PatKind::Box(fieldpat),
3364 (subpat, fieldname, true)
3367 fields.push(codemap::Spanned { span: lo.to(hi),
3368 node: ast::FieldPat {
3371 is_shorthand: is_shorthand,
3372 attrs: attrs.into(),
3376 return Ok((fields, etc));
3379 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3380 if self.token.is_path_start() {
3382 let (qself, path) = if self.eat_lt() {
3383 // Parse a qualified path
3385 self.parse_qualified_path(PathStyle::Expr)?;
3388 // Parse an unqualified path
3389 (None, self.parse_path(PathStyle::Expr)?)
3391 let hi = self.prev_span;
3392 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3394 self.parse_pat_literal_maybe_minus()
3398 // helper function to decide whether to parse as ident binding or to try to do
3399 // something more complex like range patterns
3400 fn parse_as_ident(&mut self) -> bool {
3401 self.look_ahead(1, |t| match *t {
3402 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3403 token::DotDotDot | token::ModSep | token::Not => Some(false),
3404 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3405 // range pattern branch
3406 token::DotDot => None,
3408 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3409 token::Comma | token::CloseDelim(token::Bracket) => true,
3414 /// Parse a pattern.
3415 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3416 maybe_whole!(self, NtPat, |x| x);
3421 token::Underscore => {
3424 pat = PatKind::Wild;
3426 token::BinOp(token::And) | token::AndAnd => {
3427 // Parse &pat / &mut pat
3429 let mutbl = self.parse_mutability();
3430 if let token::Lifetime(ident) = self.token {
3431 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3433 let subpat = self.parse_pat()?;
3434 pat = PatKind::Ref(subpat, mutbl);
3436 token::OpenDelim(token::Paren) => {
3437 // Parse (pat,pat,pat,...) as tuple pattern
3439 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3440 self.expect(&token::CloseDelim(token::Paren))?;
3441 pat = PatKind::Tuple(fields, ddpos);
3443 token::OpenDelim(token::Bracket) => {
3444 // Parse [pat,pat,...] as slice pattern
3446 let (before, slice, after) = self.parse_pat_vec_elements()?;
3447 self.expect(&token::CloseDelim(token::Bracket))?;
3448 pat = PatKind::Slice(before, slice, after);
3450 // At this point, token != _, &, &&, (, [
3451 _ => if self.eat_keyword(keywords::Mut) {
3452 // Parse mut ident @ pat
3453 pat = self.parse_pat_ident(BindingMode::ByValue(Mutability::Mutable))?;
3454 } else if self.eat_keyword(keywords::Ref) {
3455 // Parse ref ident @ pat / ref mut ident @ pat
3456 let mutbl = self.parse_mutability();
3457 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3458 } else if self.eat_keyword(keywords::Box) {
3460 let subpat = self.parse_pat()?;
3461 pat = PatKind::Box(subpat);
3462 } else if self.token.is_ident() && !self.token.is_any_keyword() &&
3463 self.parse_as_ident() {
3464 // Parse ident @ pat
3465 // This can give false positives and parse nullary enums,
3466 // they are dealt with later in resolve
3467 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3468 pat = self.parse_pat_ident(binding_mode)?;
3469 } else if self.token.is_path_start() {
3470 // Parse pattern starting with a path
3471 let (qself, path) = if self.eat_lt() {
3472 // Parse a qualified path
3473 let (qself, path) = self.parse_qualified_path(PathStyle::Expr)?;
3476 // Parse an unqualified path
3477 (None, self.parse_path(PathStyle::Expr)?)
3480 token::Not if qself.is_none() => {
3481 // Parse macro invocation
3483 let (_, tts) = self.expect_delimited_token_tree()?;
3484 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3485 pat = PatKind::Mac(mac);
3487 token::DotDotDot | token::DotDot => {
3488 let end_kind = match self.token {
3489 token::DotDot => RangeEnd::Excluded,
3490 token::DotDotDot => RangeEnd::Included,
3491 _ => panic!("can only parse `..` or `...` for ranges (checked above)"),
3494 let span = lo.to(self.prev_span);
3495 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3497 let end = self.parse_pat_range_end()?;
3498 pat = PatKind::Range(begin, end, end_kind);
3500 token::OpenDelim(token::Brace) => {
3501 if qself.is_some() {
3502 return Err(self.fatal("unexpected `{` after qualified path"));
3504 // Parse struct pattern
3506 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3508 self.recover_stmt();
3512 pat = PatKind::Struct(path, fields, etc);
3514 token::OpenDelim(token::Paren) => {
3515 if qself.is_some() {
3516 return Err(self.fatal("unexpected `(` after qualified path"));
3518 // Parse tuple struct or enum pattern
3520 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3521 self.expect(&token::CloseDelim(token::Paren))?;
3522 pat = PatKind::TupleStruct(path, fields, ddpos)
3524 _ => pat = PatKind::Path(qself, path),
3527 // Try to parse everything else as literal with optional minus
3528 match self.parse_pat_literal_maybe_minus() {
3530 if self.eat(&token::DotDotDot) {
3531 let end = self.parse_pat_range_end()?;
3532 pat = PatKind::Range(begin, end, RangeEnd::Included);
3533 } else if self.eat(&token::DotDot) {
3534 let end = self.parse_pat_range_end()?;
3535 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3537 pat = PatKind::Lit(begin);
3541 self.cancel(&mut err);
3542 let msg = format!("expected pattern, found {}", self.this_token_descr());
3543 return Err(self.fatal(&msg));
3550 id: ast::DUMMY_NODE_ID,
3552 span: lo.to(self.prev_span),
3556 /// Parse ident or ident @ pat
3557 /// used by the copy foo and ref foo patterns to give a good
3558 /// error message when parsing mistakes like ref foo(a,b)
3559 fn parse_pat_ident(&mut self,
3560 binding_mode: ast::BindingMode)
3561 -> PResult<'a, PatKind> {
3562 let ident_span = self.span;
3563 let ident = self.parse_ident()?;
3564 let name = codemap::Spanned{span: ident_span, node: ident};
3565 let sub = if self.eat(&token::At) {
3566 Some(self.parse_pat()?)
3571 // just to be friendly, if they write something like
3573 // we end up here with ( as the current token. This shortly
3574 // leads to a parse error. Note that if there is no explicit
3575 // binding mode then we do not end up here, because the lookahead
3576 // will direct us over to parse_enum_variant()
3577 if self.token == token::OpenDelim(token::Paren) {
3578 return Err(self.span_fatal(
3580 "expected identifier, found enum pattern"))
3583 Ok(PatKind::Ident(binding_mode, name, sub))
3586 /// Parse a local variable declaration
3587 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3589 let pat = self.parse_pat()?;
3591 let ty = if self.eat(&token::Colon) {
3592 Some(self.parse_ty()?)
3596 let init = self.parse_initializer()?;
3601 id: ast::DUMMY_NODE_ID,
3602 span: lo.to(self.prev_span),
3607 /// Parse a structure field
3608 fn parse_name_and_ty(&mut self,
3611 attrs: Vec<Attribute>)
3612 -> PResult<'a, StructField> {
3613 let name = self.parse_ident()?;
3614 self.expect(&token::Colon)?;
3615 let ty = self.parse_ty()?;
3617 span: lo.to(self.prev_span),
3620 id: ast::DUMMY_NODE_ID,
3626 /// Emit an expected item after attributes error.
3627 fn expected_item_err(&self, attrs: &[Attribute]) {
3628 let message = match attrs.last() {
3629 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3630 _ => "expected item after attributes",
3633 self.span_err(self.prev_span, message);
3636 /// Parse a statement. This stops just before trailing semicolons on everything but items.
3637 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3638 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3639 Ok(self.parse_stmt_(true))
3642 // Eat tokens until we can be relatively sure we reached the end of the
3643 // statement. This is something of a best-effort heuristic.
3645 // We terminate when we find an unmatched `}` (without consuming it).
3646 fn recover_stmt(&mut self) {
3647 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
3650 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3651 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3652 // approximate - it can mean we break too early due to macros, but that
3653 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3655 // If `break_on_block` is `Break`, then we will stop consuming tokens
3656 // after finding (and consuming) a brace-delimited block.
3657 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
3658 let mut brace_depth = 0;
3659 let mut bracket_depth = 0;
3660 let mut in_block = false;
3661 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
3662 break_on_semi, break_on_block);
3664 debug!("recover_stmt_ loop {:?}", self.token);
3666 token::OpenDelim(token::DelimToken::Brace) => {
3669 if break_on_block == BlockMode::Break &&
3671 bracket_depth == 0 {
3675 token::OpenDelim(token::DelimToken::Bracket) => {
3679 token::CloseDelim(token::DelimToken::Brace) => {
3680 if brace_depth == 0 {
3681 debug!("recover_stmt_ return - close delim {:?}", self.token);
3686 if in_block && bracket_depth == 0 && brace_depth == 0 {
3687 debug!("recover_stmt_ return - block end {:?}", self.token);
3691 token::CloseDelim(token::DelimToken::Bracket) => {
3693 if bracket_depth < 0 {
3699 debug!("recover_stmt_ return - Eof");
3704 if break_on_semi == SemiColonMode::Break &&
3706 bracket_depth == 0 {
3707 debug!("recover_stmt_ return - Semi");
3718 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
3719 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
3721 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
3726 fn is_catch_expr(&mut self) -> bool {
3727 self.token.is_keyword(keywords::Do) &&
3728 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
3729 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
3731 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3732 !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL)
3735 fn is_union_item(&self) -> bool {
3736 self.token.is_keyword(keywords::Union) &&
3737 self.look_ahead(1, |t| t.is_ident() && !t.is_any_keyword())
3740 fn is_defaultness(&self) -> bool {
3741 // `pub` is included for better error messages
3742 self.token.is_keyword(keywords::Default) &&
3743 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
3744 t.is_keyword(keywords::Const) ||
3745 t.is_keyword(keywords::Fn) ||
3746 t.is_keyword(keywords::Unsafe) ||
3747 t.is_keyword(keywords::Extern) ||
3748 t.is_keyword(keywords::Type) ||
3749 t.is_keyword(keywords::Pub))
3752 fn eat_defaultness(&mut self) -> bool {
3753 let is_defaultness = self.is_defaultness();
3757 self.expected_tokens.push(TokenType::Keyword(keywords::Default));
3762 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility)
3763 -> PResult<'a, Option<P<Item>>> {
3765 let (ident, def) = match self.token {
3766 token::Ident(ident) if ident.name == keywords::Macro.name() => {
3768 let ident = self.parse_ident()?;
3769 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
3770 match self.parse_token_tree() {
3771 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
3772 _ => unreachable!(),
3774 } else if self.check(&token::OpenDelim(token::Paren)) {
3775 let args = self.parse_token_tree();
3776 let body = if self.check(&token::OpenDelim(token::Brace)) {
3777 self.parse_token_tree()
3782 TokenStream::concat(vec![
3784 TokenTree::Token(lo.to(self.prev_span), token::FatArrow).into(),
3792 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
3794 token::Ident(ident) if ident.name == "macro_rules" &&
3795 self.look_ahead(1, |t| *t == token::Not) => {
3796 let prev_span = self.prev_span;
3797 self.complain_if_pub_macro(vis, prev_span);
3801 let ident = self.parse_ident()?;
3802 let (delim, tokens) = self.expect_delimited_token_tree()?;
3803 if delim != token::Brace {
3804 if !self.eat(&token::Semi) {
3805 let msg = "macros that expand to items must either \
3806 be surrounded with braces or followed by a semicolon";
3807 self.span_err(self.prev_span, msg);
3811 (ident, ast::MacroDef { tokens: tokens, legacy: true })
3813 _ => return Ok(None),
3816 let span = lo.to(self.prev_span);
3817 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
3820 fn parse_stmt_without_recovery(&mut self,
3821 macro_legacy_warnings: bool)
3822 -> PResult<'a, Option<Stmt>> {
3823 maybe_whole!(self, NtStmt, |x| Some(x));
3825 let attrs = self.parse_outer_attributes()?;
3828 Ok(Some(if self.eat_keyword(keywords::Let) {
3830 id: ast::DUMMY_NODE_ID,
3831 node: StmtKind::Local(self.parse_local(attrs.into())?),
3832 span: lo.to(self.prev_span),
3834 } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited)? {
3836 id: ast::DUMMY_NODE_ID,
3837 node: StmtKind::Item(macro_def),
3838 span: lo.to(self.prev_span),
3840 // Starts like a simple path, but not a union item.
3841 } else if self.token.is_path_start() &&
3842 !self.token.is_qpath_start() &&
3843 !self.is_union_item() {
3844 let pth = self.parse_path(PathStyle::Expr)?;
3846 if !self.eat(&token::Not) {
3847 let expr = if self.check(&token::OpenDelim(token::Brace)) {
3848 self.parse_struct_expr(lo, pth, ThinVec::new())?
3850 let hi = self.prev_span;
3851 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
3854 let expr = self.with_res(RESTRICTION_STMT_EXPR, |this| {
3855 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
3856 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
3859 return Ok(Some(Stmt {
3860 id: ast::DUMMY_NODE_ID,
3861 node: StmtKind::Expr(expr),
3862 span: lo.to(self.prev_span),
3866 // it's a macro invocation
3867 let id = match self.token {
3868 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
3869 _ => self.parse_ident()?,
3872 // check that we're pointing at delimiters (need to check
3873 // again after the `if`, because of `parse_ident`
3874 // consuming more tokens).
3875 let delim = match self.token {
3876 token::OpenDelim(delim) => delim,
3878 // we only expect an ident if we didn't parse one
3880 let ident_str = if id.name == keywords::Invalid.name() {
3885 let tok_str = self.this_token_to_string();
3886 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3892 let (_, tts) = self.expect_delimited_token_tree()?;
3893 let hi = self.prev_span;
3895 let style = if delim == token::Brace {
3896 MacStmtStyle::Braces
3898 MacStmtStyle::NoBraces
3901 if id.name == keywords::Invalid.name() {
3902 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
3903 let node = if delim == token::Brace ||
3904 self.token == token::Semi || self.token == token::Eof {
3905 StmtKind::Mac(P((mac, style, attrs.into())))
3907 // We used to incorrectly stop parsing macro-expanded statements here.
3908 // If the next token will be an error anyway but could have parsed with the
3909 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
3910 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
3911 // These can continue an expression, so we can't stop parsing and warn.
3912 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
3913 token::BinOp(token::Minus) | token::BinOp(token::Star) |
3914 token::BinOp(token::And) | token::BinOp(token::Or) |
3915 token::AndAnd | token::OrOr |
3916 token::DotDot | token::DotDotDot => false,
3919 self.warn_missing_semicolon();
3920 StmtKind::Mac(P((mac, style, attrs.into())))
3922 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
3923 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
3924 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
3928 id: ast::DUMMY_NODE_ID,
3933 // if it has a special ident, it's definitely an item
3935 // Require a semicolon or braces.
3936 if style != MacStmtStyle::Braces {
3937 if !self.eat(&token::Semi) {
3938 self.span_err(self.prev_span,
3939 "macros that expand to items must \
3940 either be surrounded with braces or \
3941 followed by a semicolon");
3944 let span = lo.to(hi);
3946 id: ast::DUMMY_NODE_ID,
3948 node: StmtKind::Item({
3950 span, id /*id is good here*/,
3951 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
3952 Visibility::Inherited,
3958 // FIXME: Bad copy of attrs
3959 let old_directory_ownership =
3960 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
3961 let item = self.parse_item_(attrs.clone(), false, true)?;
3962 self.directory.ownership = old_directory_ownership;
3966 id: ast::DUMMY_NODE_ID,
3967 span: lo.to(i.span),
3968 node: StmtKind::Item(i),
3971 let unused_attrs = |attrs: &[_], s: &mut Self| {
3972 if !attrs.is_empty() {
3973 if s.prev_token_kind == PrevTokenKind::DocComment {
3974 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
3976 s.span_err(s.span, "expected statement after outer attribute");
3981 // Do not attempt to parse an expression if we're done here.
3982 if self.token == token::Semi {
3983 unused_attrs(&attrs, self);
3988 if self.token == token::CloseDelim(token::Brace) {
3989 unused_attrs(&attrs, self);
3993 // Remainder are line-expr stmts.
3994 let e = self.parse_expr_res(
3995 RESTRICTION_STMT_EXPR, Some(attrs.into()))?;
3997 id: ast::DUMMY_NODE_ID,
3998 span: lo.to(e.span),
3999 node: StmtKind::Expr(e),
4006 /// Is this expression a successfully-parsed statement?
4007 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4008 self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
4009 !classify::expr_requires_semi_to_be_stmt(e)
4012 /// Parse a block. No inner attrs are allowed.
4013 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4014 maybe_whole!(self, NtBlock, |x| x);
4018 if !self.eat(&token::OpenDelim(token::Brace)) {
4020 let tok = self.this_token_to_string();
4021 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4023 // Check to see if the user has written something like
4028 // Which is valid in other languages, but not Rust.
4029 match self.parse_stmt_without_recovery(false) {
4031 let mut stmt_span = stmt.span;
4032 // expand the span to include the semicolon, if it exists
4033 if self.eat(&token::Semi) {
4034 stmt_span.hi = self.prev_span.hi;
4036 let sugg = pprust::to_string(|s| {
4037 use print::pprust::{PrintState, INDENT_UNIT};
4038 s.ibox(INDENT_UNIT)?;
4040 s.print_stmt(&stmt)?;
4041 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4043 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4046 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4047 self.cancel(&mut e);
4054 self.parse_block_tail(lo, BlockCheckMode::Default)
4057 /// Parse a block. Inner attrs are allowed.
4058 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4059 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4062 self.expect(&token::OpenDelim(token::Brace))?;
4063 Ok((self.parse_inner_attributes()?,
4064 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4067 /// Parse the rest of a block expression or function body
4068 /// Precondition: already parsed the '{'.
4069 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4070 let mut stmts = vec![];
4072 while !self.eat(&token::CloseDelim(token::Brace)) {
4073 if let Some(stmt) = self.parse_full_stmt(false)? {
4075 } else if self.token == token::Eof {
4078 // Found only `;` or `}`.
4085 id: ast::DUMMY_NODE_ID,
4087 span: lo.to(self.prev_span),
4091 /// Parse a statement, including the trailing semicolon.
4092 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4093 let mut stmt = match self.parse_stmt_(macro_legacy_warnings) {
4095 None => return Ok(None),
4099 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4100 // expression without semicolon
4101 if classify::expr_requires_semi_to_be_stmt(expr) {
4102 // Just check for errors and recover; do not eat semicolon yet.
4104 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4107 self.recover_stmt();
4111 StmtKind::Local(..) => {
4112 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4113 if macro_legacy_warnings && self.token != token::Semi {
4114 self.warn_missing_semicolon();
4116 self.expect_one_of(&[token::Semi], &[])?;
4122 if self.eat(&token::Semi) {
4123 stmt = stmt.add_trailing_semicolon();
4126 stmt.span.hi = self.prev_span.hi;
4130 fn warn_missing_semicolon(&self) {
4131 self.diagnostic().struct_span_warn(self.span, {
4132 &format!("expected `;`, found `{}`", self.this_token_to_string())
4134 "This was erroneously allowed and will become a hard error in a future release"
4138 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4139 // BOUND = TY_BOUND | LT_BOUND
4140 // LT_BOUND = LIFETIME (e.g. `'a`)
4141 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4142 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4143 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4144 let mut bounds = Vec::new();
4146 let is_bound_start = self.check_path() || self.check_lifetime() ||
4147 self.check(&token::Question) ||
4148 self.check_keyword(keywords::For) ||
4149 self.check(&token::OpenDelim(token::Paren));
4151 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4152 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4153 if self.token.is_lifetime() {
4154 if let Some(question_span) = question {
4155 self.span_err(question_span,
4156 "`?` may only modify trait bounds, not lifetime bounds");
4158 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4161 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4162 let path = self.parse_path(PathStyle::Type)?;
4163 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4164 let modifier = if question.is_some() {
4165 TraitBoundModifier::Maybe
4167 TraitBoundModifier::None
4169 bounds.push(TraitTyParamBound(poly_trait, modifier));
4172 self.expect(&token::CloseDelim(token::Paren))?;
4173 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4174 self.span_err(self.prev_span,
4175 "parenthesized lifetime bounds are not supported");
4182 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4190 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4191 self.parse_ty_param_bounds_common(true)
4194 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4195 // BOUND = LT_BOUND (e.g. `'a`)
4196 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4197 let mut lifetimes = Vec::new();
4198 while self.check_lifetime() {
4199 lifetimes.push(self.expect_lifetime());
4201 if !self.eat(&token::BinOp(token::Plus)) {
4208 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4209 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4210 let span = self.span;
4211 let ident = self.parse_ident()?;
4213 // Parse optional colon and param bounds.
4214 let bounds = if self.eat(&token::Colon) {
4215 self.parse_ty_param_bounds()?
4220 let default = if self.eat(&token::Eq) {
4221 Some(self.parse_ty()?)
4227 attrs: preceding_attrs.into(),
4229 id: ast::DUMMY_NODE_ID,
4236 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4237 /// trailing comma and erroneous trailing attributes.
4238 pub fn parse_generic_params(&mut self) -> PResult<'a, (Vec<LifetimeDef>, Vec<TyParam>)> {
4239 let mut lifetime_defs = Vec::new();
4240 let mut ty_params = Vec::new();
4241 let mut seen_ty_param = false;
4243 let attrs = self.parse_outer_attributes()?;
4244 if self.check_lifetime() {
4245 let lifetime = self.expect_lifetime();
4246 // Parse lifetime parameter.
4247 let bounds = if self.eat(&token::Colon) {
4248 self.parse_lt_param_bounds()
4252 lifetime_defs.push(LifetimeDef {
4253 attrs: attrs.into(),
4258 self.span_err(self.prev_span,
4259 "lifetime parameters must be declared prior to type parameters");
4261 } else if self.check_ident() {
4262 // Parse type parameter.
4263 ty_params.push(self.parse_ty_param(attrs)?);
4264 seen_ty_param = true;
4266 // Check for trailing attributes and stop parsing.
4267 if !attrs.is_empty() {
4268 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4269 self.span_err(attrs[0].span,
4270 &format!("trailing attribute after {} parameters", param_kind));
4275 if !self.eat(&token::Comma) {
4279 Ok((lifetime_defs, ty_params))
4282 /// Parse a set of optional generic type parameter declarations. Where
4283 /// clauses are not parsed here, and must be added later via
4284 /// `parse_where_clause()`.
4286 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4287 /// | ( < lifetimes , typaramseq ( , )? > )
4288 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4289 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4290 maybe_whole!(self, NtGenerics, |x| x);
4292 let span_lo = self.span;
4294 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4297 lifetimes: lifetime_defs,
4298 ty_params: ty_params,
4299 where_clause: WhereClause {
4300 id: ast::DUMMY_NODE_ID,
4301 predicates: Vec::new(),
4303 span: span_lo.to(self.prev_span),
4306 Ok(ast::Generics::default())
4310 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4311 /// possibly including trailing comma.
4312 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4313 let mut lifetimes = Vec::new();
4314 let mut types = Vec::new();
4315 let mut bindings = Vec::new();
4316 let mut seen_type = false;
4317 let mut seen_binding = false;
4319 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4320 // Parse lifetime argument.
4321 lifetimes.push(self.expect_lifetime());
4322 if seen_type || seen_binding {
4323 self.span_err(self.prev_span,
4324 "lifetime parameters must be declared prior to type parameters");
4326 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4327 // Parse associated type binding.
4329 let ident = self.parse_ident()?;
4331 let ty = self.parse_ty()?;
4332 bindings.push(TypeBinding {
4333 id: ast::DUMMY_NODE_ID,
4336 span: lo.to(self.prev_span),
4338 seen_binding = true;
4339 } else if self.check_type() {
4340 // Parse type argument.
4341 types.push(self.parse_ty()?);
4343 self.span_err(types[types.len() - 1].span,
4344 "type parameters must be declared prior to associated type bindings");
4351 if !self.eat(&token::Comma) {
4355 Ok((lifetimes, types, bindings))
4358 /// Parses an optional `where` clause and places it in `generics`.
4361 /// where T : Trait<U, V> + 'b, 'a : 'b
4363 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4364 maybe_whole!(self, NtWhereClause, |x| x);
4366 let mut where_clause = WhereClause {
4367 id: ast::DUMMY_NODE_ID,
4368 predicates: Vec::new(),
4371 if !self.eat_keyword(keywords::Where) {
4372 return Ok(where_clause);
4375 // This is a temporary future proofing.
4377 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4378 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4379 // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4380 if token::Lt == self.token {
4381 let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4382 if ident_or_lifetime {
4383 let gt_comma_or_colon = self.look_ahead(2, |t| {
4384 *t == token::Gt || *t == token::Comma || *t == token::Colon
4386 if gt_comma_or_colon {
4387 self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4394 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4395 let lifetime = self.expect_lifetime();
4396 // Bounds starting with a colon are mandatory, but possibly empty.
4397 self.expect(&token::Colon)?;
4398 let bounds = self.parse_lt_param_bounds();
4399 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4400 ast::WhereRegionPredicate {
4401 span: lo.to(self.prev_span),
4406 } else if self.check_type() {
4407 // Parse optional `for<'a, 'b>`.
4408 // This `for` is parsed greedily and applies to the whole predicate,
4409 // the bounded type can have its own `for` applying only to it.
4410 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4411 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4412 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4413 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4415 // Parse type with mandatory colon and (possibly empty) bounds,
4416 // or with mandatory equality sign and the second type.
4417 let ty = self.parse_ty()?;
4418 if self.eat(&token::Colon) {
4419 let bounds = self.parse_ty_param_bounds()?;
4420 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4421 ast::WhereBoundPredicate {
4422 span: lo.to(self.prev_span),
4423 bound_lifetimes: lifetime_defs,
4428 // FIXME: Decide what should be used here, `=` or `==`.
4429 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4430 let rhs_ty = self.parse_ty()?;
4431 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4432 ast::WhereEqPredicate {
4433 span: lo.to(self.prev_span),
4436 id: ast::DUMMY_NODE_ID,
4440 return self.unexpected();
4446 if !self.eat(&token::Comma) {
4454 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4455 -> PResult<'a, (Vec<Arg> , bool)> {
4457 let mut variadic = false;
4458 let args: Vec<Option<Arg>> =
4459 self.parse_unspanned_seq(
4460 &token::OpenDelim(token::Paren),
4461 &token::CloseDelim(token::Paren),
4462 SeqSep::trailing_allowed(token::Comma),
4464 if p.token == token::DotDotDot {
4467 if p.token != token::CloseDelim(token::Paren) {
4470 "`...` must be last in argument list for variadic function");
4475 "only foreign functions are allowed to be variadic");
4480 match p.parse_arg_general(named_args) {
4481 Ok(arg) => Ok(Some(arg)),
4484 let lo = p.prev_span;
4485 // Skip every token until next possible arg or end.
4486 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4487 // Create a placeholder argument for proper arg count (#34264).
4488 let span = lo.to(p.prev_span);
4489 Ok(Some(dummy_arg(span)))
4496 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4498 if variadic && args.is_empty() {
4500 "variadic function must be declared with at least one named argument");
4503 Ok((args, variadic))
4506 /// Parse the argument list and result type of a function declaration
4507 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4509 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4510 let ret_ty = self.parse_ret_ty()?;
4519 /// Returns the parsed optional self argument and whether a self shortcut was used.
4520 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4521 let expect_ident = |this: &mut Self| match this.token {
4522 // Preserve hygienic context.
4523 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4526 let isolated_self = |this: &mut Self, n| {
4527 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4528 this.look_ahead(n + 1, |t| t != &token::ModSep)
4531 // Parse optional self parameter of a method.
4532 // Only a limited set of initial token sequences is considered self parameters, anything
4533 // else is parsed as a normal function parameter list, so some lookahead is required.
4534 let eself_lo = self.span;
4535 let (eself, eself_ident) = match self.token {
4536 token::BinOp(token::And) => {
4542 if isolated_self(self, 1) {
4544 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4545 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4546 isolated_self(self, 2) {
4549 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4550 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4551 isolated_self(self, 2) {
4553 let lt = self.expect_lifetime();
4554 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4555 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4556 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4557 isolated_self(self, 3) {
4559 let lt = self.expect_lifetime();
4561 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4566 token::BinOp(token::Star) => {
4571 // Emit special error for `self` cases.
4572 if isolated_self(self, 1) {
4574 self.span_err(self.span, "cannot pass `self` by raw pointer");
4575 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4576 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4577 isolated_self(self, 2) {
4580 self.span_err(self.span, "cannot pass `self` by raw pointer");
4581 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4586 token::Ident(..) => {
4587 if isolated_self(self, 0) {
4590 let eself_ident = expect_ident(self);
4591 if self.eat(&token::Colon) {
4592 let ty = self.parse_ty()?;
4593 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4595 (SelfKind::Value(Mutability::Immutable), eself_ident)
4597 } else if self.token.is_keyword(keywords::Mut) &&
4598 isolated_self(self, 1) {
4602 let eself_ident = expect_ident(self);
4603 if self.eat(&token::Colon) {
4604 let ty = self.parse_ty()?;
4605 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4607 (SelfKind::Value(Mutability::Mutable), eself_ident)
4613 _ => return Ok(None),
4616 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
4617 Ok(Some(Arg::from_self(eself, eself_ident)))
4620 /// Parse the parameter list and result type of a function that may have a `self` parameter.
4621 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
4622 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4624 self.expect(&token::OpenDelim(token::Paren))?;
4626 // Parse optional self argument
4627 let self_arg = self.parse_self_arg()?;
4629 // Parse the rest of the function parameter list.
4630 let sep = SeqSep::trailing_allowed(token::Comma);
4631 let fn_inputs = if let Some(self_arg) = self_arg {
4632 if self.check(&token::CloseDelim(token::Paren)) {
4634 } else if self.eat(&token::Comma) {
4635 let mut fn_inputs = vec![self_arg];
4636 fn_inputs.append(&mut self.parse_seq_to_before_end(
4637 &token::CloseDelim(token::Paren), sep, parse_arg_fn)
4641 return self.unexpected();
4644 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4647 // Parse closing paren and return type.
4648 self.expect(&token::CloseDelim(token::Paren))?;
4651 output: self.parse_ret_ty()?,
4656 // parse the |arg, arg| header on a lambda
4657 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4658 let inputs_captures = {
4659 if self.eat(&token::OrOr) {
4662 self.expect(&token::BinOp(token::Or))?;
4663 let args = self.parse_seq_to_before_end(
4664 &token::BinOp(token::Or),
4665 SeqSep::trailing_allowed(token::Comma),
4666 |p| p.parse_fn_block_arg()
4672 let output = self.parse_ret_ty()?;
4675 inputs: inputs_captures,
4681 /// Parse the name and optional generic types of a function header.
4682 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4683 let id = self.parse_ident()?;
4684 let generics = self.parse_generics()?;
4688 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
4689 attrs: Vec<Attribute>) -> P<Item> {
4693 id: ast::DUMMY_NODE_ID,
4700 /// Parse an item-position function declaration.
4701 fn parse_item_fn(&mut self,
4703 constness: Spanned<Constness>,
4705 -> PResult<'a, ItemInfo> {
4706 let (ident, mut generics) = self.parse_fn_header()?;
4707 let decl = self.parse_fn_decl(false)?;
4708 generics.where_clause = self.parse_where_clause()?;
4709 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4710 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4713 /// true if we are looking at `const ID`, false for things like `const fn` etc
4714 pub fn is_const_item(&mut self) -> bool {
4715 self.token.is_keyword(keywords::Const) &&
4716 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4717 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4720 /// parses all the "front matter" for a `fn` declaration, up to
4721 /// and including the `fn` keyword:
4725 /// - `const unsafe fn`
4728 pub fn parse_fn_front_matter(&mut self)
4729 -> PResult<'a, (Spanned<ast::Constness>,
4732 let is_const_fn = self.eat_keyword(keywords::Const);
4733 let const_span = self.prev_span;
4734 let unsafety = self.parse_unsafety()?;
4735 let (constness, unsafety, abi) = if is_const_fn {
4736 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
4738 let abi = if self.eat_keyword(keywords::Extern) {
4739 self.parse_opt_abi()?.unwrap_or(Abi::C)
4743 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
4745 self.expect_keyword(keywords::Fn)?;
4746 Ok((constness, unsafety, abi))
4749 /// Parse an impl item.
4750 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
4751 maybe_whole!(self, NtImplItem, |x| x);
4753 let mut attrs = self.parse_outer_attributes()?;
4755 let vis = self.parse_visibility(false)?;
4756 let defaultness = self.parse_defaultness()?;
4757 let (name, node) = if self.eat_keyword(keywords::Type) {
4758 let name = self.parse_ident()?;
4759 self.expect(&token::Eq)?;
4760 let typ = self.parse_ty()?;
4761 self.expect(&token::Semi)?;
4762 (name, ast::ImplItemKind::Type(typ))
4763 } else if self.is_const_item() {
4764 self.expect_keyword(keywords::Const)?;
4765 let name = self.parse_ident()?;
4766 self.expect(&token::Colon)?;
4767 let typ = self.parse_ty()?;
4768 self.expect(&token::Eq)?;
4769 let expr = self.parse_expr()?;
4770 self.expect(&token::Semi)?;
4771 (name, ast::ImplItemKind::Const(typ, expr))
4773 let (name, inner_attrs, node) = self.parse_impl_method(&vis, at_end)?;
4774 attrs.extend(inner_attrs);
4779 id: ast::DUMMY_NODE_ID,
4780 span: lo.to(self.prev_span),
4783 defaultness: defaultness,
4789 fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
4790 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
4795 fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
4797 Visibility::Inherited => Ok(()),
4799 let is_macro_rules: bool = match self.token {
4800 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
4804 let mut err = self.diagnostic()
4805 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
4806 err.help("did you mean #[macro_export]?");
4809 let mut err = self.diagnostic()
4810 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
4811 err.help("try adjusting the macro to put `pub` inside the invocation");
4818 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
4819 -> DiagnosticBuilder<'a>
4821 // Given this code `path(`, it seems like this is not
4822 // setting the visibility of a macro invocation, but rather
4823 // a mistyped method declaration.
4824 // Create a diagnostic pointing out that `fn` is missing.
4826 // x | pub path(&self) {
4827 // | ^ missing `fn`, `type`, or `const`
4829 // ^^ `sp` below will point to this
4830 let sp = prev_span.between(self.prev_span);
4831 let mut err = self.diagnostic().struct_span_err(
4833 &format!("missing `fn`, `type`, or `const` for {}-item declaration",
4835 err.span_label(sp, "missing `fn`, `type`, or `const`");
4839 /// Parse a method or a macro invocation in a trait impl.
4840 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
4841 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4842 // code copied from parse_macro_use_or_failure... abstraction!
4843 if self.token.is_path_start() {
4846 let prev_span = self.prev_span;
4849 let pth = self.parse_path(PathStyle::Mod)?;
4850 if pth.segments.len() == 1 {
4851 if !self.eat(&token::Not) {
4852 return Err(self.missing_assoc_item_kind_err("impl", prev_span));
4855 self.expect(&token::Not)?;
4858 self.complain_if_pub_macro(vis, prev_span);
4860 // eat a matched-delimiter token tree:
4862 let (delim, tts) = self.expect_delimited_token_tree()?;
4863 if delim != token::Brace {
4864 self.expect(&token::Semi)?
4867 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
4868 Ok((keywords::Invalid.ident(), vec![], ast::ImplItemKind::Macro(mac)))
4870 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
4871 let ident = self.parse_ident()?;
4872 let mut generics = self.parse_generics()?;
4873 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
4874 generics.where_clause = self.parse_where_clause()?;
4876 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4877 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4881 constness: constness,
4887 /// Parse trait Foo { ... }
4888 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4889 let ident = self.parse_ident()?;
4890 let mut tps = self.parse_generics()?;
4892 // Parse optional colon and supertrait bounds.
4893 let bounds = if self.eat(&token::Colon) {
4894 self.parse_ty_param_bounds()?
4899 tps.where_clause = self.parse_where_clause()?;
4901 self.expect(&token::OpenDelim(token::Brace))?;
4902 let mut trait_items = vec![];
4903 while !self.eat(&token::CloseDelim(token::Brace)) {
4904 let mut at_end = false;
4905 match self.parse_trait_item(&mut at_end) {
4906 Ok(item) => trait_items.push(item),
4910 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
4915 Ok((ident, ItemKind::Trait(unsafety, tps, bounds, trait_items), None))
4918 /// Parses items implementations variants
4919 /// impl<T> Foo { ... }
4920 /// impl<T> ToString for &'static T { ... }
4921 /// impl Send for .. {}
4922 fn parse_item_impl(&mut self,
4923 unsafety: ast::Unsafety,
4924 defaultness: Defaultness) -> PResult<'a, ItemInfo> {
4925 let impl_span = self.span;
4927 // First, parse type parameters if necessary.
4928 let mut generics = self.parse_generics()?;
4930 // Special case: if the next identifier that follows is '(', don't
4931 // allow this to be parsed as a trait.
4932 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4934 let neg_span = self.span;
4935 let polarity = if self.eat(&token::Not) {
4936 ast::ImplPolarity::Negative
4938 ast::ImplPolarity::Positive
4942 let mut ty = self.parse_ty()?;
4944 // Parse traits, if necessary.
4945 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4946 // New-style trait. Reinterpret the type as a trait.
4948 TyKind::Path(None, ref path) => {
4950 path: (*path).clone(),
4955 self.span_err(ty.span, "not a trait");
4960 if polarity == ast::ImplPolarity::Negative {
4961 // This is a negated type implementation
4962 // `impl !MyType {}`, which is not allowed.
4963 self.span_err(neg_span, "inherent implementation can't be negated");
4968 if opt_trait.is_some() && self.eat(&token::DotDot) {
4969 if generics.is_parameterized() {
4970 self.span_err(impl_span, "default trait implementations are not \
4971 allowed to have generics");
4974 if let ast::Defaultness::Default = defaultness {
4975 self.span_err(impl_span, "`default impl` is not allowed for \
4976 default trait implementations");
4979 self.expect(&token::OpenDelim(token::Brace))?;
4980 self.expect(&token::CloseDelim(token::Brace))?;
4981 Ok((keywords::Invalid.ident(),
4982 ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
4984 if opt_trait.is_some() {
4985 ty = self.parse_ty()?;
4987 generics.where_clause = self.parse_where_clause()?;
4989 self.expect(&token::OpenDelim(token::Brace))?;
4990 let attrs = self.parse_inner_attributes()?;
4992 let mut impl_items = vec![];
4993 while !self.eat(&token::CloseDelim(token::Brace)) {
4994 let mut at_end = false;
4995 match self.parse_impl_item(&mut at_end) {
4996 Ok(item) => impl_items.push(item),
5000 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5006 Ok((keywords::Invalid.ident(),
5007 ItemKind::Impl(unsafety, polarity, defaultness, generics, opt_trait, ty, impl_items),
5012 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<LifetimeDef>> {
5013 if self.eat_keyword(keywords::For) {
5015 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
5017 if !ty_params.is_empty() {
5018 self.span_err(ty_params[0].span,
5019 "only lifetime parameters can be used in this context");
5027 /// Parse struct Foo { ... }
5028 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5029 let class_name = self.parse_ident()?;
5031 let mut generics = self.parse_generics()?;
5033 // There is a special case worth noting here, as reported in issue #17904.
5034 // If we are parsing a tuple struct it is the case that the where clause
5035 // should follow the field list. Like so:
5037 // struct Foo<T>(T) where T: Copy;
5039 // If we are parsing a normal record-style struct it is the case
5040 // that the where clause comes before the body, and after the generics.
5041 // So if we look ahead and see a brace or a where-clause we begin
5042 // parsing a record style struct.
5044 // Otherwise if we look ahead and see a paren we parse a tuple-style
5047 let vdata = if self.token.is_keyword(keywords::Where) {
5048 generics.where_clause = self.parse_where_clause()?;
5049 if self.eat(&token::Semi) {
5050 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5051 VariantData::Unit(ast::DUMMY_NODE_ID)
5053 // If we see: `struct Foo<T> where T: Copy { ... }`
5054 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5056 // No `where` so: `struct Foo<T>;`
5057 } else if self.eat(&token::Semi) {
5058 VariantData::Unit(ast::DUMMY_NODE_ID)
5059 // Record-style struct definition
5060 } else if self.token == token::OpenDelim(token::Brace) {
5061 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5062 // Tuple-style struct definition with optional where-clause.
5063 } else if self.token == token::OpenDelim(token::Paren) {
5064 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5065 generics.where_clause = self.parse_where_clause()?;
5066 self.expect(&token::Semi)?;
5069 let token_str = self.this_token_to_string();
5070 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5071 name, found `{}`", token_str)))
5074 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5077 /// Parse union Foo { ... }
5078 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5079 let class_name = self.parse_ident()?;
5081 let mut generics = self.parse_generics()?;
5083 let vdata = if self.token.is_keyword(keywords::Where) {
5084 generics.where_clause = self.parse_where_clause()?;
5085 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5086 } else if self.token == token::OpenDelim(token::Brace) {
5087 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5089 let token_str = self.this_token_to_string();
5090 return Err(self.fatal(&format!("expected `where` or `{{` after union \
5091 name, found `{}`", token_str)))
5094 Ok((class_name, ItemKind::Union(vdata, generics), None))
5097 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5098 let mut fields = Vec::new();
5099 if self.eat(&token::OpenDelim(token::Brace)) {
5100 while self.token != token::CloseDelim(token::Brace) {
5101 fields.push(self.parse_struct_decl_field().map_err(|e| {
5102 self.recover_stmt();
5103 self.eat(&token::CloseDelim(token::Brace));
5110 let token_str = self.this_token_to_string();
5111 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5119 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5120 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5121 // Unit like structs are handled in parse_item_struct function
5122 let fields = self.parse_unspanned_seq(
5123 &token::OpenDelim(token::Paren),
5124 &token::CloseDelim(token::Paren),
5125 SeqSep::trailing_allowed(token::Comma),
5127 let attrs = p.parse_outer_attributes()?;
5129 let vis = p.parse_visibility(true)?;
5130 let ty = p.parse_ty()?;
5132 span: lo.to(p.span),
5135 id: ast::DUMMY_NODE_ID,
5144 /// Parse a structure field declaration
5145 pub fn parse_single_struct_field(&mut self,
5148 attrs: Vec<Attribute> )
5149 -> PResult<'a, StructField> {
5150 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5155 token::CloseDelim(token::Brace) => {}
5156 token::DocComment(_) => return Err(self.span_fatal_err(self.span,
5157 Error::UselessDocComment)),
5158 _ => return Err(self.span_fatal_help(self.span,
5159 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5160 "struct fields should be separated by commas")),
5165 /// Parse an element of a struct definition
5166 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5167 let attrs = self.parse_outer_attributes()?;
5169 let vis = self.parse_visibility(false)?;
5170 self.parse_single_struct_field(lo, vis, attrs)
5173 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5174 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5175 /// a function definition, it's not a tuple struct field) and the contents within the parens
5176 /// isn't valid, emit a proper diagnostic.
5177 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5178 maybe_whole!(self, NtVis, |x| x);
5180 if !self.eat_keyword(keywords::Pub) {
5181 return Ok(Visibility::Inherited)
5184 if self.check(&token::OpenDelim(token::Paren)) {
5185 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5186 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5187 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5188 // by the following tokens.
5189 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5192 self.bump(); // `crate`
5193 let vis = Visibility::Crate(self.prev_span);
5194 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5196 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5199 self.bump(); // `in`
5200 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5201 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5202 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5204 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5205 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5206 t.is_keyword(keywords::SelfValue)) {
5207 // `pub(self)` or `pub(super)`
5209 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5210 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5211 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5213 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5214 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5216 let msg = "incorrect visibility restriction";
5217 let suggestion = r##"some possible visibility restrictions are:
5218 `pub(crate)`: visible only on the current crate
5219 `pub(super)`: visible only in the current module's parent
5220 `pub(in path::to::module)`: visible only on the specified path"##;
5221 let path = self.parse_path(PathStyle::Mod)?;
5222 let path_span = self.prev_span;
5223 let help_msg = format!("make this visible only to module `{}` with `in`:", path);
5224 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5225 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5226 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5227 err.emit(); // emit diagnostic, but continue with public visibility
5231 Ok(Visibility::Public)
5234 /// Parse defaultness: DEFAULT or nothing
5235 fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5236 if self.eat_defaultness() {
5237 Ok(Defaultness::Default)
5239 Ok(Defaultness::Final)
5243 /// Given a termination token, parse all of the items in a module
5244 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5245 let mut items = vec![];
5246 while let Some(item) = self.parse_item()? {
5250 if !self.eat(term) {
5251 let token_str = self.this_token_to_string();
5252 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5255 let hi = if self.span == syntax_pos::DUMMY_SP {
5262 inner: inner_lo.to(hi),
5267 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5268 let id = self.parse_ident()?;
5269 self.expect(&token::Colon)?;
5270 let ty = self.parse_ty()?;
5271 self.expect(&token::Eq)?;
5272 let e = self.parse_expr()?;
5273 self.expect(&token::Semi)?;
5274 let item = match m {
5275 Some(m) => ItemKind::Static(ty, m, e),
5276 None => ItemKind::Const(ty, e),
5278 Ok((id, item, None))
5281 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5282 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5283 let (in_cfg, outer_attrs) = {
5284 let mut strip_unconfigured = ::config::StripUnconfigured {
5286 should_test: false, // irrelevant
5287 features: None, // don't perform gated feature checking
5289 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5290 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5293 let id_span = self.span;
5294 let id = self.parse_ident()?;
5295 if self.check(&token::Semi) {
5297 if in_cfg && self.recurse_into_file_modules {
5298 // This mod is in an external file. Let's go get it!
5299 let ModulePathSuccess { path, directory_ownership, warn } =
5300 self.submod_path(id, &outer_attrs, id_span)?;
5301 let (module, mut attrs) =
5302 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5304 let attr = ast::Attribute {
5305 id: attr::mk_attr_id(),
5306 style: ast::AttrStyle::Outer,
5307 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5308 Ident::from_str("warn_directory_ownership")),
5309 tokens: TokenStream::empty(),
5310 is_sugared_doc: false,
5311 span: syntax_pos::DUMMY_SP,
5313 attr::mark_known(&attr);
5316 Ok((id, module, Some(attrs)))
5318 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5319 Ok((id, ItemKind::Mod(placeholder), None))
5322 let old_directory = self.directory.clone();
5323 self.push_directory(id, &outer_attrs);
5325 self.expect(&token::OpenDelim(token::Brace))?;
5326 let mod_inner_lo = self.span;
5327 let attrs = self.parse_inner_attributes()?;
5328 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5330 self.directory = old_directory;
5331 Ok((id, ItemKind::Mod(module), Some(attrs)))
5335 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5336 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5337 self.directory.path.push(&path.as_str());
5338 self.directory.ownership = DirectoryOwnership::Owned;
5340 self.directory.path.push(&id.name.as_str());
5344 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5345 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5348 /// Returns either a path to a module, or .
5349 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5350 let mod_name = id.to_string();
5351 let default_path_str = format!("{}.rs", mod_name);
5352 let secondary_path_str = format!("{}{}mod.rs", mod_name, path::MAIN_SEPARATOR);
5353 let default_path = dir_path.join(&default_path_str);
5354 let secondary_path = dir_path.join(&secondary_path_str);
5355 let default_exists = codemap.file_exists(&default_path);
5356 let secondary_exists = codemap.file_exists(&secondary_path);
5358 let result = match (default_exists, secondary_exists) {
5359 (true, false) => Ok(ModulePathSuccess {
5361 directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5364 (false, true) => Ok(ModulePathSuccess {
5365 path: secondary_path,
5366 directory_ownership: DirectoryOwnership::Owned,
5369 (false, false) => Err(Error::FileNotFoundForModule {
5370 mod_name: mod_name.clone(),
5371 default_path: default_path_str,
5372 secondary_path: secondary_path_str,
5373 dir_path: format!("{}", dir_path.display()),
5375 (true, true) => Err(Error::DuplicatePaths {
5376 mod_name: mod_name.clone(),
5377 default_path: default_path_str,
5378 secondary_path: secondary_path_str,
5384 path_exists: default_exists || secondary_exists,
5389 fn submod_path(&mut self,
5391 outer_attrs: &[ast::Attribute],
5393 -> PResult<'a, ModulePathSuccess> {
5394 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5395 return Ok(ModulePathSuccess {
5396 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5397 Some("mod.rs") => DirectoryOwnership::Owned,
5398 _ => DirectoryOwnership::UnownedViaMod(true),
5405 let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5407 if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5409 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5410 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5411 if paths.path_exists {
5412 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5414 err.span_note(id_sp, &msg);
5417 } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5419 if let Ok(result) = paths.result {
5420 return Ok(ModulePathSuccess { warn: true, ..result });
5423 let mut err = self.diagnostic().struct_span_err(id_sp,
5424 "cannot declare a new module at this location");
5425 if id_sp != syntax_pos::DUMMY_SP {
5426 let src_path = PathBuf::from(self.sess.codemap().span_to_filename(id_sp));
5427 if let Some(stem) = src_path.file_stem() {
5428 let mut dest_path = src_path.clone();
5429 dest_path.set_file_name(stem);
5430 dest_path.push("mod.rs");
5431 err.span_note(id_sp,
5432 &format!("maybe move this module `{}` to its own \
5433 directory via `{}`", src_path.to_string_lossy(),
5434 dest_path.to_string_lossy()));
5437 if paths.path_exists {
5438 err.span_note(id_sp,
5439 &format!("... or maybe `use` the module `{}` instead \
5440 of possibly redeclaring it",
5445 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5449 /// Read a module from a source file.
5450 fn eval_src_mod(&mut self,
5452 directory_ownership: DirectoryOwnership,
5455 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5456 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5457 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5458 let mut err = String::from("circular modules: ");
5459 let len = included_mod_stack.len();
5460 for p in &included_mod_stack[i.. len] {
5461 err.push_str(&p.to_string_lossy());
5462 err.push_str(" -> ");
5464 err.push_str(&path.to_string_lossy());
5465 return Err(self.span_fatal(id_sp, &err[..]));
5467 included_mod_stack.push(path.clone());
5468 drop(included_mod_stack);
5471 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5472 p0.cfg_mods = self.cfg_mods;
5473 let mod_inner_lo = p0.span;
5474 let mod_attrs = p0.parse_inner_attributes()?;
5475 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5476 self.sess.included_mod_stack.borrow_mut().pop();
5477 Ok((ast::ItemKind::Mod(m0), mod_attrs))
5480 /// Parse a function declaration from a foreign module
5481 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5482 -> PResult<'a, ForeignItem> {
5483 self.expect_keyword(keywords::Fn)?;
5485 let (ident, mut generics) = self.parse_fn_header()?;
5486 let decl = self.parse_fn_decl(true)?;
5487 generics.where_clause = self.parse_where_clause()?;
5489 self.expect(&token::Semi)?;
5490 Ok(ast::ForeignItem {
5493 node: ForeignItemKind::Fn(decl, generics),
5494 id: ast::DUMMY_NODE_ID,
5500 /// Parse a static item from a foreign module
5501 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5502 -> PResult<'a, ForeignItem> {
5503 self.expect_keyword(keywords::Static)?;
5504 let mutbl = self.eat_keyword(keywords::Mut);
5506 let ident = self.parse_ident()?;
5507 self.expect(&token::Colon)?;
5508 let ty = self.parse_ty()?;
5510 self.expect(&token::Semi)?;
5514 node: ForeignItemKind::Static(ty, mutbl),
5515 id: ast::DUMMY_NODE_ID,
5521 /// Parse extern crate links
5525 /// extern crate foo;
5526 /// extern crate bar as foo;
5527 fn parse_item_extern_crate(&mut self,
5529 visibility: Visibility,
5530 attrs: Vec<Attribute>)
5531 -> PResult<'a, P<Item>> {
5533 let crate_name = self.parse_ident()?;
5534 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
5535 (Some(crate_name.name), ident)
5539 self.expect(&token::Semi)?;
5541 let prev_span = self.prev_span;
5542 Ok(self.mk_item(lo.to(prev_span),
5544 ItemKind::ExternCrate(maybe_path),
5549 /// Parse `extern` for foreign ABIs
5552 /// `extern` is expected to have been
5553 /// consumed before calling this method
5559 fn parse_item_foreign_mod(&mut self,
5561 opt_abi: Option<abi::Abi>,
5562 visibility: Visibility,
5563 mut attrs: Vec<Attribute>)
5564 -> PResult<'a, P<Item>> {
5565 self.expect(&token::OpenDelim(token::Brace))?;
5567 let abi = opt_abi.unwrap_or(Abi::C);
5569 attrs.extend(self.parse_inner_attributes()?);
5571 let mut foreign_items = vec![];
5572 while let Some(item) = self.parse_foreign_item()? {
5573 foreign_items.push(item);
5575 self.expect(&token::CloseDelim(token::Brace))?;
5577 let prev_span = self.prev_span;
5578 let m = ast::ForeignMod {
5580 items: foreign_items
5582 let invalid = keywords::Invalid.ident();
5583 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
5586 /// Parse type Foo = Bar;
5587 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5588 let ident = self.parse_ident()?;
5589 let mut tps = self.parse_generics()?;
5590 tps.where_clause = self.parse_where_clause()?;
5591 self.expect(&token::Eq)?;
5592 let ty = self.parse_ty()?;
5593 self.expect(&token::Semi)?;
5594 Ok((ident, ItemKind::Ty(ty, tps), None))
5597 /// Parse the part of an "enum" decl following the '{'
5598 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5599 let mut variants = Vec::new();
5600 let mut all_nullary = true;
5601 let mut any_disr = None;
5602 while self.token != token::CloseDelim(token::Brace) {
5603 let variant_attrs = self.parse_outer_attributes()?;
5604 let vlo = self.span;
5607 let mut disr_expr = None;
5608 let ident = self.parse_ident()?;
5609 if self.check(&token::OpenDelim(token::Brace)) {
5610 // Parse a struct variant.
5611 all_nullary = false;
5612 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
5613 ast::DUMMY_NODE_ID);
5614 } else if self.check(&token::OpenDelim(token::Paren)) {
5615 all_nullary = false;
5616 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
5617 ast::DUMMY_NODE_ID);
5618 } else if self.eat(&token::Eq) {
5619 disr_expr = Some(self.parse_expr()?);
5620 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5621 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5623 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5626 let vr = ast::Variant_ {
5628 attrs: variant_attrs,
5630 disr_expr: disr_expr,
5632 variants.push(respan(vlo.to(self.prev_span), vr));
5634 if !self.eat(&token::Comma) { break; }
5636 self.expect(&token::CloseDelim(token::Brace))?;
5638 Some(disr_span) if !all_nullary =>
5639 self.span_err(disr_span,
5640 "discriminator values can only be used with a c-like enum"),
5644 Ok(ast::EnumDef { variants: variants })
5647 /// Parse an "enum" declaration
5648 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5649 let id = self.parse_ident()?;
5650 let mut generics = self.parse_generics()?;
5651 generics.where_clause = self.parse_where_clause()?;
5652 self.expect(&token::OpenDelim(token::Brace))?;
5654 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
5655 self.recover_stmt();
5656 self.eat(&token::CloseDelim(token::Brace));
5659 Ok((id, ItemKind::Enum(enum_definition, generics), None))
5662 /// Parses a string as an ABI spec on an extern type or module. Consumes
5663 /// the `extern` keyword, if one is found.
5664 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5666 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5668 self.expect_no_suffix(sp, "ABI spec", suf);
5670 match abi::lookup(&s.as_str()) {
5671 Some(abi) => Ok(Some(abi)),
5673 let prev_span = self.prev_span;
5676 &format!("invalid ABI: expected one of [{}], \
5678 abi::all_names().join(", "),
5689 /// Parse one of the items allowed by the flags.
5690 /// NB: this function no longer parses the items inside an
5692 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5693 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5694 maybe_whole!(self, NtItem, |item| {
5695 let mut item = item.unwrap();
5696 let mut attrs = attrs;
5697 mem::swap(&mut item.attrs, &mut attrs);
5698 item.attrs.extend(attrs);
5704 let visibility = self.parse_visibility(false)?;
5706 if self.eat_keyword(keywords::Use) {
5708 let item_ = ItemKind::Use(self.parse_view_path()?);
5709 self.expect(&token::Semi)?;
5711 let prev_span = self.prev_span;
5712 let invalid = keywords::Invalid.ident();
5713 let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
5714 return Ok(Some(item));
5717 if self.eat_keyword(keywords::Extern) {
5718 if self.eat_keyword(keywords::Crate) {
5719 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
5722 let opt_abi = self.parse_opt_abi()?;
5724 if self.eat_keyword(keywords::Fn) {
5725 // EXTERN FUNCTION ITEM
5726 let fn_span = self.prev_span;
5727 let abi = opt_abi.unwrap_or(Abi::C);
5728 let (ident, item_, extra_attrs) =
5729 self.parse_item_fn(Unsafety::Normal,
5730 respan(fn_span, Constness::NotConst),
5732 let prev_span = self.prev_span;
5733 let item = self.mk_item(lo.to(prev_span),
5737 maybe_append(attrs, extra_attrs));
5738 return Ok(Some(item));
5739 } else if self.check(&token::OpenDelim(token::Brace)) {
5740 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
5746 if self.eat_keyword(keywords::Static) {
5748 let m = if self.eat_keyword(keywords::Mut) {
5751 Mutability::Immutable
5753 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
5754 let prev_span = self.prev_span;
5755 let item = self.mk_item(lo.to(prev_span),
5759 maybe_append(attrs, extra_attrs));
5760 return Ok(Some(item));
5762 if self.eat_keyword(keywords::Const) {
5763 let const_span = self.prev_span;
5764 if self.check_keyword(keywords::Fn)
5765 || (self.check_keyword(keywords::Unsafe)
5766 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5767 // CONST FUNCTION ITEM
5768 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5774 let (ident, item_, extra_attrs) =
5775 self.parse_item_fn(unsafety,
5776 respan(const_span, Constness::Const),
5778 let prev_span = self.prev_span;
5779 let item = self.mk_item(lo.to(prev_span),
5783 maybe_append(attrs, extra_attrs));
5784 return Ok(Some(item));
5788 if self.eat_keyword(keywords::Mut) {
5789 let prev_span = self.prev_span;
5790 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
5791 .help("did you mean to declare a static?")
5794 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
5795 let prev_span = self.prev_span;
5796 let item = self.mk_item(lo.to(prev_span),
5800 maybe_append(attrs, extra_attrs));
5801 return Ok(Some(item));
5803 if self.check_keyword(keywords::Unsafe) &&
5804 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5806 // UNSAFE TRAIT ITEM
5807 self.expect_keyword(keywords::Unsafe)?;
5808 self.expect_keyword(keywords::Trait)?;
5809 let (ident, item_, extra_attrs) =
5810 self.parse_item_trait(ast::Unsafety::Unsafe)?;
5811 let prev_span = self.prev_span;
5812 let item = self.mk_item(lo.to(prev_span),
5816 maybe_append(attrs, extra_attrs));
5817 return Ok(Some(item));
5819 if (self.check_keyword(keywords::Unsafe) &&
5820 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))) ||
5821 (self.check_keyword(keywords::Default) &&
5822 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) &&
5823 self.look_ahead(2, |t| t.is_keyword(keywords::Impl)))
5826 let defaultness = self.parse_defaultness()?;
5827 self.expect_keyword(keywords::Unsafe)?;
5828 self.expect_keyword(keywords::Impl)?;
5831 extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe, defaultness)?;
5832 let prev_span = self.prev_span;
5833 let item = self.mk_item(lo.to(prev_span),
5837 maybe_append(attrs, extra_attrs));
5838 return Ok(Some(item));
5840 if self.check_keyword(keywords::Fn) {
5843 let fn_span = self.prev_span;
5844 let (ident, item_, extra_attrs) =
5845 self.parse_item_fn(Unsafety::Normal,
5846 respan(fn_span, Constness::NotConst),
5848 let prev_span = self.prev_span;
5849 let item = self.mk_item(lo.to(prev_span),
5853 maybe_append(attrs, extra_attrs));
5854 return Ok(Some(item));
5856 if self.check_keyword(keywords::Unsafe)
5857 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5858 // UNSAFE FUNCTION ITEM
5860 let abi = if self.eat_keyword(keywords::Extern) {
5861 self.parse_opt_abi()?.unwrap_or(Abi::C)
5865 self.expect_keyword(keywords::Fn)?;
5866 let fn_span = self.prev_span;
5867 let (ident, item_, extra_attrs) =
5868 self.parse_item_fn(Unsafety::Unsafe,
5869 respan(fn_span, Constness::NotConst),
5871 let prev_span = self.prev_span;
5872 let item = self.mk_item(lo.to(prev_span),
5876 maybe_append(attrs, extra_attrs));
5877 return Ok(Some(item));
5879 if self.eat_keyword(keywords::Mod) {
5881 let (ident, item_, extra_attrs) =
5882 self.parse_item_mod(&attrs[..])?;
5883 let prev_span = self.prev_span;
5884 let item = self.mk_item(lo.to(prev_span),
5888 maybe_append(attrs, extra_attrs));
5889 return Ok(Some(item));
5891 if self.eat_keyword(keywords::Type) {
5893 let (ident, item_, extra_attrs) = self.parse_item_type()?;
5894 let prev_span = self.prev_span;
5895 let item = self.mk_item(lo.to(prev_span),
5899 maybe_append(attrs, extra_attrs));
5900 return Ok(Some(item));
5902 if self.eat_keyword(keywords::Enum) {
5904 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
5905 let prev_span = self.prev_span;
5906 let item = self.mk_item(lo.to(prev_span),
5910 maybe_append(attrs, extra_attrs));
5911 return Ok(Some(item));
5913 if self.eat_keyword(keywords::Trait) {
5915 let (ident, item_, extra_attrs) =
5916 self.parse_item_trait(ast::Unsafety::Normal)?;
5917 let prev_span = self.prev_span;
5918 let item = self.mk_item(lo.to(prev_span),
5922 maybe_append(attrs, extra_attrs));
5923 return Ok(Some(item));
5925 if (self.check_keyword(keywords::Impl)) ||
5926 (self.check_keyword(keywords::Default) &&
5927 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)))
5930 let defaultness = self.parse_defaultness()?;
5931 self.expect_keyword(keywords::Impl)?;
5934 extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal, defaultness)?;
5935 let prev_span = self.prev_span;
5936 let item = self.mk_item(lo.to(prev_span),
5940 maybe_append(attrs, extra_attrs));
5941 return Ok(Some(item));
5943 if self.eat_keyword(keywords::Struct) {
5945 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
5946 let prev_span = self.prev_span;
5947 let item = self.mk_item(lo.to(prev_span),
5951 maybe_append(attrs, extra_attrs));
5952 return Ok(Some(item));
5954 if self.is_union_item() {
5957 let (ident, item_, extra_attrs) = self.parse_item_union()?;
5958 let prev_span = self.prev_span;
5959 let item = self.mk_item(lo.to(prev_span),
5963 maybe_append(attrs, extra_attrs));
5964 return Ok(Some(item));
5966 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility)? {
5967 return Ok(Some(macro_def));
5970 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5973 /// Parse a foreign item.
5974 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
5975 let attrs = self.parse_outer_attributes()?;
5977 let visibility = self.parse_visibility(false)?;
5979 if self.check_keyword(keywords::Static) {
5980 // FOREIGN STATIC ITEM
5981 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
5983 if self.check_keyword(keywords::Fn) {
5984 // FOREIGN FUNCTION ITEM
5985 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
5988 if self.check_keyword(keywords::Const) {
5989 return Err(self.span_fatal(self.span, "extern items cannot be `const`"));
5992 // FIXME #5668: this will occur for a macro invocation:
5993 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
5995 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
6001 /// This is the fall-through for parsing items.
6002 fn parse_macro_use_or_failure(
6004 attrs: Vec<Attribute> ,
6005 macros_allowed: bool,
6006 attributes_allowed: bool,
6008 visibility: Visibility
6009 ) -> PResult<'a, Option<P<Item>>> {
6010 if macros_allowed && self.token.is_path_start() {
6011 // MACRO INVOCATION ITEM
6013 let prev_span = self.prev_span;
6014 self.complain_if_pub_macro(&visibility, prev_span);
6016 let mac_lo = self.span;
6019 let pth = self.parse_path(PathStyle::Mod)?;
6020 self.expect(&token::Not)?;
6022 // a 'special' identifier (like what `macro_rules!` uses)
6023 // is optional. We should eventually unify invoc syntax
6025 let id = if self.token.is_ident() {
6028 keywords::Invalid.ident() // no special identifier
6030 // eat a matched-delimiter token tree:
6031 let (delim, tts) = self.expect_delimited_token_tree()?;
6032 if delim != token::Brace {
6033 if !self.eat(&token::Semi) {
6034 let prev_span = self.prev_span;
6035 self.span_err(prev_span,
6036 "macros that expand to items must either \
6037 be surrounded with braces or followed by \
6042 let hi = self.prev_span;
6043 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6044 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6045 return Ok(Some(item));
6048 // FAILURE TO PARSE ITEM
6050 Visibility::Inherited => {}
6052 let prev_span = self.prev_span;
6053 return Err(self.span_fatal(prev_span, "unmatched visibility `pub`"));
6057 if !attributes_allowed && !attrs.is_empty() {
6058 self.expected_item_err(&attrs);
6063 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6064 let attrs = self.parse_outer_attributes()?;
6065 self.parse_item_(attrs, true, false)
6068 fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> {
6069 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
6070 &token::CloseDelim(token::Brace),
6071 SeqSep::trailing_allowed(token::Comma), |this| {
6073 let ident = if this.eat_keyword(keywords::SelfValue) {
6074 keywords::SelfValue.ident()
6078 let rename = this.parse_rename()?;
6079 let node = ast::PathListItem_ {
6082 id: ast::DUMMY_NODE_ID
6084 Ok(respan(lo.to(this.prev_span), node))
6089 fn is_import_coupler(&mut self) -> bool {
6090 self.check(&token::ModSep) &&
6091 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6092 *t == token::BinOp(token::Star))
6095 /// Matches ViewPath:
6096 /// MOD_SEP? non_global_path
6097 /// MOD_SEP? non_global_path as IDENT
6098 /// MOD_SEP? non_global_path MOD_SEP STAR
6099 /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE
6100 /// MOD_SEP? LBRACE item_seq RBRACE
6101 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
6103 if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) ||
6104 self.is_import_coupler() {
6105 // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`.
6106 self.eat(&token::ModSep);
6107 let prefix = ast::Path {
6108 segments: vec![PathSegment::crate_root()],
6109 span: lo.to(self.span),
6111 let view_path_kind = if self.eat(&token::BinOp(token::Star)) {
6112 ViewPathGlob(prefix)
6114 ViewPathList(prefix, self.parse_path_list_items()?)
6116 Ok(P(respan(lo.to(self.span), view_path_kind)))
6118 let prefix = self.parse_path(PathStyle::Mod)?.default_to_global();
6119 if self.is_import_coupler() {
6120 // `foo::bar::{a, b}` or `foo::bar::*`
6122 if self.check(&token::BinOp(token::Star)) {
6124 Ok(P(respan(lo.to(self.span), ViewPathGlob(prefix))))
6126 let items = self.parse_path_list_items()?;
6127 Ok(P(respan(lo.to(self.span), ViewPathList(prefix, items))))
6130 // `foo::bar` or `foo::bar as baz`
6131 let rename = self.parse_rename()?.
6132 unwrap_or(prefix.segments.last().unwrap().identifier);
6133 Ok(P(respan(lo.to(self.prev_span), ViewPathSimple(rename, prefix))))
6138 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6139 if self.eat_keyword(keywords::As) {
6140 self.parse_ident().map(Some)
6146 /// Parses a source module as a crate. This is the main
6147 /// entry point for the parser.
6148 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6151 attrs: self.parse_inner_attributes()?,
6152 module: self.parse_mod_items(&token::Eof, lo)?,
6153 span: lo.to(self.span),
6157 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6158 let ret = match self.token {
6159 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6160 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6167 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6168 match self.parse_optional_str() {
6169 Some((s, style, suf)) => {
6170 let sp = self.prev_span;
6171 self.expect_no_suffix(sp, "string literal", suf);
6174 _ => Err(self.fatal("expected string literal"))