1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use ast::{AttrStyle, BareFnTy};
13 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
15 use ast::{Mod, Arg, Arm, Attribute, BindingMode, TraitItemKind};
17 use ast::{BlockCheckMode, CaptureBy};
18 use ast::{Constness, Crate};
21 use ast::{Expr, ExprKind, RangeLimits};
22 use ast::{Field, FnDecl};
23 use ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
24 use ast::{Ident, ImplItem, Item, ItemKind};
25 use ast::{Lifetime, LifetimeDef, Lit, LitKind, UintTy};
27 use ast::MacStmtStyle;
29 use ast::{MutTy, Mutability};
30 use ast::{Pat, PatKind, PathSegment};
31 use ast::{PolyTraitRef, QSelf};
32 use ast::{Stmt, StmtKind};
33 use ast::{VariantData, StructField};
36 use ast::{TraitItem, TraitRef};
37 use ast::{Ty, TyKind, TypeBinding, TyParam, TyParamBounds};
38 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
39 use ast::{Visibility, WhereClause};
40 use ast::{BinOpKind, UnOp};
43 use codemap::{self, CodeMap, Spanned, respan};
44 use syntax_pos::{self, Span, BytePos};
45 use errors::{self, DiagnosticBuilder};
46 use parse::{self, classify, token};
47 use parse::common::SeqSep;
48 use parse::lexer::TokenAndSpan;
49 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
50 use parse::obsolete::ObsoleteSyntax;
51 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
52 use util::parser::{AssocOp, Fixity};
56 use tokenstream::{self, Delimited, ThinTokenStream, TokenTree, TokenStream};
57 use symbol::{Symbol, keywords};
61 use std::collections::HashSet;
63 use std::path::{self, Path, PathBuf};
67 pub flags Restrictions: u8 {
68 const RESTRICTION_STMT_EXPR = 1 << 0,
69 const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1,
73 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute> >);
75 /// How to parse a path. There are three different kinds of paths, all of which
76 /// are parsed somewhat differently.
77 #[derive(Copy, Clone, PartialEq)]
79 /// A path with no type parameters, e.g. `foo::bar::Baz`, used in imports or visibilities.
81 /// A path with a lifetime and type parameters, with no double colons
82 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`, used in types.
83 /// Paths using this style can be passed into macros expecting `path` nonterminals.
85 /// A path with a lifetime and type parameters with double colons before
86 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`, used in expressions or patterns.
90 #[derive(Clone, Copy, Debug, PartialEq)]
91 pub enum SemiColonMode {
96 #[derive(Clone, Copy, Debug, PartialEq)]
102 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
103 /// dropped into the token stream, which happens while parsing the result of
104 /// macro expansion). Placement of these is not as complex as I feared it would
105 /// be. The important thing is to make sure that lookahead doesn't balk at
106 /// `token::Interpolated` tokens.
107 macro_rules! maybe_whole_expr {
109 if let token::Interpolated(nt) = $p.token.clone() {
111 token::NtExpr(ref e) => {
113 return Ok((*e).clone());
115 token::NtPath(ref path) => {
118 let kind = ExprKind::Path(None, (*path).clone());
119 return Ok($p.mk_expr(span, kind, ThinVec::new()));
121 token::NtBlock(ref block) => {
124 let kind = ExprKind::Block((*block).clone());
125 return Ok($p.mk_expr(span, kind, ThinVec::new()));
133 /// As maybe_whole_expr, but for things other than expressions
134 macro_rules! maybe_whole {
135 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
136 if let token::Interpolated(nt) = $p.token.clone() {
137 if let token::$constructor($x) = (*nt).clone() {
145 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
147 if let Some(ref attrs) = rhs {
148 lhs.extend(attrs.iter().cloned())
163 /* ident is handled by common.rs */
165 pub struct Parser<'a> {
166 pub sess: &'a ParseSess,
167 /// the current token:
168 pub token: token::Token,
169 /// the span of the current token:
171 /// the span of the previous token:
172 pub meta_var_span: Option<Span>,
174 /// the previous token kind
175 prev_token_kind: PrevTokenKind,
176 pub restrictions: Restrictions,
177 /// The set of seen errors about obsolete syntax. Used to suppress
178 /// extra detail when the same error is seen twice
179 pub obsolete_set: HashSet<ObsoleteSyntax>,
180 /// Used to determine the path to externally loaded source files
181 pub directory: Directory,
182 /// Name of the root module this parser originated from. If `None`, then the
183 /// name is not known. This does not change while the parser is descending
184 /// into modules, and sub-parsers have new values for this name.
185 pub root_module_name: Option<String>,
186 pub expected_tokens: Vec<TokenType>,
187 token_cursor: TokenCursor,
188 pub desugar_doc_comments: bool,
189 /// Whether we should configure out of line modules as we parse.
194 frame: TokenCursorFrame,
195 stack: Vec<TokenCursorFrame>,
198 struct TokenCursorFrame {
199 delim: token::DelimToken,
202 tree_cursor: tokenstream::Cursor,
206 impl TokenCursorFrame {
207 fn new(sp: Span, delimited: &Delimited) -> Self {
209 delim: delimited.delim,
211 open_delim: delimited.delim == token::NoDelim,
212 tree_cursor: delimited.stream().into_trees(),
213 close_delim: delimited.delim == token::NoDelim,
219 fn next(&mut self) -> TokenAndSpan {
221 let tree = if !self.frame.open_delim {
222 self.frame.open_delim = true;
223 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
224 .open_tt(self.frame.span)
225 } else if let Some(tree) = self.frame.tree_cursor.next() {
227 } else if !self.frame.close_delim {
228 self.frame.close_delim = true;
229 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
230 .close_tt(self.frame.span)
231 } else if let Some(frame) = self.stack.pop() {
235 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
239 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
240 TokenTree::Delimited(sp, ref delimited) => {
241 let frame = TokenCursorFrame::new(sp, delimited);
242 self.stack.push(mem::replace(&mut self.frame, frame));
248 fn next_desugared(&mut self) -> TokenAndSpan {
249 let (sp, name) = match self.next() {
250 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
254 let stripped = strip_doc_comment_decoration(&name.as_str());
256 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
257 // required to wrap the text.
258 let mut num_of_hashes = 0;
260 for ch in stripped.chars() {
263 '#' if count > 0 => count + 1,
266 num_of_hashes = cmp::max(num_of_hashes, count);
269 let body = TokenTree::Delimited(sp, Delimited {
270 delim: token::Bracket,
271 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"))),
272 TokenTree::Token(sp, token::Eq),
273 TokenTree::Token(sp, token::Literal(
274 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
275 .iter().cloned().collect::<TokenStream>().into(),
278 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
279 delim: token::NoDelim,
280 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
281 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
282 .iter().cloned().collect::<TokenStream>().into()
284 [TokenTree::Token(sp, token::Pound), body]
285 .iter().cloned().collect::<TokenStream>().into()
293 #[derive(PartialEq, Eq, Clone)]
296 Keyword(keywords::Keyword),
305 fn to_string(&self) -> String {
307 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
308 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
309 TokenType::Operator => "an operator".to_string(),
310 TokenType::Lifetime => "lifetime".to_string(),
311 TokenType::Ident => "identifier".to_string(),
312 TokenType::Path => "path".to_string(),
313 TokenType::Type => "type".to_string(),
318 fn is_ident_or_underscore(t: &token::Token) -> bool {
319 t.is_ident() || *t == token::Underscore
322 /// Information about the path to a module.
323 pub struct ModulePath {
325 pub path_exists: bool,
326 pub result: Result<ModulePathSuccess, Error>,
329 pub struct ModulePathSuccess {
331 pub directory_ownership: DirectoryOwnership,
335 pub struct ModulePathError {
337 pub help_msg: String,
341 FileNotFoundForModule {
343 default_path: String,
344 secondary_path: String,
349 default_path: String,
350 secondary_path: String,
353 InclusiveRangeWithNoEnd,
357 pub fn span_err(self, sp: Span, handler: &errors::Handler) -> DiagnosticBuilder {
359 Error::FileNotFoundForModule { ref mod_name,
363 let mut err = struct_span_err!(handler, sp, E0583,
364 "file not found for module `{}`", mod_name);
365 err.help(&format!("name the file either {} or {} inside the directory {:?}",
371 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
372 let mut err = struct_span_err!(handler, sp, E0584,
373 "file for module `{}` found at both {} and {}",
377 err.help("delete or rename one of them to remove the ambiguity");
380 Error::UselessDocComment => {
381 let mut err = struct_span_err!(handler, sp, E0585,
382 "found a documentation comment that doesn't document anything");
383 err.help("doc comments must come before what they document, maybe a comment was \
384 intended with `//`?");
387 Error::InclusiveRangeWithNoEnd => {
388 let mut err = struct_span_err!(handler, sp, E0586,
389 "inclusive range with no end");
390 err.help("inclusive ranges must be bounded at the end (`...b` or `a...b`)");
399 AttributesParsed(ThinVec<Attribute>),
400 AlreadyParsed(P<Expr>),
403 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
404 fn from(o: Option<ThinVec<Attribute>>) -> Self {
405 if let Some(attrs) = o {
406 LhsExpr::AttributesParsed(attrs)
408 LhsExpr::NotYetParsed
413 impl From<P<Expr>> for LhsExpr {
414 fn from(expr: P<Expr>) -> Self {
415 LhsExpr::AlreadyParsed(expr)
419 /// Create a placeholder argument.
420 fn dummy_arg(span: Span) -> Arg {
421 let spanned = Spanned {
423 node: keywords::Invalid.ident()
426 id: ast::DUMMY_NODE_ID,
427 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), spanned, None),
433 id: ast::DUMMY_NODE_ID
435 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
438 impl<'a> Parser<'a> {
439 pub fn new(sess: &'a ParseSess,
441 directory: Option<Directory>,
442 desugar_doc_comments: bool)
444 let mut parser = Parser {
446 token: token::Underscore,
447 span: syntax_pos::DUMMY_SP,
448 prev_span: syntax_pos::DUMMY_SP,
450 prev_token_kind: PrevTokenKind::Other,
451 restrictions: Restrictions::empty(),
452 obsolete_set: HashSet::new(),
453 directory: Directory { path: PathBuf::new(), ownership: DirectoryOwnership::Owned },
454 root_module_name: None,
455 expected_tokens: Vec::new(),
456 token_cursor: TokenCursor {
457 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
458 delim: token::NoDelim,
463 desugar_doc_comments: desugar_doc_comments,
467 let tok = parser.next_tok();
468 parser.token = tok.tok;
469 parser.span = tok.sp;
470 if let Some(directory) = directory {
471 parser.directory = directory;
472 } else if parser.span != syntax_pos::DUMMY_SP {
473 parser.directory.path = PathBuf::from(sess.codemap().span_to_filename(parser.span));
474 parser.directory.path.pop();
476 parser.process_potential_macro_variable();
480 fn next_tok(&mut self) -> TokenAndSpan {
481 let mut next = if self.desugar_doc_comments {
482 self.token_cursor.next_desugared()
484 self.token_cursor.next()
486 if next.sp == syntax_pos::DUMMY_SP {
487 next.sp = self.prev_span;
492 /// Convert a token to a string using self's reader
493 pub fn token_to_string(token: &token::Token) -> String {
494 pprust::token_to_string(token)
497 /// Convert the current token to a string using self's reader
498 pub fn this_token_to_string(&self) -> String {
499 Parser::token_to_string(&self.token)
502 pub fn this_token_descr(&self) -> String {
503 let s = self.this_token_to_string();
504 if self.token.is_strict_keyword() {
505 format!("keyword `{}`", s)
506 } else if self.token.is_reserved_keyword() {
507 format!("reserved keyword `{}`", s)
513 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
514 let token_str = Parser::token_to_string(t);
515 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
518 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
519 match self.expect_one_of(&[], &[]) {
521 Ok(_) => unreachable!(),
525 /// Expect and consume the token t. Signal an error if
526 /// the next token is not t.
527 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
528 if self.expected_tokens.is_empty() {
529 if self.token == *t {
533 let token_str = Parser::token_to_string(t);
534 let this_token_str = self.this_token_to_string();
535 Err(self.fatal(&format!("expected `{}`, found `{}`",
540 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
544 /// Expect next token to be edible or inedible token. If edible,
545 /// then consume it; if inedible, then return without consuming
546 /// anything. Signal a fatal error if next token is unexpected.
547 pub fn expect_one_of(&mut self,
548 edible: &[token::Token],
549 inedible: &[token::Token]) -> PResult<'a, ()>{
550 fn tokens_to_string(tokens: &[TokenType]) -> String {
551 let mut i = tokens.iter();
552 // This might be a sign we need a connect method on Iterator.
554 .map_or("".to_string(), |t| t.to_string());
555 i.enumerate().fold(b, |mut b, (i, a)| {
556 if tokens.len() > 2 && i == tokens.len() - 2 {
558 } else if tokens.len() == 2 && i == tokens.len() - 2 {
563 b.push_str(&a.to_string());
567 if edible.contains(&self.token) {
570 } else if inedible.contains(&self.token) {
571 // leave it in the input
574 let mut expected = edible.iter()
575 .map(|x| TokenType::Token(x.clone()))
576 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
577 .chain(self.expected_tokens.iter().cloned())
578 .collect::<Vec<_>>();
579 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
581 let expect = tokens_to_string(&expected[..]);
582 let actual = self.this_token_to_string();
583 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
584 let short_expect = if expected.len() > 6 {
585 format!("{} possible tokens", expected.len())
589 (format!("expected one of {}, found `{}`", expect, actual),
590 (self.prev_span.next_point(), format!("expected one of {} here", short_expect)))
591 } else if expected.is_empty() {
592 (format!("unexpected token: `{}`", actual),
593 (self.prev_span, "unexpected token after this".to_string()))
595 (format!("expected {}, found `{}`", expect, actual),
596 (self.prev_span.next_point(), format!("expected {} here", expect)))
598 let mut err = self.fatal(&msg_exp);
599 let sp = if self.token == token::Token::Eof {
600 // This is EOF, don't want to point at the following char, but rather the last token
605 if self.span.contains(sp) {
606 err.span_label(self.span, label_exp);
608 err.span_label(sp, label_exp);
609 err.span_label(self.span, "unexpected token");
615 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
616 fn interpolated_or_expr_span(&self,
617 expr: PResult<'a, P<Expr>>)
618 -> PResult<'a, (Span, P<Expr>)> {
620 if self.prev_token_kind == PrevTokenKind::Interpolated {
628 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
629 self.check_strict_keywords();
630 self.check_reserved_keywords();
637 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
638 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
640 let mut err = self.fatal(&format!("expected identifier, found `{}`",
641 self.this_token_to_string()));
642 if self.token == token::Underscore {
643 err.note("`_` is a wildcard pattern, not an identifier");
651 /// Check if the next token is `tok`, and return `true` if so.
653 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
655 pub fn check(&mut self, tok: &token::Token) -> bool {
656 let is_present = self.token == *tok;
657 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
661 /// Consume token 'tok' if it exists. Returns true if the given
662 /// token was present, false otherwise.
663 pub fn eat(&mut self, tok: &token::Token) -> bool {
664 let is_present = self.check(tok);
665 if is_present { self.bump() }
669 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
670 self.expected_tokens.push(TokenType::Keyword(kw));
671 self.token.is_keyword(kw)
674 /// If the next token is the given keyword, eat it and return
675 /// true. Otherwise, return false.
676 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
677 if self.check_keyword(kw) {
685 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
686 if self.token.is_keyword(kw) {
694 pub fn check_contextual_keyword(&mut self, ident: Ident) -> bool {
695 self.expected_tokens.push(TokenType::Token(token::Ident(ident)));
696 if let token::Ident(ref cur_ident) = self.token {
697 cur_ident.name == ident.name
703 pub fn eat_contextual_keyword(&mut self, ident: Ident) -> bool {
704 if self.check_contextual_keyword(ident) {
712 /// If the given word is not a keyword, signal an error.
713 /// If the next token is not the given word, signal an error.
714 /// Otherwise, eat it.
715 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
716 if !self.eat_keyword(kw) {
723 /// Signal an error if the given string is a strict keyword
724 pub fn check_strict_keywords(&mut self) {
725 if self.token.is_strict_keyword() {
726 let token_str = self.this_token_to_string();
727 let span = self.span;
729 &format!("expected identifier, found keyword `{}`",
734 /// Signal an error if the current token is a reserved keyword
735 pub fn check_reserved_keywords(&mut self) {
736 if self.token.is_reserved_keyword() {
737 let token_str = self.this_token_to_string();
738 self.fatal(&format!("`{}` is a reserved keyword", token_str)).emit()
742 fn check_ident(&mut self) -> bool {
743 if self.token.is_ident() {
746 self.expected_tokens.push(TokenType::Ident);
751 fn check_path(&mut self) -> bool {
752 if self.token.is_path_start() {
755 self.expected_tokens.push(TokenType::Path);
760 fn check_type(&mut self) -> bool {
761 if self.token.can_begin_type() {
764 self.expected_tokens.push(TokenType::Type);
769 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
770 /// `&` and continue. If an `&` is not seen, signal an error.
771 fn expect_and(&mut self) -> PResult<'a, ()> {
772 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
774 token::BinOp(token::And) => {
779 let span = self.span;
780 let lo = span.lo + BytePos(1);
781 Ok(self.bump_with(token::BinOp(token::And), Span { lo: lo, ..span }))
783 _ => self.unexpected()
787 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
789 None => {/* everything ok */}
791 let text = suf.as_str();
793 self.span_bug(sp, "found empty literal suffix in Some")
795 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
800 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
801 /// `<` and continue. If a `<` is not seen, return false.
803 /// This is meant to be used when parsing generics on a path to get the
805 fn eat_lt(&mut self) -> bool {
806 self.expected_tokens.push(TokenType::Token(token::Lt));
812 token::BinOp(token::Shl) => {
813 let span = self.span;
814 let lo = span.lo + BytePos(1);
815 self.bump_with(token::Lt, Span { lo: lo, ..span });
822 fn expect_lt(&mut self) -> PResult<'a, ()> {
830 /// Expect and consume a GT. if a >> is seen, replace it
831 /// with a single > and continue. If a GT is not seen,
833 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
834 self.expected_tokens.push(TokenType::Token(token::Gt));
840 token::BinOp(token::Shr) => {
841 let span = self.span;
842 let lo = span.lo + BytePos(1);
843 Ok(self.bump_with(token::Gt, Span { lo: lo, ..span }))
845 token::BinOpEq(token::Shr) => {
846 let span = self.span;
847 let lo = span.lo + BytePos(1);
848 Ok(self.bump_with(token::Ge, Span { lo: lo, ..span }))
851 let span = self.span;
852 let lo = span.lo + BytePos(1);
853 Ok(self.bump_with(token::Eq, Span { lo: lo, ..span }))
855 _ => self.unexpected()
859 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
860 sep: Option<token::Token>,
862 -> PResult<'a, (Vec<T>, bool)>
863 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
865 let mut v = Vec::new();
866 // This loop works by alternating back and forth between parsing types
867 // and commas. For example, given a string `A, B,>`, the parser would
868 // first parse `A`, then a comma, then `B`, then a comma. After that it
869 // would encounter a `>` and stop. This lets the parser handle trailing
870 // commas in generic parameters, because it can stop either after
871 // parsing a type or after parsing a comma.
873 if self.check(&token::Gt)
874 || self.token == token::BinOp(token::Shr)
875 || self.token == token::Ge
876 || self.token == token::BinOpEq(token::Shr) {
882 Some(result) => v.push(result),
883 None => return Ok((v, true))
886 if let Some(t) = sep.as_ref() {
892 return Ok((v, false));
895 /// Parse a sequence bracketed by '<' and '>', stopping
897 pub fn parse_seq_to_before_gt<T, F>(&mut self,
898 sep: Option<token::Token>,
900 -> PResult<'a, Vec<T>> where
901 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
903 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
904 |p| Ok(Some(f(p)?)))?;
909 pub fn parse_seq_to_gt<T, F>(&mut self,
910 sep: Option<token::Token>,
912 -> PResult<'a, Vec<T>> where
913 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
915 let v = self.parse_seq_to_before_gt(sep, f)?;
920 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
921 sep: Option<token::Token>,
923 -> PResult<'a, (Vec<T>, bool)> where
924 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
926 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
930 return Ok((v, returned));
933 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
934 /// passes through any errors encountered. Used for error recovery.
935 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
936 let handler = self.diagnostic();
938 self.parse_seq_to_before_tokens(kets,
940 |p| Ok(p.parse_token_tree()),
941 |mut e| handler.cancel(&mut e));
944 /// Parse a sequence, including the closing delimiter. The function
945 /// f must consume tokens until reaching the next separator or
947 pub fn parse_seq_to_end<T, F>(&mut self,
951 -> PResult<'a, Vec<T>> where
952 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
954 let val = self.parse_seq_to_before_end(ket, sep, f);
959 /// Parse a sequence, not including the closing delimiter. The function
960 /// f must consume tokens until reaching the next separator or
962 pub fn parse_seq_to_before_end<T, F>(&mut self,
967 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
969 self.parse_seq_to_before_tokens(&[ket], sep, f, |mut e| e.emit())
972 // `fe` is an error handler.
973 fn parse_seq_to_before_tokens<T, F, Fe>(&mut self,
974 kets: &[&token::Token],
979 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
980 Fe: FnMut(DiagnosticBuilder)
982 let mut first: bool = true;
984 while !kets.contains(&&self.token) {
986 token::CloseDelim(..) | token::Eof => break,
989 if let Some(ref t) = sep.sep {
993 if let Err(e) = self.expect(t) {
999 if sep.trailing_sep_allowed && kets.iter().any(|k| self.check(k)) {
1015 /// Parse a sequence, including the closing delimiter. The function
1016 /// f must consume tokens until reaching the next separator or
1017 /// closing bracket.
1018 pub fn parse_unspanned_seq<T, F>(&mut self,
1023 -> PResult<'a, Vec<T>> where
1024 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1027 let result = self.parse_seq_to_before_end(ket, sep, f);
1028 if self.token == *ket {
1034 // NB: Do not use this function unless you actually plan to place the
1035 // spanned list in the AST.
1036 pub fn parse_seq<T, F>(&mut self,
1041 -> PResult<'a, Spanned<Vec<T>>> where
1042 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1046 let result = self.parse_seq_to_before_end(ket, sep, f);
1049 Ok(respan(lo.to(hi), result))
1052 /// Advance the parser by one token
1053 pub fn bump(&mut self) {
1054 if self.prev_token_kind == PrevTokenKind::Eof {
1055 // Bumping after EOF is a bad sign, usually an infinite loop.
1056 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1059 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1061 // Record last token kind for possible error recovery.
1062 self.prev_token_kind = match self.token {
1063 token::DocComment(..) => PrevTokenKind::DocComment,
1064 token::Comma => PrevTokenKind::Comma,
1065 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1066 token::Interpolated(..) => PrevTokenKind::Interpolated,
1067 token::Eof => PrevTokenKind::Eof,
1068 _ => PrevTokenKind::Other,
1071 let next = self.next_tok();
1072 self.span = next.sp;
1073 self.token = next.tok;
1074 self.expected_tokens.clear();
1075 // check after each token
1076 self.process_potential_macro_variable();
1079 /// Advance the parser using provided token as a next one. Use this when
1080 /// consuming a part of a token. For example a single `<` from `<<`.
1081 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1082 self.prev_span = Span { hi: span.lo, ..self.span };
1083 // It would be incorrect to record the kind of the current token, but
1084 // fortunately for tokens currently using `bump_with`, the
1085 // prev_token_kind will be of no use anyway.
1086 self.prev_token_kind = PrevTokenKind::Other;
1089 self.expected_tokens.clear();
1092 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1093 F: FnOnce(&token::Token) -> R,
1096 return f(&self.token)
1099 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1100 Some(tree) => match tree {
1101 TokenTree::Token(_, tok) => tok,
1102 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1104 None => token::CloseDelim(self.token_cursor.frame.delim),
1107 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1108 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1110 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1111 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1113 pub fn span_fatal_err(&self, sp: Span, err: Error) -> DiagnosticBuilder<'a> {
1114 err.span_err(sp, self.diagnostic())
1116 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1117 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1121 pub fn bug(&self, m: &str) -> ! {
1122 self.sess.span_diagnostic.span_bug(self.span, m)
1124 pub fn warn(&self, m: &str) {
1125 self.sess.span_diagnostic.span_warn(self.span, m)
1127 pub fn span_warn(&self, sp: Span, m: &str) {
1128 self.sess.span_diagnostic.span_warn(sp, m)
1130 pub fn span_err(&self, sp: Span, m: &str) {
1131 self.sess.span_diagnostic.span_err(sp, m)
1133 pub fn span_err_help(&self, sp: Span, m: &str, h: &str) {
1134 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1138 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1139 self.sess.span_diagnostic.span_bug(sp, m)
1141 pub fn abort_if_errors(&self) {
1142 self.sess.span_diagnostic.abort_if_errors();
1145 fn cancel(&self, err: &mut DiagnosticBuilder) {
1146 self.sess.span_diagnostic.cancel(err)
1149 pub fn diagnostic(&self) -> &'a errors::Handler {
1150 &self.sess.span_diagnostic
1153 /// Is the current token one of the keywords that signals a bare function
1155 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1156 self.check_keyword(keywords::Fn) ||
1157 self.check_keyword(keywords::Unsafe) ||
1158 self.check_keyword(keywords::Extern)
1161 fn get_label(&mut self) -> ast::Ident {
1163 token::Lifetime(ref ident) => *ident,
1164 _ => self.bug("not a lifetime"),
1168 /// parse a TyKind::BareFn type:
1169 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<LifetimeDef>)
1170 -> PResult<'a, TyKind> {
1173 [unsafe] [extern "ABI"] fn (S) -> T
1183 let unsafety = self.parse_unsafety()?;
1184 let abi = if self.eat_keyword(keywords::Extern) {
1185 self.parse_opt_abi()?.unwrap_or(Abi::C)
1190 self.expect_keyword(keywords::Fn)?;
1191 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1192 let ret_ty = self.parse_ret_ty()?;
1193 let decl = P(FnDecl {
1198 Ok(TyKind::BareFn(P(BareFnTy {
1201 lifetimes: lifetime_defs,
1206 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1207 if self.eat_keyword(keywords::Unsafe) {
1208 return Ok(Unsafety::Unsafe);
1210 return Ok(Unsafety::Normal);
1214 /// Parse the items in a trait declaration
1215 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1216 maybe_whole!(self, NtTraitItem, |x| x);
1217 let mut attrs = self.parse_outer_attributes()?;
1220 let (name, node) = if self.eat_keyword(keywords::Type) {
1221 let TyParam {ident, bounds, default, ..} = self.parse_ty_param(vec![])?;
1222 self.expect(&token::Semi)?;
1223 (ident, TraitItemKind::Type(bounds, default))
1224 } else if self.is_const_item() {
1225 self.expect_keyword(keywords::Const)?;
1226 let ident = self.parse_ident()?;
1227 self.expect(&token::Colon)?;
1228 let ty = self.parse_ty()?;
1229 let default = if self.check(&token::Eq) {
1231 let expr = self.parse_expr()?;
1232 self.expect(&token::Semi)?;
1235 self.expect(&token::Semi)?;
1238 (ident, TraitItemKind::Const(ty, default))
1239 } else if self.token.is_path_start() {
1240 // trait item macro.
1241 // code copied from parse_macro_use_or_failure... abstraction!
1242 let prev_span = self.prev_span;
1244 let pth = self.parse_path(PathStyle::Mod)?;
1246 if pth.segments.len() == 1 {
1247 if !self.eat(&token::Not) {
1248 return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1251 self.expect(&token::Not)?;
1254 // eat a matched-delimiter token tree:
1255 let (delim, tts) = self.expect_delimited_token_tree()?;
1256 if delim != token::Brace {
1257 self.expect(&token::Semi)?
1260 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1261 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac))
1263 let (constness, unsafety, abi) = match self.parse_fn_front_matter() {
1265 Err(e) => return Err(e),
1268 let ident = self.parse_ident()?;
1269 let mut generics = self.parse_generics()?;
1271 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1272 // This is somewhat dubious; We don't want to allow
1273 // argument names to be left off if there is a
1275 p.parse_arg_general(false)
1278 generics.where_clause = self.parse_where_clause()?;
1279 let sig = ast::MethodSig {
1281 constness: constness,
1287 let body = match self.token {
1291 debug!("parse_trait_methods(): parsing required method");
1294 token::OpenDelim(token::Brace) => {
1295 debug!("parse_trait_methods(): parsing provided method");
1297 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1298 attrs.extend(inner_attrs.iter().cloned());
1302 let token_str = self.this_token_to_string();
1303 return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1306 (ident, ast::TraitItemKind::Method(sig, body))
1310 id: ast::DUMMY_NODE_ID,
1314 span: lo.to(self.prev_span),
1318 /// Parse optional return type [ -> TY ] in function decl
1319 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1320 if self.eat(&token::RArrow) {
1321 Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
1323 Ok(FunctionRetTy::Default(Span { hi: self.span.lo, ..self.span }))
1328 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1329 self.parse_ty_common(true)
1332 /// Parse a type in restricted contexts where `+` is not permitted.
1333 /// Example 1: `&'a TYPE`
1334 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1335 /// Example 2: `value1 as TYPE + value2`
1336 /// `+` is prohibited to avoid interactions with expression grammar.
1337 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1338 self.parse_ty_common(false)
1341 fn parse_ty_common(&mut self, allow_plus: bool) -> PResult<'a, P<Ty>> {
1342 maybe_whole!(self, NtTy, |x| x);
1345 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1346 // `(TYPE)` is a parenthesized type.
1347 // `(TYPE,)` is a tuple with a single field of type TYPE.
1348 let mut ts = vec![];
1349 let mut last_comma = false;
1350 while self.token != token::CloseDelim(token::Paren) {
1351 ts.push(self.parse_ty()?);
1352 if self.eat(&token::Comma) {
1359 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1360 self.expect(&token::CloseDelim(token::Paren))?;
1362 if ts.len() == 1 && !last_comma {
1363 let ty = ts.into_iter().nth(0).unwrap().unwrap();
1364 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1366 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1367 TyKind::Path(None, ref path) if maybe_bounds => {
1368 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1370 TyKind::TraitObject(ref bounds)
1371 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1372 let path = match bounds[0] {
1373 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1374 _ => self.bug("unexpected lifetime bound"),
1376 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1379 _ => TyKind::Paren(P(ty))
1384 } else if self.eat(&token::Not) {
1387 } else if self.eat(&token::BinOp(token::Star)) {
1389 TyKind::Ptr(self.parse_ptr()?)
1390 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1392 let t = self.parse_ty()?;
1393 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1394 let t = match self.maybe_parse_fixed_length_of_vec()? {
1395 None => TyKind::Slice(t),
1396 Some(suffix) => TyKind::Array(t, suffix),
1398 self.expect(&token::CloseDelim(token::Bracket))?;
1400 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1403 self.parse_borrowed_pointee()?
1404 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1406 // In order to not be ambiguous, the type must be surrounded by parens.
1407 self.expect(&token::OpenDelim(token::Paren))?;
1408 let e = self.parse_expr()?;
1409 self.expect(&token::CloseDelim(token::Paren))?;
1411 } else if self.eat(&token::Underscore) {
1412 // A type to be inferred `_`
1414 } else if self.eat_lt() {
1416 let (qself, path) = self.parse_qualified_path(PathStyle::Type)?;
1417 TyKind::Path(Some(qself), path)
1418 } else if self.token.is_path_start() {
1420 let path = self.parse_path(PathStyle::Type)?;
1421 if self.eat(&token::Not) {
1422 // Macro invocation in type position
1423 let (_, tts) = self.expect_delimited_token_tree()?;
1424 TyKind::Mac(respan(lo.to(self.span), Mac_ { path: path, tts: tts }))
1426 // Just a type path or bound list (trait object type) starting with a trait.
1428 // `Trait1 + Trait2 + 'a`
1429 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1430 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1432 TyKind::Path(None, path)
1435 } else if self.token_is_bare_fn_keyword() {
1436 // Function pointer type
1437 self.parse_ty_bare_fn(Vec::new())?
1438 } else if self.check_keyword(keywords::For) {
1439 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1440 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1441 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1443 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1444 if self.token_is_bare_fn_keyword() {
1445 self.parse_ty_bare_fn(lifetime_defs)?
1447 let path = self.parse_path(PathStyle::Type)?;
1448 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1449 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1451 } else if self.eat_keyword(keywords::Impl) {
1452 // FIXME: figure out priority of `+` in `impl Trait1 + Trait2` (#34511).
1453 TyKind::ImplTrait(self.parse_ty_param_bounds()?)
1454 } else if self.check(&token::Question) ||
1455 self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)){
1456 // Bound list (trait object type)
1457 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?)
1459 let msg = format!("expected type, found {}", self.this_token_descr());
1460 return Err(self.fatal(&msg));
1463 let span = lo.to(self.prev_span);
1464 let ty = Ty { node: node, span: span, id: ast::DUMMY_NODE_ID };
1466 // Try to recover from use of `+` with incorrect priority.
1467 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1472 fn parse_remaining_bounds(&mut self, lifetime_defs: Vec<LifetimeDef>, path: ast::Path,
1473 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1474 let poly_trait_ref = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
1475 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1478 bounds.append(&mut self.parse_ty_param_bounds()?);
1480 Ok(TyKind::TraitObject(bounds))
1483 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1484 // Do not add `+` to expected tokens.
1485 if !allow_plus || self.token != token::BinOp(token::Plus) {
1490 let bounds = self.parse_ty_param_bounds()?;
1491 let sum_span = ty.span.to(self.prev_span);
1493 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1494 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1497 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1498 let sum_with_parens = pprust::to_string(|s| {
1499 use print::pp::word;
1500 use print::pprust::PrintState;
1502 word(&mut s.s, "&")?;
1503 s.print_opt_lifetime(lifetime)?;
1504 s.print_mutability(mut_ty.mutbl)?;
1506 s.print_type(&mut_ty.ty)?;
1507 s.print_bounds(" +", &bounds)?;
1510 err.span_suggestion(sum_span, "try adding parentheses:", sum_with_parens);
1512 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1513 err.span_label(sum_span, "perhaps you forgot parentheses?");
1516 err.span_label(sum_span, "expected a path");
1523 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1524 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1525 let mutbl = self.parse_mutability();
1526 let ty = self.parse_ty_no_plus()?;
1527 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1530 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1531 let mutbl = if self.eat_keyword(keywords::Mut) {
1533 } else if self.eat_keyword(keywords::Const) {
1534 Mutability::Immutable
1536 let span = self.prev_span;
1538 "expected mut or const in raw pointer type (use \
1539 `*mut T` or `*const T` as appropriate)");
1540 Mutability::Immutable
1542 let t = self.parse_ty_no_plus()?;
1543 Ok(MutTy { ty: t, mutbl: mutbl })
1546 pub fn is_named_argument(&mut self) -> bool {
1547 let offset = match self.token {
1548 token::BinOp(token::And) |
1550 _ if self.token.is_keyword(keywords::Mut) => 1,
1554 debug!("parser is_named_argument offset:{}", offset);
1557 is_ident_or_underscore(&self.token)
1558 && self.look_ahead(1, |t| *t == token::Colon)
1560 self.look_ahead(offset, |t| is_ident_or_underscore(t))
1561 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1565 /// This version of parse arg doesn't necessarily require
1566 /// identifier names.
1567 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1568 maybe_whole!(self, NtArg, |x| x);
1570 let pat = if require_name || self.is_named_argument() {
1571 debug!("parse_arg_general parse_pat (require_name:{})",
1573 let pat = self.parse_pat()?;
1575 self.expect(&token::Colon)?;
1578 debug!("parse_arg_general ident_to_pat");
1579 let sp = self.prev_span;
1580 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1582 id: ast::DUMMY_NODE_ID,
1583 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1589 let t = self.parse_ty()?;
1594 id: ast::DUMMY_NODE_ID,
1598 /// Parse a single function argument
1599 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1600 self.parse_arg_general(true)
1603 /// Parse an argument in a lambda header e.g. |arg, arg|
1604 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1605 let pat = self.parse_pat()?;
1606 let t = if self.eat(&token::Colon) {
1610 id: ast::DUMMY_NODE_ID,
1611 node: TyKind::Infer,
1618 id: ast::DUMMY_NODE_ID
1622 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1623 if self.eat(&token::Semi) {
1624 Ok(Some(self.parse_expr()?))
1630 /// Matches token_lit = LIT_INTEGER | ...
1631 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1632 let out = match self.token {
1633 token::Interpolated(ref nt) => match **nt {
1634 token::NtExpr(ref v) => match v.node {
1635 ExprKind::Lit(ref lit) => { lit.node.clone() }
1636 _ => { return self.unexpected_last(&self.token); }
1638 _ => { return self.unexpected_last(&self.token); }
1640 token::Literal(lit, suf) => {
1641 let diag = Some((self.span, &self.sess.span_diagnostic));
1642 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1646 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1651 _ => { return self.unexpected_last(&self.token); }
1658 /// Matches lit = true | false | token_lit
1659 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1661 let lit = if self.eat_keyword(keywords::True) {
1663 } else if self.eat_keyword(keywords::False) {
1664 LitKind::Bool(false)
1666 let lit = self.parse_lit_token()?;
1669 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1672 /// matches '-' lit | lit
1673 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1674 let minus_lo = self.span;
1675 let minus_present = self.eat(&token::BinOp(token::Minus));
1677 let literal = P(self.parse_lit()?);
1678 let hi = self.prev_span;
1679 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1682 let minus_hi = self.prev_span;
1683 let unary = self.mk_unary(UnOp::Neg, expr);
1684 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1690 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1692 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1696 _ => self.parse_ident(),
1700 /// Parses qualified path.
1702 /// Assumes that the leading `<` has been parsed already.
1704 /// Qualifed paths are a part of the universal function call
1707 /// `qualified_path = <type [as trait_ref]>::path`
1709 /// See `parse_path` for `mode` meaning.
1714 /// `<T as U>::F::a::<S>`
1715 pub fn parse_qualified_path(&mut self, mode: PathStyle)
1716 -> PResult<'a, (QSelf, ast::Path)> {
1717 let span = self.prev_span;
1718 let self_type = self.parse_ty()?;
1719 let mut path = if self.eat_keyword(keywords::As) {
1720 self.parse_path(PathStyle::Type)?
1730 position: path.segments.len()
1733 self.expect(&token::Gt)?;
1734 self.expect(&token::ModSep)?;
1736 let segments = match mode {
1737 PathStyle::Type => {
1738 self.parse_path_segments_without_colons()?
1740 PathStyle::Expr => {
1741 self.parse_path_segments_with_colons()?
1744 self.parse_path_segments_without_types()?
1747 path.segments.extend(segments);
1749 path.span.hi = self.prev_span.hi;
1754 /// Parses a path and optional type parameter bounds, depending on the
1755 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1756 /// bounds are permitted and whether `::` must precede type parameter
1758 pub fn parse_path(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1759 maybe_whole!(self, NtPath, |x| x);
1761 let lo = self.meta_var_span.unwrap_or(self.span);
1762 let is_global = self.eat(&token::ModSep);
1764 // Parse any number of segments and bound sets. A segment is an
1765 // identifier followed by an optional lifetime and a set of types.
1766 // A bound set is a set of type parameter bounds.
1767 let mut segments = match mode {
1768 PathStyle::Type => {
1769 self.parse_path_segments_without_colons()?
1771 PathStyle::Expr => {
1772 self.parse_path_segments_with_colons()?
1775 self.parse_path_segments_without_types()?
1780 segments.insert(0, PathSegment::crate_root());
1783 // Assemble the result.
1785 span: lo.to(self.prev_span),
1790 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1791 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1792 pub fn parse_path_allowing_meta(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1793 let meta_ident = match self.token {
1794 token::Interpolated(ref nt) => match **nt {
1795 token::NtMeta(ref meta) => match meta.node {
1796 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
1803 if let Some(ident) = meta_ident {
1805 return Ok(ast::Path::from_ident(self.prev_span, ident));
1807 self.parse_path(mode)
1811 /// - `a::b<T,U>::c<V,W>`
1812 /// - `a::b<T,U>::c(V) -> W`
1813 /// - `a::b<T,U>::c(V)`
1814 pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1815 let mut segments = Vec::new();
1817 // First, parse an identifier.
1818 let ident_span = self.span;
1819 let identifier = self.parse_path_segment_ident()?;
1821 if self.check(&token::ModSep) && self.look_ahead(1, |t| *t == token::Lt) {
1823 let prev_span = self.prev_span;
1825 let mut err = self.diagnostic().struct_span_err(prev_span,
1826 "unexpected token: `::`");
1828 "use `<...>` instead of `::<...>` if you meant to specify type arguments");
1832 // Parse types, optionally.
1833 let parameters = if self.eat_lt() {
1834 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1836 ast::AngleBracketedParameterData {
1837 lifetimes: lifetimes,
1841 } else if self.eat(&token::OpenDelim(token::Paren)) {
1842 let lo = self.prev_span;
1844 let inputs = self.parse_seq_to_end(
1845 &token::CloseDelim(token::Paren),
1846 SeqSep::trailing_allowed(token::Comma),
1849 let output_ty = if self.eat(&token::RArrow) {
1850 Some(self.parse_ty_no_plus()?)
1855 let hi = self.prev_span;
1857 Some(P(ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData {
1866 // Assemble and push the result.
1867 segments.push(PathSegment {
1868 identifier: identifier,
1870 parameters: parameters
1873 // Continue only if we see a `::`
1874 if !self.eat(&token::ModSep) {
1875 return Ok(segments);
1881 /// - `a::b::<T,U>::c`
1882 pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1883 let mut segments = Vec::new();
1885 // First, parse an identifier.
1886 let ident_span = self.span;
1887 let identifier = self.parse_path_segment_ident()?;
1889 // If we do not see a `::`, stop.
1890 if !self.eat(&token::ModSep) {
1891 segments.push(PathSegment::from_ident(identifier, ident_span));
1892 return Ok(segments);
1895 // Check for a type segment.
1897 // Consumed `a::b::<`, go look for types
1898 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1900 segments.push(PathSegment {
1901 identifier: identifier,
1903 parameters: ast::AngleBracketedParameterData {
1904 lifetimes: lifetimes,
1910 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1911 if !self.eat(&token::ModSep) {
1912 return Ok(segments);
1915 // Consumed `a::`, go look for `b`
1916 segments.push(PathSegment::from_ident(identifier, ident_span));
1923 pub fn parse_path_segments_without_types(&mut self)
1924 -> PResult<'a, Vec<PathSegment>> {
1925 let mut segments = Vec::new();
1927 // First, parse an identifier.
1928 let ident_span = self.span;
1929 let identifier = self.parse_path_segment_ident()?;
1931 // Assemble and push the result.
1932 segments.push(PathSegment::from_ident(identifier, ident_span));
1934 // If we do not see a `::` or see `::{`/`::*`, stop.
1935 if !self.check(&token::ModSep) || self.is_import_coupler() {
1936 return Ok(segments);
1943 fn check_lifetime(&mut self) -> bool {
1944 self.expected_tokens.push(TokenType::Lifetime);
1945 self.token.is_lifetime()
1948 /// Parse single lifetime 'a or panic.
1949 fn expect_lifetime(&mut self) -> Lifetime {
1951 token::Lifetime(ident) => {
1952 let ident_span = self.span;
1954 Lifetime { name: ident.name, span: ident_span, id: ast::DUMMY_NODE_ID }
1956 _ => self.span_bug(self.span, "not a lifetime")
1960 /// Parse mutability (`mut` or nothing).
1961 fn parse_mutability(&mut self) -> Mutability {
1962 if self.eat_keyword(keywords::Mut) {
1965 Mutability::Immutable
1969 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1970 if let token::Literal(token::Integer(name), None) = self.token {
1972 Ok(Ident::with_empty_ctxt(name))
1978 /// Parse ident (COLON expr)?
1979 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1980 let attrs = self.parse_outer_attributes()?;
1984 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1985 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1986 let fieldname = self.parse_field_name()?;
1988 hi = self.prev_span;
1989 (fieldname, self.parse_expr()?, false)
1991 let fieldname = self.parse_ident()?;
1992 hi = self.prev_span;
1994 // Mimic `x: x` for the `x` field shorthand.
1995 let path = ast::Path::from_ident(lo.to(hi), fieldname);
1996 (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
1999 ident: respan(lo.to(hi), fieldname),
2000 span: lo.to(expr.span),
2002 is_shorthand: is_shorthand,
2003 attrs: attrs.into(),
2007 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2009 id: ast::DUMMY_NODE_ID,
2012 attrs: attrs.into(),
2016 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2017 ExprKind::Unary(unop, expr)
2020 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2021 ExprKind::Binary(binop, lhs, rhs)
2024 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2025 ExprKind::Call(f, args)
2028 fn mk_method_call(&mut self,
2029 ident: ast::SpannedIdent,
2033 ExprKind::MethodCall(ident, tps, args)
2036 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2037 ExprKind::Index(expr, idx)
2040 pub fn mk_range(&mut self,
2041 start: Option<P<Expr>>,
2042 end: Option<P<Expr>>,
2043 limits: RangeLimits)
2044 -> PResult<'a, ast::ExprKind> {
2045 if end.is_none() && limits == RangeLimits::Closed {
2046 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2048 Ok(ExprKind::Range(start, end, limits))
2052 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::ExprKind {
2053 ExprKind::Field(expr, ident)
2056 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2057 ExprKind::TupField(expr, idx)
2060 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2061 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2062 ExprKind::AssignOp(binop, lhs, rhs)
2065 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2067 id: ast::DUMMY_NODE_ID,
2068 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2074 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2075 let span = &self.span;
2076 let lv_lit = P(codemap::Spanned {
2077 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2082 id: ast::DUMMY_NODE_ID,
2083 node: ExprKind::Lit(lv_lit),
2089 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2091 token::OpenDelim(delim) => match self.parse_token_tree() {
2092 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2093 _ => unreachable!(),
2095 _ => Err(self.fatal("expected open delimiter")),
2099 /// At the bottom (top?) of the precedence hierarchy,
2100 /// parse things like parenthesized exprs,
2101 /// macros, return, etc.
2103 /// NB: This does not parse outer attributes,
2104 /// and is private because it only works
2105 /// correctly if called from parse_dot_or_call_expr().
2106 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2107 maybe_whole_expr!(self);
2109 // Outer attributes are already parsed and will be
2110 // added to the return value after the fact.
2112 // Therefore, prevent sub-parser from parsing
2113 // attributes by giving them a empty "already parsed" list.
2114 let mut attrs = ThinVec::new();
2117 let mut hi = self.span;
2121 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2123 token::OpenDelim(token::Paren) => {
2126 attrs.extend(self.parse_inner_attributes()?);
2128 // (e) is parenthesized e
2129 // (e,) is a tuple with only one field, e
2130 let mut es = vec![];
2131 let mut trailing_comma = false;
2132 while self.token != token::CloseDelim(token::Paren) {
2133 es.push(self.parse_expr()?);
2134 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2135 if self.check(&token::Comma) {
2136 trailing_comma = true;
2140 trailing_comma = false;
2146 hi = self.prev_span;
2147 let span = lo.to(hi);
2148 return if es.len() == 1 && !trailing_comma {
2149 Ok(self.mk_expr(span, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2151 Ok(self.mk_expr(span, ExprKind::Tup(es), attrs))
2154 token::OpenDelim(token::Brace) => {
2155 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2157 token::BinOp(token::Or) | token::OrOr => {
2159 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2161 token::OpenDelim(token::Bracket) => {
2164 attrs.extend(self.parse_inner_attributes()?);
2166 if self.check(&token::CloseDelim(token::Bracket)) {
2169 ex = ExprKind::Array(Vec::new());
2172 let first_expr = self.parse_expr()?;
2173 if self.check(&token::Semi) {
2174 // Repeating array syntax: [ 0; 512 ]
2176 let count = self.parse_expr()?;
2177 self.expect(&token::CloseDelim(token::Bracket))?;
2178 ex = ExprKind::Repeat(first_expr, count);
2179 } else if self.check(&token::Comma) {
2180 // Vector with two or more elements.
2182 let remaining_exprs = self.parse_seq_to_end(
2183 &token::CloseDelim(token::Bracket),
2184 SeqSep::trailing_allowed(token::Comma),
2185 |p| Ok(p.parse_expr()?)
2187 let mut exprs = vec![first_expr];
2188 exprs.extend(remaining_exprs);
2189 ex = ExprKind::Array(exprs);
2191 // Vector with one element.
2192 self.expect(&token::CloseDelim(token::Bracket))?;
2193 ex = ExprKind::Array(vec![first_expr]);
2196 hi = self.prev_span;
2201 self.parse_qualified_path(PathStyle::Expr)?;
2203 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2205 if self.eat_keyword(keywords::Move) {
2206 let lo = self.prev_span;
2207 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2209 if self.eat_keyword(keywords::If) {
2210 return self.parse_if_expr(attrs);
2212 if self.eat_keyword(keywords::For) {
2213 let lo = self.prev_span;
2214 return self.parse_for_expr(None, lo, attrs);
2216 if self.eat_keyword(keywords::While) {
2217 let lo = self.prev_span;
2218 return self.parse_while_expr(None, lo, attrs);
2220 if self.token.is_lifetime() {
2221 let label = Spanned { node: self.get_label(),
2225 self.expect(&token::Colon)?;
2226 if self.eat_keyword(keywords::While) {
2227 return self.parse_while_expr(Some(label), lo, attrs)
2229 if self.eat_keyword(keywords::For) {
2230 return self.parse_for_expr(Some(label), lo, attrs)
2232 if self.eat_keyword(keywords::Loop) {
2233 return self.parse_loop_expr(Some(label), lo, attrs)
2235 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2237 if self.eat_keyword(keywords::Loop) {
2238 let lo = self.prev_span;
2239 return self.parse_loop_expr(None, lo, attrs);
2241 if self.eat_keyword(keywords::Continue) {
2242 let ex = if self.token.is_lifetime() {
2243 let ex = ExprKind::Continue(Some(Spanned{
2244 node: self.get_label(),
2250 ExprKind::Continue(None)
2252 let hi = self.prev_span;
2253 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2255 if self.eat_keyword(keywords::Match) {
2256 return self.parse_match_expr(attrs);
2258 if self.eat_keyword(keywords::Unsafe) {
2259 return self.parse_block_expr(
2261 BlockCheckMode::Unsafe(ast::UserProvided),
2264 if self.is_catch_expr() {
2265 assert!(self.eat_keyword(keywords::Do));
2266 assert!(self.eat_keyword(keywords::Catch));
2267 let lo = self.prev_span;
2268 return self.parse_catch_expr(lo, attrs);
2270 if self.eat_keyword(keywords::Return) {
2271 if self.token.can_begin_expr() {
2272 let e = self.parse_expr()?;
2274 ex = ExprKind::Ret(Some(e));
2276 ex = ExprKind::Ret(None);
2278 } else if self.eat_keyword(keywords::Break) {
2279 let lt = if self.token.is_lifetime() {
2280 let spanned_lt = Spanned {
2281 node: self.get_label(),
2289 let e = if self.token.can_begin_expr()
2290 && !(self.token == token::OpenDelim(token::Brace)
2291 && self.restrictions.contains(
2292 RESTRICTION_NO_STRUCT_LITERAL)) {
2293 Some(self.parse_expr()?)
2297 ex = ExprKind::Break(lt, e);
2298 hi = self.prev_span;
2299 } else if self.token.is_keyword(keywords::Let) {
2300 // Catch this syntax error here, instead of in `check_strict_keywords`, so
2301 // that we can explicitly mention that let is not to be used as an expression
2302 let mut db = self.fatal("expected expression, found statement (`let`)");
2303 db.note("variable declaration using `let` is a statement");
2305 } else if self.token.is_path_start() {
2306 let pth = self.parse_path(PathStyle::Expr)?;
2308 // `!`, as an operator, is prefix, so we know this isn't that
2309 if self.eat(&token::Not) {
2310 // MACRO INVOCATION expression
2311 let (_, tts) = self.expect_delimited_token_tree()?;
2312 let hi = self.prev_span;
2313 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2315 if self.check(&token::OpenDelim(token::Brace)) {
2316 // This is a struct literal, unless we're prohibited
2317 // from parsing struct literals here.
2318 let prohibited = self.restrictions.contains(
2319 RESTRICTION_NO_STRUCT_LITERAL
2322 return self.parse_struct_expr(lo, pth, attrs);
2327 ex = ExprKind::Path(None, pth);
2329 match self.parse_lit() {
2332 ex = ExprKind::Lit(P(lit));
2335 self.cancel(&mut err);
2336 let msg = format!("expected expression, found {}",
2337 self.this_token_descr());
2338 return Err(self.fatal(&msg));
2345 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2348 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2349 -> PResult<'a, P<Expr>> {
2351 let mut fields = Vec::new();
2352 let mut base = None;
2354 attrs.extend(self.parse_inner_attributes()?);
2356 while self.token != token::CloseDelim(token::Brace) {
2357 if self.eat(&token::DotDot) {
2358 match self.parse_expr() {
2364 self.recover_stmt();
2370 match self.parse_field() {
2371 Ok(f) => fields.push(f),
2374 self.recover_stmt();
2379 match self.expect_one_of(&[token::Comma],
2380 &[token::CloseDelim(token::Brace)]) {
2384 self.recover_stmt();
2390 let span = lo.to(self.span);
2391 self.expect(&token::CloseDelim(token::Brace))?;
2392 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2395 fn parse_or_use_outer_attributes(&mut self,
2396 already_parsed_attrs: Option<ThinVec<Attribute>>)
2397 -> PResult<'a, ThinVec<Attribute>> {
2398 if let Some(attrs) = already_parsed_attrs {
2401 self.parse_outer_attributes().map(|a| a.into())
2405 /// Parse a block or unsafe block
2406 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2407 outer_attrs: ThinVec<Attribute>)
2408 -> PResult<'a, P<Expr>> {
2410 self.expect(&token::OpenDelim(token::Brace))?;
2412 let mut attrs = outer_attrs;
2413 attrs.extend(self.parse_inner_attributes()?);
2415 let blk = self.parse_block_tail(lo, blk_mode)?;
2416 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2419 /// parse a.b or a(13) or a[4] or just a
2420 pub fn parse_dot_or_call_expr(&mut self,
2421 already_parsed_attrs: Option<ThinVec<Attribute>>)
2422 -> PResult<'a, P<Expr>> {
2423 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2425 let b = self.parse_bottom_expr();
2426 let (span, b) = self.interpolated_or_expr_span(b)?;
2427 self.parse_dot_or_call_expr_with(b, span, attrs)
2430 pub fn parse_dot_or_call_expr_with(&mut self,
2433 mut attrs: ThinVec<Attribute>)
2434 -> PResult<'a, P<Expr>> {
2435 // Stitch the list of outer attributes onto the return value.
2436 // A little bit ugly, but the best way given the current code
2438 self.parse_dot_or_call_expr_with_(e0, lo)
2440 expr.map(|mut expr| {
2441 attrs.extend::<Vec<_>>(expr.attrs.into());
2444 ExprKind::If(..) | ExprKind::IfLet(..) => {
2445 if !expr.attrs.is_empty() {
2446 // Just point to the first attribute in there...
2447 let span = expr.attrs[0].span;
2450 "attributes are not yet allowed on `if` \
2461 // Assuming we have just parsed `.foo` (i.e., a dot and an ident), continue
2462 // parsing into an expression.
2463 fn parse_dot_suffix(&mut self, ident: Ident, ident_span: Span, self_value: P<Expr>, lo: Span)
2464 -> PResult<'a, P<Expr>> {
2465 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2467 let args = self.parse_generic_args()?;
2471 (Vec::new(), Vec::new(), Vec::new())
2474 if !bindings.is_empty() {
2475 let prev_span = self.prev_span;
2476 self.span_err(prev_span, "type bindings are only permitted on trait paths");
2479 Ok(match self.token {
2480 // expr.f() method call.
2481 token::OpenDelim(token::Paren) => {
2482 let mut es = self.parse_unspanned_seq(
2483 &token::OpenDelim(token::Paren),
2484 &token::CloseDelim(token::Paren),
2485 SeqSep::trailing_allowed(token::Comma),
2486 |p| Ok(p.parse_expr()?)
2488 let hi = self.prev_span;
2490 es.insert(0, self_value);
2491 let id = respan(ident_span.to(ident_span), ident);
2492 let nd = self.mk_method_call(id, tys, es);
2493 self.mk_expr(lo.to(hi), nd, ThinVec::new())
2497 if !tys.is_empty() {
2498 let prev_span = self.prev_span;
2499 self.span_err(prev_span,
2500 "field expressions may not \
2501 have type parameters");
2504 let id = respan(ident_span.to(ident_span), ident);
2505 let field = self.mk_field(self_value, id);
2506 self.mk_expr(lo.to(ident_span), field, ThinVec::new())
2511 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2516 while self.eat(&token::Question) {
2517 let hi = self.prev_span;
2518 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2522 if self.eat(&token::Dot) {
2524 token::Ident(i) => {
2525 let ident_span = self.span;
2527 e = self.parse_dot_suffix(i, ident_span, e, lo)?;
2529 token::Literal(token::Integer(n), suf) => {
2532 // A tuple index may not have a suffix
2533 self.expect_no_suffix(sp, "tuple index", suf);
2535 let dot_span = self.prev_span;
2539 let index = n.as_str().parse::<usize>().ok();
2542 let id = respan(dot_span.to(hi), n);
2543 let field = self.mk_tup_field(e, id);
2544 e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2547 let prev_span = self.prev_span;
2548 self.span_err(prev_span, "invalid tuple or tuple struct index");
2552 token::Literal(token::Float(n), _suf) => {
2554 let fstr = n.as_str();
2555 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2556 &format!("unexpected token: `{}`", n));
2557 err.span_label(self.prev_span, "unexpected token");
2558 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2559 let float = match fstr.parse::<f64>().ok() {
2563 let sugg = pprust::to_string(|s| {
2564 use print::pprust::PrintState;
2565 use print::pp::word;
2568 word(&mut s.s, ".")?;
2569 s.print_usize(float.trunc() as usize)?;
2571 word(&mut s.s, ".")?;
2572 word(&mut s.s, fstr.splitn(2, ".").last().unwrap())
2574 err.span_suggestion(
2575 lo.to(self.prev_span),
2576 "try parenthesizing the first index",
2583 // FIXME Could factor this out into non_fatal_unexpected or something.
2584 let actual = self.this_token_to_string();
2585 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2587 let dot_span = self.prev_span;
2588 e = self.parse_dot_suffix(keywords::Invalid.ident(), dot_span, e, lo)?;
2593 if self.expr_is_complete(&e) { break; }
2596 token::OpenDelim(token::Paren) => {
2597 let es = self.parse_unspanned_seq(
2598 &token::OpenDelim(token::Paren),
2599 &token::CloseDelim(token::Paren),
2600 SeqSep::trailing_allowed(token::Comma),
2601 |p| Ok(p.parse_expr()?)
2603 hi = self.prev_span;
2605 let nd = self.mk_call(e, es);
2606 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2610 // Could be either an index expression or a slicing expression.
2611 token::OpenDelim(token::Bracket) => {
2613 let ix = self.parse_expr()?;
2615 self.expect(&token::CloseDelim(token::Bracket))?;
2616 let index = self.mk_index(e, ix);
2617 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2625 pub fn process_potential_macro_variable(&mut self) {
2626 let ident = match self.token {
2627 token::SubstNt(name) => {
2628 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2631 token::Interpolated(ref nt) => {
2632 self.meta_var_span = Some(self.span);
2634 token::NtIdent(ident) => ident,
2640 self.token = token::Ident(ident.node);
2641 self.span = ident.span;
2644 /// parse a single token tree from the input.
2645 pub fn parse_token_tree(&mut self) -> TokenTree {
2647 token::OpenDelim(..) => {
2648 let frame = mem::replace(&mut self.token_cursor.frame,
2649 self.token_cursor.stack.pop().unwrap());
2650 self.span = frame.span;
2652 TokenTree::Delimited(frame.span, Delimited {
2654 tts: frame.tree_cursor.original_stream().into(),
2657 token::CloseDelim(_) | token::Eof => unreachable!(),
2659 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2661 TokenTree::Token(span, token)
2666 // parse a stream of tokens into a list of TokenTree's,
2668 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2669 let mut tts = Vec::new();
2670 while self.token != token::Eof {
2671 tts.push(self.parse_token_tree());
2676 pub fn parse_tokens(&mut self) -> TokenStream {
2677 let mut result = Vec::new();
2680 token::Eof | token::CloseDelim(..) => break,
2681 _ => result.push(self.parse_token_tree().into()),
2684 TokenStream::concat(result)
2687 /// Parse a prefix-unary-operator expr
2688 pub fn parse_prefix_expr(&mut self,
2689 already_parsed_attrs: Option<ThinVec<Attribute>>)
2690 -> PResult<'a, P<Expr>> {
2691 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2693 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2694 let (hi, ex) = match self.token {
2697 let e = self.parse_prefix_expr(None);
2698 let (span, e) = self.interpolated_or_expr_span(e)?;
2699 (span, self.mk_unary(UnOp::Not, e))
2701 // Suggest `!` for bitwise negation when encountering a `~`
2704 let e = self.parse_prefix_expr(None);
2705 let (span, e) = self.interpolated_or_expr_span(e)?;
2706 let span_of_tilde = lo;
2707 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2708 "`~` can not be used as a unary operator");
2709 err.span_label(span_of_tilde, "did you mean `!`?");
2710 err.help("use `!` instead of `~` if you meant to perform bitwise negation");
2712 (span, self.mk_unary(UnOp::Not, e))
2714 token::BinOp(token::Minus) => {
2716 let e = self.parse_prefix_expr(None);
2717 let (span, e) = self.interpolated_or_expr_span(e)?;
2718 (span, self.mk_unary(UnOp::Neg, e))
2720 token::BinOp(token::Star) => {
2722 let e = self.parse_prefix_expr(None);
2723 let (span, e) = self.interpolated_or_expr_span(e)?;
2724 (span, self.mk_unary(UnOp::Deref, e))
2726 token::BinOp(token::And) | token::AndAnd => {
2728 let m = self.parse_mutability();
2729 let e = self.parse_prefix_expr(None);
2730 let (span, e) = self.interpolated_or_expr_span(e)?;
2731 (span, ExprKind::AddrOf(m, e))
2733 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2735 let place = self.parse_expr_res(
2736 RESTRICTION_NO_STRUCT_LITERAL,
2739 let blk = self.parse_block()?;
2740 let span = blk.span;
2741 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2742 (span, ExprKind::InPlace(place, blk_expr))
2744 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2746 let e = self.parse_prefix_expr(None);
2747 let (span, e) = self.interpolated_or_expr_span(e)?;
2748 (span, ExprKind::Box(e))
2750 _ => return self.parse_dot_or_call_expr(Some(attrs))
2752 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2755 /// Parse an associative expression
2757 /// This parses an expression accounting for associativity and precedence of the operators in
2759 pub fn parse_assoc_expr(&mut self,
2760 already_parsed_attrs: Option<ThinVec<Attribute>>)
2761 -> PResult<'a, P<Expr>> {
2762 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2765 /// Parse an associative expression with operators of at least `min_prec` precedence
2766 pub fn parse_assoc_expr_with(&mut self,
2769 -> PResult<'a, P<Expr>> {
2770 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2773 let attrs = match lhs {
2774 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2777 if self.token == token::DotDot || self.token == token::DotDotDot {
2778 return self.parse_prefix_range_expr(attrs);
2780 self.parse_prefix_expr(attrs)?
2784 if self.expr_is_complete(&lhs) {
2785 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2788 self.expected_tokens.push(TokenType::Operator);
2789 while let Some(op) = AssocOp::from_token(&self.token) {
2791 let lhs_span = if self.prev_token_kind == PrevTokenKind::Interpolated {
2797 let cur_op_span = self.span;
2798 let restrictions = if op.is_assign_like() {
2799 self.restrictions & RESTRICTION_NO_STRUCT_LITERAL
2803 if op.precedence() < min_prec {
2807 if op.is_comparison() {
2808 self.check_no_chained_comparison(&lhs, &op);
2811 if op == AssocOp::As {
2812 let rhs = self.parse_ty_no_plus()?;
2813 lhs = self.mk_expr(lhs_span.to(rhs.span), ExprKind::Cast(lhs, rhs), ThinVec::new());
2815 } else if op == AssocOp::Colon {
2816 let rhs = self.parse_ty_no_plus()?;
2817 lhs = self.mk_expr(lhs_span.to(rhs.span), ExprKind::Type(lhs, rhs), ThinVec::new());
2819 } else if op == AssocOp::DotDot || op == AssocOp::DotDotDot {
2820 // If we didn’t have to handle `x..`/`x...`, it would be pretty easy to
2821 // generalise it to the Fixity::None code.
2823 // We have 2 alternatives here: `x..y`/`x...y` and `x..`/`x...` The other
2824 // two variants are handled with `parse_prefix_range_expr` call above.
2825 let rhs = if self.is_at_start_of_range_notation_rhs() {
2826 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2827 LhsExpr::NotYetParsed)?)
2831 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2836 let limits = if op == AssocOp::DotDot {
2837 RangeLimits::HalfOpen
2842 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2843 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2847 let rhs = match op.fixity() {
2848 Fixity::Right => self.with_res(
2849 restrictions - RESTRICTION_STMT_EXPR,
2851 this.parse_assoc_expr_with(op.precedence(),
2852 LhsExpr::NotYetParsed)
2854 Fixity::Left => self.with_res(
2855 restrictions - RESTRICTION_STMT_EXPR,
2857 this.parse_assoc_expr_with(op.precedence() + 1,
2858 LhsExpr::NotYetParsed)
2860 // We currently have no non-associative operators that are not handled above by
2861 // the special cases. The code is here only for future convenience.
2862 Fixity::None => self.with_res(
2863 restrictions - RESTRICTION_STMT_EXPR,
2865 this.parse_assoc_expr_with(op.precedence() + 1,
2866 LhsExpr::NotYetParsed)
2870 let span = lhs_span.to(rhs.span);
2872 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2873 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2874 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2875 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2876 AssocOp::Greater | AssocOp::GreaterEqual => {
2877 let ast_op = op.to_ast_binop().unwrap();
2878 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2879 self.mk_expr(span, binary, ThinVec::new())
2882 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2884 self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
2885 AssocOp::AssignOp(k) => {
2887 token::Plus => BinOpKind::Add,
2888 token::Minus => BinOpKind::Sub,
2889 token::Star => BinOpKind::Mul,
2890 token::Slash => BinOpKind::Div,
2891 token::Percent => BinOpKind::Rem,
2892 token::Caret => BinOpKind::BitXor,
2893 token::And => BinOpKind::BitAnd,
2894 token::Or => BinOpKind::BitOr,
2895 token::Shl => BinOpKind::Shl,
2896 token::Shr => BinOpKind::Shr,
2898 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2899 self.mk_expr(span, aopexpr, ThinVec::new())
2901 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotDot => {
2902 self.bug("As, Colon, DotDot or DotDotDot branch reached")
2906 if op.fixity() == Fixity::None { break }
2911 /// Produce an error if comparison operators are chained (RFC #558).
2912 /// We only need to check lhs, not rhs, because all comparison ops
2913 /// have same precedence and are left-associative
2914 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2915 debug_assert!(outer_op.is_comparison());
2917 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2918 // respan to include both operators
2919 let op_span = op.span.to(self.span);
2920 let mut err = self.diagnostic().struct_span_err(op_span,
2921 "chained comparison operators require parentheses");
2922 if op.node == BinOpKind::Lt &&
2923 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
2924 *outer_op == AssocOp::Greater // even in a case like the following:
2925 { // Foo<Bar<Baz<Qux, ()>>>
2927 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2935 /// Parse prefix-forms of range notation: `..expr`, `..`, `...expr`
2936 fn parse_prefix_range_expr(&mut self,
2937 already_parsed_attrs: Option<ThinVec<Attribute>>)
2938 -> PResult<'a, P<Expr>> {
2939 debug_assert!(self.token == token::DotDot || self.token == token::DotDotDot);
2940 let tok = self.token.clone();
2941 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2943 let mut hi = self.span;
2945 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2946 // RHS must be parsed with more associativity than the dots.
2947 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
2948 Some(self.parse_assoc_expr_with(next_prec,
2949 LhsExpr::NotYetParsed)
2957 let limits = if tok == token::DotDot {
2958 RangeLimits::HalfOpen
2963 let r = try!(self.mk_range(None,
2966 Ok(self.mk_expr(lo.to(hi), r, attrs))
2969 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2970 if self.token.can_begin_expr() {
2971 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2972 if self.token == token::OpenDelim(token::Brace) {
2973 return !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL);
2981 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2982 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
2983 if self.check_keyword(keywords::Let) {
2984 return self.parse_if_let_expr(attrs);
2986 let lo = self.prev_span;
2987 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
2988 let thn = self.parse_block()?;
2989 let mut els: Option<P<Expr>> = None;
2990 let mut hi = thn.span;
2991 if self.eat_keyword(keywords::Else) {
2992 let elexpr = self.parse_else_expr()?;
2996 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
2999 /// Parse an 'if let' expression ('if' token already eaten)
3000 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3001 -> PResult<'a, P<Expr>> {
3002 let lo = self.prev_span;
3003 self.expect_keyword(keywords::Let)?;
3004 let pat = self.parse_pat()?;
3005 self.expect(&token::Eq)?;
3006 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3007 let thn = self.parse_block()?;
3008 let (hi, els) = if self.eat_keyword(keywords::Else) {
3009 let expr = self.parse_else_expr()?;
3010 (expr.span, Some(expr))
3014 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
3017 // `move |args| expr`
3018 pub fn parse_lambda_expr(&mut self,
3020 capture_clause: CaptureBy,
3021 attrs: ThinVec<Attribute>)
3022 -> PResult<'a, P<Expr>>
3024 let decl = self.parse_fn_block_decl()?;
3025 let decl_hi = self.prev_span;
3026 let body = match decl.output {
3027 FunctionRetTy::Default(_) => self.parse_expr()?,
3029 // If an explicit return type is given, require a
3030 // block to appear (RFC 968).
3031 let body_lo = self.span;
3032 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3038 ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3042 // `else` token already eaten
3043 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3044 if self.eat_keyword(keywords::If) {
3045 return self.parse_if_expr(ThinVec::new());
3047 let blk = self.parse_block()?;
3048 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3052 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3053 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3055 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3056 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3058 let pat = self.parse_pat()?;
3059 self.expect_keyword(keywords::In)?;
3060 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3061 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3062 attrs.extend(iattrs);
3064 let hi = self.prev_span;
3065 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3068 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3069 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3071 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3072 if self.token.is_keyword(keywords::Let) {
3073 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3075 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3076 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3077 attrs.extend(iattrs);
3078 let span = span_lo.to(body.span);
3079 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3082 /// Parse a 'while let' expression ('while' token already eaten)
3083 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3085 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3086 self.expect_keyword(keywords::Let)?;
3087 let pat = self.parse_pat()?;
3088 self.expect(&token::Eq)?;
3089 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3090 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3091 attrs.extend(iattrs);
3092 let span = span_lo.to(body.span);
3093 return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3096 // parse `loop {...}`, `loop` token already eaten
3097 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3099 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3100 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3101 attrs.extend(iattrs);
3102 let span = span_lo.to(body.span);
3103 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3106 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3107 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3108 -> PResult<'a, P<Expr>>
3110 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3111 attrs.extend(iattrs);
3112 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3115 // `match` token already eaten
3116 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3117 let match_span = self.prev_span;
3118 let lo = self.prev_span;
3119 let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL,
3121 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3122 if self.token == token::Token::Semi {
3123 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3127 attrs.extend(self.parse_inner_attributes()?);
3129 let mut arms: Vec<Arm> = Vec::new();
3130 while self.token != token::CloseDelim(token::Brace) {
3131 match self.parse_arm() {
3132 Ok(arm) => arms.push(arm),
3134 // Recover by skipping to the end of the block.
3136 self.recover_stmt();
3137 let span = lo.to(self.span);
3138 if self.token == token::CloseDelim(token::Brace) {
3141 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3147 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3150 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3151 maybe_whole!(self, NtArm, |x| x);
3153 let attrs = self.parse_outer_attributes()?;
3154 let pats = self.parse_pats()?;
3155 let guard = if self.eat_keyword(keywords::If) {
3156 Some(self.parse_expr()?)
3160 self.expect(&token::FatArrow)?;
3161 let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR, None)?;
3164 !classify::expr_is_simple_block(&expr)
3165 && self.token != token::CloseDelim(token::Brace);
3168 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3170 self.eat(&token::Comma);
3181 /// Parse an expression
3182 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3183 self.parse_expr_res(Restrictions::empty(), None)
3186 /// Evaluate the closure with restrictions in place.
3188 /// After the closure is evaluated, restrictions are reset.
3189 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3190 where F: FnOnce(&mut Self) -> T
3192 let old = self.restrictions;
3193 self.restrictions = r;
3195 self.restrictions = old;
3200 /// Parse an expression, subject to the given restrictions
3201 pub fn parse_expr_res(&mut self, r: Restrictions,
3202 already_parsed_attrs: Option<ThinVec<Attribute>>)
3203 -> PResult<'a, P<Expr>> {
3204 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3207 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3208 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3209 if self.check(&token::Eq) {
3211 Ok(Some(self.parse_expr()?))
3217 /// Parse patterns, separated by '|' s
3218 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3219 let mut pats = Vec::new();
3221 pats.push(self.parse_pat()?);
3222 if self.check(&token::BinOp(token::Or)) { self.bump();}
3223 else { return Ok(pats); }
3227 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3228 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3229 let mut fields = vec![];
3230 let mut ddpos = None;
3232 while !self.check(&token::CloseDelim(token::Paren)) {
3233 if ddpos.is_none() && self.eat(&token::DotDot) {
3234 ddpos = Some(fields.len());
3235 if self.eat(&token::Comma) {
3236 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3237 fields.push(self.parse_pat()?);
3239 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3240 // Emit a friendly error, ignore `..` and continue parsing
3241 self.span_err(self.prev_span, "`..` can only be used once per \
3242 tuple or tuple struct pattern");
3244 fields.push(self.parse_pat()?);
3247 if !self.check(&token::CloseDelim(token::Paren)) ||
3248 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3249 self.expect(&token::Comma)?;
3256 fn parse_pat_vec_elements(
3258 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3259 let mut before = Vec::new();
3260 let mut slice = None;
3261 let mut after = Vec::new();
3262 let mut first = true;
3263 let mut before_slice = true;
3265 while self.token != token::CloseDelim(token::Bracket) {
3269 self.expect(&token::Comma)?;
3271 if self.token == token::CloseDelim(token::Bracket)
3272 && (before_slice || !after.is_empty()) {
3278 if self.eat(&token::DotDot) {
3280 if self.check(&token::Comma) ||
3281 self.check(&token::CloseDelim(token::Bracket)) {
3282 slice = Some(P(ast::Pat {
3283 id: ast::DUMMY_NODE_ID,
3284 node: PatKind::Wild,
3287 before_slice = false;
3293 let subpat = self.parse_pat()?;
3294 if before_slice && self.eat(&token::DotDot) {
3295 slice = Some(subpat);
3296 before_slice = false;
3297 } else if before_slice {
3298 before.push(subpat);
3304 Ok((before, slice, after))
3307 /// Parse the fields of a struct-like pattern
3308 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3309 let mut fields = Vec::new();
3310 let mut etc = false;
3311 let mut first = true;
3312 while self.token != token::CloseDelim(token::Brace) {
3316 self.expect(&token::Comma)?;
3317 // accept trailing commas
3318 if self.check(&token::CloseDelim(token::Brace)) { break }
3321 let attrs = self.parse_outer_attributes()?;
3325 if self.check(&token::DotDot) {
3327 if self.token != token::CloseDelim(token::Brace) {
3328 let token_str = self.this_token_to_string();
3329 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3336 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3337 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3338 // Parsing a pattern of the form "fieldname: pat"
3339 let fieldname = self.parse_field_name()?;
3341 let pat = self.parse_pat()?;
3343 (pat, fieldname, false)
3345 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3346 let is_box = self.eat_keyword(keywords::Box);
3347 let boxed_span = self.span;
3348 let is_ref = self.eat_keyword(keywords::Ref);
3349 let is_mut = self.eat_keyword(keywords::Mut);
3350 let fieldname = self.parse_ident()?;
3351 hi = self.prev_span;
3353 let bind_type = match (is_ref, is_mut) {
3354 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3355 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3356 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3357 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3359 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3360 let fieldpat = P(ast::Pat{
3361 id: ast::DUMMY_NODE_ID,
3362 node: PatKind::Ident(bind_type, fieldpath, None),
3363 span: boxed_span.to(hi),
3366 let subpat = if is_box {
3368 id: ast::DUMMY_NODE_ID,
3369 node: PatKind::Box(fieldpat),
3375 (subpat, fieldname, true)
3378 fields.push(codemap::Spanned { span: lo.to(hi),
3379 node: ast::FieldPat {
3382 is_shorthand: is_shorthand,
3383 attrs: attrs.into(),
3387 return Ok((fields, etc));
3390 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3391 if self.token.is_path_start() {
3393 let (qself, path) = if self.eat_lt() {
3394 // Parse a qualified path
3396 self.parse_qualified_path(PathStyle::Expr)?;
3399 // Parse an unqualified path
3400 (None, self.parse_path(PathStyle::Expr)?)
3402 let hi = self.prev_span;
3403 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3405 self.parse_pat_literal_maybe_minus()
3409 // helper function to decide whether to parse as ident binding or to try to do
3410 // something more complex like range patterns
3411 fn parse_as_ident(&mut self) -> bool {
3412 self.look_ahead(1, |t| match *t {
3413 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3414 token::DotDotDot | token::ModSep | token::Not => Some(false),
3415 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3416 // range pattern branch
3417 token::DotDot => None,
3419 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3420 token::Comma | token::CloseDelim(token::Bracket) => true,
3425 /// Parse a pattern.
3426 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3427 maybe_whole!(self, NtPat, |x| x);
3432 token::Underscore => {
3435 pat = PatKind::Wild;
3437 token::BinOp(token::And) | token::AndAnd => {
3438 // Parse &pat / &mut pat
3440 let mutbl = self.parse_mutability();
3441 if let token::Lifetime(ident) = self.token {
3442 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3444 let subpat = self.parse_pat()?;
3445 pat = PatKind::Ref(subpat, mutbl);
3447 token::OpenDelim(token::Paren) => {
3448 // Parse (pat,pat,pat,...) as tuple pattern
3450 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3451 self.expect(&token::CloseDelim(token::Paren))?;
3452 pat = PatKind::Tuple(fields, ddpos);
3454 token::OpenDelim(token::Bracket) => {
3455 // Parse [pat,pat,...] as slice pattern
3457 let (before, slice, after) = self.parse_pat_vec_elements()?;
3458 self.expect(&token::CloseDelim(token::Bracket))?;
3459 pat = PatKind::Slice(before, slice, after);
3461 // At this point, token != _, &, &&, (, [
3462 _ => if self.eat_keyword(keywords::Mut) {
3463 // Parse mut ident @ pat
3464 pat = self.parse_pat_ident(BindingMode::ByValue(Mutability::Mutable))?;
3465 } else if self.eat_keyword(keywords::Ref) {
3466 // Parse ref ident @ pat / ref mut ident @ pat
3467 let mutbl = self.parse_mutability();
3468 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3469 } else if self.eat_keyword(keywords::Box) {
3471 let subpat = self.parse_pat()?;
3472 pat = PatKind::Box(subpat);
3473 } else if self.token.is_ident() && !self.token.is_any_keyword() &&
3474 self.parse_as_ident() {
3475 // Parse ident @ pat
3476 // This can give false positives and parse nullary enums,
3477 // they are dealt with later in resolve
3478 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3479 pat = self.parse_pat_ident(binding_mode)?;
3480 } else if self.token.is_path_start() {
3481 // Parse pattern starting with a path
3482 let (qself, path) = if self.eat_lt() {
3483 // Parse a qualified path
3484 let (qself, path) = self.parse_qualified_path(PathStyle::Expr)?;
3487 // Parse an unqualified path
3488 (None, self.parse_path(PathStyle::Expr)?)
3491 token::Not if qself.is_none() => {
3492 // Parse macro invocation
3494 let (_, tts) = self.expect_delimited_token_tree()?;
3495 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3496 pat = PatKind::Mac(mac);
3498 token::DotDotDot | token::DotDot => {
3499 let end_kind = match self.token {
3500 token::DotDot => RangeEnd::Excluded,
3501 token::DotDotDot => RangeEnd::Included,
3502 _ => panic!("can only parse `..` or `...` for ranges (checked above)"),
3505 let span = lo.to(self.prev_span);
3506 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3508 let end = self.parse_pat_range_end()?;
3509 pat = PatKind::Range(begin, end, end_kind);
3511 token::OpenDelim(token::Brace) => {
3512 if qself.is_some() {
3513 return Err(self.fatal("unexpected `{` after qualified path"));
3515 // Parse struct pattern
3517 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3519 self.recover_stmt();
3523 pat = PatKind::Struct(path, fields, etc);
3525 token::OpenDelim(token::Paren) => {
3526 if qself.is_some() {
3527 return Err(self.fatal("unexpected `(` after qualified path"));
3529 // Parse tuple struct or enum pattern
3531 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3532 self.expect(&token::CloseDelim(token::Paren))?;
3533 pat = PatKind::TupleStruct(path, fields, ddpos)
3535 _ => pat = PatKind::Path(qself, path),
3538 // Try to parse everything else as literal with optional minus
3539 match self.parse_pat_literal_maybe_minus() {
3541 if self.eat(&token::DotDotDot) {
3542 let end = self.parse_pat_range_end()?;
3543 pat = PatKind::Range(begin, end, RangeEnd::Included);
3544 } else if self.eat(&token::DotDot) {
3545 let end = self.parse_pat_range_end()?;
3546 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3548 pat = PatKind::Lit(begin);
3552 self.cancel(&mut err);
3553 let msg = format!("expected pattern, found {}", self.this_token_descr());
3554 return Err(self.fatal(&msg));
3561 id: ast::DUMMY_NODE_ID,
3563 span: lo.to(self.prev_span),
3567 /// Parse ident or ident @ pat
3568 /// used by the copy foo and ref foo patterns to give a good
3569 /// error message when parsing mistakes like ref foo(a,b)
3570 fn parse_pat_ident(&mut self,
3571 binding_mode: ast::BindingMode)
3572 -> PResult<'a, PatKind> {
3573 let ident_span = self.span;
3574 let ident = self.parse_ident()?;
3575 let name = codemap::Spanned{span: ident_span, node: ident};
3576 let sub = if self.eat(&token::At) {
3577 Some(self.parse_pat()?)
3582 // just to be friendly, if they write something like
3584 // we end up here with ( as the current token. This shortly
3585 // leads to a parse error. Note that if there is no explicit
3586 // binding mode then we do not end up here, because the lookahead
3587 // will direct us over to parse_enum_variant()
3588 if self.token == token::OpenDelim(token::Paren) {
3589 return Err(self.span_fatal(
3591 "expected identifier, found enum pattern"))
3594 Ok(PatKind::Ident(binding_mode, name, sub))
3597 /// Parse a local variable declaration
3598 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3600 let pat = self.parse_pat()?;
3602 let ty = if self.eat(&token::Colon) {
3603 Some(self.parse_ty()?)
3607 let init = self.parse_initializer()?;
3612 id: ast::DUMMY_NODE_ID,
3613 span: lo.to(self.prev_span),
3618 /// Parse a structure field
3619 fn parse_name_and_ty(&mut self,
3622 attrs: Vec<Attribute>)
3623 -> PResult<'a, StructField> {
3624 let name = self.parse_ident()?;
3625 self.expect(&token::Colon)?;
3626 let ty = self.parse_ty()?;
3628 span: lo.to(self.prev_span),
3631 id: ast::DUMMY_NODE_ID,
3637 /// Emit an expected item after attributes error.
3638 fn expected_item_err(&self, attrs: &[Attribute]) {
3639 let message = match attrs.last() {
3640 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3641 _ => "expected item after attributes",
3644 self.span_err(self.prev_span, message);
3647 /// Parse a statement. This stops just before trailing semicolons on everything but items.
3648 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3649 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3650 Ok(self.parse_stmt_(true))
3653 // Eat tokens until we can be relatively sure we reached the end of the
3654 // statement. This is something of a best-effort heuristic.
3656 // We terminate when we find an unmatched `}` (without consuming it).
3657 fn recover_stmt(&mut self) {
3658 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
3661 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3662 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3663 // approximate - it can mean we break too early due to macros, but that
3664 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3666 // If `break_on_block` is `Break`, then we will stop consuming tokens
3667 // after finding (and consuming) a brace-delimited block.
3668 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
3669 let mut brace_depth = 0;
3670 let mut bracket_depth = 0;
3671 let mut in_block = false;
3672 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
3673 break_on_semi, break_on_block);
3675 debug!("recover_stmt_ loop {:?}", self.token);
3677 token::OpenDelim(token::DelimToken::Brace) => {
3680 if break_on_block == BlockMode::Break &&
3682 bracket_depth == 0 {
3686 token::OpenDelim(token::DelimToken::Bracket) => {
3690 token::CloseDelim(token::DelimToken::Brace) => {
3691 if brace_depth == 0 {
3692 debug!("recover_stmt_ return - close delim {:?}", self.token);
3697 if in_block && bracket_depth == 0 && brace_depth == 0 {
3698 debug!("recover_stmt_ return - block end {:?}", self.token);
3702 token::CloseDelim(token::DelimToken::Bracket) => {
3704 if bracket_depth < 0 {
3710 debug!("recover_stmt_ return - Eof");
3715 if break_on_semi == SemiColonMode::Break &&
3717 bracket_depth == 0 {
3718 debug!("recover_stmt_ return - Semi");
3729 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
3730 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
3732 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
3737 fn is_catch_expr(&mut self) -> bool {
3738 self.token.is_keyword(keywords::Do) &&
3739 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
3740 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
3742 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3743 !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL)
3746 fn is_union_item(&self) -> bool {
3747 self.token.is_keyword(keywords::Union) &&
3748 self.look_ahead(1, |t| t.is_ident() && !t.is_any_keyword())
3751 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility)
3752 -> PResult<'a, Option<P<Item>>> {
3755 token::Ident(ident) if ident.name == "macro_rules" => {
3756 if self.look_ahead(1, |t| *t == token::Not) {
3757 let prev_span = self.prev_span;
3758 self.complain_if_pub_macro(vis, prev_span);
3763 _ => return Ok(None),
3766 let id = self.parse_ident()?;
3767 let (delim, tts) = self.expect_delimited_token_tree()?;
3768 if delim != token::Brace {
3769 if !self.eat(&token::Semi) {
3770 let msg = "macros that expand to items must either be surrounded with braces \
3771 or followed by a semicolon";
3772 self.span_err(self.prev_span, msg);
3776 let span = lo.to(self.prev_span);
3777 let kind = ItemKind::MacroDef(tts);
3778 Ok(Some(self.mk_item(span, id, kind, Visibility::Inherited, attrs.to_owned())))
3781 fn parse_stmt_without_recovery(&mut self,
3782 macro_legacy_warnings: bool)
3783 -> PResult<'a, Option<Stmt>> {
3784 maybe_whole!(self, NtStmt, |x| Some(x));
3786 let attrs = self.parse_outer_attributes()?;
3789 Ok(Some(if self.eat_keyword(keywords::Let) {
3791 id: ast::DUMMY_NODE_ID,
3792 node: StmtKind::Local(self.parse_local(attrs.into())?),
3793 span: lo.to(self.prev_span),
3795 } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited)? {
3797 id: ast::DUMMY_NODE_ID,
3798 node: StmtKind::Item(macro_def),
3799 span: lo.to(self.prev_span),
3801 // Starts like a simple path, but not a union item.
3802 } else if self.token.is_path_start() &&
3803 !self.token.is_qpath_start() &&
3804 !self.is_union_item() {
3805 let pth = self.parse_path(PathStyle::Expr)?;
3807 if !self.eat(&token::Not) {
3808 let expr = if self.check(&token::OpenDelim(token::Brace)) {
3809 self.parse_struct_expr(lo, pth, ThinVec::new())?
3811 let hi = self.prev_span;
3812 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
3815 let expr = self.with_res(RESTRICTION_STMT_EXPR, |this| {
3816 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
3817 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
3820 return Ok(Some(Stmt {
3821 id: ast::DUMMY_NODE_ID,
3822 node: StmtKind::Expr(expr),
3823 span: lo.to(self.prev_span),
3827 // it's a macro invocation
3828 let id = match self.token {
3829 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
3830 _ => self.parse_ident()?,
3833 // check that we're pointing at delimiters (need to check
3834 // again after the `if`, because of `parse_ident`
3835 // consuming more tokens).
3836 let delim = match self.token {
3837 token::OpenDelim(delim) => delim,
3839 // we only expect an ident if we didn't parse one
3841 let ident_str = if id.name == keywords::Invalid.name() {
3846 let tok_str = self.this_token_to_string();
3847 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3853 let (_, tts) = self.expect_delimited_token_tree()?;
3854 let hi = self.prev_span;
3856 let style = if delim == token::Brace {
3857 MacStmtStyle::Braces
3859 MacStmtStyle::NoBraces
3862 if id.name == keywords::Invalid.name() {
3863 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
3864 let node = if delim == token::Brace ||
3865 self.token == token::Semi || self.token == token::Eof {
3866 StmtKind::Mac(P((mac, style, attrs.into())))
3868 // We used to incorrectly stop parsing macro-expanded statements here.
3869 // If the next token will be an error anyway but could have parsed with the
3870 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
3871 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
3872 // These can continue an expression, so we can't stop parsing and warn.
3873 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
3874 token::BinOp(token::Minus) | token::BinOp(token::Star) |
3875 token::BinOp(token::And) | token::BinOp(token::Or) |
3876 token::AndAnd | token::OrOr |
3877 token::DotDot | token::DotDotDot => false,
3880 self.warn_missing_semicolon();
3881 StmtKind::Mac(P((mac, style, attrs.into())))
3883 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
3884 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
3885 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
3889 id: ast::DUMMY_NODE_ID,
3894 // if it has a special ident, it's definitely an item
3896 // Require a semicolon or braces.
3897 if style != MacStmtStyle::Braces {
3898 if !self.eat(&token::Semi) {
3899 self.span_err(self.prev_span,
3900 "macros that expand to items must \
3901 either be surrounded with braces or \
3902 followed by a semicolon");
3905 let span = lo.to(hi);
3907 id: ast::DUMMY_NODE_ID,
3909 node: StmtKind::Item({
3911 span, id /*id is good here*/,
3912 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
3913 Visibility::Inherited,
3919 // FIXME: Bad copy of attrs
3920 let old_directory_ownership =
3921 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
3922 let item = self.parse_item_(attrs.clone(), false, true)?;
3923 self.directory.ownership = old_directory_ownership;
3926 id: ast::DUMMY_NODE_ID,
3927 span: lo.to(i.span),
3928 node: StmtKind::Item(i),
3931 let unused_attrs = |attrs: &[_], s: &mut Self| {
3932 if !attrs.is_empty() {
3933 if s.prev_token_kind == PrevTokenKind::DocComment {
3934 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
3936 s.span_err(s.span, "expected statement after outer attribute");
3941 // Do not attempt to parse an expression if we're done here.
3942 if self.token == token::Semi {
3943 unused_attrs(&attrs, self);
3948 if self.token == token::CloseDelim(token::Brace) {
3949 unused_attrs(&attrs, self);
3953 // Remainder are line-expr stmts.
3954 let e = self.parse_expr_res(
3955 RESTRICTION_STMT_EXPR, Some(attrs.into()))?;
3957 id: ast::DUMMY_NODE_ID,
3958 span: lo.to(e.span),
3959 node: StmtKind::Expr(e),
3966 /// Is this expression a successfully-parsed statement?
3967 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3968 self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
3969 !classify::expr_requires_semi_to_be_stmt(e)
3972 /// Parse a block. No inner attrs are allowed.
3973 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
3974 maybe_whole!(self, NtBlock, |x| x);
3978 if !self.eat(&token::OpenDelim(token::Brace)) {
3980 let tok = self.this_token_to_string();
3981 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
3983 // Check to see if the user has written something like
3988 // Which is valid in other languages, but not Rust.
3989 match self.parse_stmt_without_recovery(false) {
3991 let mut stmt_span = stmt.span;
3992 // expand the span to include the semicolon, if it exists
3993 if self.eat(&token::Semi) {
3994 stmt_span.hi = self.prev_span.hi;
3996 let sugg = pprust::to_string(|s| {
3997 use print::pprust::{PrintState, INDENT_UNIT};
3998 s.ibox(INDENT_UNIT)?;
4000 s.print_stmt(&stmt)?;
4001 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4003 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4006 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4007 self.cancel(&mut e);
4014 self.parse_block_tail(lo, BlockCheckMode::Default)
4017 /// Parse a block. Inner attrs are allowed.
4018 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4019 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4022 self.expect(&token::OpenDelim(token::Brace))?;
4023 Ok((self.parse_inner_attributes()?,
4024 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4027 /// Parse the rest of a block expression or function body
4028 /// Precondition: already parsed the '{'.
4029 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4030 let mut stmts = vec![];
4032 while !self.eat(&token::CloseDelim(token::Brace)) {
4033 if let Some(stmt) = self.parse_full_stmt(false)? {
4035 } else if self.token == token::Eof {
4038 // Found only `;` or `}`.
4045 id: ast::DUMMY_NODE_ID,
4047 span: lo.to(self.prev_span),
4051 /// Parse a statement, including the trailing semicolon.
4052 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4053 let mut stmt = match self.parse_stmt_(macro_legacy_warnings) {
4055 None => return Ok(None),
4059 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4060 // expression without semicolon
4061 if classify::expr_requires_semi_to_be_stmt(expr) {
4062 // Just check for errors and recover; do not eat semicolon yet.
4064 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4067 self.recover_stmt();
4071 StmtKind::Local(..) => {
4072 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4073 if macro_legacy_warnings && self.token != token::Semi {
4074 self.warn_missing_semicolon();
4076 self.expect_one_of(&[token::Semi], &[])?;
4082 if self.eat(&token::Semi) {
4083 stmt = stmt.add_trailing_semicolon();
4086 stmt.span.hi = self.prev_span.hi;
4090 fn warn_missing_semicolon(&self) {
4091 self.diagnostic().struct_span_warn(self.span, {
4092 &format!("expected `;`, found `{}`", self.this_token_to_string())
4094 "This was erroneously allowed and will become a hard error in a future release"
4098 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4099 // BOUND = TY_BOUND | LT_BOUND
4100 // LT_BOUND = LIFETIME (e.g. `'a`)
4101 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4102 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4103 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4104 let mut bounds = Vec::new();
4106 let is_bound_start = self.check_path() || self.check_lifetime() ||
4107 self.check(&token::Question) ||
4108 self.check_keyword(keywords::For) ||
4109 self.check(&token::OpenDelim(token::Paren));
4111 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4112 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4113 if self.token.is_lifetime() {
4114 if let Some(question_span) = question {
4115 self.span_err(question_span,
4116 "`?` may only modify trait bounds, not lifetime bounds");
4118 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4121 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4122 let path = self.parse_path(PathStyle::Type)?;
4123 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4124 let modifier = if question.is_some() {
4125 TraitBoundModifier::Maybe
4127 TraitBoundModifier::None
4129 bounds.push(TraitTyParamBound(poly_trait, modifier));
4132 self.expect(&token::CloseDelim(token::Paren))?;
4133 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4134 self.span_err(self.prev_span,
4135 "parenthesized lifetime bounds are not supported");
4142 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4150 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4151 self.parse_ty_param_bounds_common(true)
4154 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4155 // BOUND = LT_BOUND (e.g. `'a`)
4156 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4157 let mut lifetimes = Vec::new();
4158 while self.check_lifetime() {
4159 lifetimes.push(self.expect_lifetime());
4161 if !self.eat(&token::BinOp(token::Plus)) {
4168 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4169 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4170 let span = self.span;
4171 let ident = self.parse_ident()?;
4173 // Parse optional colon and param bounds.
4174 let bounds = if self.eat(&token::Colon) {
4175 self.parse_ty_param_bounds()?
4180 let default = if self.eat(&token::Eq) {
4181 Some(self.parse_ty()?)
4187 attrs: preceding_attrs.into(),
4189 id: ast::DUMMY_NODE_ID,
4196 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4197 /// trailing comma and erroneous trailing attributes.
4198 pub fn parse_generic_params(&mut self) -> PResult<'a, (Vec<LifetimeDef>, Vec<TyParam>)> {
4199 let mut lifetime_defs = Vec::new();
4200 let mut ty_params = Vec::new();
4201 let mut seen_ty_param = false;
4203 let attrs = self.parse_outer_attributes()?;
4204 if self.check_lifetime() {
4205 let lifetime = self.expect_lifetime();
4206 // Parse lifetime parameter.
4207 let bounds = if self.eat(&token::Colon) {
4208 self.parse_lt_param_bounds()
4212 lifetime_defs.push(LifetimeDef {
4213 attrs: attrs.into(),
4218 self.span_err(self.prev_span,
4219 "lifetime parameters must be declared prior to type parameters");
4221 } else if self.check_ident() {
4222 // Parse type parameter.
4223 ty_params.push(self.parse_ty_param(attrs)?);
4224 seen_ty_param = true;
4226 // Check for trailing attributes and stop parsing.
4227 if !attrs.is_empty() {
4228 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4229 self.span_err(attrs[0].span,
4230 &format!("trailing attribute after {} parameters", param_kind));
4235 if !self.eat(&token::Comma) {
4239 Ok((lifetime_defs, ty_params))
4242 /// Parse a set of optional generic type parameter declarations. Where
4243 /// clauses are not parsed here, and must be added later via
4244 /// `parse_where_clause()`.
4246 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4247 /// | ( < lifetimes , typaramseq ( , )? > )
4248 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4249 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4250 maybe_whole!(self, NtGenerics, |x| x);
4252 let span_lo = self.span;
4254 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4257 lifetimes: lifetime_defs,
4258 ty_params: ty_params,
4259 where_clause: WhereClause {
4260 id: ast::DUMMY_NODE_ID,
4261 predicates: Vec::new(),
4263 span: span_lo.to(self.prev_span),
4266 Ok(ast::Generics::default())
4270 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4271 /// possibly including trailing comma.
4272 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4273 let mut lifetimes = Vec::new();
4274 let mut types = Vec::new();
4275 let mut bindings = Vec::new();
4276 let mut seen_type = false;
4277 let mut seen_binding = false;
4279 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4280 // Parse lifetime argument.
4281 lifetimes.push(self.expect_lifetime());
4282 if seen_type || seen_binding {
4283 self.span_err(self.prev_span,
4284 "lifetime parameters must be declared prior to type parameters");
4286 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4287 // Parse associated type binding.
4289 let ident = self.parse_ident()?;
4291 let ty = self.parse_ty()?;
4292 bindings.push(TypeBinding {
4293 id: ast::DUMMY_NODE_ID,
4296 span: lo.to(self.prev_span),
4298 seen_binding = true;
4299 } else if self.check_type() {
4300 // Parse type argument.
4301 types.push(self.parse_ty()?);
4303 self.span_err(types[types.len() - 1].span,
4304 "type parameters must be declared prior to associated type bindings");
4311 if !self.eat(&token::Comma) {
4315 Ok((lifetimes, types, bindings))
4318 /// Parses an optional `where` clause and places it in `generics`.
4321 /// where T : Trait<U, V> + 'b, 'a : 'b
4323 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4324 maybe_whole!(self, NtWhereClause, |x| x);
4326 let mut where_clause = WhereClause {
4327 id: ast::DUMMY_NODE_ID,
4328 predicates: Vec::new(),
4331 if !self.eat_keyword(keywords::Where) {
4332 return Ok(where_clause);
4335 // This is a temporary future proofing.
4337 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4338 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4339 // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4340 if token::Lt == self.token {
4341 let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4342 if ident_or_lifetime {
4343 let gt_comma_or_colon = self.look_ahead(2, |t| {
4344 *t == token::Gt || *t == token::Comma || *t == token::Colon
4346 if gt_comma_or_colon {
4347 self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4354 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4355 let lifetime = self.expect_lifetime();
4356 // Bounds starting with a colon are mandatory, but possibly empty.
4357 self.expect(&token::Colon)?;
4358 let bounds = self.parse_lt_param_bounds();
4359 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4360 ast::WhereRegionPredicate {
4361 span: lo.to(self.prev_span),
4366 } else if self.check_type() {
4367 // Parse optional `for<'a, 'b>`.
4368 // This `for` is parsed greedily and applies to the whole predicate,
4369 // the bounded type can have its own `for` applying only to it.
4370 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4371 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4372 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4373 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4375 // Parse type with mandatory colon and (possibly empty) bounds,
4376 // or with mandatory equality sign and the second type.
4377 let ty = self.parse_ty()?;
4378 if self.eat(&token::Colon) {
4379 let bounds = self.parse_ty_param_bounds()?;
4380 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4381 ast::WhereBoundPredicate {
4382 span: lo.to(self.prev_span),
4383 bound_lifetimes: lifetime_defs,
4388 // FIXME: Decide what should be used here, `=` or `==`.
4389 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4390 let rhs_ty = self.parse_ty()?;
4391 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4392 ast::WhereEqPredicate {
4393 span: lo.to(self.prev_span),
4396 id: ast::DUMMY_NODE_ID,
4400 return self.unexpected();
4406 if !self.eat(&token::Comma) {
4414 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4415 -> PResult<'a, (Vec<Arg> , bool)> {
4417 let mut variadic = false;
4418 let args: Vec<Option<Arg>> =
4419 self.parse_unspanned_seq(
4420 &token::OpenDelim(token::Paren),
4421 &token::CloseDelim(token::Paren),
4422 SeqSep::trailing_allowed(token::Comma),
4424 if p.token == token::DotDotDot {
4427 if p.token != token::CloseDelim(token::Paren) {
4430 "`...` must be last in argument list for variadic function");
4435 "only foreign functions are allowed to be variadic");
4440 match p.parse_arg_general(named_args) {
4441 Ok(arg) => Ok(Some(arg)),
4444 let lo = p.prev_span;
4445 // Skip every token until next possible arg or end.
4446 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4447 // Create a placeholder argument for proper arg count (#34264).
4448 let span = lo.to(p.prev_span);
4449 Ok(Some(dummy_arg(span)))
4456 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4458 if variadic && args.is_empty() {
4460 "variadic function must be declared with at least one named argument");
4463 Ok((args, variadic))
4466 /// Parse the argument list and result type of a function declaration
4467 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4469 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4470 let ret_ty = self.parse_ret_ty()?;
4479 /// Returns the parsed optional self argument and whether a self shortcut was used.
4480 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4481 let expect_ident = |this: &mut Self| match this.token {
4482 // Preserve hygienic context.
4483 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4486 let isolated_self = |this: &mut Self, n| {
4487 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4488 this.look_ahead(n + 1, |t| t != &token::ModSep)
4491 // Parse optional self parameter of a method.
4492 // Only a limited set of initial token sequences is considered self parameters, anything
4493 // else is parsed as a normal function parameter list, so some lookahead is required.
4494 let eself_lo = self.span;
4495 let (eself, eself_ident) = match self.token {
4496 token::BinOp(token::And) => {
4502 if isolated_self(self, 1) {
4504 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4505 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4506 isolated_self(self, 2) {
4509 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4510 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4511 isolated_self(self, 2) {
4513 let lt = self.expect_lifetime();
4514 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4515 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4516 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4517 isolated_self(self, 3) {
4519 let lt = self.expect_lifetime();
4521 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4526 token::BinOp(token::Star) => {
4531 // Emit special error for `self` cases.
4532 if isolated_self(self, 1) {
4534 self.span_err(self.span, "cannot pass `self` by raw pointer");
4535 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4536 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4537 isolated_self(self, 2) {
4540 self.span_err(self.span, "cannot pass `self` by raw pointer");
4541 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4546 token::Ident(..) => {
4547 if isolated_self(self, 0) {
4550 let eself_ident = expect_ident(self);
4551 if self.eat(&token::Colon) {
4552 let ty = self.parse_ty()?;
4553 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4555 (SelfKind::Value(Mutability::Immutable), eself_ident)
4557 } else if self.token.is_keyword(keywords::Mut) &&
4558 isolated_self(self, 1) {
4562 let eself_ident = expect_ident(self);
4563 if self.eat(&token::Colon) {
4564 let ty = self.parse_ty()?;
4565 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4567 (SelfKind::Value(Mutability::Mutable), eself_ident)
4573 _ => return Ok(None),
4576 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
4577 Ok(Some(Arg::from_self(eself, eself_ident)))
4580 /// Parse the parameter list and result type of a function that may have a `self` parameter.
4581 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
4582 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4584 self.expect(&token::OpenDelim(token::Paren))?;
4586 // Parse optional self argument
4587 let self_arg = self.parse_self_arg()?;
4589 // Parse the rest of the function parameter list.
4590 let sep = SeqSep::trailing_allowed(token::Comma);
4591 let fn_inputs = if let Some(self_arg) = self_arg {
4592 if self.check(&token::CloseDelim(token::Paren)) {
4594 } else if self.eat(&token::Comma) {
4595 let mut fn_inputs = vec![self_arg];
4596 fn_inputs.append(&mut self.parse_seq_to_before_end(
4597 &token::CloseDelim(token::Paren), sep, parse_arg_fn)
4601 return self.unexpected();
4604 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4607 // Parse closing paren and return type.
4608 self.expect(&token::CloseDelim(token::Paren))?;
4611 output: self.parse_ret_ty()?,
4616 // parse the |arg, arg| header on a lambda
4617 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4618 let inputs_captures = {
4619 if self.eat(&token::OrOr) {
4622 self.expect(&token::BinOp(token::Or))?;
4623 let args = self.parse_seq_to_before_end(
4624 &token::BinOp(token::Or),
4625 SeqSep::trailing_allowed(token::Comma),
4626 |p| p.parse_fn_block_arg()
4632 let output = self.parse_ret_ty()?;
4635 inputs: inputs_captures,
4641 /// Parse the name and optional generic types of a function header.
4642 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4643 let id = self.parse_ident()?;
4644 let generics = self.parse_generics()?;
4648 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
4649 attrs: Vec<Attribute>) -> P<Item> {
4653 id: ast::DUMMY_NODE_ID,
4660 /// Parse an item-position function declaration.
4661 fn parse_item_fn(&mut self,
4663 constness: Spanned<Constness>,
4665 -> PResult<'a, ItemInfo> {
4666 let (ident, mut generics) = self.parse_fn_header()?;
4667 let decl = self.parse_fn_decl(false)?;
4668 generics.where_clause = self.parse_where_clause()?;
4669 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4670 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4673 /// true if we are looking at `const ID`, false for things like `const fn` etc
4674 pub fn is_const_item(&mut self) -> bool {
4675 self.token.is_keyword(keywords::Const) &&
4676 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4677 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4680 /// parses all the "front matter" for a `fn` declaration, up to
4681 /// and including the `fn` keyword:
4685 /// - `const unsafe fn`
4688 pub fn parse_fn_front_matter(&mut self)
4689 -> PResult<'a, (Spanned<ast::Constness>,
4692 let is_const_fn = self.eat_keyword(keywords::Const);
4693 let const_span = self.prev_span;
4694 let unsafety = self.parse_unsafety()?;
4695 let (constness, unsafety, abi) = if is_const_fn {
4696 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
4698 let abi = if self.eat_keyword(keywords::Extern) {
4699 self.parse_opt_abi()?.unwrap_or(Abi::C)
4703 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
4705 self.expect_keyword(keywords::Fn)?;
4706 Ok((constness, unsafety, abi))
4709 /// Parse an impl item.
4710 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
4711 maybe_whole!(self, NtImplItem, |x| x);
4713 let mut attrs = self.parse_outer_attributes()?;
4715 let vis = self.parse_visibility(false)?;
4716 let defaultness = self.parse_defaultness()?;
4717 let (name, node) = if self.eat_keyword(keywords::Type) {
4718 let name = self.parse_ident()?;
4719 self.expect(&token::Eq)?;
4720 let typ = self.parse_ty()?;
4721 self.expect(&token::Semi)?;
4722 (name, ast::ImplItemKind::Type(typ))
4723 } else if self.is_const_item() {
4724 self.expect_keyword(keywords::Const)?;
4725 let name = self.parse_ident()?;
4726 self.expect(&token::Colon)?;
4727 let typ = self.parse_ty()?;
4728 self.expect(&token::Eq)?;
4729 let expr = self.parse_expr()?;
4730 self.expect(&token::Semi)?;
4731 (name, ast::ImplItemKind::Const(typ, expr))
4733 let (name, inner_attrs, node) = self.parse_impl_method(&vis, at_end)?;
4734 attrs.extend(inner_attrs);
4739 id: ast::DUMMY_NODE_ID,
4740 span: lo.to(self.prev_span),
4743 defaultness: defaultness,
4749 fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
4750 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
4755 fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
4757 Visibility::Inherited => Ok(()),
4759 let is_macro_rules: bool = match self.token {
4760 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
4764 let mut err = self.diagnostic()
4765 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
4766 err.help("did you mean #[macro_export]?");
4769 let mut err = self.diagnostic()
4770 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
4771 err.help("try adjusting the macro to put `pub` inside the invocation");
4778 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
4779 -> DiagnosticBuilder<'a>
4781 // Given this code `path(`, it seems like this is not
4782 // setting the visibility of a macro invocation, but rather
4783 // a mistyped method declaration.
4784 // Create a diagnostic pointing out that `fn` is missing.
4786 // x | pub path(&self) {
4787 // | ^ missing `fn`, `type`, or `const`
4789 // ^^ `sp` below will point to this
4790 let sp = prev_span.between(self.prev_span);
4791 let mut err = self.diagnostic().struct_span_err(
4793 &format!("missing `fn`, `type`, or `const` for {}-item declaration",
4795 err.span_label(sp, "missing `fn`, `type`, or `const`");
4799 /// Parse a method or a macro invocation in a trait impl.
4800 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
4801 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4802 // code copied from parse_macro_use_or_failure... abstraction!
4803 if self.token.is_path_start() {
4806 let prev_span = self.prev_span;
4809 let pth = self.parse_path(PathStyle::Mod)?;
4810 if pth.segments.len() == 1 {
4811 if !self.eat(&token::Not) {
4812 return Err(self.missing_assoc_item_kind_err("impl", prev_span));
4815 self.expect(&token::Not)?;
4818 self.complain_if_pub_macro(vis, prev_span);
4820 // eat a matched-delimiter token tree:
4822 let (delim, tts) = self.expect_delimited_token_tree()?;
4823 if delim != token::Brace {
4824 self.expect(&token::Semi)?
4827 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
4828 Ok((keywords::Invalid.ident(), vec![], ast::ImplItemKind::Macro(mac)))
4830 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
4831 let ident = self.parse_ident()?;
4832 let mut generics = self.parse_generics()?;
4833 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
4834 generics.where_clause = self.parse_where_clause()?;
4836 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4837 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4841 constness: constness,
4847 /// Parse trait Foo { ... }
4848 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4849 let ident = self.parse_ident()?;
4850 let mut tps = self.parse_generics()?;
4852 // Parse optional colon and supertrait bounds.
4853 let bounds = if self.eat(&token::Colon) {
4854 self.parse_ty_param_bounds()?
4859 tps.where_clause = self.parse_where_clause()?;
4861 self.expect(&token::OpenDelim(token::Brace))?;
4862 let mut trait_items = vec![];
4863 while !self.eat(&token::CloseDelim(token::Brace)) {
4864 let mut at_end = false;
4865 match self.parse_trait_item(&mut at_end) {
4866 Ok(item) => trait_items.push(item),
4870 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
4875 Ok((ident, ItemKind::Trait(unsafety, tps, bounds, trait_items), None))
4878 /// Parses items implementations variants
4879 /// impl<T> Foo { ... }
4880 /// impl<T> ToString for &'static T { ... }
4881 /// impl Send for .. {}
4882 fn parse_item_impl(&mut self,
4883 unsafety: ast::Unsafety,
4884 defaultness: Defaultness) -> PResult<'a, ItemInfo> {
4885 let impl_span = self.span;
4887 // First, parse type parameters if necessary.
4888 let mut generics = self.parse_generics()?;
4890 // Special case: if the next identifier that follows is '(', don't
4891 // allow this to be parsed as a trait.
4892 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4894 let neg_span = self.span;
4895 let polarity = if self.eat(&token::Not) {
4896 ast::ImplPolarity::Negative
4898 ast::ImplPolarity::Positive
4902 let mut ty = self.parse_ty()?;
4904 // Parse traits, if necessary.
4905 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4906 // New-style trait. Reinterpret the type as a trait.
4908 TyKind::Path(None, ref path) => {
4910 path: (*path).clone(),
4915 self.span_err(ty.span, "not a trait");
4920 if polarity == ast::ImplPolarity::Negative {
4921 // This is a negated type implementation
4922 // `impl !MyType {}`, which is not allowed.
4923 self.span_err(neg_span, "inherent implementation can't be negated");
4928 if opt_trait.is_some() && self.eat(&token::DotDot) {
4929 if generics.is_parameterized() {
4930 self.span_err(impl_span, "default trait implementations are not \
4931 allowed to have generics");
4934 if let ast::Defaultness::Default = defaultness {
4935 self.span_err(impl_span, "`default impl` is not allowed for \
4936 default trait implementations");
4939 self.expect(&token::OpenDelim(token::Brace))?;
4940 self.expect(&token::CloseDelim(token::Brace))?;
4941 Ok((keywords::Invalid.ident(),
4942 ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
4944 if opt_trait.is_some() {
4945 ty = self.parse_ty()?;
4947 generics.where_clause = self.parse_where_clause()?;
4949 self.expect(&token::OpenDelim(token::Brace))?;
4950 let attrs = self.parse_inner_attributes()?;
4952 let mut impl_items = vec![];
4953 while !self.eat(&token::CloseDelim(token::Brace)) {
4954 let mut at_end = false;
4955 match self.parse_impl_item(&mut at_end) {
4956 Ok(item) => impl_items.push(item),
4960 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
4966 Ok((keywords::Invalid.ident(),
4967 ItemKind::Impl(unsafety, polarity, defaultness, generics, opt_trait, ty, impl_items),
4972 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<LifetimeDef>> {
4973 if self.eat_keyword(keywords::For) {
4975 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4977 if !ty_params.is_empty() {
4978 self.span_err(ty_params[0].span,
4979 "only lifetime parameters can be used in this context");
4987 /// Parse struct Foo { ... }
4988 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
4989 let class_name = self.parse_ident()?;
4991 let mut generics = self.parse_generics()?;
4993 // There is a special case worth noting here, as reported in issue #17904.
4994 // If we are parsing a tuple struct it is the case that the where clause
4995 // should follow the field list. Like so:
4997 // struct Foo<T>(T) where T: Copy;
4999 // If we are parsing a normal record-style struct it is the case
5000 // that the where clause comes before the body, and after the generics.
5001 // So if we look ahead and see a brace or a where-clause we begin
5002 // parsing a record style struct.
5004 // Otherwise if we look ahead and see a paren we parse a tuple-style
5007 let vdata = if self.token.is_keyword(keywords::Where) {
5008 generics.where_clause = self.parse_where_clause()?;
5009 if self.eat(&token::Semi) {
5010 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5011 VariantData::Unit(ast::DUMMY_NODE_ID)
5013 // If we see: `struct Foo<T> where T: Copy { ... }`
5014 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5016 // No `where` so: `struct Foo<T>;`
5017 } else if self.eat(&token::Semi) {
5018 VariantData::Unit(ast::DUMMY_NODE_ID)
5019 // Record-style struct definition
5020 } else if self.token == token::OpenDelim(token::Brace) {
5021 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5022 // Tuple-style struct definition with optional where-clause.
5023 } else if self.token == token::OpenDelim(token::Paren) {
5024 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5025 generics.where_clause = self.parse_where_clause()?;
5026 self.expect(&token::Semi)?;
5029 let token_str = self.this_token_to_string();
5030 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5031 name, found `{}`", token_str)))
5034 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5037 /// Parse union Foo { ... }
5038 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5039 let class_name = self.parse_ident()?;
5041 let mut generics = self.parse_generics()?;
5043 let vdata = if self.token.is_keyword(keywords::Where) {
5044 generics.where_clause = self.parse_where_clause()?;
5045 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5046 } else if self.token == token::OpenDelim(token::Brace) {
5047 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5049 let token_str = self.this_token_to_string();
5050 return Err(self.fatal(&format!("expected `where` or `{{` after union \
5051 name, found `{}`", token_str)))
5054 Ok((class_name, ItemKind::Union(vdata, generics), None))
5057 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5058 let mut fields = Vec::new();
5059 if self.eat(&token::OpenDelim(token::Brace)) {
5060 while self.token != token::CloseDelim(token::Brace) {
5061 fields.push(self.parse_struct_decl_field().map_err(|e| {
5062 self.recover_stmt();
5063 self.eat(&token::CloseDelim(token::Brace));
5070 let token_str = self.this_token_to_string();
5071 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5079 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5080 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5081 // Unit like structs are handled in parse_item_struct function
5082 let fields = self.parse_unspanned_seq(
5083 &token::OpenDelim(token::Paren),
5084 &token::CloseDelim(token::Paren),
5085 SeqSep::trailing_allowed(token::Comma),
5087 let attrs = p.parse_outer_attributes()?;
5089 let vis = p.parse_visibility(true)?;
5090 let ty = p.parse_ty()?;
5092 span: lo.to(p.span),
5095 id: ast::DUMMY_NODE_ID,
5104 /// Parse a structure field declaration
5105 pub fn parse_single_struct_field(&mut self,
5108 attrs: Vec<Attribute> )
5109 -> PResult<'a, StructField> {
5110 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5115 token::CloseDelim(token::Brace) => {}
5116 token::DocComment(_) => return Err(self.span_fatal_err(self.span,
5117 Error::UselessDocComment)),
5118 _ => return Err(self.span_fatal_help(self.span,
5119 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5120 "struct fields should be separated by commas")),
5125 /// Parse an element of a struct definition
5126 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5127 let attrs = self.parse_outer_attributes()?;
5129 let vis = self.parse_visibility(false)?;
5130 self.parse_single_struct_field(lo, vis, attrs)
5133 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5134 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5135 /// a function definition, it's not a tuple struct field) and the contents within the parens
5136 /// isn't valid, emit a proper diagnostic.
5137 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5138 maybe_whole!(self, NtVis, |x| x);
5140 if !self.eat_keyword(keywords::Pub) {
5141 return Ok(Visibility::Inherited)
5144 if self.check(&token::OpenDelim(token::Paren)) {
5145 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5146 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5147 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5148 // by the following tokens.
5149 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5152 self.bump(); // `crate`
5153 let vis = Visibility::Crate(self.prev_span);
5154 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5156 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5159 self.bump(); // `in`
5160 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5161 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5162 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5164 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5165 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5166 t.is_keyword(keywords::SelfValue)) {
5167 // `pub(self)` or `pub(super)`
5169 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5170 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5171 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5173 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5174 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5176 let msg = "incorrect visibility restriction";
5177 let suggestion = r##"some possible visibility restrictions are:
5178 `pub(crate)`: visible only on the current crate
5179 `pub(super)`: visible only in the current module's parent
5180 `pub(in path::to::module)`: visible only on the specified path"##;
5181 let path = self.parse_path(PathStyle::Mod)?;
5182 let path_span = self.prev_span;
5183 let help_msg = format!("make this visible only to module `{}` with `in`:", path);
5184 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5185 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5186 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5187 err.emit(); // emit diagnostic, but continue with public visibility
5191 Ok(Visibility::Public)
5194 /// Parse defaultness: DEFAULT or nothing
5195 fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5196 if self.eat_contextual_keyword(keywords::Default.ident()) {
5197 Ok(Defaultness::Default)
5199 Ok(Defaultness::Final)
5203 /// Given a termination token, parse all of the items in a module
5204 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5205 let mut items = vec![];
5206 while let Some(item) = self.parse_item()? {
5210 if !self.eat(term) {
5211 let token_str = self.this_token_to_string();
5212 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5215 let hi = if self.span == syntax_pos::DUMMY_SP {
5222 inner: inner_lo.to(hi),
5227 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5228 let id = self.parse_ident()?;
5229 self.expect(&token::Colon)?;
5230 let ty = self.parse_ty()?;
5231 self.expect(&token::Eq)?;
5232 let e = self.parse_expr()?;
5233 self.expect(&token::Semi)?;
5234 let item = match m {
5235 Some(m) => ItemKind::Static(ty, m, e),
5236 None => ItemKind::Const(ty, e),
5238 Ok((id, item, None))
5241 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5242 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5243 let (in_cfg, outer_attrs) = {
5244 let mut strip_unconfigured = ::config::StripUnconfigured {
5246 should_test: false, // irrelevant
5247 features: None, // don't perform gated feature checking
5249 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5250 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5253 let id_span = self.span;
5254 let id = self.parse_ident()?;
5255 if self.check(&token::Semi) {
5258 // This mod is in an external file. Let's go get it!
5259 let ModulePathSuccess { path, directory_ownership, warn } =
5260 self.submod_path(id, &outer_attrs, id_span)?;
5261 let (module, mut attrs) =
5262 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5264 let attr = ast::Attribute {
5265 id: attr::mk_attr_id(),
5266 style: ast::AttrStyle::Outer,
5267 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5268 Ident::from_str("warn_directory_ownership")),
5269 tokens: TokenStream::empty(),
5270 is_sugared_doc: false,
5271 span: syntax_pos::DUMMY_SP,
5273 attr::mark_known(&attr);
5276 Ok((id, module, Some(attrs)))
5278 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5279 Ok((id, ItemKind::Mod(placeholder), None))
5282 let old_directory = self.directory.clone();
5283 self.push_directory(id, &outer_attrs);
5284 self.expect(&token::OpenDelim(token::Brace))?;
5285 let mod_inner_lo = self.span;
5286 let attrs = self.parse_inner_attributes()?;
5287 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5288 self.directory = old_directory;
5289 Ok((id, ItemKind::Mod(module), Some(attrs)))
5293 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5294 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5295 self.directory.path.push(&path.as_str());
5296 self.directory.ownership = DirectoryOwnership::Owned;
5298 self.directory.path.push(&id.name.as_str());
5302 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5303 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5306 /// Returns either a path to a module, or .
5307 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5308 let mod_name = id.to_string();
5309 let default_path_str = format!("{}.rs", mod_name);
5310 let secondary_path_str = format!("{}{}mod.rs", mod_name, path::MAIN_SEPARATOR);
5311 let default_path = dir_path.join(&default_path_str);
5312 let secondary_path = dir_path.join(&secondary_path_str);
5313 let default_exists = codemap.file_exists(&default_path);
5314 let secondary_exists = codemap.file_exists(&secondary_path);
5316 let result = match (default_exists, secondary_exists) {
5317 (true, false) => Ok(ModulePathSuccess {
5319 directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5322 (false, true) => Ok(ModulePathSuccess {
5323 path: secondary_path,
5324 directory_ownership: DirectoryOwnership::Owned,
5327 (false, false) => Err(Error::FileNotFoundForModule {
5328 mod_name: mod_name.clone(),
5329 default_path: default_path_str,
5330 secondary_path: secondary_path_str,
5331 dir_path: format!("{}", dir_path.display()),
5333 (true, true) => Err(Error::DuplicatePaths {
5334 mod_name: mod_name.clone(),
5335 default_path: default_path_str,
5336 secondary_path: secondary_path_str,
5342 path_exists: default_exists || secondary_exists,
5347 fn submod_path(&mut self,
5349 outer_attrs: &[ast::Attribute],
5350 id_sp: Span) -> PResult<'a, ModulePathSuccess> {
5351 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5352 return Ok(ModulePathSuccess {
5353 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5354 Some("mod.rs") => DirectoryOwnership::Owned,
5355 _ => DirectoryOwnership::UnownedViaMod(true),
5362 let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5364 if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5366 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5367 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5368 if paths.path_exists {
5369 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5371 err.span_note(id_sp, &msg);
5374 } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5376 if let Ok(result) = paths.result {
5377 return Ok(ModulePathSuccess { warn: true, ..result });
5380 let mut err = self.diagnostic().struct_span_err(id_sp,
5381 "cannot declare a new module at this location");
5382 if id_sp != syntax_pos::DUMMY_SP {
5383 let src_path = PathBuf::from(self.sess.codemap().span_to_filename(id_sp));
5384 if let Some(stem) = src_path.file_stem() {
5385 let mut dest_path = src_path.clone();
5386 dest_path.set_file_name(stem);
5387 dest_path.push("mod.rs");
5388 err.span_note(id_sp,
5389 &format!("maybe move this module `{}` to its own \
5390 directory via `{}`", src_path.to_string_lossy(),
5391 dest_path.to_string_lossy()));
5394 if paths.path_exists {
5395 err.span_note(id_sp,
5396 &format!("... or maybe `use` the module `{}` instead \
5397 of possibly redeclaring it",
5402 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5406 /// Read a module from a source file.
5407 fn eval_src_mod(&mut self,
5409 directory_ownership: DirectoryOwnership,
5412 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5413 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5414 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5415 let mut err = String::from("circular modules: ");
5416 let len = included_mod_stack.len();
5417 for p in &included_mod_stack[i.. len] {
5418 err.push_str(&p.to_string_lossy());
5419 err.push_str(" -> ");
5421 err.push_str(&path.to_string_lossy());
5422 return Err(self.span_fatal(id_sp, &err[..]));
5424 included_mod_stack.push(path.clone());
5425 drop(included_mod_stack);
5428 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5429 p0.cfg_mods = self.cfg_mods;
5430 let mod_inner_lo = p0.span;
5431 let mod_attrs = p0.parse_inner_attributes()?;
5432 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5433 self.sess.included_mod_stack.borrow_mut().pop();
5434 Ok((ast::ItemKind::Mod(m0), mod_attrs))
5437 /// Parse a function declaration from a foreign module
5438 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5439 -> PResult<'a, ForeignItem> {
5440 self.expect_keyword(keywords::Fn)?;
5442 let (ident, mut generics) = self.parse_fn_header()?;
5443 let decl = self.parse_fn_decl(true)?;
5444 generics.where_clause = self.parse_where_clause()?;
5446 self.expect(&token::Semi)?;
5447 Ok(ast::ForeignItem {
5450 node: ForeignItemKind::Fn(decl, generics),
5451 id: ast::DUMMY_NODE_ID,
5457 /// Parse a static item from a foreign module
5458 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5459 -> PResult<'a, ForeignItem> {
5460 self.expect_keyword(keywords::Static)?;
5461 let mutbl = self.eat_keyword(keywords::Mut);
5463 let ident = self.parse_ident()?;
5464 self.expect(&token::Colon)?;
5465 let ty = self.parse_ty()?;
5467 self.expect(&token::Semi)?;
5471 node: ForeignItemKind::Static(ty, mutbl),
5472 id: ast::DUMMY_NODE_ID,
5478 /// Parse extern crate links
5482 /// extern crate foo;
5483 /// extern crate bar as foo;
5484 fn parse_item_extern_crate(&mut self,
5486 visibility: Visibility,
5487 attrs: Vec<Attribute>)
5488 -> PResult<'a, P<Item>> {
5490 let crate_name = self.parse_ident()?;
5491 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
5492 (Some(crate_name.name), ident)
5496 self.expect(&token::Semi)?;
5498 let prev_span = self.prev_span;
5499 Ok(self.mk_item(lo.to(prev_span),
5501 ItemKind::ExternCrate(maybe_path),
5506 /// Parse `extern` for foreign ABIs
5509 /// `extern` is expected to have been
5510 /// consumed before calling this method
5516 fn parse_item_foreign_mod(&mut self,
5518 opt_abi: Option<abi::Abi>,
5519 visibility: Visibility,
5520 mut attrs: Vec<Attribute>)
5521 -> PResult<'a, P<Item>> {
5522 self.expect(&token::OpenDelim(token::Brace))?;
5524 let abi = opt_abi.unwrap_or(Abi::C);
5526 attrs.extend(self.parse_inner_attributes()?);
5528 let mut foreign_items = vec![];
5529 while let Some(item) = self.parse_foreign_item()? {
5530 foreign_items.push(item);
5532 self.expect(&token::CloseDelim(token::Brace))?;
5534 let prev_span = self.prev_span;
5535 let m = ast::ForeignMod {
5537 items: foreign_items
5539 let invalid = keywords::Invalid.ident();
5540 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
5543 /// Parse type Foo = Bar;
5544 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5545 let ident = self.parse_ident()?;
5546 let mut tps = self.parse_generics()?;
5547 tps.where_clause = self.parse_where_clause()?;
5548 self.expect(&token::Eq)?;
5549 let ty = self.parse_ty()?;
5550 self.expect(&token::Semi)?;
5551 Ok((ident, ItemKind::Ty(ty, tps), None))
5554 /// Parse the part of an "enum" decl following the '{'
5555 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5556 let mut variants = Vec::new();
5557 let mut all_nullary = true;
5558 let mut any_disr = None;
5559 while self.token != token::CloseDelim(token::Brace) {
5560 let variant_attrs = self.parse_outer_attributes()?;
5561 let vlo = self.span;
5564 let mut disr_expr = None;
5565 let ident = self.parse_ident()?;
5566 if self.check(&token::OpenDelim(token::Brace)) {
5567 // Parse a struct variant.
5568 all_nullary = false;
5569 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
5570 ast::DUMMY_NODE_ID);
5571 } else if self.check(&token::OpenDelim(token::Paren)) {
5572 all_nullary = false;
5573 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
5574 ast::DUMMY_NODE_ID);
5575 } else if self.eat(&token::Eq) {
5576 disr_expr = Some(self.parse_expr()?);
5577 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5578 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5580 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5583 let vr = ast::Variant_ {
5585 attrs: variant_attrs,
5587 disr_expr: disr_expr,
5589 variants.push(respan(vlo.to(self.prev_span), vr));
5591 if !self.eat(&token::Comma) { break; }
5593 self.expect(&token::CloseDelim(token::Brace))?;
5595 Some(disr_span) if !all_nullary =>
5596 self.span_err(disr_span,
5597 "discriminator values can only be used with a c-like enum"),
5601 Ok(ast::EnumDef { variants: variants })
5604 /// Parse an "enum" declaration
5605 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5606 let id = self.parse_ident()?;
5607 let mut generics = self.parse_generics()?;
5608 generics.where_clause = self.parse_where_clause()?;
5609 self.expect(&token::OpenDelim(token::Brace))?;
5611 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
5612 self.recover_stmt();
5613 self.eat(&token::CloseDelim(token::Brace));
5616 Ok((id, ItemKind::Enum(enum_definition, generics), None))
5619 /// Parses a string as an ABI spec on an extern type or module. Consumes
5620 /// the `extern` keyword, if one is found.
5621 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5623 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5625 self.expect_no_suffix(sp, "ABI spec", suf);
5627 match abi::lookup(&s.as_str()) {
5628 Some(abi) => Ok(Some(abi)),
5630 let prev_span = self.prev_span;
5633 &format!("invalid ABI: expected one of [{}], \
5635 abi::all_names().join(", "),
5646 /// Parse one of the items allowed by the flags.
5647 /// NB: this function no longer parses the items inside an
5649 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5650 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5651 maybe_whole!(self, NtItem, |item| {
5652 let mut item = item.unwrap();
5653 let mut attrs = attrs;
5654 mem::swap(&mut item.attrs, &mut attrs);
5655 item.attrs.extend(attrs);
5661 let visibility = self.parse_visibility(false)?;
5663 if self.eat_keyword(keywords::Use) {
5665 let item_ = ItemKind::Use(self.parse_view_path()?);
5666 self.expect(&token::Semi)?;
5668 let prev_span = self.prev_span;
5669 let invalid = keywords::Invalid.ident();
5670 let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
5671 return Ok(Some(item));
5674 if self.eat_keyword(keywords::Extern) {
5675 if self.eat_keyword(keywords::Crate) {
5676 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
5679 let opt_abi = self.parse_opt_abi()?;
5681 if self.eat_keyword(keywords::Fn) {
5682 // EXTERN FUNCTION ITEM
5683 let fn_span = self.prev_span;
5684 let abi = opt_abi.unwrap_or(Abi::C);
5685 let (ident, item_, extra_attrs) =
5686 self.parse_item_fn(Unsafety::Normal,
5687 respan(fn_span, Constness::NotConst),
5689 let prev_span = self.prev_span;
5690 let item = self.mk_item(lo.to(prev_span),
5694 maybe_append(attrs, extra_attrs));
5695 return Ok(Some(item));
5696 } else if self.check(&token::OpenDelim(token::Brace)) {
5697 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
5703 if self.eat_keyword(keywords::Static) {
5705 let m = if self.eat_keyword(keywords::Mut) {
5708 Mutability::Immutable
5710 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
5711 let prev_span = self.prev_span;
5712 let item = self.mk_item(lo.to(prev_span),
5716 maybe_append(attrs, extra_attrs));
5717 return Ok(Some(item));
5719 if self.eat_keyword(keywords::Const) {
5720 let const_span = self.prev_span;
5721 if self.check_keyword(keywords::Fn)
5722 || (self.check_keyword(keywords::Unsafe)
5723 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5724 // CONST FUNCTION ITEM
5725 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5731 let (ident, item_, extra_attrs) =
5732 self.parse_item_fn(unsafety,
5733 respan(const_span, Constness::Const),
5735 let prev_span = self.prev_span;
5736 let item = self.mk_item(lo.to(prev_span),
5740 maybe_append(attrs, extra_attrs));
5741 return Ok(Some(item));
5745 if self.eat_keyword(keywords::Mut) {
5746 let prev_span = self.prev_span;
5747 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
5748 .help("did you mean to declare a static?")
5751 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
5752 let prev_span = self.prev_span;
5753 let item = self.mk_item(lo.to(prev_span),
5757 maybe_append(attrs, extra_attrs));
5758 return Ok(Some(item));
5760 if self.check_keyword(keywords::Unsafe) &&
5761 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5763 // UNSAFE TRAIT ITEM
5764 self.expect_keyword(keywords::Unsafe)?;
5765 self.expect_keyword(keywords::Trait)?;
5766 let (ident, item_, extra_attrs) =
5767 self.parse_item_trait(ast::Unsafety::Unsafe)?;
5768 let prev_span = self.prev_span;
5769 let item = self.mk_item(lo.to(prev_span),
5773 maybe_append(attrs, extra_attrs));
5774 return Ok(Some(item));
5776 if (self.check_keyword(keywords::Unsafe) &&
5777 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))) ||
5778 (self.check_keyword(keywords::Default) &&
5779 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) &&
5780 self.look_ahead(2, |t| t.is_keyword(keywords::Impl)))
5783 let defaultness = self.parse_defaultness()?;
5784 self.expect_keyword(keywords::Unsafe)?;
5785 self.expect_keyword(keywords::Impl)?;
5788 extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe, defaultness)?;
5789 let prev_span = self.prev_span;
5790 let item = self.mk_item(lo.to(prev_span),
5794 maybe_append(attrs, extra_attrs));
5795 return Ok(Some(item));
5797 if self.check_keyword(keywords::Fn) {
5800 let fn_span = self.prev_span;
5801 let (ident, item_, extra_attrs) =
5802 self.parse_item_fn(Unsafety::Normal,
5803 respan(fn_span, Constness::NotConst),
5805 let prev_span = self.prev_span;
5806 let item = self.mk_item(lo.to(prev_span),
5810 maybe_append(attrs, extra_attrs));
5811 return Ok(Some(item));
5813 if self.check_keyword(keywords::Unsafe)
5814 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5815 // UNSAFE FUNCTION ITEM
5817 let abi = if self.eat_keyword(keywords::Extern) {
5818 self.parse_opt_abi()?.unwrap_or(Abi::C)
5822 self.expect_keyword(keywords::Fn)?;
5823 let fn_span = self.prev_span;
5824 let (ident, item_, extra_attrs) =
5825 self.parse_item_fn(Unsafety::Unsafe,
5826 respan(fn_span, Constness::NotConst),
5828 let prev_span = self.prev_span;
5829 let item = self.mk_item(lo.to(prev_span),
5833 maybe_append(attrs, extra_attrs));
5834 return Ok(Some(item));
5836 if self.eat_keyword(keywords::Mod) {
5838 let (ident, item_, extra_attrs) =
5839 self.parse_item_mod(&attrs[..])?;
5840 let prev_span = self.prev_span;
5841 let item = self.mk_item(lo.to(prev_span),
5845 maybe_append(attrs, extra_attrs));
5846 return Ok(Some(item));
5848 if self.eat_keyword(keywords::Type) {
5850 let (ident, item_, extra_attrs) = self.parse_item_type()?;
5851 let prev_span = self.prev_span;
5852 let item = self.mk_item(lo.to(prev_span),
5856 maybe_append(attrs, extra_attrs));
5857 return Ok(Some(item));
5859 if self.eat_keyword(keywords::Enum) {
5861 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
5862 let prev_span = self.prev_span;
5863 let item = self.mk_item(lo.to(prev_span),
5867 maybe_append(attrs, extra_attrs));
5868 return Ok(Some(item));
5870 if self.eat_keyword(keywords::Trait) {
5872 let (ident, item_, extra_attrs) =
5873 self.parse_item_trait(ast::Unsafety::Normal)?;
5874 let prev_span = self.prev_span;
5875 let item = self.mk_item(lo.to(prev_span),
5879 maybe_append(attrs, extra_attrs));
5880 return Ok(Some(item));
5882 if (self.check_keyword(keywords::Impl)) ||
5883 (self.check_keyword(keywords::Default) &&
5884 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)))
5887 let defaultness = self.parse_defaultness()?;
5888 self.expect_keyword(keywords::Impl)?;
5891 extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal, defaultness)?;
5892 let prev_span = self.prev_span;
5893 let item = self.mk_item(lo.to(prev_span),
5897 maybe_append(attrs, extra_attrs));
5898 return Ok(Some(item));
5900 if self.eat_keyword(keywords::Struct) {
5902 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
5903 let prev_span = self.prev_span;
5904 let item = self.mk_item(lo.to(prev_span),
5908 maybe_append(attrs, extra_attrs));
5909 return Ok(Some(item));
5911 if self.is_union_item() {
5914 let (ident, item_, extra_attrs) = self.parse_item_union()?;
5915 let prev_span = self.prev_span;
5916 let item = self.mk_item(lo.to(prev_span),
5920 maybe_append(attrs, extra_attrs));
5921 return Ok(Some(item));
5923 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility)? {
5924 return Ok(Some(macro_def));
5927 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5930 /// Parse a foreign item.
5931 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
5932 let attrs = self.parse_outer_attributes()?;
5934 let visibility = self.parse_visibility(false)?;
5936 if self.check_keyword(keywords::Static) {
5937 // FOREIGN STATIC ITEM
5938 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
5940 if self.check_keyword(keywords::Fn) {
5941 // FOREIGN FUNCTION ITEM
5942 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
5945 // FIXME #5668: this will occur for a macro invocation:
5946 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
5948 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5954 /// This is the fall-through for parsing items.
5955 fn parse_macro_use_or_failure(
5957 attrs: Vec<Attribute> ,
5958 macros_allowed: bool,
5959 attributes_allowed: bool,
5961 visibility: Visibility
5962 ) -> PResult<'a, Option<P<Item>>> {
5963 if macros_allowed && self.token.is_path_start() {
5964 // MACRO INVOCATION ITEM
5966 let prev_span = self.prev_span;
5967 self.complain_if_pub_macro(&visibility, prev_span);
5969 let mac_lo = self.span;
5972 let pth = self.parse_path(PathStyle::Mod)?;
5973 self.expect(&token::Not)?;
5975 // a 'special' identifier (like what `macro_rules!` uses)
5976 // is optional. We should eventually unify invoc syntax
5978 let id = if self.token.is_ident() {
5981 keywords::Invalid.ident() // no special identifier
5983 // eat a matched-delimiter token tree:
5984 let (delim, tts) = self.expect_delimited_token_tree()?;
5985 if delim != token::Brace {
5986 if !self.eat(&token::Semi) {
5987 let prev_span = self.prev_span;
5988 self.span_err(prev_span,
5989 "macros that expand to items must either \
5990 be surrounded with braces or followed by \
5995 let hi = self.prev_span;
5996 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
5997 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
5998 return Ok(Some(item));
6001 // FAILURE TO PARSE ITEM
6003 Visibility::Inherited => {}
6005 let prev_span = self.prev_span;
6006 return Err(self.span_fatal(prev_span, "unmatched visibility `pub`"));
6010 if !attributes_allowed && !attrs.is_empty() {
6011 self.expected_item_err(&attrs);
6016 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6017 let attrs = self.parse_outer_attributes()?;
6018 self.parse_item_(attrs, true, false)
6021 fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> {
6022 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
6023 &token::CloseDelim(token::Brace),
6024 SeqSep::trailing_allowed(token::Comma), |this| {
6026 let ident = if this.eat_keyword(keywords::SelfValue) {
6027 keywords::SelfValue.ident()
6031 let rename = this.parse_rename()?;
6032 let node = ast::PathListItem_ {
6035 id: ast::DUMMY_NODE_ID
6037 Ok(respan(lo.to(this.prev_span), node))
6042 fn is_import_coupler(&mut self) -> bool {
6043 self.check(&token::ModSep) &&
6044 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6045 *t == token::BinOp(token::Star))
6048 /// Matches ViewPath:
6049 /// MOD_SEP? non_global_path
6050 /// MOD_SEP? non_global_path as IDENT
6051 /// MOD_SEP? non_global_path MOD_SEP STAR
6052 /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE
6053 /// MOD_SEP? LBRACE item_seq RBRACE
6054 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
6056 if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) ||
6057 self.is_import_coupler() {
6058 // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`.
6059 self.eat(&token::ModSep);
6060 let prefix = ast::Path {
6061 segments: vec![PathSegment::crate_root()],
6062 span: lo.to(self.span),
6064 let view_path_kind = if self.eat(&token::BinOp(token::Star)) {
6065 ViewPathGlob(prefix)
6067 ViewPathList(prefix, self.parse_path_list_items()?)
6069 Ok(P(respan(lo.to(self.span), view_path_kind)))
6071 let prefix = self.parse_path(PathStyle::Mod)?.default_to_global();
6072 if self.is_import_coupler() {
6073 // `foo::bar::{a, b}` or `foo::bar::*`
6075 if self.check(&token::BinOp(token::Star)) {
6077 Ok(P(respan(lo.to(self.span), ViewPathGlob(prefix))))
6079 let items = self.parse_path_list_items()?;
6080 Ok(P(respan(lo.to(self.span), ViewPathList(prefix, items))))
6083 // `foo::bar` or `foo::bar as baz`
6084 let rename = self.parse_rename()?.
6085 unwrap_or(prefix.segments.last().unwrap().identifier);
6086 Ok(P(respan(lo.to(self.prev_span), ViewPathSimple(rename, prefix))))
6091 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6092 if self.eat_keyword(keywords::As) {
6093 self.parse_ident().map(Some)
6099 /// Parses a source module as a crate. This is the main
6100 /// entry point for the parser.
6101 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6104 attrs: self.parse_inner_attributes()?,
6105 module: self.parse_mod_items(&token::Eof, lo)?,
6106 span: lo.to(self.span),
6110 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6111 let ret = match self.token {
6112 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6113 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6120 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6121 match self.parse_optional_str() {
6122 Some((s, style, suf)) => {
6123 let sp = self.prev_span;
6124 self.expect_no_suffix(sp, "string literal", suf);
6127 _ => Err(self.fatal("expected string literal"))