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};
60 use std::collections::HashSet;
61 use std::{cmp, mem, slice};
62 use std::path::{self, Path, PathBuf};
65 flags Restrictions: u8 {
66 const RESTRICTION_STMT_EXPR = 1 << 0,
67 const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1,
71 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute> >);
73 /// How to parse a path. There are three different kinds of paths, all of which
74 /// are parsed somewhat differently.
75 #[derive(Copy, Clone, PartialEq)]
77 /// A path with no type parameters, e.g. `foo::bar::Baz`, used in imports or visibilities.
79 /// A path with a lifetime and type parameters, with no double colons
80 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`, used in types.
81 /// Paths using this style can be passed into macros expecting `path` nonterminals.
83 /// A path with a lifetime and type parameters with double colons before
84 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`, used in expressions or patterns.
88 #[derive(Clone, Copy, Debug, PartialEq)]
89 pub enum SemiColonMode {
94 #[derive(Clone, Copy, Debug, PartialEq)]
100 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
101 /// dropped into the token stream, which happens while parsing the result of
102 /// macro expansion). Placement of these is not as complex as I feared it would
103 /// be. The important thing is to make sure that lookahead doesn't balk at
104 /// `token::Interpolated` tokens.
105 macro_rules! maybe_whole_expr {
107 if let token::Interpolated(nt) = $p.token.clone() {
109 token::NtExpr(ref e) => {
111 return Ok((*e).clone());
113 token::NtPath(ref path) => {
116 let kind = ExprKind::Path(None, (*path).clone());
117 return Ok($p.mk_expr(span, kind, ThinVec::new()));
119 token::NtBlock(ref block) => {
122 let kind = ExprKind::Block((*block).clone());
123 return Ok($p.mk_expr(span, kind, ThinVec::new()));
131 /// As maybe_whole_expr, but for things other than expressions
132 macro_rules! maybe_whole {
133 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
134 if let token::Interpolated(nt) = $p.token.clone() {
135 if let token::$constructor($x) = (*nt).clone() {
143 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
145 if let Some(ref attrs) = rhs {
146 lhs.extend(attrs.iter().cloned())
160 /* ident is handled by common.rs */
162 pub struct Parser<'a> {
163 pub sess: &'a ParseSess,
164 /// the current token:
165 pub token: token::Token,
166 /// the span of the current token:
168 /// the span of the previous token:
169 pub meta_var_span: Option<Span>,
171 /// the previous token kind
172 prev_token_kind: PrevTokenKind,
173 pub restrictions: Restrictions,
174 /// The set of seen errors about obsolete syntax. Used to suppress
175 /// extra detail when the same error is seen twice
176 pub obsolete_set: HashSet<ObsoleteSyntax>,
177 /// Used to determine the path to externally loaded source files
178 pub directory: Directory,
179 /// Name of the root module this parser originated from. If `None`, then the
180 /// name is not known. This does not change while the parser is descending
181 /// into modules, and sub-parsers have new values for this name.
182 pub root_module_name: Option<String>,
183 pub expected_tokens: Vec<TokenType>,
184 token_cursor: TokenCursor,
185 pub desugar_doc_comments: bool,
186 /// Whether we should configure out of line modules as we parse.
191 frame: TokenCursorFrame,
192 stack: Vec<TokenCursorFrame>,
195 struct TokenCursorFrame {
196 delim: token::DelimToken,
199 tree_cursor: tokenstream::Cursor,
203 impl TokenCursorFrame {
204 fn new(sp: Span, delimited: &Delimited) -> Self {
206 delim: delimited.delim,
208 open_delim: delimited.delim == token::NoDelim,
209 tree_cursor: delimited.stream().into_trees(),
210 close_delim: delimited.delim == token::NoDelim,
216 fn next(&mut self) -> TokenAndSpan {
218 let tree = if !self.frame.open_delim {
219 self.frame.open_delim = true;
220 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
221 .open_tt(self.frame.span)
222 } else if let Some(tree) = self.frame.tree_cursor.next() {
224 } else if !self.frame.close_delim {
225 self.frame.close_delim = true;
226 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
227 .close_tt(self.frame.span)
228 } else if let Some(frame) = self.stack.pop() {
232 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
236 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
237 TokenTree::Delimited(sp, ref delimited) => {
238 let frame = TokenCursorFrame::new(sp, delimited);
239 self.stack.push(mem::replace(&mut self.frame, frame));
245 fn next_desugared(&mut self) -> TokenAndSpan {
246 let (sp, name) = match self.next() {
247 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
248 tok @ _ => return tok,
251 let stripped = strip_doc_comment_decoration(&name.as_str());
253 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
254 // required to wrap the text.
255 let mut num_of_hashes = 0;
257 for ch in stripped.chars() {
260 '#' if count > 0 => count + 1,
263 num_of_hashes = cmp::max(num_of_hashes, count);
266 let body = TokenTree::Delimited(sp, Delimited {
267 delim: token::Bracket,
268 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"))),
269 TokenTree::Token(sp, token::Eq),
270 TokenTree::Token(sp, token::Literal(
271 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
272 .iter().cloned().collect::<TokenStream>().into(),
275 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
276 delim: token::NoDelim,
277 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
278 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
279 .iter().cloned().collect::<TokenStream>().into()
281 [TokenTree::Token(sp, token::Pound), body]
282 .iter().cloned().collect::<TokenStream>().into()
290 #[derive(PartialEq, Eq, Clone)]
293 Keyword(keywords::Keyword),
302 fn to_string(&self) -> String {
304 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
305 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
306 TokenType::Operator => "an operator".to_string(),
307 TokenType::Lifetime => "lifetime".to_string(),
308 TokenType::Ident => "identifier".to_string(),
309 TokenType::Path => "path".to_string(),
310 TokenType::Type => "type".to_string(),
315 fn is_ident_or_underscore(t: &token::Token) -> bool {
316 t.is_ident() || *t == token::Underscore
319 /// Information about the path to a module.
320 pub struct ModulePath {
322 pub path_exists: bool,
323 pub result: Result<ModulePathSuccess, Error>,
326 pub struct ModulePathSuccess {
328 pub directory_ownership: DirectoryOwnership,
332 pub struct ModulePathError {
334 pub help_msg: String,
338 FileNotFoundForModule {
340 default_path: String,
341 secondary_path: String,
346 default_path: String,
347 secondary_path: String,
350 InclusiveRangeWithNoEnd,
354 pub fn span_err<'a>(self, sp: Span, handler: &'a errors::Handler) -> DiagnosticBuilder<'a> {
356 Error::FileNotFoundForModule { ref mod_name,
360 let mut err = struct_span_err!(handler, sp, E0583,
361 "file not found for module `{}`", mod_name);
362 err.help(&format!("name the file either {} or {} inside the directory {:?}",
368 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
369 let mut err = struct_span_err!(handler, sp, E0584,
370 "file for module `{}` found at both {} and {}",
374 err.help("delete or rename one of them to remove the ambiguity");
377 Error::UselessDocComment => {
378 let mut err = struct_span_err!(handler, sp, E0585,
379 "found a documentation comment that doesn't document anything");
380 err.help("doc comments must come before what they document, maybe a comment was \
381 intended with `//`?");
384 Error::InclusiveRangeWithNoEnd => {
385 let mut err = struct_span_err!(handler, sp, E0586,
386 "inclusive range with no end");
387 err.help("inclusive ranges must be bounded at the end (`...b` or `a...b`)");
396 AttributesParsed(ThinVec<Attribute>),
397 AlreadyParsed(P<Expr>),
400 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
401 fn from(o: Option<ThinVec<Attribute>>) -> Self {
402 if let Some(attrs) = o {
403 LhsExpr::AttributesParsed(attrs)
405 LhsExpr::NotYetParsed
410 impl From<P<Expr>> for LhsExpr {
411 fn from(expr: P<Expr>) -> Self {
412 LhsExpr::AlreadyParsed(expr)
416 /// Create a placeholder argument.
417 fn dummy_arg(span: Span) -> Arg {
418 let spanned = Spanned {
420 node: keywords::Invalid.ident()
423 id: ast::DUMMY_NODE_ID,
424 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), spanned, None),
430 id: ast::DUMMY_NODE_ID
432 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
435 impl<'a> Parser<'a> {
436 pub fn new(sess: &'a ParseSess,
438 directory: Option<Directory>,
439 desugar_doc_comments: bool)
441 let mut parser = Parser {
443 token: token::Underscore,
444 span: syntax_pos::DUMMY_SP,
445 prev_span: syntax_pos::DUMMY_SP,
447 prev_token_kind: PrevTokenKind::Other,
448 restrictions: Restrictions::empty(),
449 obsolete_set: HashSet::new(),
450 directory: Directory { path: PathBuf::new(), ownership: DirectoryOwnership::Owned },
451 root_module_name: None,
452 expected_tokens: Vec::new(),
453 token_cursor: TokenCursor {
454 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
455 delim: token::NoDelim,
460 desugar_doc_comments: desugar_doc_comments,
464 let tok = parser.next_tok();
465 parser.token = tok.tok;
466 parser.span = tok.sp;
467 if let Some(directory) = directory {
468 parser.directory = directory;
469 } else if parser.span != syntax_pos::DUMMY_SP {
470 parser.directory.path = PathBuf::from(sess.codemap().span_to_filename(parser.span));
471 parser.directory.path.pop();
473 parser.process_potential_macro_variable();
477 fn next_tok(&mut self) -> TokenAndSpan {
478 let mut next = match self.desugar_doc_comments {
479 true => self.token_cursor.next_desugared(),
480 false => self.token_cursor.next(),
482 if next.sp == syntax_pos::DUMMY_SP {
483 next.sp = self.prev_span;
488 /// Convert a token to a string using self's reader
489 pub fn token_to_string(token: &token::Token) -> String {
490 pprust::token_to_string(token)
493 /// Convert the current token to a string using self's reader
494 pub fn this_token_to_string(&self) -> String {
495 Parser::token_to_string(&self.token)
498 pub fn this_token_descr(&self) -> String {
499 let s = self.this_token_to_string();
500 if self.token.is_strict_keyword() {
501 format!("keyword `{}`", s)
502 } else if self.token.is_reserved_keyword() {
503 format!("reserved keyword `{}`", s)
509 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
510 let token_str = Parser::token_to_string(t);
511 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
514 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
515 match self.expect_one_of(&[], &[]) {
517 Ok(_) => unreachable!(),
521 /// Expect and consume the token t. Signal an error if
522 /// the next token is not t.
523 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
524 if self.expected_tokens.is_empty() {
525 if self.token == *t {
529 let token_str = Parser::token_to_string(t);
530 let this_token_str = self.this_token_to_string();
531 Err(self.fatal(&format!("expected `{}`, found `{}`",
536 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
540 /// Expect next token to be edible or inedible token. If edible,
541 /// then consume it; if inedible, then return without consuming
542 /// anything. Signal a fatal error if next token is unexpected.
543 pub fn expect_one_of(&mut self,
544 edible: &[token::Token],
545 inedible: &[token::Token]) -> PResult<'a, ()>{
546 fn tokens_to_string(tokens: &[TokenType]) -> String {
547 let mut i = tokens.iter();
548 // This might be a sign we need a connect method on Iterator.
550 .map_or("".to_string(), |t| t.to_string());
551 i.enumerate().fold(b, |mut b, (i, ref a)| {
552 if tokens.len() > 2 && i == tokens.len() - 2 {
554 } else if tokens.len() == 2 && i == tokens.len() - 2 {
559 b.push_str(&a.to_string());
563 if edible.contains(&self.token) {
566 } else if inedible.contains(&self.token) {
567 // leave it in the input
570 let mut expected = edible.iter()
571 .map(|x| TokenType::Token(x.clone()))
572 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
573 .chain(self.expected_tokens.iter().cloned())
574 .collect::<Vec<_>>();
575 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
577 let expect = tokens_to_string(&expected[..]);
578 let actual = self.this_token_to_string();
579 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
580 let short_expect = if expected.len() > 6 {
581 format!("{} possible tokens", expected.len())
585 (format!("expected one of {}, found `{}`", expect, actual),
586 (self.prev_span.next_point(), format!("expected one of {} here", short_expect)))
587 } else if expected.is_empty() {
588 (format!("unexpected token: `{}`", actual),
589 (self.prev_span, "unexpected token after this".to_string()))
591 (format!("expected {}, found `{}`", expect, actual),
592 (self.prev_span.next_point(), format!("expected {} here", expect)))
594 let mut err = self.fatal(&msg_exp);
595 let sp = if self.token == token::Token::Eof {
596 // This is EOF, don't want to point at the following char, but rather the last token
601 if self.span.contains(sp) {
602 err.span_label(self.span, &label_exp);
604 err.span_label(sp, &label_exp);
605 err.span_label(self.span, &"unexpected token");
611 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
612 fn interpolated_or_expr_span(&self,
613 expr: PResult<'a, P<Expr>>)
614 -> PResult<'a, (Span, P<Expr>)> {
616 if self.prev_token_kind == PrevTokenKind::Interpolated {
624 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
625 self.check_strict_keywords();
626 self.check_reserved_keywords();
633 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
634 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
636 let mut err = self.fatal(&format!("expected identifier, found `{}`",
637 self.this_token_to_string()));
638 if self.token == token::Underscore {
639 err.note("`_` is a wildcard pattern, not an identifier");
647 /// Check if the next token is `tok`, and return `true` if so.
649 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
651 pub fn check(&mut self, tok: &token::Token) -> bool {
652 let is_present = self.token == *tok;
653 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
657 /// Consume token 'tok' if it exists. Returns true if the given
658 /// token was present, false otherwise.
659 pub fn eat(&mut self, tok: &token::Token) -> bool {
660 let is_present = self.check(tok);
661 if is_present { self.bump() }
665 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
666 self.expected_tokens.push(TokenType::Keyword(kw));
667 self.token.is_keyword(kw)
670 /// If the next token is the given keyword, eat it and return
671 /// true. Otherwise, return false.
672 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
673 if self.check_keyword(kw) {
681 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
682 if self.token.is_keyword(kw) {
690 pub fn check_contextual_keyword(&mut self, ident: Ident) -> bool {
691 self.expected_tokens.push(TokenType::Token(token::Ident(ident)));
692 if let token::Ident(ref cur_ident) = self.token {
693 cur_ident.name == ident.name
699 pub fn eat_contextual_keyword(&mut self, ident: Ident) -> bool {
700 if self.check_contextual_keyword(ident) {
708 /// If the given word is not a keyword, signal an error.
709 /// If the next token is not the given word, signal an error.
710 /// Otherwise, eat it.
711 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
712 if !self.eat_keyword(kw) {
719 /// Signal an error if the given string is a strict keyword
720 pub fn check_strict_keywords(&mut self) {
721 if self.token.is_strict_keyword() {
722 let token_str = self.this_token_to_string();
723 let span = self.span;
725 &format!("expected identifier, found keyword `{}`",
730 /// Signal an error if the current token is a reserved keyword
731 pub fn check_reserved_keywords(&mut self) {
732 if self.token.is_reserved_keyword() {
733 let token_str = self.this_token_to_string();
734 self.fatal(&format!("`{}` is a reserved keyword", token_str)).emit()
738 fn check_ident(&mut self) -> bool {
739 if self.token.is_ident() {
742 self.expected_tokens.push(TokenType::Ident);
747 fn check_path(&mut self) -> bool {
748 if self.token.is_path_start() {
751 self.expected_tokens.push(TokenType::Path);
756 fn check_type(&mut self) -> bool {
757 if self.token.can_begin_type() {
760 self.expected_tokens.push(TokenType::Type);
765 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
766 /// `&` and continue. If an `&` is not seen, signal an error.
767 fn expect_and(&mut self) -> PResult<'a, ()> {
768 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
770 token::BinOp(token::And) => {
775 let span = self.span;
776 let lo = span.lo + BytePos(1);
777 Ok(self.bump_with(token::BinOp(token::And), Span { lo: lo, ..span }))
779 _ => self.unexpected()
783 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
785 None => {/* everything ok */}
787 let text = suf.as_str();
789 self.span_bug(sp, "found empty literal suffix in Some")
791 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
796 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
797 /// `<` and continue. If a `<` is not seen, return false.
799 /// This is meant to be used when parsing generics on a path to get the
801 fn eat_lt(&mut self) -> bool {
802 self.expected_tokens.push(TokenType::Token(token::Lt));
808 token::BinOp(token::Shl) => {
809 let span = self.span;
810 let lo = span.lo + BytePos(1);
811 self.bump_with(token::Lt, Span { lo: lo, ..span });
818 fn expect_lt(&mut self) -> PResult<'a, ()> {
826 /// Expect and consume a GT. if a >> is seen, replace it
827 /// with a single > and continue. If a GT is not seen,
829 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
830 self.expected_tokens.push(TokenType::Token(token::Gt));
836 token::BinOp(token::Shr) => {
837 let span = self.span;
838 let lo = span.lo + BytePos(1);
839 Ok(self.bump_with(token::Gt, Span { lo: lo, ..span }))
841 token::BinOpEq(token::Shr) => {
842 let span = self.span;
843 let lo = span.lo + BytePos(1);
844 Ok(self.bump_with(token::Ge, Span { lo: lo, ..span }))
847 let span = self.span;
848 let lo = span.lo + BytePos(1);
849 Ok(self.bump_with(token::Eq, Span { lo: lo, ..span }))
851 _ => self.unexpected()
855 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
856 sep: Option<token::Token>,
858 -> PResult<'a, (Vec<T>, bool)>
859 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
861 let mut v = Vec::new();
862 // This loop works by alternating back and forth between parsing types
863 // and commas. For example, given a string `A, B,>`, the parser would
864 // first parse `A`, then a comma, then `B`, then a comma. After that it
865 // would encounter a `>` and stop. This lets the parser handle trailing
866 // commas in generic parameters, because it can stop either after
867 // parsing a type or after parsing a comma.
869 if self.check(&token::Gt)
870 || self.token == token::BinOp(token::Shr)
871 || self.token == token::Ge
872 || self.token == token::BinOpEq(token::Shr) {
878 Some(result) => v.push(result),
879 None => return Ok((v, true))
882 if let Some(t) = sep.as_ref() {
888 return Ok((v, false));
891 /// Parse a sequence bracketed by '<' and '>', stopping
893 pub fn parse_seq_to_before_gt<T, F>(&mut self,
894 sep: Option<token::Token>,
896 -> PResult<'a, Vec<T>> where
897 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
899 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
900 |p| Ok(Some(f(p)?)))?;
905 pub fn parse_seq_to_gt<T, F>(&mut self,
906 sep: Option<token::Token>,
908 -> PResult<'a, Vec<T>> where
909 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
911 let v = self.parse_seq_to_before_gt(sep, f)?;
916 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
917 sep: Option<token::Token>,
919 -> PResult<'a, (Vec<T>, bool)> where
920 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
922 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
926 return Ok((v, returned));
929 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
930 /// passes through any errors encountered. Used for error recovery.
931 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
932 let handler = self.diagnostic();
934 self.parse_seq_to_before_tokens(kets,
936 |p| Ok(p.parse_token_tree()),
937 |mut e| handler.cancel(&mut e));
940 /// Parse a sequence, including the closing delimiter. The function
941 /// f must consume tokens until reaching the next separator or
943 pub fn parse_seq_to_end<T, F>(&mut self,
947 -> PResult<'a, Vec<T>> where
948 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
950 let val = self.parse_seq_to_before_end(ket, sep, f);
955 /// Parse a sequence, not including the closing delimiter. The function
956 /// f must consume tokens until reaching the next separator or
958 pub fn parse_seq_to_before_end<T, F>(&mut self,
963 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
965 self.parse_seq_to_before_tokens(&[ket], sep, f, |mut e| e.emit())
968 // `fe` is an error handler.
969 fn parse_seq_to_before_tokens<T, F, Fe>(&mut self,
970 kets: &[&token::Token],
975 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
976 Fe: FnMut(DiagnosticBuilder)
978 let mut first: bool = true;
980 while !kets.contains(&&self.token) {
982 token::CloseDelim(..) | token::Eof => break,
990 if let Err(e) = self.expect(t) {
998 if sep.trailing_sep_allowed && kets.iter().any(|k| self.check(k)) {
1014 /// Parse a sequence, including the closing delimiter. The function
1015 /// f must consume tokens until reaching the next separator or
1016 /// closing bracket.
1017 pub fn parse_unspanned_seq<T, F>(&mut self,
1022 -> PResult<'a, Vec<T>> where
1023 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1026 let result = self.parse_seq_to_before_end(ket, sep, f);
1027 if self.token == *ket {
1033 // NB: Do not use this function unless you actually plan to place the
1034 // spanned list in the AST.
1035 pub fn parse_seq<T, F>(&mut self,
1040 -> PResult<'a, Spanned<Vec<T>>> where
1041 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1045 let result = self.parse_seq_to_before_end(ket, sep, f);
1048 Ok(respan(lo.to(hi), result))
1051 /// Advance the parser by one token
1052 pub fn bump(&mut self) {
1053 if self.prev_token_kind == PrevTokenKind::Eof {
1054 // Bumping after EOF is a bad sign, usually an infinite loop.
1055 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1058 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1060 // Record last token kind for possible error recovery.
1061 self.prev_token_kind = match self.token {
1062 token::DocComment(..) => PrevTokenKind::DocComment,
1063 token::Comma => PrevTokenKind::Comma,
1064 token::Interpolated(..) => PrevTokenKind::Interpolated,
1065 token::Eof => PrevTokenKind::Eof,
1066 _ => PrevTokenKind::Other,
1069 let next = self.next_tok();
1070 self.span = next.sp;
1071 self.token = next.tok;
1072 self.expected_tokens.clear();
1073 // check after each token
1074 self.process_potential_macro_variable();
1077 /// Advance the parser using provided token as a next one. Use this when
1078 /// consuming a part of a token. For example a single `<` from `<<`.
1079 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1080 self.prev_span = Span { hi: span.lo, ..self.span };
1081 // It would be incorrect to record the kind of the current token, but
1082 // fortunately for tokens currently using `bump_with`, the
1083 // prev_token_kind will be of no use anyway.
1084 self.prev_token_kind = PrevTokenKind::Other;
1087 self.expected_tokens.clear();
1090 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1091 F: FnOnce(&token::Token) -> R,
1094 return f(&self.token)
1097 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1098 Some(tree) => match tree {
1099 TokenTree::Token(_, tok) => tok,
1100 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1102 None => token::CloseDelim(self.token_cursor.frame.delim),
1105 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1106 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1108 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1109 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1111 pub fn span_fatal_err(&self, sp: Span, err: Error) -> DiagnosticBuilder<'a> {
1112 err.span_err(sp, self.diagnostic())
1114 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1115 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1119 pub fn bug(&self, m: &str) -> ! {
1120 self.sess.span_diagnostic.span_bug(self.span, m)
1122 pub fn warn(&self, m: &str) {
1123 self.sess.span_diagnostic.span_warn(self.span, m)
1125 pub fn span_warn(&self, sp: Span, m: &str) {
1126 self.sess.span_diagnostic.span_warn(sp, m)
1128 pub fn span_err(&self, sp: Span, m: &str) {
1129 self.sess.span_diagnostic.span_err(sp, m)
1131 pub fn span_err_help(&self, sp: Span, m: &str, h: &str) {
1132 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1136 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1137 self.sess.span_diagnostic.span_bug(sp, m)
1139 pub fn abort_if_errors(&self) {
1140 self.sess.span_diagnostic.abort_if_errors();
1143 fn cancel(&self, err: &mut DiagnosticBuilder) {
1144 self.sess.span_diagnostic.cancel(err)
1147 pub fn diagnostic(&self) -> &'a errors::Handler {
1148 &self.sess.span_diagnostic
1151 /// Is the current token one of the keywords that signals a bare function
1153 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1154 self.check_keyword(keywords::Fn) ||
1155 self.check_keyword(keywords::Unsafe) ||
1156 self.check_keyword(keywords::Extern)
1159 fn get_label(&mut self) -> ast::Ident {
1161 token::Lifetime(ref ident) => *ident,
1162 _ => self.bug("not a lifetime"),
1166 /// parse a TyKind::BareFn type:
1167 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<LifetimeDef>)
1168 -> PResult<'a, TyKind> {
1171 [unsafe] [extern "ABI"] fn (S) -> T
1181 let unsafety = self.parse_unsafety()?;
1182 let abi = if self.eat_keyword(keywords::Extern) {
1183 self.parse_opt_abi()?.unwrap_or(Abi::C)
1188 self.expect_keyword(keywords::Fn)?;
1189 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1190 let ret_ty = self.parse_ret_ty()?;
1191 let decl = P(FnDecl {
1196 Ok(TyKind::BareFn(P(BareFnTy {
1199 lifetimes: lifetime_defs,
1204 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1205 if self.eat_keyword(keywords::Unsafe) {
1206 return Ok(Unsafety::Unsafe);
1208 return Ok(Unsafety::Normal);
1212 /// Parse the items in a trait declaration
1213 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1214 maybe_whole!(self, NtTraitItem, |x| x);
1215 let mut attrs = self.parse_outer_attributes()?;
1218 let (name, node) = if self.eat_keyword(keywords::Type) {
1219 let TyParam {ident, bounds, default, ..} = self.parse_ty_param(vec![])?;
1220 self.expect(&token::Semi)?;
1221 (ident, TraitItemKind::Type(bounds, default))
1222 } else if self.is_const_item() {
1223 self.expect_keyword(keywords::Const)?;
1224 let ident = self.parse_ident()?;
1225 self.expect(&token::Colon)?;
1226 let ty = self.parse_ty()?;
1227 let default = if self.check(&token::Eq) {
1229 let expr = self.parse_expr()?;
1230 self.expect(&token::Semi)?;
1233 self.expect(&token::Semi)?;
1236 (ident, TraitItemKind::Const(ty, default))
1237 } else if self.token.is_path_start() {
1238 // trait item macro.
1239 // code copied from parse_macro_use_or_failure... abstraction!
1240 let prev_span = self.prev_span;
1242 let pth = self.parse_path(PathStyle::Mod)?;
1244 if pth.segments.len() == 1 {
1245 if !self.eat(&token::Not) {
1246 return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1249 self.expect(&token::Not)?;
1252 // eat a matched-delimiter token tree:
1253 let (delim, tts) = self.expect_delimited_token_tree()?;
1254 if delim != token::Brace {
1255 self.expect(&token::Semi)?
1258 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1259 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac))
1261 let (constness, unsafety, abi) = match self.parse_fn_front_matter() {
1263 Err(e) => return Err(e),
1266 let ident = self.parse_ident()?;
1267 let mut generics = self.parse_generics()?;
1269 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1270 // This is somewhat dubious; We don't want to allow
1271 // argument names to be left off if there is a
1273 p.parse_arg_general(false)
1276 generics.where_clause = self.parse_where_clause()?;
1277 let sig = ast::MethodSig {
1279 constness: constness,
1285 let body = match self.token {
1289 debug!("parse_trait_methods(): parsing required method");
1292 token::OpenDelim(token::Brace) => {
1293 debug!("parse_trait_methods(): parsing provided method");
1295 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1296 attrs.extend(inner_attrs.iter().cloned());
1300 let token_str = self.this_token_to_string();
1301 return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1304 (ident, ast::TraitItemKind::Method(sig, body))
1308 id: ast::DUMMY_NODE_ID,
1312 span: lo.to(self.prev_span),
1316 /// Parse optional return type [ -> TY ] in function decl
1317 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1318 if self.eat(&token::RArrow) {
1319 Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
1321 Ok(FunctionRetTy::Default(Span { hi: self.span.lo, ..self.span }))
1326 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1327 self.parse_ty_common(true)
1330 /// Parse a type in restricted contexts where `+` is not permitted.
1331 /// Example 1: `&'a TYPE`
1332 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1333 /// Example 2: `value1 as TYPE + value2`
1334 /// `+` is prohibited to avoid interactions with expression grammar.
1335 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1336 self.parse_ty_common(false)
1339 fn parse_ty_common(&mut self, allow_plus: bool) -> PResult<'a, P<Ty>> {
1340 maybe_whole!(self, NtTy, |x| x);
1343 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1344 // `(TYPE)` is a parenthesized type.
1345 // `(TYPE,)` is a tuple with a single field of type TYPE.
1346 let mut ts = vec![];
1347 let mut last_comma = false;
1348 while self.token != token::CloseDelim(token::Paren) {
1349 ts.push(self.parse_ty()?);
1350 if self.eat(&token::Comma) {
1357 self.expect(&token::CloseDelim(token::Paren))?;
1359 if ts.len() == 1 && !last_comma {
1360 let ty = ts.into_iter().nth(0).unwrap().unwrap();
1362 // Accept `(Trait1) + Trait2 + 'a` for backward compatibility (#39318).
1363 TyKind::Path(None, ref path)
1364 if allow_plus && self.token == token::BinOp(token::Plus) => {
1366 let pt = PolyTraitRef::new(Vec::new(), path.clone(), lo.to(self.prev_span));
1367 let mut bounds = vec![TraitTyParamBound(pt, TraitBoundModifier::None)];
1368 bounds.append(&mut self.parse_ty_param_bounds()?);
1369 TyKind::TraitObject(bounds)
1371 _ => TyKind::Paren(P(ty))
1376 } else if self.eat(&token::Not) {
1379 } else if self.eat(&token::BinOp(token::Star)) {
1381 TyKind::Ptr(self.parse_ptr()?)
1382 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1384 let t = self.parse_ty()?;
1385 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1386 let t = match self.maybe_parse_fixed_length_of_vec()? {
1387 None => TyKind::Slice(t),
1388 Some(suffix) => TyKind::Array(t, suffix),
1390 self.expect(&token::CloseDelim(token::Bracket))?;
1392 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1395 self.parse_borrowed_pointee()?
1396 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1398 // In order to not be ambiguous, the type must be surrounded by parens.
1399 self.expect(&token::OpenDelim(token::Paren))?;
1400 let e = self.parse_expr()?;
1401 self.expect(&token::CloseDelim(token::Paren))?;
1403 } else if self.eat(&token::Underscore) {
1404 // A type to be inferred `_`
1406 } else if self.eat_lt() {
1408 let (qself, path) = self.parse_qualified_path(PathStyle::Type)?;
1409 TyKind::Path(Some(qself), path)
1410 } else if self.token.is_path_start() {
1412 let path = self.parse_path(PathStyle::Type)?;
1413 if self.eat(&token::Not) {
1414 // Macro invocation in type position
1415 let (_, tts) = self.expect_delimited_token_tree()?;
1416 TyKind::Mac(respan(lo.to(self.span), Mac_ { path: path, tts: tts }))
1418 // Just a type path or bound list (trait object type) starting with a trait.
1420 // `Trait1 + Trait2 + 'a`
1421 if allow_plus && self.eat(&token::BinOp(token::Plus)) {
1422 let poly_trait = PolyTraitRef::new(Vec::new(), path, lo.to(self.prev_span));
1423 let mut bounds = vec![TraitTyParamBound(poly_trait, TraitBoundModifier::None)];
1424 bounds.append(&mut self.parse_ty_param_bounds()?);
1425 TyKind::TraitObject(bounds)
1427 TyKind::Path(None, path)
1430 } else if self.token_is_bare_fn_keyword() {
1431 // Function pointer type
1432 self.parse_ty_bare_fn(Vec::new())?
1433 } else if self.check_keyword(keywords::For) {
1434 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1435 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1436 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1438 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1439 if self.token_is_bare_fn_keyword() {
1440 self.parse_ty_bare_fn(lifetime_defs)?
1442 let path = self.parse_path(PathStyle::Type)?;
1443 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
1444 let mut bounds = vec![TraitTyParamBound(poly_trait, TraitBoundModifier::None)];
1445 if allow_plus && self.eat(&token::BinOp(token::Plus)) {
1446 bounds.append(&mut self.parse_ty_param_bounds()?)
1448 TyKind::TraitObject(bounds)
1450 } else if self.eat_keyword(keywords::Impl) {
1451 // FIXME: figure out priority of `+` in `impl Trait1 + Trait2` (#34511).
1452 TyKind::ImplTrait(self.parse_ty_param_bounds()?)
1453 } else if self.check(&token::Question) {
1454 // Bound list (trait object type)
1455 // Bound lists starting with `'lt` are not currently supported (#40043)
1456 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?)
1458 let msg = format!("expected type, found {}", self.this_token_descr());
1459 return Err(self.fatal(&msg));
1462 let span = lo.to(self.prev_span);
1463 let ty = Ty { node: node, span: span, id: ast::DUMMY_NODE_ID };
1465 // Try to recover from use of `+` with incorrect priority.
1466 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1471 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1472 // Do not add `+` to expected tokens.
1473 if !allow_plus || self.token != token::BinOp(token::Plus) {
1478 let bounds = self.parse_ty_param_bounds()?;
1479 let sum_span = ty.span.to(self.prev_span);
1481 let mut err = struct_span_err!(self.sess.span_diagnostic, ty.span, E0178,
1482 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(&ty));
1483 err.span_label(ty.span, &format!("expected a path"));
1486 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1487 let sum_with_parens = pprust::to_string(|s| {
1488 use print::pp::word;
1489 use print::pprust::PrintState;
1491 word(&mut s.s, "&")?;
1492 s.print_opt_lifetime(lifetime)?;
1493 s.print_mutability(mut_ty.mutbl)?;
1495 s.print_type(&mut_ty.ty)?;
1496 s.print_bounds(" +", &bounds)?;
1499 err.span_suggestion(sum_span, "try adding parentheses:", sum_with_parens);
1501 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1502 help!(&mut err, "perhaps you forgot parentheses?");
1510 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1511 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1512 let mutbl = self.parse_mutability();
1513 let ty = self.parse_ty_no_plus()?;
1514 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1517 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1518 let mutbl = if self.eat_keyword(keywords::Mut) {
1520 } else if self.eat_keyword(keywords::Const) {
1521 Mutability::Immutable
1523 let span = self.prev_span;
1525 "expected mut or const in raw pointer type (use \
1526 `*mut T` or `*const T` as appropriate)");
1527 Mutability::Immutable
1529 let t = self.parse_ty_no_plus()?;
1530 Ok(MutTy { ty: t, mutbl: mutbl })
1533 pub fn is_named_argument(&mut self) -> bool {
1534 let offset = match self.token {
1535 token::BinOp(token::And) => 1,
1537 _ if self.token.is_keyword(keywords::Mut) => 1,
1541 debug!("parser is_named_argument offset:{}", offset);
1544 is_ident_or_underscore(&self.token)
1545 && self.look_ahead(1, |t| *t == token::Colon)
1547 self.look_ahead(offset, |t| is_ident_or_underscore(t))
1548 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1552 /// This version of parse arg doesn't necessarily require
1553 /// identifier names.
1554 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1555 maybe_whole!(self, NtArg, |x| x);
1557 let pat = if require_name || self.is_named_argument() {
1558 debug!("parse_arg_general parse_pat (require_name:{})",
1560 let pat = self.parse_pat()?;
1562 self.expect(&token::Colon)?;
1565 debug!("parse_arg_general ident_to_pat");
1566 let sp = self.prev_span;
1567 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1569 id: ast::DUMMY_NODE_ID,
1570 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1576 let t = self.parse_ty()?;
1581 id: ast::DUMMY_NODE_ID,
1585 /// Parse a single function argument
1586 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1587 self.parse_arg_general(true)
1590 /// Parse an argument in a lambda header e.g. |arg, arg|
1591 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1592 let pat = self.parse_pat()?;
1593 let t = if self.eat(&token::Colon) {
1597 id: ast::DUMMY_NODE_ID,
1598 node: TyKind::Infer,
1605 id: ast::DUMMY_NODE_ID
1609 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1610 if self.eat(&token::Semi) {
1611 Ok(Some(self.parse_expr()?))
1617 /// Matches token_lit = LIT_INTEGER | ...
1618 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1619 let out = match self.token {
1620 token::Interpolated(ref nt) => match **nt {
1621 token::NtExpr(ref v) => match v.node {
1622 ExprKind::Lit(ref lit) => { lit.node.clone() }
1623 _ => { return self.unexpected_last(&self.token); }
1625 _ => { return self.unexpected_last(&self.token); }
1627 token::Literal(lit, suf) => {
1628 let diag = Some((self.span, &self.sess.span_diagnostic));
1629 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1633 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1638 _ => { return self.unexpected_last(&self.token); }
1645 /// Matches lit = true | false | token_lit
1646 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1648 let lit = if self.eat_keyword(keywords::True) {
1650 } else if self.eat_keyword(keywords::False) {
1651 LitKind::Bool(false)
1653 let lit = self.parse_lit_token()?;
1656 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1659 /// matches '-' lit | lit
1660 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1661 let minus_lo = self.span;
1662 let minus_present = self.eat(&token::BinOp(token::Minus));
1664 let literal = P(self.parse_lit()?);
1665 let hi = self.prev_span;
1666 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1669 let minus_hi = self.prev_span;
1670 let unary = self.mk_unary(UnOp::Neg, expr);
1671 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1677 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1679 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1683 _ => self.parse_ident(),
1687 /// Parses qualified path.
1689 /// Assumes that the leading `<` has been parsed already.
1691 /// Qualifed paths are a part of the universal function call
1694 /// `qualified_path = <type [as trait_ref]>::path`
1696 /// See `parse_path` for `mode` meaning.
1701 /// `<T as U>::F::a::<S>`
1702 pub fn parse_qualified_path(&mut self, mode: PathStyle)
1703 -> PResult<'a, (QSelf, ast::Path)> {
1704 let span = self.prev_span;
1705 let self_type = self.parse_ty()?;
1706 let mut path = if self.eat_keyword(keywords::As) {
1707 self.parse_path(PathStyle::Type)?
1717 position: path.segments.len()
1720 self.expect(&token::Gt)?;
1721 self.expect(&token::ModSep)?;
1723 let segments = match mode {
1724 PathStyle::Type => {
1725 self.parse_path_segments_without_colons()?
1727 PathStyle::Expr => {
1728 self.parse_path_segments_with_colons()?
1731 self.parse_path_segments_without_types()?
1734 path.segments.extend(segments);
1736 path.span.hi = self.prev_span.hi;
1741 /// Parses a path and optional type parameter bounds, depending on the
1742 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1743 /// bounds are permitted and whether `::` must precede type parameter
1745 pub fn parse_path(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1746 maybe_whole!(self, NtPath, |x| x);
1748 let lo = self.meta_var_span.unwrap_or(self.span);
1749 let is_global = self.eat(&token::ModSep);
1751 // Parse any number of segments and bound sets. A segment is an
1752 // identifier followed by an optional lifetime and a set of types.
1753 // A bound set is a set of type parameter bounds.
1754 let mut segments = match mode {
1755 PathStyle::Type => {
1756 self.parse_path_segments_without_colons()?
1758 PathStyle::Expr => {
1759 self.parse_path_segments_with_colons()?
1762 self.parse_path_segments_without_types()?
1767 segments.insert(0, PathSegment::crate_root());
1770 // Assemble the result.
1772 span: lo.to(self.prev_span),
1777 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1778 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1779 pub fn parse_path_allowing_meta(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1780 let meta_ident = match self.token {
1781 token::Interpolated(ref nt) => match **nt {
1782 token::NtMeta(ref meta) => match meta.node {
1783 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
1790 if let Some(ident) = meta_ident {
1792 return Ok(ast::Path::from_ident(self.prev_span, ident));
1794 self.parse_path(mode)
1798 /// - `a::b<T,U>::c<V,W>`
1799 /// - `a::b<T,U>::c(V) -> W`
1800 /// - `a::b<T,U>::c(V)`
1801 pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1802 let mut segments = Vec::new();
1804 // First, parse an identifier.
1805 let ident_span = self.span;
1806 let identifier = self.parse_path_segment_ident()?;
1808 if self.check(&token::ModSep) && self.look_ahead(1, |t| *t == token::Lt) {
1810 let prev_span = self.prev_span;
1812 let mut err = self.diagnostic().struct_span_err(prev_span,
1813 "unexpected token: `::`");
1815 "use `<...>` instead of `::<...>` if you meant to specify type arguments");
1819 // Parse types, optionally.
1820 let parameters = if self.eat_lt() {
1821 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1823 ast::AngleBracketedParameterData {
1824 lifetimes: lifetimes,
1828 } else if self.eat(&token::OpenDelim(token::Paren)) {
1829 let lo = self.prev_span;
1831 let inputs = self.parse_seq_to_end(
1832 &token::CloseDelim(token::Paren),
1833 SeqSep::trailing_allowed(token::Comma),
1836 let output_ty = if self.eat(&token::RArrow) {
1837 Some(self.parse_ty_no_plus()?)
1842 let hi = self.prev_span;
1844 Some(P(ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData {
1853 // Assemble and push the result.
1854 segments.push(PathSegment {
1855 identifier: identifier,
1857 parameters: parameters
1860 // Continue only if we see a `::`
1861 if !self.eat(&token::ModSep) {
1862 return Ok(segments);
1868 /// - `a::b::<T,U>::c`
1869 pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1870 let mut segments = Vec::new();
1872 // First, parse an identifier.
1873 let ident_span = self.span;
1874 let identifier = self.parse_path_segment_ident()?;
1876 // If we do not see a `::`, stop.
1877 if !self.eat(&token::ModSep) {
1878 segments.push(PathSegment::from_ident(identifier, ident_span));
1879 return Ok(segments);
1882 // Check for a type segment.
1884 // Consumed `a::b::<`, go look for types
1885 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1887 segments.push(PathSegment {
1888 identifier: identifier,
1890 parameters: ast::AngleBracketedParameterData {
1891 lifetimes: lifetimes,
1897 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1898 if !self.eat(&token::ModSep) {
1899 return Ok(segments);
1902 // Consumed `a::`, go look for `b`
1903 segments.push(PathSegment::from_ident(identifier, ident_span));
1910 pub fn parse_path_segments_without_types(&mut self)
1911 -> PResult<'a, Vec<PathSegment>> {
1912 let mut segments = Vec::new();
1914 // First, parse an identifier.
1915 let ident_span = self.span;
1916 let identifier = self.parse_path_segment_ident()?;
1918 // Assemble and push the result.
1919 segments.push(PathSegment::from_ident(identifier, ident_span));
1921 // If we do not see a `::` or see `::{`/`::*`, stop.
1922 if !self.check(&token::ModSep) || self.is_import_coupler() {
1923 return Ok(segments);
1930 fn check_lifetime(&mut self) -> bool {
1931 self.expected_tokens.push(TokenType::Lifetime);
1932 self.token.is_lifetime()
1935 /// Parse single lifetime 'a or panic.
1936 fn expect_lifetime(&mut self) -> Lifetime {
1938 token::Lifetime(ident) => {
1939 let ident_span = self.span;
1941 Lifetime { name: ident.name, span: ident_span, id: ast::DUMMY_NODE_ID }
1943 _ => self.span_bug(self.span, "not a lifetime")
1947 /// Parse mutability (`mut` or nothing).
1948 fn parse_mutability(&mut self) -> Mutability {
1949 if self.eat_keyword(keywords::Mut) {
1952 Mutability::Immutable
1956 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1957 if let token::Literal(token::Integer(name), None) = self.token {
1959 Ok(Ident::with_empty_ctxt(name))
1965 /// Parse ident (COLON expr)?
1966 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1967 let attrs = self.parse_outer_attributes()?;
1971 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1972 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1973 let fieldname = self.parse_field_name()?;
1975 hi = self.prev_span;
1976 (fieldname, self.parse_expr()?, false)
1978 let fieldname = self.parse_ident()?;
1979 hi = self.prev_span;
1981 // Mimic `x: x` for the `x` field shorthand.
1982 let path = ast::Path::from_ident(lo.to(hi), fieldname);
1983 (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
1986 ident: respan(lo.to(hi), fieldname),
1987 span: lo.to(expr.span),
1989 is_shorthand: is_shorthand,
1990 attrs: attrs.into(),
1994 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1996 id: ast::DUMMY_NODE_ID,
1999 attrs: attrs.into(),
2003 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2004 ExprKind::Unary(unop, expr)
2007 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2008 ExprKind::Binary(binop, lhs, rhs)
2011 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2012 ExprKind::Call(f, args)
2015 fn mk_method_call(&mut self,
2016 ident: ast::SpannedIdent,
2020 ExprKind::MethodCall(ident, tps, args)
2023 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2024 ExprKind::Index(expr, idx)
2027 pub fn mk_range(&mut self,
2028 start: Option<P<Expr>>,
2029 end: Option<P<Expr>>,
2030 limits: RangeLimits)
2031 -> PResult<'a, ast::ExprKind> {
2032 if end.is_none() && limits == RangeLimits::Closed {
2033 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2035 Ok(ExprKind::Range(start, end, limits))
2039 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::ExprKind {
2040 ExprKind::Field(expr, ident)
2043 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2044 ExprKind::TupField(expr, idx)
2047 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2048 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2049 ExprKind::AssignOp(binop, lhs, rhs)
2052 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2054 id: ast::DUMMY_NODE_ID,
2055 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2061 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2062 let span = &self.span;
2063 let lv_lit = P(codemap::Spanned {
2064 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2069 id: ast::DUMMY_NODE_ID,
2070 node: ExprKind::Lit(lv_lit),
2076 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2078 token::OpenDelim(delim) => match self.parse_token_tree() {
2079 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2080 _ => unreachable!(),
2082 _ => Err(self.fatal("expected open delimiter")),
2086 /// At the bottom (top?) of the precedence hierarchy,
2087 /// parse things like parenthesized exprs,
2088 /// macros, return, etc.
2090 /// NB: This does not parse outer attributes,
2091 /// and is private because it only works
2092 /// correctly if called from parse_dot_or_call_expr().
2093 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2094 maybe_whole_expr!(self);
2096 // Outer attributes are already parsed and will be
2097 // added to the return value after the fact.
2099 // Therefore, prevent sub-parser from parsing
2100 // attributes by giving them a empty "already parsed" list.
2101 let mut attrs = ThinVec::new();
2104 let mut hi = self.span;
2108 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2110 token::OpenDelim(token::Paren) => {
2113 attrs.extend(self.parse_inner_attributes()?);
2115 // (e) is parenthesized e
2116 // (e,) is a tuple with only one field, e
2117 let mut es = vec![];
2118 let mut trailing_comma = false;
2119 while self.token != token::CloseDelim(token::Paren) {
2120 es.push(self.parse_expr()?);
2121 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2122 if self.check(&token::Comma) {
2123 trailing_comma = true;
2127 trailing_comma = false;
2133 hi = self.prev_span;
2134 let span = lo.to(hi);
2135 return if es.len() == 1 && !trailing_comma {
2136 Ok(self.mk_expr(span, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2138 Ok(self.mk_expr(span, ExprKind::Tup(es), attrs))
2141 token::OpenDelim(token::Brace) => {
2142 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2144 token::BinOp(token::Or) | token::OrOr => {
2146 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2148 token::OpenDelim(token::Bracket) => {
2151 attrs.extend(self.parse_inner_attributes()?);
2153 if self.check(&token::CloseDelim(token::Bracket)) {
2156 ex = ExprKind::Array(Vec::new());
2159 let first_expr = self.parse_expr()?;
2160 if self.check(&token::Semi) {
2161 // Repeating array syntax: [ 0; 512 ]
2163 let count = self.parse_expr()?;
2164 self.expect(&token::CloseDelim(token::Bracket))?;
2165 ex = ExprKind::Repeat(first_expr, count);
2166 } else if self.check(&token::Comma) {
2167 // Vector with two or more elements.
2169 let remaining_exprs = self.parse_seq_to_end(
2170 &token::CloseDelim(token::Bracket),
2171 SeqSep::trailing_allowed(token::Comma),
2172 |p| Ok(p.parse_expr()?)
2174 let mut exprs = vec![first_expr];
2175 exprs.extend(remaining_exprs);
2176 ex = ExprKind::Array(exprs);
2178 // Vector with one element.
2179 self.expect(&token::CloseDelim(token::Bracket))?;
2180 ex = ExprKind::Array(vec![first_expr]);
2183 hi = self.prev_span;
2188 self.parse_qualified_path(PathStyle::Expr)?;
2190 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2192 if self.eat_keyword(keywords::Move) {
2193 let lo = self.prev_span;
2194 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2196 if self.eat_keyword(keywords::If) {
2197 return self.parse_if_expr(attrs);
2199 if self.eat_keyword(keywords::For) {
2200 let lo = self.prev_span;
2201 return self.parse_for_expr(None, lo, attrs);
2203 if self.eat_keyword(keywords::While) {
2204 let lo = self.prev_span;
2205 return self.parse_while_expr(None, lo, attrs);
2207 if self.token.is_lifetime() {
2208 let label = Spanned { node: self.get_label(),
2212 self.expect(&token::Colon)?;
2213 if self.eat_keyword(keywords::While) {
2214 return self.parse_while_expr(Some(label), lo, attrs)
2216 if self.eat_keyword(keywords::For) {
2217 return self.parse_for_expr(Some(label), lo, attrs)
2219 if self.eat_keyword(keywords::Loop) {
2220 return self.parse_loop_expr(Some(label), lo, attrs)
2222 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2224 if self.eat_keyword(keywords::Loop) {
2225 let lo = self.prev_span;
2226 return self.parse_loop_expr(None, lo, attrs);
2228 if self.eat_keyword(keywords::Continue) {
2229 let ex = if self.token.is_lifetime() {
2230 let ex = ExprKind::Continue(Some(Spanned{
2231 node: self.get_label(),
2237 ExprKind::Continue(None)
2239 let hi = self.prev_span;
2240 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2242 if self.eat_keyword(keywords::Match) {
2243 return self.parse_match_expr(attrs);
2245 if self.eat_keyword(keywords::Unsafe) {
2246 return self.parse_block_expr(
2248 BlockCheckMode::Unsafe(ast::UserProvided),
2251 if self.is_catch_expr() {
2252 assert!(self.eat_keyword(keywords::Do));
2253 assert!(self.eat_keyword(keywords::Catch));
2254 let lo = self.prev_span;
2255 return self.parse_catch_expr(lo, attrs);
2257 if self.eat_keyword(keywords::Return) {
2258 if self.token.can_begin_expr() {
2259 let e = self.parse_expr()?;
2261 ex = ExprKind::Ret(Some(e));
2263 ex = ExprKind::Ret(None);
2265 } else if self.eat_keyword(keywords::Break) {
2266 let lt = if self.token.is_lifetime() {
2267 let spanned_lt = Spanned {
2268 node: self.get_label(),
2276 let e = if self.token.can_begin_expr()
2277 && !(self.token == token::OpenDelim(token::Brace)
2278 && self.restrictions.contains(
2279 Restrictions::RESTRICTION_NO_STRUCT_LITERAL)) {
2280 Some(self.parse_expr()?)
2284 ex = ExprKind::Break(lt, e);
2285 hi = self.prev_span;
2286 } else if self.token.is_keyword(keywords::Let) {
2287 // Catch this syntax error here, instead of in `check_strict_keywords`, so
2288 // that we can explicitly mention that let is not to be used as an expression
2289 let mut db = self.fatal("expected expression, found statement (`let`)");
2290 db.note("variable declaration using `let` is a statement");
2292 } else if self.token.is_path_start() {
2293 let pth = self.parse_path(PathStyle::Expr)?;
2295 // `!`, as an operator, is prefix, so we know this isn't that
2296 if self.eat(&token::Not) {
2297 // MACRO INVOCATION expression
2298 let (_, tts) = self.expect_delimited_token_tree()?;
2299 let hi = self.prev_span;
2300 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2302 if self.check(&token::OpenDelim(token::Brace)) {
2303 // This is a struct literal, unless we're prohibited
2304 // from parsing struct literals here.
2305 let prohibited = self.restrictions.contains(
2306 Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2309 return self.parse_struct_expr(lo, pth, attrs);
2314 ex = ExprKind::Path(None, pth);
2316 match self.parse_lit() {
2319 ex = ExprKind::Lit(P(lit));
2322 self.cancel(&mut err);
2323 let msg = format!("expected expression, found {}",
2324 self.this_token_descr());
2325 return Err(self.fatal(&msg));
2332 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2335 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2336 -> PResult<'a, P<Expr>> {
2338 let mut fields = Vec::new();
2339 let mut base = None;
2341 attrs.extend(self.parse_inner_attributes()?);
2343 while self.token != token::CloseDelim(token::Brace) {
2344 if self.eat(&token::DotDot) {
2345 match self.parse_expr() {
2351 self.recover_stmt();
2357 match self.parse_field() {
2358 Ok(f) => fields.push(f),
2361 self.recover_stmt();
2366 match self.expect_one_of(&[token::Comma],
2367 &[token::CloseDelim(token::Brace)]) {
2371 self.recover_stmt();
2377 let span = lo.to(self.span);
2378 self.expect(&token::CloseDelim(token::Brace))?;
2379 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2382 fn parse_or_use_outer_attributes(&mut self,
2383 already_parsed_attrs: Option<ThinVec<Attribute>>)
2384 -> PResult<'a, ThinVec<Attribute>> {
2385 if let Some(attrs) = already_parsed_attrs {
2388 self.parse_outer_attributes().map(|a| a.into())
2392 /// Parse a block or unsafe block
2393 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2394 outer_attrs: ThinVec<Attribute>)
2395 -> PResult<'a, P<Expr>> {
2397 self.expect(&token::OpenDelim(token::Brace))?;
2399 let mut attrs = outer_attrs;
2400 attrs.extend(self.parse_inner_attributes()?);
2402 let blk = self.parse_block_tail(lo, blk_mode)?;
2403 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2406 /// parse a.b or a(13) or a[4] or just a
2407 pub fn parse_dot_or_call_expr(&mut self,
2408 already_parsed_attrs: Option<ThinVec<Attribute>>)
2409 -> PResult<'a, P<Expr>> {
2410 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2412 let b = self.parse_bottom_expr();
2413 let (span, b) = self.interpolated_or_expr_span(b)?;
2414 self.parse_dot_or_call_expr_with(b, span, attrs)
2417 pub fn parse_dot_or_call_expr_with(&mut self,
2420 mut attrs: ThinVec<Attribute>)
2421 -> PResult<'a, P<Expr>> {
2422 // Stitch the list of outer attributes onto the return value.
2423 // A little bit ugly, but the best way given the current code
2425 self.parse_dot_or_call_expr_with_(e0, lo)
2427 expr.map(|mut expr| {
2428 attrs.extend::<Vec<_>>(expr.attrs.into());
2431 ExprKind::If(..) | ExprKind::IfLet(..) => {
2432 if !expr.attrs.is_empty() {
2433 // Just point to the first attribute in there...
2434 let span = expr.attrs[0].span;
2437 "attributes are not yet allowed on `if` \
2448 // Assuming we have just parsed `.foo` (i.e., a dot and an ident), continue
2449 // parsing into an expression.
2450 fn parse_dot_suffix(&mut self, ident: Ident, ident_span: Span, self_value: P<Expr>, lo: Span)
2451 -> PResult<'a, P<Expr>> {
2452 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2454 let args = self.parse_generic_args()?;
2458 (Vec::new(), Vec::new(), Vec::new())
2461 if !bindings.is_empty() {
2462 let prev_span = self.prev_span;
2463 self.span_err(prev_span, "type bindings are only permitted on trait paths");
2466 Ok(match self.token {
2467 // expr.f() method call.
2468 token::OpenDelim(token::Paren) => {
2469 let mut es = self.parse_unspanned_seq(
2470 &token::OpenDelim(token::Paren),
2471 &token::CloseDelim(token::Paren),
2472 SeqSep::trailing_allowed(token::Comma),
2473 |p| Ok(p.parse_expr()?)
2475 let hi = self.prev_span;
2477 es.insert(0, self_value);
2478 let id = respan(ident_span.to(ident_span), ident);
2479 let nd = self.mk_method_call(id, tys, es);
2480 self.mk_expr(lo.to(hi), nd, ThinVec::new())
2484 if !tys.is_empty() {
2485 let prev_span = self.prev_span;
2486 self.span_err(prev_span,
2487 "field expressions may not \
2488 have type parameters");
2491 let id = respan(ident_span.to(ident_span), ident);
2492 let field = self.mk_field(self_value, id);
2493 self.mk_expr(lo.to(ident_span), field, ThinVec::new())
2498 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2503 while self.eat(&token::Question) {
2504 let hi = self.prev_span;
2505 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2509 if self.eat(&token::Dot) {
2511 token::Ident(i) => {
2512 let ident_span = self.span;
2514 e = self.parse_dot_suffix(i, ident_span, e, lo)?;
2516 token::Literal(token::Integer(n), suf) => {
2519 // A tuple index may not have a suffix
2520 self.expect_no_suffix(sp, "tuple index", suf);
2522 let dot_span = self.prev_span;
2526 let index = n.as_str().parse::<usize>().ok();
2529 let id = respan(dot_span.to(hi), n);
2530 let field = self.mk_tup_field(e, id);
2531 e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2534 let prev_span = self.prev_span;
2535 self.span_err(prev_span, "invalid tuple or tuple struct index");
2539 token::Literal(token::Float(n), _suf) => {
2541 let fstr = n.as_str();
2542 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2543 &format!("unexpected token: `{}`", n));
2544 err.span_label(self.prev_span, &"unexpected token");
2545 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2546 let float = match fstr.parse::<f64>().ok() {
2550 let sugg = pprust::to_string(|s| {
2551 use print::pprust::PrintState;
2552 use print::pp::word;
2555 word(&mut s.s, ".")?;
2556 s.print_usize(float.trunc() as usize)?;
2558 word(&mut s.s, ".")?;
2559 word(&mut s.s, fstr.splitn(2, ".").last().unwrap())
2561 err.span_suggestion(
2562 lo.to(self.prev_span),
2563 "try parenthesizing the first index",
2570 // FIXME Could factor this out into non_fatal_unexpected or something.
2571 let actual = self.this_token_to_string();
2572 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2574 let dot_span = self.prev_span;
2575 e = self.parse_dot_suffix(keywords::Invalid.ident(), dot_span, e, lo)?;
2580 if self.expr_is_complete(&e) { break; }
2583 token::OpenDelim(token::Paren) => {
2584 let es = self.parse_unspanned_seq(
2585 &token::OpenDelim(token::Paren),
2586 &token::CloseDelim(token::Paren),
2587 SeqSep::trailing_allowed(token::Comma),
2588 |p| Ok(p.parse_expr()?)
2590 hi = self.prev_span;
2592 let nd = self.mk_call(e, es);
2593 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2597 // Could be either an index expression or a slicing expression.
2598 token::OpenDelim(token::Bracket) => {
2600 let ix = self.parse_expr()?;
2602 self.expect(&token::CloseDelim(token::Bracket))?;
2603 let index = self.mk_index(e, ix);
2604 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2612 pub fn process_potential_macro_variable(&mut self) {
2613 let ident = match self.token {
2614 token::SubstNt(name) => {
2615 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2618 token::Interpolated(ref nt) => {
2619 self.meta_var_span = Some(self.span);
2621 token::NtIdent(ident) => ident,
2627 self.token = token::Ident(ident.node);
2628 self.span = ident.span;
2631 /// parse a single token tree from the input.
2632 pub fn parse_token_tree(&mut self) -> TokenTree {
2634 token::OpenDelim(..) => {
2635 let frame = mem::replace(&mut self.token_cursor.frame,
2636 self.token_cursor.stack.pop().unwrap());
2637 self.span = frame.span;
2639 TokenTree::Delimited(frame.span, Delimited {
2641 tts: frame.tree_cursor.original_stream().into(),
2644 token::CloseDelim(_) | token::Eof => unreachable!(),
2646 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2648 TokenTree::Token(span, token)
2653 // parse a stream of tokens into a list of TokenTree's,
2655 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2656 let mut tts = Vec::new();
2657 while self.token != token::Eof {
2658 tts.push(self.parse_token_tree());
2663 pub fn parse_tokens(&mut self) -> TokenStream {
2664 let mut result = Vec::new();
2667 token::Eof | token::CloseDelim(..) => break,
2668 _ => result.push(self.parse_token_tree().into()),
2671 TokenStream::concat(result)
2674 /// Parse a prefix-unary-operator expr
2675 pub fn parse_prefix_expr(&mut self,
2676 already_parsed_attrs: Option<ThinVec<Attribute>>)
2677 -> PResult<'a, P<Expr>> {
2678 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2680 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2681 let (hi, ex) = match self.token {
2684 let e = self.parse_prefix_expr(None);
2685 let (span, e) = self.interpolated_or_expr_span(e)?;
2686 (span, self.mk_unary(UnOp::Not, e))
2688 token::BinOp(token::Minus) => {
2690 let e = self.parse_prefix_expr(None);
2691 let (span, e) = self.interpolated_or_expr_span(e)?;
2692 (span, self.mk_unary(UnOp::Neg, e))
2694 token::BinOp(token::Star) => {
2696 let e = self.parse_prefix_expr(None);
2697 let (span, e) = self.interpolated_or_expr_span(e)?;
2698 (span, self.mk_unary(UnOp::Deref, e))
2700 token::BinOp(token::And) | token::AndAnd => {
2702 let m = self.parse_mutability();
2703 let e = self.parse_prefix_expr(None);
2704 let (span, e) = self.interpolated_or_expr_span(e)?;
2705 (span, ExprKind::AddrOf(m, e))
2707 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2709 let place = self.parse_expr_res(
2710 Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
2713 let blk = self.parse_block()?;
2714 let span = blk.span;
2715 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2716 (span, ExprKind::InPlace(place, blk_expr))
2718 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2720 let e = self.parse_prefix_expr(None);
2721 let (span, e) = self.interpolated_or_expr_span(e)?;
2722 (span, ExprKind::Box(e))
2724 _ => return self.parse_dot_or_call_expr(Some(attrs))
2726 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2729 /// Parse an associative expression
2731 /// This parses an expression accounting for associativity and precedence of the operators in
2733 pub fn parse_assoc_expr(&mut self,
2734 already_parsed_attrs: Option<ThinVec<Attribute>>)
2735 -> PResult<'a, P<Expr>> {
2736 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2739 /// Parse an associative expression with operators of at least `min_prec` precedence
2740 pub fn parse_assoc_expr_with(&mut self,
2743 -> PResult<'a, P<Expr>> {
2744 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2747 let attrs = match lhs {
2748 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2751 if self.token == token::DotDot || self.token == token::DotDotDot {
2752 return self.parse_prefix_range_expr(attrs);
2754 self.parse_prefix_expr(attrs)?
2758 if self.expr_is_complete(&lhs) {
2759 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2762 self.expected_tokens.push(TokenType::Operator);
2763 while let Some(op) = AssocOp::from_token(&self.token) {
2765 let lhs_span = if self.prev_token_kind == PrevTokenKind::Interpolated {
2771 let cur_op_span = self.span;
2772 let restrictions = if op.is_assign_like() {
2773 self.restrictions & Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2777 if op.precedence() < min_prec {
2781 if op.is_comparison() {
2782 self.check_no_chained_comparison(&lhs, &op);
2785 if op == AssocOp::As {
2786 let rhs = self.parse_ty_no_plus()?;
2787 lhs = self.mk_expr(lhs_span.to(rhs.span), ExprKind::Cast(lhs, rhs), ThinVec::new());
2789 } else if op == AssocOp::Colon {
2790 let rhs = self.parse_ty_no_plus()?;
2791 lhs = self.mk_expr(lhs_span.to(rhs.span), ExprKind::Type(lhs, rhs), ThinVec::new());
2793 } else if op == AssocOp::DotDot || op == AssocOp::DotDotDot {
2794 // If we didn’t have to handle `x..`/`x...`, it would be pretty easy to
2795 // generalise it to the Fixity::None code.
2797 // We have 2 alternatives here: `x..y`/`x...y` and `x..`/`x...` The other
2798 // two variants are handled with `parse_prefix_range_expr` call above.
2799 let rhs = if self.is_at_start_of_range_notation_rhs() {
2800 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2801 LhsExpr::NotYetParsed)?)
2805 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2810 let limits = if op == AssocOp::DotDot {
2811 RangeLimits::HalfOpen
2816 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2817 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2821 let rhs = match op.fixity() {
2822 Fixity::Right => self.with_res(
2823 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2825 this.parse_assoc_expr_with(op.precedence(),
2826 LhsExpr::NotYetParsed)
2828 Fixity::Left => self.with_res(
2829 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2831 this.parse_assoc_expr_with(op.precedence() + 1,
2832 LhsExpr::NotYetParsed)
2834 // We currently have no non-associative operators that are not handled above by
2835 // the special cases. The code is here only for future convenience.
2836 Fixity::None => self.with_res(
2837 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2839 this.parse_assoc_expr_with(op.precedence() + 1,
2840 LhsExpr::NotYetParsed)
2844 let span = lhs_span.to(rhs.span);
2846 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2847 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2848 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2849 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2850 AssocOp::Greater | AssocOp::GreaterEqual => {
2851 let ast_op = op.to_ast_binop().unwrap();
2852 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2853 self.mk_expr(span, binary, ThinVec::new())
2856 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2858 self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
2859 AssocOp::AssignOp(k) => {
2861 token::Plus => BinOpKind::Add,
2862 token::Minus => BinOpKind::Sub,
2863 token::Star => BinOpKind::Mul,
2864 token::Slash => BinOpKind::Div,
2865 token::Percent => BinOpKind::Rem,
2866 token::Caret => BinOpKind::BitXor,
2867 token::And => BinOpKind::BitAnd,
2868 token::Or => BinOpKind::BitOr,
2869 token::Shl => BinOpKind::Shl,
2870 token::Shr => BinOpKind::Shr,
2872 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2873 self.mk_expr(span, aopexpr, ThinVec::new())
2875 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotDot => {
2876 self.bug("As, Colon, DotDot or DotDotDot branch reached")
2880 if op.fixity() == Fixity::None { break }
2885 /// Produce an error if comparison operators are chained (RFC #558).
2886 /// We only need to check lhs, not rhs, because all comparison ops
2887 /// have same precedence and are left-associative
2888 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2889 debug_assert!(outer_op.is_comparison());
2891 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2892 // respan to include both operators
2893 let op_span = op.span.to(self.span);
2894 let mut err = self.diagnostic().struct_span_err(op_span,
2895 "chained comparison operators require parentheses");
2896 if op.node == BinOpKind::Lt &&
2897 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
2898 *outer_op == AssocOp::Greater // even in a case like the following:
2899 { // Foo<Bar<Baz<Qux, ()>>>
2901 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2909 /// Parse prefix-forms of range notation: `..expr`, `..`, `...expr`
2910 fn parse_prefix_range_expr(&mut self,
2911 already_parsed_attrs: Option<ThinVec<Attribute>>)
2912 -> PResult<'a, P<Expr>> {
2913 debug_assert!(self.token == token::DotDot || self.token == token::DotDotDot);
2914 let tok = self.token.clone();
2915 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2917 let mut hi = self.span;
2919 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2920 // RHS must be parsed with more associativity than the dots.
2921 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
2922 Some(self.parse_assoc_expr_with(next_prec,
2923 LhsExpr::NotYetParsed)
2931 let limits = if tok == token::DotDot {
2932 RangeLimits::HalfOpen
2937 let r = try!(self.mk_range(None,
2940 Ok(self.mk_expr(lo.to(hi), r, attrs))
2943 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2944 if self.token.can_begin_expr() {
2945 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2946 if self.token == token::OpenDelim(token::Brace) {
2947 return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
2955 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2956 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
2957 if self.check_keyword(keywords::Let) {
2958 return self.parse_if_let_expr(attrs);
2960 let lo = self.prev_span;
2961 let cond = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
2962 let thn = self.parse_block()?;
2963 let mut els: Option<P<Expr>> = None;
2964 let mut hi = thn.span;
2965 if self.eat_keyword(keywords::Else) {
2966 let elexpr = self.parse_else_expr()?;
2970 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
2973 /// Parse an 'if let' expression ('if' token already eaten)
2974 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
2975 -> PResult<'a, P<Expr>> {
2976 let lo = self.prev_span;
2977 self.expect_keyword(keywords::Let)?;
2978 let pat = self.parse_pat()?;
2979 self.expect(&token::Eq)?;
2980 let expr = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
2981 let thn = self.parse_block()?;
2982 let (hi, els) = if self.eat_keyword(keywords::Else) {
2983 let expr = self.parse_else_expr()?;
2984 (expr.span, Some(expr))
2988 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
2991 // `move |args| expr`
2992 pub fn parse_lambda_expr(&mut self,
2994 capture_clause: CaptureBy,
2995 attrs: ThinVec<Attribute>)
2996 -> PResult<'a, P<Expr>>
2998 let decl = self.parse_fn_block_decl()?;
2999 let decl_hi = self.prev_span;
3000 let body = match decl.output {
3001 FunctionRetTy::Default(_) => self.parse_expr()?,
3003 // If an explicit return type is given, require a
3004 // block to appear (RFC 968).
3005 let body_lo = self.span;
3006 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3012 ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3016 // `else` token already eaten
3017 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3018 if self.eat_keyword(keywords::If) {
3019 return self.parse_if_expr(ThinVec::new());
3021 let blk = self.parse_block()?;
3022 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3026 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3027 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3029 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3030 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3032 let pat = self.parse_pat()?;
3033 self.expect_keyword(keywords::In)?;
3034 let expr = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
3035 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3036 attrs.extend(iattrs);
3038 let hi = self.prev_span;
3039 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3042 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3043 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3045 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3046 if self.token.is_keyword(keywords::Let) {
3047 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3049 let cond = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
3050 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3051 attrs.extend(iattrs);
3052 let span = span_lo.to(body.span);
3053 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3056 /// Parse a 'while let' expression ('while' token already eaten)
3057 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3059 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3060 self.expect_keyword(keywords::Let)?;
3061 let pat = self.parse_pat()?;
3062 self.expect(&token::Eq)?;
3063 let expr = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
3064 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3065 attrs.extend(iattrs);
3066 let span = span_lo.to(body.span);
3067 return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3070 // parse `loop {...}`, `loop` token already eaten
3071 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3073 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3074 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3075 attrs.extend(iattrs);
3076 let span = span_lo.to(body.span);
3077 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3080 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3081 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3082 -> PResult<'a, P<Expr>>
3084 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3085 attrs.extend(iattrs);
3086 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3089 // `match` token already eaten
3090 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3091 let match_span = self.prev_span;
3092 let lo = self.prev_span;
3093 let discriminant = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
3095 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3096 if self.token == token::Token::Semi {
3097 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3101 attrs.extend(self.parse_inner_attributes()?);
3103 let mut arms: Vec<Arm> = Vec::new();
3104 while self.token != token::CloseDelim(token::Brace) {
3105 match self.parse_arm() {
3106 Ok(arm) => arms.push(arm),
3108 // Recover by skipping to the end of the block.
3110 self.recover_stmt();
3111 let span = lo.to(self.span);
3112 if self.token == token::CloseDelim(token::Brace) {
3115 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3121 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3124 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3125 maybe_whole!(self, NtArm, |x| x);
3127 let attrs = self.parse_outer_attributes()?;
3128 let pats = self.parse_pats()?;
3129 let mut guard = None;
3130 if self.eat_keyword(keywords::If) {
3131 guard = Some(self.parse_expr()?);
3133 self.expect(&token::FatArrow)?;
3134 let expr = self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR, None)?;
3137 !classify::expr_is_simple_block(&expr)
3138 && self.token != token::CloseDelim(token::Brace);
3141 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3143 self.eat(&token::Comma);
3154 /// Parse an expression
3155 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3156 self.parse_expr_res(Restrictions::empty(), None)
3159 /// Evaluate the closure with restrictions in place.
3161 /// After the closure is evaluated, restrictions are reset.
3162 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3163 where F: FnOnce(&mut Self) -> T
3165 let old = self.restrictions;
3166 self.restrictions = r;
3168 self.restrictions = old;
3173 /// Parse an expression, subject to the given restrictions
3174 pub fn parse_expr_res(&mut self, r: Restrictions,
3175 already_parsed_attrs: Option<ThinVec<Attribute>>)
3176 -> PResult<'a, P<Expr>> {
3177 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3180 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3181 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3182 if self.check(&token::Eq) {
3184 Ok(Some(self.parse_expr()?))
3190 /// Parse patterns, separated by '|' s
3191 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3192 let mut pats = Vec::new();
3194 pats.push(self.parse_pat()?);
3195 if self.check(&token::BinOp(token::Or)) { self.bump();}
3196 else { return Ok(pats); }
3200 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3201 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3202 let mut fields = vec![];
3203 let mut ddpos = None;
3205 while !self.check(&token::CloseDelim(token::Paren)) {
3206 if ddpos.is_none() && self.eat(&token::DotDot) {
3207 ddpos = Some(fields.len());
3208 if self.eat(&token::Comma) {
3209 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3210 fields.push(self.parse_pat()?);
3212 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3213 // Emit a friendly error, ignore `..` and continue parsing
3214 self.span_err(self.prev_span, "`..` can only be used once per \
3215 tuple or tuple struct pattern");
3217 fields.push(self.parse_pat()?);
3220 if !self.check(&token::CloseDelim(token::Paren)) ||
3221 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3222 self.expect(&token::Comma)?;
3229 fn parse_pat_vec_elements(
3231 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3232 let mut before = Vec::new();
3233 let mut slice = None;
3234 let mut after = Vec::new();
3235 let mut first = true;
3236 let mut before_slice = true;
3238 while self.token != token::CloseDelim(token::Bracket) {
3242 self.expect(&token::Comma)?;
3244 if self.token == token::CloseDelim(token::Bracket)
3245 && (before_slice || !after.is_empty()) {
3251 if self.eat(&token::DotDot) {
3253 if self.check(&token::Comma) ||
3254 self.check(&token::CloseDelim(token::Bracket)) {
3255 slice = Some(P(ast::Pat {
3256 id: ast::DUMMY_NODE_ID,
3257 node: PatKind::Wild,
3260 before_slice = false;
3266 let subpat = self.parse_pat()?;
3267 if before_slice && self.eat(&token::DotDot) {
3268 slice = Some(subpat);
3269 before_slice = false;
3270 } else if before_slice {
3271 before.push(subpat);
3277 Ok((before, slice, after))
3280 /// Parse the fields of a struct-like pattern
3281 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3282 let mut fields = Vec::new();
3283 let mut etc = false;
3284 let mut first = true;
3285 while self.token != token::CloseDelim(token::Brace) {
3289 self.expect(&token::Comma)?;
3290 // accept trailing commas
3291 if self.check(&token::CloseDelim(token::Brace)) { break }
3294 let attrs = self.parse_outer_attributes()?;
3298 if self.check(&token::DotDot) {
3300 if self.token != token::CloseDelim(token::Brace) {
3301 let token_str = self.this_token_to_string();
3302 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3309 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3310 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3311 // Parsing a pattern of the form "fieldname: pat"
3312 let fieldname = self.parse_field_name()?;
3314 let pat = self.parse_pat()?;
3316 (pat, fieldname, false)
3318 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3319 let is_box = self.eat_keyword(keywords::Box);
3320 let boxed_span = self.span;
3321 let is_ref = self.eat_keyword(keywords::Ref);
3322 let is_mut = self.eat_keyword(keywords::Mut);
3323 let fieldname = self.parse_ident()?;
3324 hi = self.prev_span;
3326 let bind_type = match (is_ref, is_mut) {
3327 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3328 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3329 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3330 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3332 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3333 let fieldpat = P(ast::Pat{
3334 id: ast::DUMMY_NODE_ID,
3335 node: PatKind::Ident(bind_type, fieldpath, None),
3336 span: boxed_span.to(hi),
3339 let subpat = if is_box {
3341 id: ast::DUMMY_NODE_ID,
3342 node: PatKind::Box(fieldpat),
3348 (subpat, fieldname, true)
3351 fields.push(codemap::Spanned { span: lo.to(hi),
3352 node: ast::FieldPat {
3355 is_shorthand: is_shorthand,
3356 attrs: attrs.into(),
3360 return Ok((fields, etc));
3363 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3364 if self.token.is_path_start() {
3366 let (qself, path) = if self.eat_lt() {
3367 // Parse a qualified path
3369 self.parse_qualified_path(PathStyle::Expr)?;
3372 // Parse an unqualified path
3373 (None, self.parse_path(PathStyle::Expr)?)
3375 let hi = self.prev_span;
3376 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3378 self.parse_pat_literal_maybe_minus()
3382 // helper function to decide whether to parse as ident binding or to try to do
3383 // something more complex like range patterns
3384 fn parse_as_ident(&mut self) -> bool {
3385 self.look_ahead(1, |t| match *t {
3386 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3387 token::DotDotDot | token::ModSep | token::Not => Some(false),
3388 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3389 // range pattern branch
3390 token::DotDot => None,
3392 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3393 token::Comma | token::CloseDelim(token::Bracket) => true,
3398 /// Parse a pattern.
3399 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3400 maybe_whole!(self, NtPat, |x| x);
3405 token::Underscore => {
3408 pat = PatKind::Wild;
3410 token::BinOp(token::And) | token::AndAnd => {
3411 // Parse &pat / &mut pat
3413 let mutbl = self.parse_mutability();
3414 if let token::Lifetime(ident) = self.token {
3415 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3417 let subpat = self.parse_pat()?;
3418 pat = PatKind::Ref(subpat, mutbl);
3420 token::OpenDelim(token::Paren) => {
3421 // Parse (pat,pat,pat,...) as tuple pattern
3423 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3424 self.expect(&token::CloseDelim(token::Paren))?;
3425 pat = PatKind::Tuple(fields, ddpos);
3427 token::OpenDelim(token::Bracket) => {
3428 // Parse [pat,pat,...] as slice pattern
3430 let (before, slice, after) = self.parse_pat_vec_elements()?;
3431 self.expect(&token::CloseDelim(token::Bracket))?;
3432 pat = PatKind::Slice(before, slice, after);
3434 // At this point, token != _, &, &&, (, [
3435 _ => if self.eat_keyword(keywords::Mut) {
3436 // Parse mut ident @ pat
3437 pat = self.parse_pat_ident(BindingMode::ByValue(Mutability::Mutable))?;
3438 } else if self.eat_keyword(keywords::Ref) {
3439 // Parse ref ident @ pat / ref mut ident @ pat
3440 let mutbl = self.parse_mutability();
3441 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3442 } else if self.eat_keyword(keywords::Box) {
3444 let subpat = self.parse_pat()?;
3445 pat = PatKind::Box(subpat);
3446 } else if self.token.is_ident() && !self.token.is_any_keyword() &&
3447 self.parse_as_ident() {
3448 // Parse ident @ pat
3449 // This can give false positives and parse nullary enums,
3450 // they are dealt with later in resolve
3451 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3452 pat = self.parse_pat_ident(binding_mode)?;
3453 } else if self.token.is_path_start() {
3454 // Parse pattern starting with a path
3455 let (qself, path) = if self.eat_lt() {
3456 // Parse a qualified path
3457 let (qself, path) = self.parse_qualified_path(PathStyle::Expr)?;
3460 // Parse an unqualified path
3461 (None, self.parse_path(PathStyle::Expr)?)
3464 token::Not if qself.is_none() => {
3465 // Parse macro invocation
3467 let (_, tts) = self.expect_delimited_token_tree()?;
3468 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3469 pat = PatKind::Mac(mac);
3471 token::DotDotDot | token::DotDot => {
3472 let end_kind = match self.token {
3473 token::DotDot => RangeEnd::Excluded,
3474 token::DotDotDot => RangeEnd::Included,
3475 _ => panic!("can only parse `..` or `...` for ranges (checked above)"),
3478 let span = lo.to(self.prev_span);
3479 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3481 let end = self.parse_pat_range_end()?;
3482 pat = PatKind::Range(begin, end, end_kind);
3484 token::OpenDelim(token::Brace) => {
3485 if qself.is_some() {
3486 return Err(self.fatal("unexpected `{` after qualified path"));
3488 // Parse struct pattern
3490 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3492 self.recover_stmt();
3496 pat = PatKind::Struct(path, fields, etc);
3498 token::OpenDelim(token::Paren) => {
3499 if qself.is_some() {
3500 return Err(self.fatal("unexpected `(` after qualified path"));
3502 // Parse tuple struct or enum pattern
3504 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3505 self.expect(&token::CloseDelim(token::Paren))?;
3506 pat = PatKind::TupleStruct(path, fields, ddpos)
3508 _ => pat = PatKind::Path(qself, path),
3511 // Try to parse everything else as literal with optional minus
3512 match self.parse_pat_literal_maybe_minus() {
3514 if self.eat(&token::DotDotDot) {
3515 let end = self.parse_pat_range_end()?;
3516 pat = PatKind::Range(begin, end, RangeEnd::Included);
3517 } else if self.eat(&token::DotDot) {
3518 let end = self.parse_pat_range_end()?;
3519 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3521 pat = PatKind::Lit(begin);
3525 self.cancel(&mut err);
3526 let msg = format!("expected pattern, found {}", self.this_token_descr());
3527 return Err(self.fatal(&msg));
3534 id: ast::DUMMY_NODE_ID,
3536 span: lo.to(self.prev_span),
3540 /// Parse ident or ident @ pat
3541 /// used by the copy foo and ref foo patterns to give a good
3542 /// error message when parsing mistakes like ref foo(a,b)
3543 fn parse_pat_ident(&mut self,
3544 binding_mode: ast::BindingMode)
3545 -> PResult<'a, PatKind> {
3546 let ident_span = self.span;
3547 let ident = self.parse_ident()?;
3548 let name = codemap::Spanned{span: ident_span, node: ident};
3549 let sub = if self.eat(&token::At) {
3550 Some(self.parse_pat()?)
3555 // just to be friendly, if they write something like
3557 // we end up here with ( as the current token. This shortly
3558 // leads to a parse error. Note that if there is no explicit
3559 // binding mode then we do not end up here, because the lookahead
3560 // will direct us over to parse_enum_variant()
3561 if self.token == token::OpenDelim(token::Paren) {
3562 return Err(self.span_fatal(
3564 "expected identifier, found enum pattern"))
3567 Ok(PatKind::Ident(binding_mode, name, sub))
3570 /// Parse a local variable declaration
3571 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3573 let pat = self.parse_pat()?;
3576 if self.eat(&token::Colon) {
3577 ty = Some(self.parse_ty()?);
3579 let init = self.parse_initializer()?;
3584 id: ast::DUMMY_NODE_ID,
3585 span: lo.to(self.prev_span),
3590 /// Parse a structure field
3591 fn parse_name_and_ty(&mut self,
3594 attrs: Vec<Attribute>)
3595 -> PResult<'a, StructField> {
3596 let name = self.parse_ident()?;
3597 self.expect(&token::Colon)?;
3598 let ty = self.parse_ty()?;
3600 span: lo.to(self.prev_span),
3603 id: ast::DUMMY_NODE_ID,
3609 /// Emit an expected item after attributes error.
3610 fn expected_item_err(&self, attrs: &[Attribute]) {
3611 let message = match attrs.last() {
3612 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3613 _ => "expected item after attributes",
3616 self.span_err(self.prev_span, message);
3619 /// Parse a statement. This stops just before trailing semicolons on everything but items.
3620 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3621 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3622 Ok(self.parse_stmt_(true))
3625 // Eat tokens until we can be relatively sure we reached the end of the
3626 // statement. This is something of a best-effort heuristic.
3628 // We terminate when we find an unmatched `}` (without consuming it).
3629 fn recover_stmt(&mut self) {
3630 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
3633 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3634 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3635 // approximate - it can mean we break too early due to macros, but that
3636 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3638 // If `break_on_block` is `Break`, then we will stop consuming tokens
3639 // after finding (and consuming) a brace-delimited block.
3640 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
3641 let mut brace_depth = 0;
3642 let mut bracket_depth = 0;
3643 let mut in_block = false;
3644 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
3645 break_on_semi, break_on_block);
3647 debug!("recover_stmt_ loop {:?}", self.token);
3649 token::OpenDelim(token::DelimToken::Brace) => {
3652 if break_on_block == BlockMode::Break &&
3654 bracket_depth == 0 {
3658 token::OpenDelim(token::DelimToken::Bracket) => {
3662 token::CloseDelim(token::DelimToken::Brace) => {
3663 if brace_depth == 0 {
3664 debug!("recover_stmt_ return - close delim {:?}", self.token);
3669 if in_block && bracket_depth == 0 && brace_depth == 0 {
3670 debug!("recover_stmt_ return - block end {:?}", self.token);
3674 token::CloseDelim(token::DelimToken::Bracket) => {
3676 if bracket_depth < 0 {
3682 debug!("recover_stmt_ return - Eof");
3687 if break_on_semi == SemiColonMode::Break &&
3689 bracket_depth == 0 {
3690 debug!("recover_stmt_ return - Semi");
3701 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
3702 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
3704 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
3709 fn is_catch_expr(&mut self) -> bool {
3710 self.token.is_keyword(keywords::Do) &&
3711 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
3712 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
3714 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3715 !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL)
3718 fn is_union_item(&self) -> bool {
3719 self.token.is_keyword(keywords::Union) &&
3720 self.look_ahead(1, |t| t.is_ident() && !t.is_any_keyword())
3723 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility)
3724 -> PResult<'a, Option<P<Item>>> {
3727 token::Ident(ident) if ident.name == "macro_rules" => {
3728 if self.look_ahead(1, |t| *t == token::Not) {
3729 let prev_span = self.prev_span;
3730 self.complain_if_pub_macro(vis, prev_span);
3735 _ => return Ok(None),
3738 let id = self.parse_ident()?;
3739 let (delim, tts) = self.expect_delimited_token_tree()?;
3740 if delim != token::Brace {
3741 if !self.eat(&token::Semi) {
3742 let msg = "macros that expand to items must either be surrounded with braces \
3743 or followed by a semicolon";
3744 self.span_err(self.prev_span, msg);
3748 let span = lo.to(self.prev_span);
3749 let kind = ItemKind::MacroDef(tts);
3750 Ok(Some(self.mk_item(span, id, kind, Visibility::Inherited, attrs.to_owned())))
3753 fn parse_stmt_without_recovery(&mut self,
3754 macro_legacy_warnings: bool)
3755 -> PResult<'a, Option<Stmt>> {
3756 maybe_whole!(self, NtStmt, |x| Some(x));
3758 let attrs = self.parse_outer_attributes()?;
3761 Ok(Some(if self.eat_keyword(keywords::Let) {
3763 id: ast::DUMMY_NODE_ID,
3764 node: StmtKind::Local(self.parse_local(attrs.into())?),
3765 span: lo.to(self.prev_span),
3767 } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited)? {
3769 id: ast::DUMMY_NODE_ID,
3770 node: StmtKind::Item(macro_def),
3771 span: lo.to(self.prev_span),
3773 // Starts like a simple path, but not a union item.
3774 } else if self.token.is_path_start() &&
3775 !self.token.is_qpath_start() &&
3776 !self.is_union_item() {
3777 let pth = self.parse_path(PathStyle::Expr)?;
3779 if !self.eat(&token::Not) {
3780 let expr = if self.check(&token::OpenDelim(token::Brace)) {
3781 self.parse_struct_expr(lo, pth, ThinVec::new())?
3783 let hi = self.prev_span;
3784 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
3787 let expr = self.with_res(Restrictions::RESTRICTION_STMT_EXPR, |this| {
3788 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
3789 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
3792 return Ok(Some(Stmt {
3793 id: ast::DUMMY_NODE_ID,
3794 node: StmtKind::Expr(expr),
3795 span: lo.to(self.prev_span),
3799 // it's a macro invocation
3800 let id = match self.token {
3801 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
3802 _ => self.parse_ident()?,
3805 // check that we're pointing at delimiters (need to check
3806 // again after the `if`, because of `parse_ident`
3807 // consuming more tokens).
3808 let delim = match self.token {
3809 token::OpenDelim(delim) => delim,
3811 // we only expect an ident if we didn't parse one
3813 let ident_str = if id.name == keywords::Invalid.name() {
3818 let tok_str = self.this_token_to_string();
3819 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3825 let (_, tts) = self.expect_delimited_token_tree()?;
3826 let hi = self.prev_span;
3828 let style = if delim == token::Brace {
3829 MacStmtStyle::Braces
3831 MacStmtStyle::NoBraces
3834 if id.name == keywords::Invalid.name() {
3835 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
3836 let node = if delim == token::Brace ||
3837 self.token == token::Semi || self.token == token::Eof {
3838 StmtKind::Mac(P((mac, style, attrs.into())))
3840 // We used to incorrectly stop parsing macro-expanded statements here.
3841 // If the next token will be an error anyway but could have parsed with the
3842 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
3843 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
3844 // These can continue an expression, so we can't stop parsing and warn.
3845 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
3846 token::BinOp(token::Minus) | token::BinOp(token::Star) |
3847 token::BinOp(token::And) | token::BinOp(token::Or) |
3848 token::AndAnd | token::OrOr |
3849 token::DotDot | token::DotDotDot => false,
3852 self.warn_missing_semicolon();
3853 StmtKind::Mac(P((mac, style, attrs.into())))
3855 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
3856 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
3857 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
3861 id: ast::DUMMY_NODE_ID,
3866 // if it has a special ident, it's definitely an item
3868 // Require a semicolon or braces.
3869 if style != MacStmtStyle::Braces {
3870 if !self.eat(&token::Semi) {
3871 self.span_err(self.prev_span,
3872 "macros that expand to items must \
3873 either be surrounded with braces or \
3874 followed by a semicolon");
3877 let span = lo.to(hi);
3879 id: ast::DUMMY_NODE_ID,
3881 node: StmtKind::Item({
3883 span, id /*id is good here*/,
3884 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
3885 Visibility::Inherited,
3891 // FIXME: Bad copy of attrs
3892 let old_directory_ownership =
3893 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
3894 let item = self.parse_item_(attrs.clone(), false, true)?;
3895 self.directory.ownership = old_directory_ownership;
3898 id: ast::DUMMY_NODE_ID,
3899 span: lo.to(i.span),
3900 node: StmtKind::Item(i),
3903 let unused_attrs = |attrs: &[_], s: &mut Self| {
3904 if attrs.len() > 0 {
3905 if s.prev_token_kind == PrevTokenKind::DocComment {
3906 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
3908 s.span_err(s.span, "expected statement after outer attribute");
3913 // Do not attempt to parse an expression if we're done here.
3914 if self.token == token::Semi {
3915 unused_attrs(&attrs, self);
3920 if self.token == token::CloseDelim(token::Brace) {
3921 unused_attrs(&attrs, self);
3925 // Remainder are line-expr stmts.
3926 let e = self.parse_expr_res(
3927 Restrictions::RESTRICTION_STMT_EXPR, Some(attrs.into()))?;
3929 id: ast::DUMMY_NODE_ID,
3930 span: lo.to(e.span),
3931 node: StmtKind::Expr(e),
3938 /// Is this expression a successfully-parsed statement?
3939 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3940 self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
3941 !classify::expr_requires_semi_to_be_stmt(e)
3944 /// Parse a block. No inner attrs are allowed.
3945 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
3946 maybe_whole!(self, NtBlock, |x| x);
3950 if !self.eat(&token::OpenDelim(token::Brace)) {
3952 let tok = self.this_token_to_string();
3953 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
3955 // Check to see if the user has written something like
3960 // Which is valid in other languages, but not Rust.
3961 match self.parse_stmt_without_recovery(false) {
3963 let mut stmt_span = stmt.span;
3964 // expand the span to include the semicolon, if it exists
3965 if self.eat(&token::Semi) {
3966 stmt_span.hi = self.prev_span.hi;
3968 let sugg = pprust::to_string(|s| {
3969 use print::pprust::{PrintState, INDENT_UNIT};
3970 s.ibox(INDENT_UNIT)?;
3972 s.print_stmt(&stmt)?;
3973 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
3975 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
3978 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
3979 self.cancel(&mut e);
3986 self.parse_block_tail(lo, BlockCheckMode::Default)
3989 /// Parse a block. Inner attrs are allowed.
3990 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
3991 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
3994 self.expect(&token::OpenDelim(token::Brace))?;
3995 Ok((self.parse_inner_attributes()?,
3996 self.parse_block_tail(lo, BlockCheckMode::Default)?))
3999 /// Parse the rest of a block expression or function body
4000 /// Precondition: already parsed the '{'.
4001 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4002 let mut stmts = vec![];
4004 while !self.eat(&token::CloseDelim(token::Brace)) {
4005 if let Some(stmt) = self.parse_full_stmt(false)? {
4007 } else if self.token == token::Eof {
4010 // Found only `;` or `}`.
4017 id: ast::DUMMY_NODE_ID,
4019 span: lo.to(self.prev_span),
4023 /// Parse a statement, including the trailing semicolon.
4024 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4025 let mut stmt = match self.parse_stmt_(macro_legacy_warnings) {
4027 None => return Ok(None),
4031 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4032 // expression without semicolon
4033 if classify::expr_requires_semi_to_be_stmt(expr) {
4034 // Just check for errors and recover; do not eat semicolon yet.
4036 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4039 self.recover_stmt();
4043 StmtKind::Local(..) => {
4044 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4045 if macro_legacy_warnings && self.token != token::Semi {
4046 self.warn_missing_semicolon();
4048 self.expect_one_of(&[token::Semi], &[])?;
4054 if self.eat(&token::Semi) {
4055 stmt = stmt.add_trailing_semicolon();
4058 stmt.span.hi = self.prev_span.hi;
4062 fn warn_missing_semicolon(&self) {
4063 self.diagnostic().struct_span_warn(self.span, {
4064 &format!("expected `;`, found `{}`", self.this_token_to_string())
4066 "This was erroneously allowed and will become a hard error in a future release"
4070 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4071 // BOUND = TY_BOUND | LT_BOUND
4072 // LT_BOUND = LIFETIME (e.g. `'a`)
4073 // TY_BOUND = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4074 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4075 let mut bounds = Vec::new();
4077 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4078 if self.check_lifetime() {
4079 if let Some(question_span) = question {
4080 self.span_err(question_span,
4081 "`?` may only modify trait bounds, not lifetime bounds");
4083 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4084 } else if self.check_keyword(keywords::For) || self.check_path() {
4086 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4087 let path = self.parse_path(PathStyle::Type)?;
4088 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4089 let modifier = if question.is_some() {
4090 TraitBoundModifier::Maybe
4092 TraitBoundModifier::None
4094 bounds.push(TraitTyParamBound(poly_trait, modifier));
4099 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4107 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4108 self.parse_ty_param_bounds_common(true)
4111 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4112 // BOUND = LT_BOUND (e.g. `'a`)
4113 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4114 let mut lifetimes = Vec::new();
4115 while self.check_lifetime() {
4116 lifetimes.push(self.expect_lifetime());
4118 if !self.eat(&token::BinOp(token::Plus)) {
4125 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4126 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4127 let span = self.span;
4128 let ident = self.parse_ident()?;
4130 // Parse optional colon and param bounds.
4131 let bounds = if self.eat(&token::Colon) {
4132 self.parse_ty_param_bounds()?
4137 let default = if self.eat(&token::Eq) {
4138 Some(self.parse_ty()?)
4144 attrs: preceding_attrs.into(),
4146 id: ast::DUMMY_NODE_ID,
4153 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4154 /// trailing comma and erroneous trailing attributes.
4155 pub fn parse_generic_params(&mut self) -> PResult<'a, (Vec<LifetimeDef>, Vec<TyParam>)> {
4156 let mut lifetime_defs = Vec::new();
4157 let mut ty_params = Vec::new();
4158 let mut seen_ty_param = false;
4160 let attrs = self.parse_outer_attributes()?;
4161 if self.check_lifetime() {
4162 let lifetime = self.expect_lifetime();
4163 // Parse lifetime parameter.
4164 let bounds = if self.eat(&token::Colon) {
4165 self.parse_lt_param_bounds()
4169 lifetime_defs.push(LifetimeDef {
4170 attrs: attrs.into(),
4175 self.span_err(self.prev_span,
4176 "lifetime parameters must be declared prior to type parameters");
4178 } else if self.check_ident() {
4179 // Parse type parameter.
4180 ty_params.push(self.parse_ty_param(attrs)?);
4181 seen_ty_param = true;
4183 // Check for trailing attributes and stop parsing.
4184 if !attrs.is_empty() {
4185 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4186 self.span_err(attrs[0].span,
4187 &format!("trailing attribute after {} parameters", param_kind));
4192 if !self.eat(&token::Comma) {
4196 Ok((lifetime_defs, ty_params))
4199 /// Parse a set of optional generic type parameter declarations. Where
4200 /// clauses are not parsed here, and must be added later via
4201 /// `parse_where_clause()`.
4203 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4204 /// | ( < lifetimes , typaramseq ( , )? > )
4205 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4206 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4207 maybe_whole!(self, NtGenerics, |x| x);
4209 let span_lo = self.span;
4211 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4214 lifetimes: lifetime_defs,
4215 ty_params: ty_params,
4216 where_clause: WhereClause {
4217 id: ast::DUMMY_NODE_ID,
4218 predicates: Vec::new(),
4220 span: span_lo.to(self.prev_span),
4223 Ok(ast::Generics::default())
4227 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4228 /// possibly including trailing comma.
4229 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4230 let mut lifetimes = Vec::new();
4231 let mut types = Vec::new();
4232 let mut bindings = Vec::new();
4233 let mut seen_type = false;
4234 let mut seen_binding = false;
4236 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4237 // Parse lifetime argument.
4238 lifetimes.push(self.expect_lifetime());
4239 if seen_type || seen_binding {
4240 self.span_err(self.prev_span,
4241 "lifetime parameters must be declared prior to type parameters");
4243 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4244 // Parse associated type binding.
4246 let ident = self.parse_ident()?;
4248 let ty = self.parse_ty()?;
4249 bindings.push(TypeBinding {
4250 id: ast::DUMMY_NODE_ID,
4253 span: lo.to(self.prev_span),
4255 seen_binding = true;
4256 } else if self.check_type() {
4257 // Parse type argument.
4258 types.push(self.parse_ty()?);
4260 self.span_err(types[types.len() - 1].span,
4261 "type parameters must be declared prior to associated type bindings");
4268 if !self.eat(&token::Comma) {
4272 Ok((lifetimes, types, bindings))
4275 /// Parses an optional `where` clause and places it in `generics`.
4278 /// where T : Trait<U, V> + 'b, 'a : 'b
4280 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4281 maybe_whole!(self, NtWhereClause, |x| x);
4283 let mut where_clause = WhereClause {
4284 id: ast::DUMMY_NODE_ID,
4285 predicates: Vec::new(),
4288 if !self.eat_keyword(keywords::Where) {
4289 return Ok(where_clause);
4292 // This is a temporary future proofing.
4294 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4295 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4296 // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4297 if token::Lt == self.token {
4298 let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4299 if ident_or_lifetime {
4300 let gt_comma_or_colon = self.look_ahead(2, |t| {
4301 *t == token::Gt || *t == token::Comma || *t == token::Colon
4303 if gt_comma_or_colon {
4304 self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4311 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4312 let lifetime = self.expect_lifetime();
4313 // Bounds starting with a colon are mandatory, but possibly empty.
4314 self.expect(&token::Colon)?;
4315 let bounds = self.parse_lt_param_bounds();
4316 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4317 ast::WhereRegionPredicate {
4318 span: lo.to(self.prev_span),
4323 } else if self.check_type() {
4324 // Parse optional `for<'a, 'b>`.
4325 // This `for` is parsed greedily and applies to the whole predicate,
4326 // the bounded type can have its own `for` applying only to it.
4327 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4328 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4329 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4330 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4332 // Parse type with mandatory colon and (possibly empty) bounds,
4333 // or with mandatory equality sign and the second type.
4334 let ty = self.parse_ty()?;
4335 if self.eat(&token::Colon) {
4336 let bounds = self.parse_ty_param_bounds()?;
4337 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4338 ast::WhereBoundPredicate {
4339 span: lo.to(self.prev_span),
4340 bound_lifetimes: lifetime_defs,
4345 // FIXME: Decide what should be used here, `=` or `==`.
4346 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4347 let rhs_ty = self.parse_ty()?;
4348 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4349 ast::WhereEqPredicate {
4350 span: lo.to(self.prev_span),
4353 id: ast::DUMMY_NODE_ID,
4357 return self.unexpected();
4363 if !self.eat(&token::Comma) {
4371 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4372 -> PResult<'a, (Vec<Arg> , bool)> {
4374 let mut variadic = false;
4375 let args: Vec<Option<Arg>> =
4376 self.parse_unspanned_seq(
4377 &token::OpenDelim(token::Paren),
4378 &token::CloseDelim(token::Paren),
4379 SeqSep::trailing_allowed(token::Comma),
4381 if p.token == token::DotDotDot {
4384 if p.token != token::CloseDelim(token::Paren) {
4387 "`...` must be last in argument list for variadic function");
4392 "only foreign functions are allowed to be variadic");
4397 match p.parse_arg_general(named_args) {
4398 Ok(arg) => Ok(Some(arg)),
4401 let lo = p.prev_span;
4402 // Skip every token until next possible arg or end.
4403 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4404 // Create a placeholder argument for proper arg count (#34264).
4405 let span = lo.to(p.prev_span);
4406 Ok(Some(dummy_arg(span)))
4413 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4415 if variadic && args.is_empty() {
4417 "variadic function must be declared with at least one named argument");
4420 Ok((args, variadic))
4423 /// Parse the argument list and result type of a function declaration
4424 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4426 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4427 let ret_ty = self.parse_ret_ty()?;
4436 /// Returns the parsed optional self argument and whether a self shortcut was used.
4437 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4438 let expect_ident = |this: &mut Self| match this.token {
4439 // Preserve hygienic context.
4440 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4443 let isolated_self = |this: &mut Self, n| {
4444 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4445 this.look_ahead(n + 1, |t| t != &token::ModSep)
4448 // Parse optional self parameter of a method.
4449 // Only a limited set of initial token sequences is considered self parameters, anything
4450 // else is parsed as a normal function parameter list, so some lookahead is required.
4451 let eself_lo = self.span;
4452 let (eself, eself_ident) = match self.token {
4453 token::BinOp(token::And) => {
4459 if isolated_self(self, 1) {
4461 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4462 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4463 isolated_self(self, 2) {
4466 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4467 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4468 isolated_self(self, 2) {
4470 let lt = self.expect_lifetime();
4471 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4472 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4473 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4474 isolated_self(self, 3) {
4476 let lt = self.expect_lifetime();
4478 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4483 token::BinOp(token::Star) => {
4488 // Emit special error for `self` cases.
4489 if isolated_self(self, 1) {
4491 self.span_err(self.span, "cannot pass `self` by raw pointer");
4492 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4493 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4494 isolated_self(self, 2) {
4497 self.span_err(self.span, "cannot pass `self` by raw pointer");
4498 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4503 token::Ident(..) => {
4504 if isolated_self(self, 0) {
4507 let eself_ident = expect_ident(self);
4508 if self.eat(&token::Colon) {
4509 let ty = self.parse_ty()?;
4510 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4512 (SelfKind::Value(Mutability::Immutable), eself_ident)
4514 } else if self.token.is_keyword(keywords::Mut) &&
4515 isolated_self(self, 1) {
4519 let eself_ident = expect_ident(self);
4520 if self.eat(&token::Colon) {
4521 let ty = self.parse_ty()?;
4522 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4524 (SelfKind::Value(Mutability::Mutable), eself_ident)
4530 _ => return Ok(None),
4533 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
4534 Ok(Some(Arg::from_self(eself, eself_ident)))
4537 /// Parse the parameter list and result type of a function that may have a `self` parameter.
4538 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
4539 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4541 self.expect(&token::OpenDelim(token::Paren))?;
4543 // Parse optional self argument
4544 let self_arg = self.parse_self_arg()?;
4546 // Parse the rest of the function parameter list.
4547 let sep = SeqSep::trailing_allowed(token::Comma);
4548 let fn_inputs = if let Some(self_arg) = self_arg {
4549 if self.check(&token::CloseDelim(token::Paren)) {
4551 } else if self.eat(&token::Comma) {
4552 let mut fn_inputs = vec![self_arg];
4553 fn_inputs.append(&mut self.parse_seq_to_before_end(
4554 &token::CloseDelim(token::Paren), sep, parse_arg_fn)
4558 return self.unexpected();
4561 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4564 // Parse closing paren and return type.
4565 self.expect(&token::CloseDelim(token::Paren))?;
4568 output: self.parse_ret_ty()?,
4573 // parse the |arg, arg| header on a lambda
4574 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4575 let inputs_captures = {
4576 if self.eat(&token::OrOr) {
4579 self.expect(&token::BinOp(token::Or))?;
4580 let args = self.parse_seq_to_before_end(
4581 &token::BinOp(token::Or),
4582 SeqSep::trailing_allowed(token::Comma),
4583 |p| p.parse_fn_block_arg()
4589 let output = self.parse_ret_ty()?;
4592 inputs: inputs_captures,
4598 /// Parse the name and optional generic types of a function header.
4599 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4600 let id = self.parse_ident()?;
4601 let generics = self.parse_generics()?;
4605 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
4606 attrs: Vec<Attribute>) -> P<Item> {
4610 id: ast::DUMMY_NODE_ID,
4617 /// Parse an item-position function declaration.
4618 fn parse_item_fn(&mut self,
4620 constness: Spanned<Constness>,
4622 -> PResult<'a, ItemInfo> {
4623 let (ident, mut generics) = self.parse_fn_header()?;
4624 let decl = self.parse_fn_decl(false)?;
4625 generics.where_clause = self.parse_where_clause()?;
4626 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4627 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4630 /// true if we are looking at `const ID`, false for things like `const fn` etc
4631 pub fn is_const_item(&mut self) -> bool {
4632 self.token.is_keyword(keywords::Const) &&
4633 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4634 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4637 /// parses all the "front matter" for a `fn` declaration, up to
4638 /// and including the `fn` keyword:
4642 /// - `const unsafe fn`
4645 pub fn parse_fn_front_matter(&mut self)
4646 -> PResult<'a, (Spanned<ast::Constness>,
4649 let is_const_fn = self.eat_keyword(keywords::Const);
4650 let const_span = self.prev_span;
4651 let unsafety = self.parse_unsafety()?;
4652 let (constness, unsafety, abi) = if is_const_fn {
4653 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
4655 let abi = if self.eat_keyword(keywords::Extern) {
4656 self.parse_opt_abi()?.unwrap_or(Abi::C)
4660 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
4662 self.expect_keyword(keywords::Fn)?;
4663 Ok((constness, unsafety, abi))
4666 /// Parse an impl item.
4667 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
4668 maybe_whole!(self, NtImplItem, |x| x);
4670 let mut attrs = self.parse_outer_attributes()?;
4672 let vis = self.parse_visibility(false)?;
4673 let defaultness = self.parse_defaultness()?;
4674 let (name, node) = if self.eat_keyword(keywords::Type) {
4675 let name = self.parse_ident()?;
4676 self.expect(&token::Eq)?;
4677 let typ = self.parse_ty()?;
4678 self.expect(&token::Semi)?;
4679 (name, ast::ImplItemKind::Type(typ))
4680 } else if self.is_const_item() {
4681 self.expect_keyword(keywords::Const)?;
4682 let name = self.parse_ident()?;
4683 self.expect(&token::Colon)?;
4684 let typ = self.parse_ty()?;
4685 self.expect(&token::Eq)?;
4686 let expr = self.parse_expr()?;
4687 self.expect(&token::Semi)?;
4688 (name, ast::ImplItemKind::Const(typ, expr))
4690 let (name, inner_attrs, node) = self.parse_impl_method(&vis, at_end)?;
4691 attrs.extend(inner_attrs);
4696 id: ast::DUMMY_NODE_ID,
4697 span: lo.to(self.prev_span),
4700 defaultness: defaultness,
4706 fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
4707 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
4712 fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
4714 Visibility::Inherited => Ok(()),
4716 let is_macro_rules: bool = match self.token {
4717 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
4721 let mut err = self.diagnostic()
4722 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
4723 err.help("did you mean #[macro_export]?");
4726 let mut err = self.diagnostic()
4727 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
4728 err.help("try adjusting the macro to put `pub` inside the invocation");
4735 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
4736 -> DiagnosticBuilder<'a>
4738 // Given this code `path(`, it seems like this is not
4739 // setting the visibility of a macro invocation, but rather
4740 // a mistyped method declaration.
4741 // Create a diagnostic pointing out that `fn` is missing.
4743 // x | pub path(&self) {
4744 // | ^ missing `fn`, `type`, or `const`
4746 // ^^ `sp` below will point to this
4747 let sp = prev_span.between(self.prev_span);
4748 let mut err = self.diagnostic().struct_span_err(
4750 &format!("missing `fn`, `type`, or `const` for {}-item declaration",
4752 err.span_label(sp, &"missing `fn`, `type`, or `const`");
4756 /// Parse a method or a macro invocation in a trait impl.
4757 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
4758 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4759 // code copied from parse_macro_use_or_failure... abstraction!
4760 if self.token.is_path_start() {
4763 let prev_span = self.prev_span;
4766 let pth = self.parse_path(PathStyle::Mod)?;
4767 if pth.segments.len() == 1 {
4768 if !self.eat(&token::Not) {
4769 return Err(self.missing_assoc_item_kind_err("impl", prev_span));
4772 self.expect(&token::Not)?;
4775 self.complain_if_pub_macro(&vis, prev_span);
4777 // eat a matched-delimiter token tree:
4779 let (delim, tts) = self.expect_delimited_token_tree()?;
4780 if delim != token::Brace {
4781 self.expect(&token::Semi)?
4784 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
4785 Ok((keywords::Invalid.ident(), vec![], ast::ImplItemKind::Macro(mac)))
4787 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
4788 let ident = self.parse_ident()?;
4789 let mut generics = self.parse_generics()?;
4790 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
4791 generics.where_clause = self.parse_where_clause()?;
4793 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4794 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4798 constness: constness,
4804 /// Parse trait Foo { ... }
4805 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4806 let ident = self.parse_ident()?;
4807 let mut tps = self.parse_generics()?;
4809 // Parse optional colon and supertrait bounds.
4810 let bounds = if self.eat(&token::Colon) {
4811 self.parse_ty_param_bounds()?
4816 tps.where_clause = self.parse_where_clause()?;
4818 self.expect(&token::OpenDelim(token::Brace))?;
4819 let mut trait_items = vec![];
4820 while !self.eat(&token::CloseDelim(token::Brace)) {
4821 let mut at_end = false;
4822 match self.parse_trait_item(&mut at_end) {
4823 Ok(item) => trait_items.push(item),
4827 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
4832 Ok((ident, ItemKind::Trait(unsafety, tps, bounds, trait_items), None))
4835 /// Parses items implementations variants
4836 /// impl<T> Foo { ... }
4837 /// impl<T> ToString for &'static T { ... }
4838 /// impl Send for .. {}
4839 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<'a, ItemInfo> {
4840 let impl_span = self.span;
4842 // First, parse type parameters if necessary.
4843 let mut generics = self.parse_generics()?;
4845 // Special case: if the next identifier that follows is '(', don't
4846 // allow this to be parsed as a trait.
4847 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4849 let neg_span = self.span;
4850 let polarity = if self.eat(&token::Not) {
4851 ast::ImplPolarity::Negative
4853 ast::ImplPolarity::Positive
4857 let mut ty = self.parse_ty()?;
4859 // Parse traits, if necessary.
4860 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4861 // New-style trait. Reinterpret the type as a trait.
4863 TyKind::Path(None, ref path) => {
4865 path: (*path).clone(),
4870 self.span_err(ty.span, "not a trait");
4876 ast::ImplPolarity::Negative => {
4877 // This is a negated type implementation
4878 // `impl !MyType {}`, which is not allowed.
4879 self.span_err(neg_span, "inherent implementation can't be negated");
4886 if opt_trait.is_some() && self.eat(&token::DotDot) {
4887 if generics.is_parameterized() {
4888 self.span_err(impl_span, "default trait implementations are not \
4889 allowed to have generics");
4892 self.expect(&token::OpenDelim(token::Brace))?;
4893 self.expect(&token::CloseDelim(token::Brace))?;
4894 Ok((keywords::Invalid.ident(),
4895 ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
4897 if opt_trait.is_some() {
4898 ty = self.parse_ty()?;
4900 generics.where_clause = self.parse_where_clause()?;
4902 self.expect(&token::OpenDelim(token::Brace))?;
4903 let attrs = self.parse_inner_attributes()?;
4905 let mut impl_items = vec![];
4906 while !self.eat(&token::CloseDelim(token::Brace)) {
4907 let mut at_end = false;
4908 match self.parse_impl_item(&mut at_end) {
4909 Ok(item) => impl_items.push(item),
4913 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
4919 Ok((keywords::Invalid.ident(),
4920 ItemKind::Impl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4925 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<LifetimeDef>> {
4926 if self.eat_keyword(keywords::For) {
4928 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4930 if !ty_params.is_empty() {
4931 self.span_err(ty_params[0].span,
4932 "only lifetime parameters can be used in this context");
4940 /// Parse struct Foo { ... }
4941 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
4942 let class_name = self.parse_ident()?;
4944 let mut generics = self.parse_generics()?;
4946 // There is a special case worth noting here, as reported in issue #17904.
4947 // If we are parsing a tuple struct it is the case that the where clause
4948 // should follow the field list. Like so:
4950 // struct Foo<T>(T) where T: Copy;
4952 // If we are parsing a normal record-style struct it is the case
4953 // that the where clause comes before the body, and after the generics.
4954 // So if we look ahead and see a brace or a where-clause we begin
4955 // parsing a record style struct.
4957 // Otherwise if we look ahead and see a paren we parse a tuple-style
4960 let vdata = if self.token.is_keyword(keywords::Where) {
4961 generics.where_clause = self.parse_where_clause()?;
4962 if self.eat(&token::Semi) {
4963 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4964 VariantData::Unit(ast::DUMMY_NODE_ID)
4966 // If we see: `struct Foo<T> where T: Copy { ... }`
4967 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
4969 // No `where` so: `struct Foo<T>;`
4970 } else if self.eat(&token::Semi) {
4971 VariantData::Unit(ast::DUMMY_NODE_ID)
4972 // Record-style struct definition
4973 } else if self.token == token::OpenDelim(token::Brace) {
4974 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
4975 // Tuple-style struct definition with optional where-clause.
4976 } else if self.token == token::OpenDelim(token::Paren) {
4977 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
4978 generics.where_clause = self.parse_where_clause()?;
4979 self.expect(&token::Semi)?;
4982 let token_str = self.this_token_to_string();
4983 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
4984 name, found `{}`", token_str)))
4987 Ok((class_name, ItemKind::Struct(vdata, generics), None))
4990 /// Parse union Foo { ... }
4991 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
4992 let class_name = self.parse_ident()?;
4994 let mut generics = self.parse_generics()?;
4996 let vdata = if self.token.is_keyword(keywords::Where) {
4997 generics.where_clause = self.parse_where_clause()?;
4998 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
4999 } else if self.token == token::OpenDelim(token::Brace) {
5000 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5002 let token_str = self.this_token_to_string();
5003 return Err(self.fatal(&format!("expected `where` or `{{` after union \
5004 name, found `{}`", token_str)))
5007 Ok((class_name, ItemKind::Union(vdata, generics), None))
5010 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5011 let mut fields = Vec::new();
5012 if self.eat(&token::OpenDelim(token::Brace)) {
5013 while self.token != token::CloseDelim(token::Brace) {
5014 fields.push(self.parse_struct_decl_field().map_err(|e| {
5015 self.recover_stmt();
5016 self.eat(&token::CloseDelim(token::Brace));
5023 let token_str = self.this_token_to_string();
5024 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5032 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5033 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5034 // Unit like structs are handled in parse_item_struct function
5035 let fields = self.parse_unspanned_seq(
5036 &token::OpenDelim(token::Paren),
5037 &token::CloseDelim(token::Paren),
5038 SeqSep::trailing_allowed(token::Comma),
5040 let attrs = p.parse_outer_attributes()?;
5042 let vis = p.parse_visibility(true)?;
5043 let ty = p.parse_ty()?;
5045 span: lo.to(p.span),
5048 id: ast::DUMMY_NODE_ID,
5057 /// Parse a structure field declaration
5058 pub fn parse_single_struct_field(&mut self,
5061 attrs: Vec<Attribute> )
5062 -> PResult<'a, StructField> {
5063 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5068 token::CloseDelim(token::Brace) => {}
5069 token::DocComment(_) => return Err(self.span_fatal_err(self.span,
5070 Error::UselessDocComment)),
5071 _ => return Err(self.span_fatal_help(self.span,
5072 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5073 "struct fields should be separated by commas")),
5078 /// Parse an element of a struct definition
5079 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5080 let attrs = self.parse_outer_attributes()?;
5082 let vis = self.parse_visibility(false)?;
5083 self.parse_single_struct_field(lo, vis, attrs)
5086 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5087 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5088 /// a function definition, it's not a tuple struct field) and the contents within the parens
5089 /// isn't valid, emit a proper diagnostic.
5090 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5091 maybe_whole!(self, NtVis, |x| x);
5093 if !self.eat_keyword(keywords::Pub) {
5094 return Ok(Visibility::Inherited)
5097 if self.check(&token::OpenDelim(token::Paren)) {
5098 let start_span = self.span;
5099 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5100 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5101 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5102 // by the following tokens.
5103 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5106 self.bump(); // `crate`
5107 let vis = Visibility::Crate(self.prev_span);
5108 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5110 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5113 self.bump(); // `in`
5114 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5115 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5116 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5118 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5119 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5120 t.is_keyword(keywords::SelfValue)) {
5121 // `pub(self)` or `pub(super)`
5123 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5124 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5125 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5127 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5128 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5130 let msg = "incorrect visibility restriction";
5131 let suggestion = r##"some possible visibility restrictions are:
5132 `pub(crate)`: visible only on the current crate
5133 `pub(super)`: visible only in the current module's parent
5134 `pub(in path::to::module)`: visible only on the specified path"##;
5135 let path = self.parse_path(PathStyle::Mod)?;
5136 let path_span = self.prev_span;
5137 let help_msg = format!("to make this visible only to module `{}`, add `in` before \
5140 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5141 let sp = start_span.to(self.prev_span);
5142 let mut err = self.span_fatal_help(sp, &msg, &suggestion);
5143 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5144 err.emit(); // emit diagnostic, but continue with public visibility
5148 Ok(Visibility::Public)
5151 /// Parse defaultness: DEFAULT or nothing
5152 fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5153 if self.eat_contextual_keyword(keywords::Default.ident()) {
5154 Ok(Defaultness::Default)
5156 Ok(Defaultness::Final)
5160 /// Given a termination token, parse all of the items in a module
5161 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5162 let mut items = vec![];
5163 while let Some(item) = self.parse_item()? {
5167 if !self.eat(term) {
5168 let token_str = self.this_token_to_string();
5169 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5172 let hi = if self.span == syntax_pos::DUMMY_SP {
5179 inner: inner_lo.to(hi),
5184 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5185 let id = self.parse_ident()?;
5186 self.expect(&token::Colon)?;
5187 let ty = self.parse_ty()?;
5188 self.expect(&token::Eq)?;
5189 let e = self.parse_expr()?;
5190 self.expect(&token::Semi)?;
5191 let item = match m {
5192 Some(m) => ItemKind::Static(ty, m, e),
5193 None => ItemKind::Const(ty, e),
5195 Ok((id, item, None))
5198 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5199 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5200 let (in_cfg, outer_attrs) = {
5201 let mut strip_unconfigured = ::config::StripUnconfigured {
5203 should_test: false, // irrelevant
5204 features: None, // don't perform gated feature checking
5206 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5207 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5210 let id_span = self.span;
5211 let id = self.parse_ident()?;
5212 if self.check(&token::Semi) {
5215 // This mod is in an external file. Let's go get it!
5216 let ModulePathSuccess { path, directory_ownership, warn } =
5217 self.submod_path(id, &outer_attrs, id_span)?;
5218 let (module, mut attrs) =
5219 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5221 let attr = ast::Attribute {
5222 id: attr::mk_attr_id(),
5223 style: ast::AttrStyle::Outer,
5224 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5225 Ident::from_str("warn_directory_ownership")),
5226 tokens: TokenStream::empty(),
5227 is_sugared_doc: false,
5228 span: syntax_pos::DUMMY_SP,
5230 attr::mark_known(&attr);
5233 Ok((id, module, Some(attrs)))
5235 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5236 Ok((id, ItemKind::Mod(placeholder), None))
5239 let old_directory = self.directory.clone();
5240 self.push_directory(id, &outer_attrs);
5241 self.expect(&token::OpenDelim(token::Brace))?;
5242 let mod_inner_lo = self.span;
5243 let attrs = self.parse_inner_attributes()?;
5244 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5245 self.directory = old_directory;
5246 Ok((id, ItemKind::Mod(module), Some(attrs)))
5250 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5251 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5252 self.directory.path.push(&path.as_str());
5253 self.directory.ownership = DirectoryOwnership::Owned;
5255 self.directory.path.push(&id.name.as_str());
5259 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5260 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5263 /// Returns either a path to a module, or .
5264 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5265 let mod_name = id.to_string();
5266 let default_path_str = format!("{}.rs", mod_name);
5267 let secondary_path_str = format!("{}{}mod.rs", mod_name, path::MAIN_SEPARATOR);
5268 let default_path = dir_path.join(&default_path_str);
5269 let secondary_path = dir_path.join(&secondary_path_str);
5270 let default_exists = codemap.file_exists(&default_path);
5271 let secondary_exists = codemap.file_exists(&secondary_path);
5273 let result = match (default_exists, secondary_exists) {
5274 (true, false) => Ok(ModulePathSuccess {
5276 directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5279 (false, true) => Ok(ModulePathSuccess {
5280 path: secondary_path,
5281 directory_ownership: DirectoryOwnership::Owned,
5284 (false, false) => Err(Error::FileNotFoundForModule {
5285 mod_name: mod_name.clone(),
5286 default_path: default_path_str,
5287 secondary_path: secondary_path_str,
5288 dir_path: format!("{}", dir_path.display()),
5290 (true, true) => Err(Error::DuplicatePaths {
5291 mod_name: mod_name.clone(),
5292 default_path: default_path_str,
5293 secondary_path: secondary_path_str,
5299 path_exists: default_exists || secondary_exists,
5304 fn submod_path(&mut self,
5306 outer_attrs: &[ast::Attribute],
5307 id_sp: Span) -> PResult<'a, ModulePathSuccess> {
5308 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5309 return Ok(ModulePathSuccess {
5310 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5311 Some("mod.rs") => DirectoryOwnership::Owned,
5312 _ => DirectoryOwnership::UnownedViaMod(true),
5319 let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5321 if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5323 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5324 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5325 if paths.path_exists {
5326 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5328 err.span_note(id_sp, &msg);
5331 } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5333 if let Ok(result) = paths.result {
5334 return Ok(ModulePathSuccess { warn: true, ..result });
5337 let mut err = self.diagnostic().struct_span_err(id_sp,
5338 "cannot declare a new module at this location");
5339 let this_module = match self.directory.path.file_name() {
5340 Some(file_name) => file_name.to_str().unwrap().to_owned(),
5341 None => self.root_module_name.as_ref().unwrap().clone(),
5343 err.span_note(id_sp,
5344 &format!("maybe move this module `{0}` to its own directory \
5345 via `{0}{1}mod.rs`",
5347 path::MAIN_SEPARATOR));
5348 if paths.path_exists {
5349 err.span_note(id_sp,
5350 &format!("... or maybe `use` the module `{}` instead \
5351 of possibly redeclaring it",
5358 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5362 /// Read a module from a source file.
5363 fn eval_src_mod(&mut self,
5365 directory_ownership: DirectoryOwnership,
5368 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5369 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5370 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5371 let mut err = String::from("circular modules: ");
5372 let len = included_mod_stack.len();
5373 for p in &included_mod_stack[i.. len] {
5374 err.push_str(&p.to_string_lossy());
5375 err.push_str(" -> ");
5377 err.push_str(&path.to_string_lossy());
5378 return Err(self.span_fatal(id_sp, &err[..]));
5380 included_mod_stack.push(path.clone());
5381 drop(included_mod_stack);
5384 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5385 p0.cfg_mods = self.cfg_mods;
5386 let mod_inner_lo = p0.span;
5387 let mod_attrs = p0.parse_inner_attributes()?;
5388 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5389 self.sess.included_mod_stack.borrow_mut().pop();
5390 Ok((ast::ItemKind::Mod(m0), mod_attrs))
5393 /// Parse a function declaration from a foreign module
5394 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5395 -> PResult<'a, ForeignItem> {
5396 self.expect_keyword(keywords::Fn)?;
5398 let (ident, mut generics) = self.parse_fn_header()?;
5399 let decl = self.parse_fn_decl(true)?;
5400 generics.where_clause = self.parse_where_clause()?;
5402 self.expect(&token::Semi)?;
5403 Ok(ast::ForeignItem {
5406 node: ForeignItemKind::Fn(decl, generics),
5407 id: ast::DUMMY_NODE_ID,
5413 /// Parse a static item from a foreign module
5414 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5415 -> PResult<'a, ForeignItem> {
5416 self.expect_keyword(keywords::Static)?;
5417 let mutbl = self.eat_keyword(keywords::Mut);
5419 let ident = self.parse_ident()?;
5420 self.expect(&token::Colon)?;
5421 let ty = self.parse_ty()?;
5423 self.expect(&token::Semi)?;
5427 node: ForeignItemKind::Static(ty, mutbl),
5428 id: ast::DUMMY_NODE_ID,
5434 /// Parse extern crate links
5438 /// extern crate foo;
5439 /// extern crate bar as foo;
5440 fn parse_item_extern_crate(&mut self,
5442 visibility: Visibility,
5443 attrs: Vec<Attribute>)
5444 -> PResult<'a, P<Item>> {
5446 let crate_name = self.parse_ident()?;
5447 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
5448 (Some(crate_name.name), ident)
5452 self.expect(&token::Semi)?;
5454 let prev_span = self.prev_span;
5455 Ok(self.mk_item(lo.to(prev_span),
5457 ItemKind::ExternCrate(maybe_path),
5462 /// Parse `extern` for foreign ABIs
5465 /// `extern` is expected to have been
5466 /// consumed before calling this method
5472 fn parse_item_foreign_mod(&mut self,
5474 opt_abi: Option<abi::Abi>,
5475 visibility: Visibility,
5476 mut attrs: Vec<Attribute>)
5477 -> PResult<'a, P<Item>> {
5478 self.expect(&token::OpenDelim(token::Brace))?;
5480 let abi = opt_abi.unwrap_or(Abi::C);
5482 attrs.extend(self.parse_inner_attributes()?);
5484 let mut foreign_items = vec![];
5485 while let Some(item) = self.parse_foreign_item()? {
5486 foreign_items.push(item);
5488 self.expect(&token::CloseDelim(token::Brace))?;
5490 let prev_span = self.prev_span;
5491 let m = ast::ForeignMod {
5493 items: foreign_items
5495 let invalid = keywords::Invalid.ident();
5496 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
5499 /// Parse type Foo = Bar;
5500 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5501 let ident = self.parse_ident()?;
5502 let mut tps = self.parse_generics()?;
5503 tps.where_clause = self.parse_where_clause()?;
5504 self.expect(&token::Eq)?;
5505 let ty = self.parse_ty()?;
5506 self.expect(&token::Semi)?;
5507 Ok((ident, ItemKind::Ty(ty, tps), None))
5510 /// Parse the part of an "enum" decl following the '{'
5511 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5512 let mut variants = Vec::new();
5513 let mut all_nullary = true;
5514 let mut any_disr = None;
5515 while self.token != token::CloseDelim(token::Brace) {
5516 let variant_attrs = self.parse_outer_attributes()?;
5517 let vlo = self.span;
5520 let mut disr_expr = None;
5521 let ident = self.parse_ident()?;
5522 if self.check(&token::OpenDelim(token::Brace)) {
5523 // Parse a struct variant.
5524 all_nullary = false;
5525 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
5526 ast::DUMMY_NODE_ID);
5527 } else if self.check(&token::OpenDelim(token::Paren)) {
5528 all_nullary = false;
5529 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
5530 ast::DUMMY_NODE_ID);
5531 } else if self.eat(&token::Eq) {
5532 disr_expr = Some(self.parse_expr()?);
5533 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5534 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5536 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5539 let vr = ast::Variant_ {
5541 attrs: variant_attrs,
5543 disr_expr: disr_expr,
5545 variants.push(respan(vlo.to(self.prev_span), vr));
5547 if !self.eat(&token::Comma) { break; }
5549 self.expect(&token::CloseDelim(token::Brace))?;
5551 Some(disr_span) if !all_nullary =>
5552 self.span_err(disr_span,
5553 "discriminator values can only be used with a c-like enum"),
5557 Ok(ast::EnumDef { variants: variants })
5560 /// Parse an "enum" declaration
5561 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5562 let id = self.parse_ident()?;
5563 let mut generics = self.parse_generics()?;
5564 generics.where_clause = self.parse_where_clause()?;
5565 self.expect(&token::OpenDelim(token::Brace))?;
5567 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
5568 self.recover_stmt();
5569 self.eat(&token::CloseDelim(token::Brace));
5572 Ok((id, ItemKind::Enum(enum_definition, generics), None))
5575 /// Parses a string as an ABI spec on an extern type or module. Consumes
5576 /// the `extern` keyword, if one is found.
5577 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5579 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5581 self.expect_no_suffix(sp, "ABI spec", suf);
5583 match abi::lookup(&s.as_str()) {
5584 Some(abi) => Ok(Some(abi)),
5586 let prev_span = self.prev_span;
5589 &format!("invalid ABI: expected one of [{}], \
5591 abi::all_names().join(", "),
5602 /// Parse one of the items allowed by the flags.
5603 /// NB: this function no longer parses the items inside an
5605 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5606 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5607 maybe_whole!(self, NtItem, |item| {
5608 let mut item = item.unwrap();
5609 let mut attrs = attrs;
5610 mem::swap(&mut item.attrs, &mut attrs);
5611 item.attrs.extend(attrs);
5617 let visibility = self.parse_visibility(false)?;
5619 if self.eat_keyword(keywords::Use) {
5621 let item_ = ItemKind::Use(self.parse_view_path()?);
5622 self.expect(&token::Semi)?;
5624 let prev_span = self.prev_span;
5625 let invalid = keywords::Invalid.ident();
5626 let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
5627 return Ok(Some(item));
5630 if self.eat_keyword(keywords::Extern) {
5631 if self.eat_keyword(keywords::Crate) {
5632 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
5635 let opt_abi = self.parse_opt_abi()?;
5637 if self.eat_keyword(keywords::Fn) {
5638 // EXTERN FUNCTION ITEM
5639 let fn_span = self.prev_span;
5640 let abi = opt_abi.unwrap_or(Abi::C);
5641 let (ident, item_, extra_attrs) =
5642 self.parse_item_fn(Unsafety::Normal,
5643 respan(fn_span, Constness::NotConst),
5645 let prev_span = self.prev_span;
5646 let item = self.mk_item(lo.to(prev_span),
5650 maybe_append(attrs, extra_attrs));
5651 return Ok(Some(item));
5652 } else if self.check(&token::OpenDelim(token::Brace)) {
5653 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
5659 if self.eat_keyword(keywords::Static) {
5661 let m = if self.eat_keyword(keywords::Mut) {
5664 Mutability::Immutable
5666 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
5667 let prev_span = self.prev_span;
5668 let item = self.mk_item(lo.to(prev_span),
5672 maybe_append(attrs, extra_attrs));
5673 return Ok(Some(item));
5675 if self.eat_keyword(keywords::Const) {
5676 let const_span = self.prev_span;
5677 if self.check_keyword(keywords::Fn)
5678 || (self.check_keyword(keywords::Unsafe)
5679 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5680 // CONST FUNCTION ITEM
5681 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5687 let (ident, item_, extra_attrs) =
5688 self.parse_item_fn(unsafety,
5689 respan(const_span, Constness::Const),
5691 let prev_span = self.prev_span;
5692 let item = self.mk_item(lo.to(prev_span),
5696 maybe_append(attrs, extra_attrs));
5697 return Ok(Some(item));
5701 if self.eat_keyword(keywords::Mut) {
5702 let prev_span = self.prev_span;
5703 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
5704 .help("did you mean to declare a static?")
5707 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
5708 let prev_span = self.prev_span;
5709 let item = self.mk_item(lo.to(prev_span),
5713 maybe_append(attrs, extra_attrs));
5714 return Ok(Some(item));
5716 if self.check_keyword(keywords::Unsafe) &&
5717 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5719 // UNSAFE TRAIT ITEM
5720 self.expect_keyword(keywords::Unsafe)?;
5721 self.expect_keyword(keywords::Trait)?;
5722 let (ident, item_, extra_attrs) =
5723 self.parse_item_trait(ast::Unsafety::Unsafe)?;
5724 let prev_span = self.prev_span;
5725 let item = self.mk_item(lo.to(prev_span),
5729 maybe_append(attrs, extra_attrs));
5730 return Ok(Some(item));
5732 if self.check_keyword(keywords::Unsafe) &&
5733 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5736 self.expect_keyword(keywords::Unsafe)?;
5737 self.expect_keyword(keywords::Impl)?;
5738 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe)?;
5739 let prev_span = self.prev_span;
5740 let item = self.mk_item(lo.to(prev_span),
5744 maybe_append(attrs, extra_attrs));
5745 return Ok(Some(item));
5747 if self.check_keyword(keywords::Fn) {
5750 let fn_span = self.prev_span;
5751 let (ident, item_, extra_attrs) =
5752 self.parse_item_fn(Unsafety::Normal,
5753 respan(fn_span, Constness::NotConst),
5755 let prev_span = self.prev_span;
5756 let item = self.mk_item(lo.to(prev_span),
5760 maybe_append(attrs, extra_attrs));
5761 return Ok(Some(item));
5763 if self.check_keyword(keywords::Unsafe)
5764 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5765 // UNSAFE FUNCTION ITEM
5767 let abi = if self.eat_keyword(keywords::Extern) {
5768 self.parse_opt_abi()?.unwrap_or(Abi::C)
5772 self.expect_keyword(keywords::Fn)?;
5773 let fn_span = self.prev_span;
5774 let (ident, item_, extra_attrs) =
5775 self.parse_item_fn(Unsafety::Unsafe,
5776 respan(fn_span, Constness::NotConst),
5778 let prev_span = self.prev_span;
5779 let item = self.mk_item(lo.to(prev_span),
5783 maybe_append(attrs, extra_attrs));
5784 return Ok(Some(item));
5786 if self.eat_keyword(keywords::Mod) {
5788 let (ident, item_, extra_attrs) =
5789 self.parse_item_mod(&attrs[..])?;
5790 let prev_span = self.prev_span;
5791 let item = self.mk_item(lo.to(prev_span),
5795 maybe_append(attrs, extra_attrs));
5796 return Ok(Some(item));
5798 if self.eat_keyword(keywords::Type) {
5800 let (ident, item_, extra_attrs) = self.parse_item_type()?;
5801 let prev_span = self.prev_span;
5802 let item = self.mk_item(lo.to(prev_span),
5806 maybe_append(attrs, extra_attrs));
5807 return Ok(Some(item));
5809 if self.eat_keyword(keywords::Enum) {
5811 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
5812 let prev_span = self.prev_span;
5813 let item = self.mk_item(lo.to(prev_span),
5817 maybe_append(attrs, extra_attrs));
5818 return Ok(Some(item));
5820 if self.eat_keyword(keywords::Trait) {
5822 let (ident, item_, extra_attrs) =
5823 self.parse_item_trait(ast::Unsafety::Normal)?;
5824 let prev_span = self.prev_span;
5825 let item = self.mk_item(lo.to(prev_span),
5829 maybe_append(attrs, extra_attrs));
5830 return Ok(Some(item));
5832 if self.eat_keyword(keywords::Impl) {
5834 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal)?;
5835 let prev_span = self.prev_span;
5836 let item = self.mk_item(lo.to(prev_span),
5840 maybe_append(attrs, extra_attrs));
5841 return Ok(Some(item));
5843 if self.eat_keyword(keywords::Struct) {
5845 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
5846 let prev_span = self.prev_span;
5847 let item = self.mk_item(lo.to(prev_span),
5851 maybe_append(attrs, extra_attrs));
5852 return Ok(Some(item));
5854 if self.is_union_item() {
5857 let (ident, item_, extra_attrs) = self.parse_item_union()?;
5858 let prev_span = self.prev_span;
5859 let item = self.mk_item(lo.to(prev_span),
5863 maybe_append(attrs, extra_attrs));
5864 return Ok(Some(item));
5866 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility)? {
5867 return Ok(Some(macro_def));
5870 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5873 /// Parse a foreign item.
5874 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
5875 let attrs = self.parse_outer_attributes()?;
5877 let visibility = self.parse_visibility(false)?;
5879 if self.check_keyword(keywords::Static) {
5880 // FOREIGN STATIC ITEM
5881 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
5883 if self.check_keyword(keywords::Fn) {
5884 // FOREIGN FUNCTION ITEM
5885 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
5888 // FIXME #5668: this will occur for a macro invocation:
5889 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
5891 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5897 /// This is the fall-through for parsing items.
5898 fn parse_macro_use_or_failure(
5900 attrs: Vec<Attribute> ,
5901 macros_allowed: bool,
5902 attributes_allowed: bool,
5904 visibility: Visibility
5905 ) -> PResult<'a, Option<P<Item>>> {
5906 if macros_allowed && self.token.is_path_start() {
5907 // MACRO INVOCATION ITEM
5909 let prev_span = self.prev_span;
5910 self.complain_if_pub_macro(&visibility, prev_span);
5912 let mac_lo = self.span;
5915 let pth = self.parse_path(PathStyle::Mod)?;
5916 self.expect(&token::Not)?;
5918 // a 'special' identifier (like what `macro_rules!` uses)
5919 // is optional. We should eventually unify invoc syntax
5921 let id = if self.token.is_ident() {
5924 keywords::Invalid.ident() // no special identifier
5926 // eat a matched-delimiter token tree:
5927 let (delim, tts) = self.expect_delimited_token_tree()?;
5928 if delim != token::Brace {
5929 if !self.eat(&token::Semi) {
5930 let prev_span = self.prev_span;
5931 self.span_err(prev_span,
5932 "macros that expand to items must either \
5933 be surrounded with braces or followed by \
5938 let hi = self.prev_span;
5939 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
5940 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
5941 return Ok(Some(item));
5944 // FAILURE TO PARSE ITEM
5946 Visibility::Inherited => {}
5948 let prev_span = self.prev_span;
5949 return Err(self.span_fatal(prev_span, "unmatched visibility `pub`"));
5953 if !attributes_allowed && !attrs.is_empty() {
5954 self.expected_item_err(&attrs);
5959 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
5960 let attrs = self.parse_outer_attributes()?;
5961 self.parse_item_(attrs, true, false)
5964 fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> {
5965 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
5966 &token::CloseDelim(token::Brace),
5967 SeqSep::trailing_allowed(token::Comma), |this| {
5969 let ident = if this.eat_keyword(keywords::SelfValue) {
5970 keywords::SelfValue.ident()
5974 let rename = this.parse_rename()?;
5975 let node = ast::PathListItem_ {
5978 id: ast::DUMMY_NODE_ID
5980 Ok(respan(lo.to(this.prev_span), node))
5985 fn is_import_coupler(&mut self) -> bool {
5986 self.check(&token::ModSep) &&
5987 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
5988 *t == token::BinOp(token::Star))
5991 /// Matches ViewPath:
5992 /// MOD_SEP? non_global_path
5993 /// MOD_SEP? non_global_path as IDENT
5994 /// MOD_SEP? non_global_path MOD_SEP STAR
5995 /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE
5996 /// MOD_SEP? LBRACE item_seq RBRACE
5997 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
5999 if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) ||
6000 self.is_import_coupler() {
6001 // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`.
6002 self.eat(&token::ModSep);
6003 let prefix = ast::Path {
6004 segments: vec![PathSegment::crate_root()],
6005 span: lo.to(self.span),
6007 let view_path_kind = if self.eat(&token::BinOp(token::Star)) {
6008 ViewPathGlob(prefix)
6010 ViewPathList(prefix, self.parse_path_list_items()?)
6012 Ok(P(respan(lo.to(self.span), view_path_kind)))
6014 let prefix = self.parse_path(PathStyle::Mod)?.default_to_global();
6015 if self.is_import_coupler() {
6016 // `foo::bar::{a, b}` or `foo::bar::*`
6018 if self.check(&token::BinOp(token::Star)) {
6020 Ok(P(respan(lo.to(self.span), ViewPathGlob(prefix))))
6022 let items = self.parse_path_list_items()?;
6023 Ok(P(respan(lo.to(self.span), ViewPathList(prefix, items))))
6026 // `foo::bar` or `foo::bar as baz`
6027 let rename = self.parse_rename()?.
6028 unwrap_or(prefix.segments.last().unwrap().identifier);
6029 Ok(P(respan(lo.to(self.prev_span), ViewPathSimple(rename, prefix))))
6034 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6035 if self.eat_keyword(keywords::As) {
6036 self.parse_ident().map(Some)
6042 /// Parses a source module as a crate. This is the main
6043 /// entry point for the parser.
6044 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6047 attrs: self.parse_inner_attributes()?,
6048 module: self.parse_mod_items(&token::Eof, lo)?,
6049 span: lo.to(self.span),
6053 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6054 let ret = match self.token {
6055 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6056 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6063 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6064 match self.parse_optional_str() {
6065 Some((s, style, suf)) => {
6066 let sp = self.prev_span;
6067 self.expect_no_suffix(sp, "string literal", suf);
6070 _ => Err(self.fatal("expected string literal"))