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())
161 /* ident is handled by common.rs */
163 pub struct Parser<'a> {
164 pub sess: &'a ParseSess,
165 /// the current token:
166 pub token: token::Token,
167 /// the span of the current token:
169 /// the span of the previous token:
170 pub meta_var_span: Option<Span>,
172 /// the previous token kind
173 prev_token_kind: PrevTokenKind,
174 pub restrictions: Restrictions,
175 /// The set of seen errors about obsolete syntax. Used to suppress
176 /// extra detail when the same error is seen twice
177 pub obsolete_set: HashSet<ObsoleteSyntax>,
178 /// Used to determine the path to externally loaded source files
179 pub directory: Directory,
180 /// Name of the root module this parser originated from. If `None`, then the
181 /// name is not known. This does not change while the parser is descending
182 /// into modules, and sub-parsers have new values for this name.
183 pub root_module_name: Option<String>,
184 pub expected_tokens: Vec<TokenType>,
185 token_cursor: TokenCursor,
186 pub desugar_doc_comments: bool,
187 /// Whether we should configure out of line modules as we parse.
192 frame: TokenCursorFrame,
193 stack: Vec<TokenCursorFrame>,
196 struct TokenCursorFrame {
197 delim: token::DelimToken,
200 tree_cursor: tokenstream::Cursor,
204 impl TokenCursorFrame {
205 fn new(sp: Span, delimited: &Delimited) -> Self {
207 delim: delimited.delim,
209 open_delim: delimited.delim == token::NoDelim,
210 tree_cursor: delimited.stream().into_trees(),
211 close_delim: delimited.delim == token::NoDelim,
217 fn next(&mut self) -> TokenAndSpan {
219 let tree = if !self.frame.open_delim {
220 self.frame.open_delim = true;
221 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
222 .open_tt(self.frame.span)
223 } else if let Some(tree) = self.frame.tree_cursor.next() {
225 } else if !self.frame.close_delim {
226 self.frame.close_delim = true;
227 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
228 .close_tt(self.frame.span)
229 } else if let Some(frame) = self.stack.pop() {
233 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
237 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
238 TokenTree::Delimited(sp, ref delimited) => {
239 let frame = TokenCursorFrame::new(sp, delimited);
240 self.stack.push(mem::replace(&mut self.frame, frame));
246 fn next_desugared(&mut self) -> TokenAndSpan {
247 let (sp, name) = match self.next() {
248 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
249 tok @ _ => return tok,
252 let stripped = strip_doc_comment_decoration(&name.as_str());
254 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
255 // required to wrap the text.
256 let mut num_of_hashes = 0;
258 for ch in stripped.chars() {
261 '#' if count > 0 => count + 1,
264 num_of_hashes = cmp::max(num_of_hashes, count);
267 let body = TokenTree::Delimited(sp, Delimited {
268 delim: token::Bracket,
269 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"))),
270 TokenTree::Token(sp, token::Eq),
271 TokenTree::Token(sp, token::Literal(
272 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
273 .iter().cloned().collect::<TokenStream>().into(),
276 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
277 delim: token::NoDelim,
278 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
279 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
280 .iter().cloned().collect::<TokenStream>().into()
282 [TokenTree::Token(sp, token::Pound), body]
283 .iter().cloned().collect::<TokenStream>().into()
291 #[derive(PartialEq, Eq, Clone)]
294 Keyword(keywords::Keyword),
303 fn to_string(&self) -> String {
305 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
306 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
307 TokenType::Operator => "an operator".to_string(),
308 TokenType::Lifetime => "lifetime".to_string(),
309 TokenType::Ident => "identifier".to_string(),
310 TokenType::Path => "path".to_string(),
311 TokenType::Type => "type".to_string(),
316 fn is_ident_or_underscore(t: &token::Token) -> bool {
317 t.is_ident() || *t == token::Underscore
320 /// Information about the path to a module.
321 pub struct ModulePath {
323 pub path_exists: bool,
324 pub result: Result<ModulePathSuccess, Error>,
327 pub struct ModulePathSuccess {
329 pub directory_ownership: DirectoryOwnership,
333 pub struct ModulePathError {
335 pub help_msg: String,
339 FileNotFoundForModule {
341 default_path: String,
342 secondary_path: String,
347 default_path: String,
348 secondary_path: String,
351 InclusiveRangeWithNoEnd,
355 pub fn span_err<'a>(self, sp: Span, handler: &'a errors::Handler) -> DiagnosticBuilder<'a> {
357 Error::FileNotFoundForModule { ref mod_name,
361 let mut err = struct_span_err!(handler, sp, E0583,
362 "file not found for module `{}`", mod_name);
363 err.help(&format!("name the file either {} or {} inside the directory {:?}",
369 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
370 let mut err = struct_span_err!(handler, sp, E0584,
371 "file for module `{}` found at both {} and {}",
375 err.help("delete or rename one of them to remove the ambiguity");
378 Error::UselessDocComment => {
379 let mut err = struct_span_err!(handler, sp, E0585,
380 "found a documentation comment that doesn't document anything");
381 err.help("doc comments must come before what they document, maybe a comment was \
382 intended with `//`?");
385 Error::InclusiveRangeWithNoEnd => {
386 let mut err = struct_span_err!(handler, sp, E0586,
387 "inclusive range with no end");
388 err.help("inclusive ranges must be bounded at the end (`...b` or `a...b`)");
397 AttributesParsed(ThinVec<Attribute>),
398 AlreadyParsed(P<Expr>),
401 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
402 fn from(o: Option<ThinVec<Attribute>>) -> Self {
403 if let Some(attrs) = o {
404 LhsExpr::AttributesParsed(attrs)
406 LhsExpr::NotYetParsed
411 impl From<P<Expr>> for LhsExpr {
412 fn from(expr: P<Expr>) -> Self {
413 LhsExpr::AlreadyParsed(expr)
417 /// Create a placeholder argument.
418 fn dummy_arg(span: Span) -> Arg {
419 let spanned = Spanned {
421 node: keywords::Invalid.ident()
424 id: ast::DUMMY_NODE_ID,
425 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), spanned, None),
431 id: ast::DUMMY_NODE_ID
433 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
436 impl<'a> Parser<'a> {
437 pub fn new(sess: &'a ParseSess,
439 directory: Option<Directory>,
440 desugar_doc_comments: bool)
442 let mut parser = Parser {
444 token: token::Underscore,
445 span: syntax_pos::DUMMY_SP,
446 prev_span: syntax_pos::DUMMY_SP,
448 prev_token_kind: PrevTokenKind::Other,
449 restrictions: Restrictions::empty(),
450 obsolete_set: HashSet::new(),
451 directory: Directory { path: PathBuf::new(), ownership: DirectoryOwnership::Owned },
452 root_module_name: None,
453 expected_tokens: Vec::new(),
454 token_cursor: TokenCursor {
455 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
456 delim: token::NoDelim,
461 desugar_doc_comments: desugar_doc_comments,
465 let tok = parser.next_tok();
466 parser.token = tok.tok;
467 parser.span = tok.sp;
468 if let Some(directory) = directory {
469 parser.directory = directory;
470 } else if parser.span != syntax_pos::DUMMY_SP {
471 parser.directory.path = PathBuf::from(sess.codemap().span_to_filename(parser.span));
472 parser.directory.path.pop();
474 parser.process_potential_macro_variable();
478 fn next_tok(&mut self) -> TokenAndSpan {
479 let mut next = match self.desugar_doc_comments {
480 true => self.token_cursor.next_desugared(),
481 false => self.token_cursor.next(),
483 if next.sp == syntax_pos::DUMMY_SP {
484 next.sp = self.prev_span;
489 /// Convert a token to a string using self's reader
490 pub fn token_to_string(token: &token::Token) -> String {
491 pprust::token_to_string(token)
494 /// Convert the current token to a string using self's reader
495 pub fn this_token_to_string(&self) -> String {
496 Parser::token_to_string(&self.token)
499 pub fn this_token_descr(&self) -> String {
500 let s = self.this_token_to_string();
501 if self.token.is_strict_keyword() {
502 format!("keyword `{}`", s)
503 } else if self.token.is_reserved_keyword() {
504 format!("reserved keyword `{}`", s)
510 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
511 let token_str = Parser::token_to_string(t);
512 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
515 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
516 match self.expect_one_of(&[], &[]) {
518 Ok(_) => unreachable!(),
522 /// Expect and consume the token t. Signal an error if
523 /// the next token is not t.
524 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
525 if self.expected_tokens.is_empty() {
526 if self.token == *t {
530 let token_str = Parser::token_to_string(t);
531 let this_token_str = self.this_token_to_string();
532 Err(self.fatal(&format!("expected `{}`, found `{}`",
537 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
541 /// Expect next token to be edible or inedible token. If edible,
542 /// then consume it; if inedible, then return without consuming
543 /// anything. Signal a fatal error if next token is unexpected.
544 pub fn expect_one_of(&mut self,
545 edible: &[token::Token],
546 inedible: &[token::Token]) -> PResult<'a, ()>{
547 fn tokens_to_string(tokens: &[TokenType]) -> String {
548 let mut i = tokens.iter();
549 // This might be a sign we need a connect method on Iterator.
551 .map_or("".to_string(), |t| t.to_string());
552 i.enumerate().fold(b, |mut b, (i, ref a)| {
553 if tokens.len() > 2 && i == tokens.len() - 2 {
555 } else if tokens.len() == 2 && i == tokens.len() - 2 {
560 b.push_str(&a.to_string());
564 if edible.contains(&self.token) {
567 } else if inedible.contains(&self.token) {
568 // leave it in the input
571 let mut expected = edible.iter()
572 .map(|x| TokenType::Token(x.clone()))
573 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
574 .chain(self.expected_tokens.iter().cloned())
575 .collect::<Vec<_>>();
576 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
578 let expect = tokens_to_string(&expected[..]);
579 let actual = self.this_token_to_string();
580 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
581 let short_expect = if expected.len() > 6 {
582 format!("{} possible tokens", expected.len())
586 (format!("expected one of {}, found `{}`", expect, actual),
587 (self.prev_span.next_point(), format!("expected one of {} here", short_expect)))
588 } else if expected.is_empty() {
589 (format!("unexpected token: `{}`", actual),
590 (self.prev_span, "unexpected token after this".to_string()))
592 (format!("expected {}, found `{}`", expect, actual),
593 (self.prev_span.next_point(), format!("expected {} here", expect)))
595 let mut err = self.fatal(&msg_exp);
596 let sp = if self.token == token::Token::Eof {
597 // This is EOF, don't want to point at the following char, but rather the last token
602 if self.span.contains(sp) {
603 err.span_label(self.span, &label_exp);
605 err.span_label(sp, &label_exp);
606 err.span_label(self.span, &"unexpected token");
612 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
613 fn interpolated_or_expr_span(&self,
614 expr: PResult<'a, P<Expr>>)
615 -> PResult<'a, (Span, P<Expr>)> {
617 if self.prev_token_kind == PrevTokenKind::Interpolated {
625 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
626 self.check_strict_keywords();
627 self.check_reserved_keywords();
634 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
635 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
637 let mut err = self.fatal(&format!("expected identifier, found `{}`",
638 self.this_token_to_string()));
639 if self.token == token::Underscore {
640 err.note("`_` is a wildcard pattern, not an identifier");
648 /// Check if the next token is `tok`, and return `true` if so.
650 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
652 pub fn check(&mut self, tok: &token::Token) -> bool {
653 let is_present = self.token == *tok;
654 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
658 /// Consume token 'tok' if it exists. Returns true if the given
659 /// token was present, false otherwise.
660 pub fn eat(&mut self, tok: &token::Token) -> bool {
661 let is_present = self.check(tok);
662 if is_present { self.bump() }
666 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
667 self.expected_tokens.push(TokenType::Keyword(kw));
668 self.token.is_keyword(kw)
671 /// If the next token is the given keyword, eat it and return
672 /// true. Otherwise, return false.
673 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
674 if self.check_keyword(kw) {
682 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
683 if self.token.is_keyword(kw) {
691 pub fn check_contextual_keyword(&mut self, ident: Ident) -> bool {
692 self.expected_tokens.push(TokenType::Token(token::Ident(ident)));
693 if let token::Ident(ref cur_ident) = self.token {
694 cur_ident.name == ident.name
700 pub fn eat_contextual_keyword(&mut self, ident: Ident) -> bool {
701 if self.check_contextual_keyword(ident) {
709 /// If the given word is not a keyword, signal an error.
710 /// If the next token is not the given word, signal an error.
711 /// Otherwise, eat it.
712 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
713 if !self.eat_keyword(kw) {
720 /// Signal an error if the given string is a strict keyword
721 pub fn check_strict_keywords(&mut self) {
722 if self.token.is_strict_keyword() {
723 let token_str = self.this_token_to_string();
724 let span = self.span;
726 &format!("expected identifier, found keyword `{}`",
731 /// Signal an error if the current token is a reserved keyword
732 pub fn check_reserved_keywords(&mut self) {
733 if self.token.is_reserved_keyword() {
734 let token_str = self.this_token_to_string();
735 self.fatal(&format!("`{}` is a reserved keyword", token_str)).emit()
739 fn check_ident(&mut self) -> bool {
740 if self.token.is_ident() {
743 self.expected_tokens.push(TokenType::Ident);
748 fn check_path(&mut self) -> bool {
749 if self.token.is_path_start() {
752 self.expected_tokens.push(TokenType::Path);
757 fn check_type(&mut self) -> bool {
758 if self.token.can_begin_type() {
761 self.expected_tokens.push(TokenType::Type);
766 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
767 /// `&` and continue. If an `&` is not seen, signal an error.
768 fn expect_and(&mut self) -> PResult<'a, ()> {
769 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
771 token::BinOp(token::And) => {
776 let span = self.span;
777 let lo = span.lo + BytePos(1);
778 Ok(self.bump_with(token::BinOp(token::And), Span { lo: lo, ..span }))
780 _ => self.unexpected()
784 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
786 None => {/* everything ok */}
788 let text = suf.as_str();
790 self.span_bug(sp, "found empty literal suffix in Some")
792 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
797 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
798 /// `<` and continue. If a `<` is not seen, return false.
800 /// This is meant to be used when parsing generics on a path to get the
802 fn eat_lt(&mut self) -> bool {
803 self.expected_tokens.push(TokenType::Token(token::Lt));
809 token::BinOp(token::Shl) => {
810 let span = self.span;
811 let lo = span.lo + BytePos(1);
812 self.bump_with(token::Lt, Span { lo: lo, ..span });
819 fn expect_lt(&mut self) -> PResult<'a, ()> {
827 /// Expect and consume a GT. if a >> is seen, replace it
828 /// with a single > and continue. If a GT is not seen,
830 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
831 self.expected_tokens.push(TokenType::Token(token::Gt));
837 token::BinOp(token::Shr) => {
838 let span = self.span;
839 let lo = span.lo + BytePos(1);
840 Ok(self.bump_with(token::Gt, Span { lo: lo, ..span }))
842 token::BinOpEq(token::Shr) => {
843 let span = self.span;
844 let lo = span.lo + BytePos(1);
845 Ok(self.bump_with(token::Ge, Span { lo: lo, ..span }))
848 let span = self.span;
849 let lo = span.lo + BytePos(1);
850 Ok(self.bump_with(token::Eq, Span { lo: lo, ..span }))
852 _ => self.unexpected()
856 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
857 sep: Option<token::Token>,
859 -> PResult<'a, (Vec<T>, bool)>
860 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
862 let mut v = Vec::new();
863 // This loop works by alternating back and forth between parsing types
864 // and commas. For example, given a string `A, B,>`, the parser would
865 // first parse `A`, then a comma, then `B`, then a comma. After that it
866 // would encounter a `>` and stop. This lets the parser handle trailing
867 // commas in generic parameters, because it can stop either after
868 // parsing a type or after parsing a comma.
870 if self.check(&token::Gt)
871 || self.token == token::BinOp(token::Shr)
872 || self.token == token::Ge
873 || self.token == token::BinOpEq(token::Shr) {
879 Some(result) => v.push(result),
880 None => return Ok((v, true))
883 if let Some(t) = sep.as_ref() {
889 return Ok((v, false));
892 /// Parse a sequence bracketed by '<' and '>', stopping
894 pub fn parse_seq_to_before_gt<T, F>(&mut self,
895 sep: Option<token::Token>,
897 -> PResult<'a, Vec<T>> where
898 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
900 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
901 |p| Ok(Some(f(p)?)))?;
906 pub fn parse_seq_to_gt<T, F>(&mut self,
907 sep: Option<token::Token>,
909 -> PResult<'a, Vec<T>> where
910 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
912 let v = self.parse_seq_to_before_gt(sep, f)?;
917 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
918 sep: Option<token::Token>,
920 -> PResult<'a, (Vec<T>, bool)> where
921 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
923 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
927 return Ok((v, returned));
930 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
931 /// passes through any errors encountered. Used for error recovery.
932 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
933 let handler = self.diagnostic();
935 self.parse_seq_to_before_tokens(kets,
937 |p| Ok(p.parse_token_tree()),
938 |mut e| handler.cancel(&mut e));
941 /// Parse a sequence, including the closing delimiter. The function
942 /// f must consume tokens until reaching the next separator or
944 pub fn parse_seq_to_end<T, F>(&mut self,
948 -> PResult<'a, Vec<T>> where
949 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
951 let val = self.parse_seq_to_before_end(ket, sep, f);
956 /// Parse a sequence, not including the closing delimiter. The function
957 /// f must consume tokens until reaching the next separator or
959 pub fn parse_seq_to_before_end<T, F>(&mut self,
964 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
966 self.parse_seq_to_before_tokens(&[ket], sep, f, |mut e| e.emit())
969 // `fe` is an error handler.
970 fn parse_seq_to_before_tokens<T, F, Fe>(&mut self,
971 kets: &[&token::Token],
976 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
977 Fe: FnMut(DiagnosticBuilder)
979 let mut first: bool = true;
981 while !kets.contains(&&self.token) {
983 token::CloseDelim(..) | token::Eof => break,
991 if let Err(e) = self.expect(t) {
999 if sep.trailing_sep_allowed && kets.iter().any(|k| self.check(k)) {
1015 /// Parse a sequence, including the closing delimiter. The function
1016 /// f must consume tokens until reaching the next separator or
1017 /// closing bracket.
1018 pub fn parse_unspanned_seq<T, F>(&mut self,
1023 -> PResult<'a, Vec<T>> where
1024 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1027 let result = self.parse_seq_to_before_end(ket, sep, f);
1028 if self.token == *ket {
1034 // NB: Do not use this function unless you actually plan to place the
1035 // spanned list in the AST.
1036 pub fn parse_seq<T, F>(&mut self,
1041 -> PResult<'a, Spanned<Vec<T>>> where
1042 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1046 let result = self.parse_seq_to_before_end(ket, sep, f);
1049 Ok(respan(lo.to(hi), result))
1052 /// Advance the parser by one token
1053 pub fn bump(&mut self) {
1054 if self.prev_token_kind == PrevTokenKind::Eof {
1055 // Bumping after EOF is a bad sign, usually an infinite loop.
1056 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1059 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1061 // Record last token kind for possible error recovery.
1062 self.prev_token_kind = match self.token {
1063 token::DocComment(..) => PrevTokenKind::DocComment,
1064 token::Comma => PrevTokenKind::Comma,
1065 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1066 token::Interpolated(..) => PrevTokenKind::Interpolated,
1067 token::Eof => PrevTokenKind::Eof,
1068 _ => PrevTokenKind::Other,
1071 let next = self.next_tok();
1072 self.span = next.sp;
1073 self.token = next.tok;
1074 self.expected_tokens.clear();
1075 // check after each token
1076 self.process_potential_macro_variable();
1079 /// Advance the parser using provided token as a next one. Use this when
1080 /// consuming a part of a token. For example a single `<` from `<<`.
1081 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1082 self.prev_span = Span { hi: span.lo, ..self.span };
1083 // It would be incorrect to record the kind of the current token, but
1084 // fortunately for tokens currently using `bump_with`, the
1085 // prev_token_kind will be of no use anyway.
1086 self.prev_token_kind = PrevTokenKind::Other;
1089 self.expected_tokens.clear();
1092 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1093 F: FnOnce(&token::Token) -> R,
1096 return f(&self.token)
1099 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1100 Some(tree) => match tree {
1101 TokenTree::Token(_, tok) => tok,
1102 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1104 None => token::CloseDelim(self.token_cursor.frame.delim),
1107 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1108 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1110 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1111 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1113 pub fn span_fatal_err(&self, sp: Span, err: Error) -> DiagnosticBuilder<'a> {
1114 err.span_err(sp, self.diagnostic())
1116 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1117 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1121 pub fn bug(&self, m: &str) -> ! {
1122 self.sess.span_diagnostic.span_bug(self.span, m)
1124 pub fn warn(&self, m: &str) {
1125 self.sess.span_diagnostic.span_warn(self.span, m)
1127 pub fn span_warn(&self, sp: Span, m: &str) {
1128 self.sess.span_diagnostic.span_warn(sp, m)
1130 pub fn span_err(&self, sp: Span, m: &str) {
1131 self.sess.span_diagnostic.span_err(sp, m)
1133 pub fn span_err_help(&self, sp: Span, m: &str, h: &str) {
1134 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1138 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1139 self.sess.span_diagnostic.span_bug(sp, m)
1141 pub fn abort_if_errors(&self) {
1142 self.sess.span_diagnostic.abort_if_errors();
1145 fn cancel(&self, err: &mut DiagnosticBuilder) {
1146 self.sess.span_diagnostic.cancel(err)
1149 pub fn diagnostic(&self) -> &'a errors::Handler {
1150 &self.sess.span_diagnostic
1153 /// Is the current token one of the keywords that signals a bare function
1155 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1156 self.check_keyword(keywords::Fn) ||
1157 self.check_keyword(keywords::Unsafe) ||
1158 self.check_keyword(keywords::Extern)
1161 fn get_label(&mut self) -> ast::Ident {
1163 token::Lifetime(ref ident) => *ident,
1164 _ => self.bug("not a lifetime"),
1168 /// parse a TyKind::BareFn type:
1169 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<LifetimeDef>)
1170 -> PResult<'a, TyKind> {
1173 [unsafe] [extern "ABI"] fn (S) -> T
1183 let unsafety = self.parse_unsafety()?;
1184 let abi = if self.eat_keyword(keywords::Extern) {
1185 self.parse_opt_abi()?.unwrap_or(Abi::C)
1190 self.expect_keyword(keywords::Fn)?;
1191 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1192 let ret_ty = self.parse_ret_ty()?;
1193 let decl = P(FnDecl {
1198 Ok(TyKind::BareFn(P(BareFnTy {
1201 lifetimes: lifetime_defs,
1206 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1207 if self.eat_keyword(keywords::Unsafe) {
1208 return Ok(Unsafety::Unsafe);
1210 return Ok(Unsafety::Normal);
1214 /// Parse the items in a trait declaration
1215 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1216 maybe_whole!(self, NtTraitItem, |x| x);
1217 let mut attrs = self.parse_outer_attributes()?;
1220 let (name, node) = if self.eat_keyword(keywords::Type) {
1221 let TyParam {ident, bounds, default, ..} = self.parse_ty_param(vec![])?;
1222 self.expect(&token::Semi)?;
1223 (ident, TraitItemKind::Type(bounds, default))
1224 } else if self.is_const_item() {
1225 self.expect_keyword(keywords::Const)?;
1226 let ident = self.parse_ident()?;
1227 self.expect(&token::Colon)?;
1228 let ty = self.parse_ty()?;
1229 let default = if self.check(&token::Eq) {
1231 let expr = self.parse_expr()?;
1232 self.expect(&token::Semi)?;
1235 self.expect(&token::Semi)?;
1238 (ident, TraitItemKind::Const(ty, default))
1239 } else if self.token.is_path_start() {
1240 // trait item macro.
1241 // code copied from parse_macro_use_or_failure... abstraction!
1242 let prev_span = self.prev_span;
1244 let pth = self.parse_path(PathStyle::Mod)?;
1246 if pth.segments.len() == 1 {
1247 if !self.eat(&token::Not) {
1248 return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1251 self.expect(&token::Not)?;
1254 // eat a matched-delimiter token tree:
1255 let (delim, tts) = self.expect_delimited_token_tree()?;
1256 if delim != token::Brace {
1257 self.expect(&token::Semi)?
1260 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1261 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac))
1263 let (constness, unsafety, abi) = match self.parse_fn_front_matter() {
1265 Err(e) => return Err(e),
1268 let ident = self.parse_ident()?;
1269 let mut generics = self.parse_generics()?;
1271 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1272 // This is somewhat dubious; We don't want to allow
1273 // argument names to be left off if there is a
1275 p.parse_arg_general(false)
1278 generics.where_clause = self.parse_where_clause()?;
1279 let sig = ast::MethodSig {
1281 constness: constness,
1287 let body = match self.token {
1291 debug!("parse_trait_methods(): parsing required method");
1294 token::OpenDelim(token::Brace) => {
1295 debug!("parse_trait_methods(): parsing provided method");
1297 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1298 attrs.extend(inner_attrs.iter().cloned());
1302 let token_str = self.this_token_to_string();
1303 return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1306 (ident, ast::TraitItemKind::Method(sig, body))
1310 id: ast::DUMMY_NODE_ID,
1314 span: lo.to(self.prev_span),
1318 /// Parse optional return type [ -> TY ] in function decl
1319 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1320 if self.eat(&token::RArrow) {
1321 Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
1323 Ok(FunctionRetTy::Default(Span { hi: self.span.lo, ..self.span }))
1328 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1329 self.parse_ty_common(true)
1332 /// Parse a type in restricted contexts where `+` is not permitted.
1333 /// Example 1: `&'a TYPE`
1334 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1335 /// Example 2: `value1 as TYPE + value2`
1336 /// `+` is prohibited to avoid interactions with expression grammar.
1337 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1338 self.parse_ty_common(false)
1341 fn parse_ty_common(&mut self, allow_plus: bool) -> PResult<'a, P<Ty>> {
1342 maybe_whole!(self, NtTy, |x| x);
1345 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1346 // `(TYPE)` is a parenthesized type.
1347 // `(TYPE,)` is a tuple with a single field of type TYPE.
1348 let mut ts = vec![];
1349 let mut last_comma = false;
1350 while self.token != token::CloseDelim(token::Paren) {
1351 ts.push(self.parse_ty()?);
1352 if self.eat(&token::Comma) {
1359 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1360 self.expect(&token::CloseDelim(token::Paren))?;
1362 if ts.len() == 1 && !last_comma {
1363 let ty = ts.into_iter().nth(0).unwrap().unwrap();
1364 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1366 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1367 TyKind::Path(None, ref path) if maybe_bounds => {
1368 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1370 TyKind::TraitObject(ref bounds)
1371 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1372 let path = match bounds[0] {
1373 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1374 _ => self.bug("unexpected lifetime bound"),
1376 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1379 _ => TyKind::Paren(P(ty))
1384 } else if self.eat(&token::Not) {
1387 } else if self.eat(&token::BinOp(token::Star)) {
1389 TyKind::Ptr(self.parse_ptr()?)
1390 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1392 let t = self.parse_ty()?;
1393 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1394 let t = match self.maybe_parse_fixed_length_of_vec()? {
1395 None => TyKind::Slice(t),
1396 Some(suffix) => TyKind::Array(t, suffix),
1398 self.expect(&token::CloseDelim(token::Bracket))?;
1400 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1403 self.parse_borrowed_pointee()?
1404 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1406 // In order to not be ambiguous, the type must be surrounded by parens.
1407 self.expect(&token::OpenDelim(token::Paren))?;
1408 let e = self.parse_expr()?;
1409 self.expect(&token::CloseDelim(token::Paren))?;
1411 } else if self.eat(&token::Underscore) {
1412 // A type to be inferred `_`
1414 } else if self.eat_lt() {
1416 let (qself, path) = self.parse_qualified_path(PathStyle::Type)?;
1417 TyKind::Path(Some(qself), path)
1418 } else if self.token.is_path_start() {
1420 let path = self.parse_path(PathStyle::Type)?;
1421 if self.eat(&token::Not) {
1422 // Macro invocation in type position
1423 let (_, tts) = self.expect_delimited_token_tree()?;
1424 TyKind::Mac(respan(lo.to(self.span), Mac_ { path: path, tts: tts }))
1426 // Just a type path or bound list (trait object type) starting with a trait.
1428 // `Trait1 + Trait2 + 'a`
1429 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1430 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1432 TyKind::Path(None, path)
1435 } else if self.token_is_bare_fn_keyword() {
1436 // Function pointer type
1437 self.parse_ty_bare_fn(Vec::new())?
1438 } else if self.check_keyword(keywords::For) {
1439 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1440 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1441 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1443 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1444 if self.token_is_bare_fn_keyword() {
1445 self.parse_ty_bare_fn(lifetime_defs)?
1447 let path = self.parse_path(PathStyle::Type)?;
1448 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1449 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1451 } else if self.eat_keyword(keywords::Impl) {
1452 // FIXME: figure out priority of `+` in `impl Trait1 + Trait2` (#34511).
1453 TyKind::ImplTrait(self.parse_ty_param_bounds()?)
1454 } else if self.check(&token::Question) {
1455 // Bound list (trait object type)
1456 // Bound lists starting with `'lt` are not currently supported (#40043)
1457 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?)
1459 let msg = format!("expected type, found {}", self.this_token_descr());
1460 return Err(self.fatal(&msg));
1463 let span = lo.to(self.prev_span);
1464 let ty = Ty { node: node, span: span, id: ast::DUMMY_NODE_ID };
1466 // Try to recover from use of `+` with incorrect priority.
1467 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1472 fn parse_remaining_bounds(&mut self, lifetime_defs: Vec<LifetimeDef>, path: ast::Path,
1473 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1474 let poly_trait_ref = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
1475 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1478 bounds.append(&mut self.parse_ty_param_bounds()?);
1480 Ok(TyKind::TraitObject(bounds))
1483 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1484 // Do not add `+` to expected tokens.
1485 if !allow_plus || self.token != token::BinOp(token::Plus) {
1490 let bounds = self.parse_ty_param_bounds()?;
1491 let sum_span = ty.span.to(self.prev_span);
1493 let mut err = struct_span_err!(self.sess.span_diagnostic, ty.span, E0178,
1494 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(&ty));
1495 err.span_label(ty.span, &format!("expected a path"));
1498 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1499 let sum_with_parens = pprust::to_string(|s| {
1500 use print::pp::word;
1501 use print::pprust::PrintState;
1503 word(&mut s.s, "&")?;
1504 s.print_opt_lifetime(lifetime)?;
1505 s.print_mutability(mut_ty.mutbl)?;
1507 s.print_type(&mut_ty.ty)?;
1508 s.print_bounds(" +", &bounds)?;
1511 err.span_suggestion(sum_span, "try adding parentheses:", sum_with_parens);
1513 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1514 help!(&mut err, "perhaps you forgot parentheses?");
1522 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1523 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1524 let mutbl = self.parse_mutability();
1525 let ty = self.parse_ty_no_plus()?;
1526 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1529 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1530 let mutbl = if self.eat_keyword(keywords::Mut) {
1532 } else if self.eat_keyword(keywords::Const) {
1533 Mutability::Immutable
1535 let span = self.prev_span;
1537 "expected mut or const in raw pointer type (use \
1538 `*mut T` or `*const T` as appropriate)");
1539 Mutability::Immutable
1541 let t = self.parse_ty_no_plus()?;
1542 Ok(MutTy { ty: t, mutbl: mutbl })
1545 pub fn is_named_argument(&mut self) -> bool {
1546 let offset = match self.token {
1547 token::BinOp(token::And) => 1,
1549 _ if self.token.is_keyword(keywords::Mut) => 1,
1553 debug!("parser is_named_argument offset:{}", offset);
1556 is_ident_or_underscore(&self.token)
1557 && self.look_ahead(1, |t| *t == token::Colon)
1559 self.look_ahead(offset, |t| is_ident_or_underscore(t))
1560 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1564 /// This version of parse arg doesn't necessarily require
1565 /// identifier names.
1566 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1567 maybe_whole!(self, NtArg, |x| x);
1569 let pat = if require_name || self.is_named_argument() {
1570 debug!("parse_arg_general parse_pat (require_name:{})",
1572 let pat = self.parse_pat()?;
1574 self.expect(&token::Colon)?;
1577 debug!("parse_arg_general ident_to_pat");
1578 let sp = self.prev_span;
1579 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1581 id: ast::DUMMY_NODE_ID,
1582 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1588 let t = self.parse_ty()?;
1593 id: ast::DUMMY_NODE_ID,
1597 /// Parse a single function argument
1598 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1599 self.parse_arg_general(true)
1602 /// Parse an argument in a lambda header e.g. |arg, arg|
1603 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1604 let pat = self.parse_pat()?;
1605 let t = if self.eat(&token::Colon) {
1609 id: ast::DUMMY_NODE_ID,
1610 node: TyKind::Infer,
1617 id: ast::DUMMY_NODE_ID
1621 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1622 if self.eat(&token::Semi) {
1623 Ok(Some(self.parse_expr()?))
1629 /// Matches token_lit = LIT_INTEGER | ...
1630 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1631 let out = match self.token {
1632 token::Interpolated(ref nt) => match **nt {
1633 token::NtExpr(ref v) => match v.node {
1634 ExprKind::Lit(ref lit) => { lit.node.clone() }
1635 _ => { return self.unexpected_last(&self.token); }
1637 _ => { return self.unexpected_last(&self.token); }
1639 token::Literal(lit, suf) => {
1640 let diag = Some((self.span, &self.sess.span_diagnostic));
1641 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1645 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1650 _ => { return self.unexpected_last(&self.token); }
1657 /// Matches lit = true | false | token_lit
1658 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1660 let lit = if self.eat_keyword(keywords::True) {
1662 } else if self.eat_keyword(keywords::False) {
1663 LitKind::Bool(false)
1665 let lit = self.parse_lit_token()?;
1668 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1671 /// matches '-' lit | lit
1672 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1673 let minus_lo = self.span;
1674 let minus_present = self.eat(&token::BinOp(token::Minus));
1676 let literal = P(self.parse_lit()?);
1677 let hi = self.prev_span;
1678 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1681 let minus_hi = self.prev_span;
1682 let unary = self.mk_unary(UnOp::Neg, expr);
1683 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1689 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1691 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1695 _ => self.parse_ident(),
1699 /// Parses qualified path.
1701 /// Assumes that the leading `<` has been parsed already.
1703 /// Qualifed paths are a part of the universal function call
1706 /// `qualified_path = <type [as trait_ref]>::path`
1708 /// See `parse_path` for `mode` meaning.
1713 /// `<T as U>::F::a::<S>`
1714 pub fn parse_qualified_path(&mut self, mode: PathStyle)
1715 -> PResult<'a, (QSelf, ast::Path)> {
1716 let span = self.prev_span;
1717 let self_type = self.parse_ty()?;
1718 let mut path = if self.eat_keyword(keywords::As) {
1719 self.parse_path(PathStyle::Type)?
1729 position: path.segments.len()
1732 self.expect(&token::Gt)?;
1733 self.expect(&token::ModSep)?;
1735 let segments = match mode {
1736 PathStyle::Type => {
1737 self.parse_path_segments_without_colons()?
1739 PathStyle::Expr => {
1740 self.parse_path_segments_with_colons()?
1743 self.parse_path_segments_without_types()?
1746 path.segments.extend(segments);
1748 path.span.hi = self.prev_span.hi;
1753 /// Parses a path and optional type parameter bounds, depending on the
1754 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1755 /// bounds are permitted and whether `::` must precede type parameter
1757 pub fn parse_path(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1758 maybe_whole!(self, NtPath, |x| x);
1760 let lo = self.meta_var_span.unwrap_or(self.span);
1761 let is_global = self.eat(&token::ModSep);
1763 // Parse any number of segments and bound sets. A segment is an
1764 // identifier followed by an optional lifetime and a set of types.
1765 // A bound set is a set of type parameter bounds.
1766 let mut segments = match mode {
1767 PathStyle::Type => {
1768 self.parse_path_segments_without_colons()?
1770 PathStyle::Expr => {
1771 self.parse_path_segments_with_colons()?
1774 self.parse_path_segments_without_types()?
1779 segments.insert(0, PathSegment::crate_root());
1782 // Assemble the result.
1784 span: lo.to(self.prev_span),
1789 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1790 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1791 pub fn parse_path_allowing_meta(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1792 let meta_ident = match self.token {
1793 token::Interpolated(ref nt) => match **nt {
1794 token::NtMeta(ref meta) => match meta.node {
1795 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
1802 if let Some(ident) = meta_ident {
1804 return Ok(ast::Path::from_ident(self.prev_span, ident));
1806 self.parse_path(mode)
1810 /// - `a::b<T,U>::c<V,W>`
1811 /// - `a::b<T,U>::c(V) -> W`
1812 /// - `a::b<T,U>::c(V)`
1813 pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1814 let mut segments = Vec::new();
1816 // First, parse an identifier.
1817 let ident_span = self.span;
1818 let identifier = self.parse_path_segment_ident()?;
1820 if self.check(&token::ModSep) && self.look_ahead(1, |t| *t == token::Lt) {
1822 let prev_span = self.prev_span;
1824 let mut err = self.diagnostic().struct_span_err(prev_span,
1825 "unexpected token: `::`");
1827 "use `<...>` instead of `::<...>` if you meant to specify type arguments");
1831 // Parse types, optionally.
1832 let parameters = if self.eat_lt() {
1833 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1835 ast::AngleBracketedParameterData {
1836 lifetimes: lifetimes,
1840 } else if self.eat(&token::OpenDelim(token::Paren)) {
1841 let lo = self.prev_span;
1843 let inputs = self.parse_seq_to_end(
1844 &token::CloseDelim(token::Paren),
1845 SeqSep::trailing_allowed(token::Comma),
1848 let output_ty = if self.eat(&token::RArrow) {
1849 Some(self.parse_ty_no_plus()?)
1854 let hi = self.prev_span;
1856 Some(P(ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData {
1865 // Assemble and push the result.
1866 segments.push(PathSegment {
1867 identifier: identifier,
1869 parameters: parameters
1872 // Continue only if we see a `::`
1873 if !self.eat(&token::ModSep) {
1874 return Ok(segments);
1880 /// - `a::b::<T,U>::c`
1881 pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1882 let mut segments = Vec::new();
1884 // First, parse an identifier.
1885 let ident_span = self.span;
1886 let identifier = self.parse_path_segment_ident()?;
1888 // If we do not see a `::`, stop.
1889 if !self.eat(&token::ModSep) {
1890 segments.push(PathSegment::from_ident(identifier, ident_span));
1891 return Ok(segments);
1894 // Check for a type segment.
1896 // Consumed `a::b::<`, go look for types
1897 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1899 segments.push(PathSegment {
1900 identifier: identifier,
1902 parameters: ast::AngleBracketedParameterData {
1903 lifetimes: lifetimes,
1909 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1910 if !self.eat(&token::ModSep) {
1911 return Ok(segments);
1914 // Consumed `a::`, go look for `b`
1915 segments.push(PathSegment::from_ident(identifier, ident_span));
1922 pub fn parse_path_segments_without_types(&mut self)
1923 -> PResult<'a, Vec<PathSegment>> {
1924 let mut segments = Vec::new();
1926 // First, parse an identifier.
1927 let ident_span = self.span;
1928 let identifier = self.parse_path_segment_ident()?;
1930 // Assemble and push the result.
1931 segments.push(PathSegment::from_ident(identifier, ident_span));
1933 // If we do not see a `::` or see `::{`/`::*`, stop.
1934 if !self.check(&token::ModSep) || self.is_import_coupler() {
1935 return Ok(segments);
1942 fn check_lifetime(&mut self) -> bool {
1943 self.expected_tokens.push(TokenType::Lifetime);
1944 self.token.is_lifetime()
1947 /// Parse single lifetime 'a or panic.
1948 fn expect_lifetime(&mut self) -> Lifetime {
1950 token::Lifetime(ident) => {
1951 let ident_span = self.span;
1953 Lifetime { name: ident.name, span: ident_span, id: ast::DUMMY_NODE_ID }
1955 _ => self.span_bug(self.span, "not a lifetime")
1959 /// Parse mutability (`mut` or nothing).
1960 fn parse_mutability(&mut self) -> Mutability {
1961 if self.eat_keyword(keywords::Mut) {
1964 Mutability::Immutable
1968 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1969 if let token::Literal(token::Integer(name), None) = self.token {
1971 Ok(Ident::with_empty_ctxt(name))
1977 /// Parse ident (COLON expr)?
1978 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1979 let attrs = self.parse_outer_attributes()?;
1983 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1984 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1985 let fieldname = self.parse_field_name()?;
1987 hi = self.prev_span;
1988 (fieldname, self.parse_expr()?, false)
1990 let fieldname = self.parse_ident()?;
1991 hi = self.prev_span;
1993 // Mimic `x: x` for the `x` field shorthand.
1994 let path = ast::Path::from_ident(lo.to(hi), fieldname);
1995 (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
1998 ident: respan(lo.to(hi), fieldname),
1999 span: lo.to(expr.span),
2001 is_shorthand: is_shorthand,
2002 attrs: attrs.into(),
2006 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2008 id: ast::DUMMY_NODE_ID,
2011 attrs: attrs.into(),
2015 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2016 ExprKind::Unary(unop, expr)
2019 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2020 ExprKind::Binary(binop, lhs, rhs)
2023 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2024 ExprKind::Call(f, args)
2027 fn mk_method_call(&mut self,
2028 ident: ast::SpannedIdent,
2032 ExprKind::MethodCall(ident, tps, args)
2035 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2036 ExprKind::Index(expr, idx)
2039 pub fn mk_range(&mut self,
2040 start: Option<P<Expr>>,
2041 end: Option<P<Expr>>,
2042 limits: RangeLimits)
2043 -> PResult<'a, ast::ExprKind> {
2044 if end.is_none() && limits == RangeLimits::Closed {
2045 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2047 Ok(ExprKind::Range(start, end, limits))
2051 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::ExprKind {
2052 ExprKind::Field(expr, ident)
2055 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2056 ExprKind::TupField(expr, idx)
2059 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2060 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2061 ExprKind::AssignOp(binop, lhs, rhs)
2064 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2066 id: ast::DUMMY_NODE_ID,
2067 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2073 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2074 let span = &self.span;
2075 let lv_lit = P(codemap::Spanned {
2076 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2081 id: ast::DUMMY_NODE_ID,
2082 node: ExprKind::Lit(lv_lit),
2088 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2090 token::OpenDelim(delim) => match self.parse_token_tree() {
2091 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2092 _ => unreachable!(),
2094 _ => Err(self.fatal("expected open delimiter")),
2098 /// At the bottom (top?) of the precedence hierarchy,
2099 /// parse things like parenthesized exprs,
2100 /// macros, return, etc.
2102 /// NB: This does not parse outer attributes,
2103 /// and is private because it only works
2104 /// correctly if called from parse_dot_or_call_expr().
2105 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2106 maybe_whole_expr!(self);
2108 // Outer attributes are already parsed and will be
2109 // added to the return value after the fact.
2111 // Therefore, prevent sub-parser from parsing
2112 // attributes by giving them a empty "already parsed" list.
2113 let mut attrs = ThinVec::new();
2116 let mut hi = self.span;
2120 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2122 token::OpenDelim(token::Paren) => {
2125 attrs.extend(self.parse_inner_attributes()?);
2127 // (e) is parenthesized e
2128 // (e,) is a tuple with only one field, e
2129 let mut es = vec![];
2130 let mut trailing_comma = false;
2131 while self.token != token::CloseDelim(token::Paren) {
2132 es.push(self.parse_expr()?);
2133 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2134 if self.check(&token::Comma) {
2135 trailing_comma = true;
2139 trailing_comma = false;
2145 hi = self.prev_span;
2146 let span = lo.to(hi);
2147 return if es.len() == 1 && !trailing_comma {
2148 Ok(self.mk_expr(span, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2150 Ok(self.mk_expr(span, ExprKind::Tup(es), attrs))
2153 token::OpenDelim(token::Brace) => {
2154 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2156 token::BinOp(token::Or) | token::OrOr => {
2158 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2160 token::OpenDelim(token::Bracket) => {
2163 attrs.extend(self.parse_inner_attributes()?);
2165 if self.check(&token::CloseDelim(token::Bracket)) {
2168 ex = ExprKind::Array(Vec::new());
2171 let first_expr = self.parse_expr()?;
2172 if self.check(&token::Semi) {
2173 // Repeating array syntax: [ 0; 512 ]
2175 let count = self.parse_expr()?;
2176 self.expect(&token::CloseDelim(token::Bracket))?;
2177 ex = ExprKind::Repeat(first_expr, count);
2178 } else if self.check(&token::Comma) {
2179 // Vector with two or more elements.
2181 let remaining_exprs = self.parse_seq_to_end(
2182 &token::CloseDelim(token::Bracket),
2183 SeqSep::trailing_allowed(token::Comma),
2184 |p| Ok(p.parse_expr()?)
2186 let mut exprs = vec![first_expr];
2187 exprs.extend(remaining_exprs);
2188 ex = ExprKind::Array(exprs);
2190 // Vector with one element.
2191 self.expect(&token::CloseDelim(token::Bracket))?;
2192 ex = ExprKind::Array(vec![first_expr]);
2195 hi = self.prev_span;
2200 self.parse_qualified_path(PathStyle::Expr)?;
2202 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2204 if self.eat_keyword(keywords::Move) {
2205 let lo = self.prev_span;
2206 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2208 if self.eat_keyword(keywords::If) {
2209 return self.parse_if_expr(attrs);
2211 if self.eat_keyword(keywords::For) {
2212 let lo = self.prev_span;
2213 return self.parse_for_expr(None, lo, attrs);
2215 if self.eat_keyword(keywords::While) {
2216 let lo = self.prev_span;
2217 return self.parse_while_expr(None, lo, attrs);
2219 if self.token.is_lifetime() {
2220 let label = Spanned { node: self.get_label(),
2224 self.expect(&token::Colon)?;
2225 if self.eat_keyword(keywords::While) {
2226 return self.parse_while_expr(Some(label), lo, attrs)
2228 if self.eat_keyword(keywords::For) {
2229 return self.parse_for_expr(Some(label), lo, attrs)
2231 if self.eat_keyword(keywords::Loop) {
2232 return self.parse_loop_expr(Some(label), lo, attrs)
2234 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2236 if self.eat_keyword(keywords::Loop) {
2237 let lo = self.prev_span;
2238 return self.parse_loop_expr(None, lo, attrs);
2240 if self.eat_keyword(keywords::Continue) {
2241 let ex = if self.token.is_lifetime() {
2242 let ex = ExprKind::Continue(Some(Spanned{
2243 node: self.get_label(),
2249 ExprKind::Continue(None)
2251 let hi = self.prev_span;
2252 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2254 if self.eat_keyword(keywords::Match) {
2255 return self.parse_match_expr(attrs);
2257 if self.eat_keyword(keywords::Unsafe) {
2258 return self.parse_block_expr(
2260 BlockCheckMode::Unsafe(ast::UserProvided),
2263 if self.is_catch_expr() {
2264 assert!(self.eat_keyword(keywords::Do));
2265 assert!(self.eat_keyword(keywords::Catch));
2266 let lo = self.prev_span;
2267 return self.parse_catch_expr(lo, attrs);
2269 if self.eat_keyword(keywords::Return) {
2270 if self.token.can_begin_expr() {
2271 let e = self.parse_expr()?;
2273 ex = ExprKind::Ret(Some(e));
2275 ex = ExprKind::Ret(None);
2277 } else if self.eat_keyword(keywords::Break) {
2278 let lt = if self.token.is_lifetime() {
2279 let spanned_lt = Spanned {
2280 node: self.get_label(),
2288 let e = if self.token.can_begin_expr()
2289 && !(self.token == token::OpenDelim(token::Brace)
2290 && self.restrictions.contains(
2291 Restrictions::RESTRICTION_NO_STRUCT_LITERAL)) {
2292 Some(self.parse_expr()?)
2296 ex = ExprKind::Break(lt, e);
2297 hi = self.prev_span;
2298 } else if self.token.is_keyword(keywords::Let) {
2299 // Catch this syntax error here, instead of in `check_strict_keywords`, so
2300 // that we can explicitly mention that let is not to be used as an expression
2301 let mut db = self.fatal("expected expression, found statement (`let`)");
2302 db.note("variable declaration using `let` is a statement");
2304 } else if self.token.is_path_start() {
2305 let pth = self.parse_path(PathStyle::Expr)?;
2307 // `!`, as an operator, is prefix, so we know this isn't that
2308 if self.eat(&token::Not) {
2309 // MACRO INVOCATION expression
2310 let (_, tts) = self.expect_delimited_token_tree()?;
2311 let hi = self.prev_span;
2312 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2314 if self.check(&token::OpenDelim(token::Brace)) {
2315 // This is a struct literal, unless we're prohibited
2316 // from parsing struct literals here.
2317 let prohibited = self.restrictions.contains(
2318 Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2321 return self.parse_struct_expr(lo, pth, attrs);
2326 ex = ExprKind::Path(None, pth);
2328 match self.parse_lit() {
2331 ex = ExprKind::Lit(P(lit));
2334 self.cancel(&mut err);
2335 let msg = format!("expected expression, found {}",
2336 self.this_token_descr());
2337 return Err(self.fatal(&msg));
2344 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2347 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2348 -> PResult<'a, P<Expr>> {
2350 let mut fields = Vec::new();
2351 let mut base = None;
2353 attrs.extend(self.parse_inner_attributes()?);
2355 while self.token != token::CloseDelim(token::Brace) {
2356 if self.eat(&token::DotDot) {
2357 match self.parse_expr() {
2363 self.recover_stmt();
2369 match self.parse_field() {
2370 Ok(f) => fields.push(f),
2373 self.recover_stmt();
2378 match self.expect_one_of(&[token::Comma],
2379 &[token::CloseDelim(token::Brace)]) {
2383 self.recover_stmt();
2389 let span = lo.to(self.span);
2390 self.expect(&token::CloseDelim(token::Brace))?;
2391 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2394 fn parse_or_use_outer_attributes(&mut self,
2395 already_parsed_attrs: Option<ThinVec<Attribute>>)
2396 -> PResult<'a, ThinVec<Attribute>> {
2397 if let Some(attrs) = already_parsed_attrs {
2400 self.parse_outer_attributes().map(|a| a.into())
2404 /// Parse a block or unsafe block
2405 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2406 outer_attrs: ThinVec<Attribute>)
2407 -> PResult<'a, P<Expr>> {
2409 self.expect(&token::OpenDelim(token::Brace))?;
2411 let mut attrs = outer_attrs;
2412 attrs.extend(self.parse_inner_attributes()?);
2414 let blk = self.parse_block_tail(lo, blk_mode)?;
2415 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2418 /// parse a.b or a(13) or a[4] or just a
2419 pub fn parse_dot_or_call_expr(&mut self,
2420 already_parsed_attrs: Option<ThinVec<Attribute>>)
2421 -> PResult<'a, P<Expr>> {
2422 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2424 let b = self.parse_bottom_expr();
2425 let (span, b) = self.interpolated_or_expr_span(b)?;
2426 self.parse_dot_or_call_expr_with(b, span, attrs)
2429 pub fn parse_dot_or_call_expr_with(&mut self,
2432 mut attrs: ThinVec<Attribute>)
2433 -> PResult<'a, P<Expr>> {
2434 // Stitch the list of outer attributes onto the return value.
2435 // A little bit ugly, but the best way given the current code
2437 self.parse_dot_or_call_expr_with_(e0, lo)
2439 expr.map(|mut expr| {
2440 attrs.extend::<Vec<_>>(expr.attrs.into());
2443 ExprKind::If(..) | ExprKind::IfLet(..) => {
2444 if !expr.attrs.is_empty() {
2445 // Just point to the first attribute in there...
2446 let span = expr.attrs[0].span;
2449 "attributes are not yet allowed on `if` \
2460 // Assuming we have just parsed `.foo` (i.e., a dot and an ident), continue
2461 // parsing into an expression.
2462 fn parse_dot_suffix(&mut self, ident: Ident, ident_span: Span, self_value: P<Expr>, lo: Span)
2463 -> PResult<'a, P<Expr>> {
2464 let (_, tys, bindings) = if self.eat(&token::ModSep) {
2466 let args = self.parse_generic_args()?;
2470 (Vec::new(), Vec::new(), Vec::new())
2473 if !bindings.is_empty() {
2474 let prev_span = self.prev_span;
2475 self.span_err(prev_span, "type bindings are only permitted on trait paths");
2478 Ok(match self.token {
2479 // expr.f() method call.
2480 token::OpenDelim(token::Paren) => {
2481 let mut es = self.parse_unspanned_seq(
2482 &token::OpenDelim(token::Paren),
2483 &token::CloseDelim(token::Paren),
2484 SeqSep::trailing_allowed(token::Comma),
2485 |p| Ok(p.parse_expr()?)
2487 let hi = self.prev_span;
2489 es.insert(0, self_value);
2490 let id = respan(ident_span.to(ident_span), ident);
2491 let nd = self.mk_method_call(id, tys, es);
2492 self.mk_expr(lo.to(hi), nd, ThinVec::new())
2496 if !tys.is_empty() {
2497 let prev_span = self.prev_span;
2498 self.span_err(prev_span,
2499 "field expressions may not \
2500 have type parameters");
2503 let id = respan(ident_span.to(ident_span), ident);
2504 let field = self.mk_field(self_value, id);
2505 self.mk_expr(lo.to(ident_span), field, ThinVec::new())
2510 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2515 while self.eat(&token::Question) {
2516 let hi = self.prev_span;
2517 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2521 if self.eat(&token::Dot) {
2523 token::Ident(i) => {
2524 let ident_span = self.span;
2526 e = self.parse_dot_suffix(i, ident_span, e, lo)?;
2528 token::Literal(token::Integer(n), suf) => {
2531 // A tuple index may not have a suffix
2532 self.expect_no_suffix(sp, "tuple index", suf);
2534 let dot_span = self.prev_span;
2538 let index = n.as_str().parse::<usize>().ok();
2541 let id = respan(dot_span.to(hi), n);
2542 let field = self.mk_tup_field(e, id);
2543 e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2546 let prev_span = self.prev_span;
2547 self.span_err(prev_span, "invalid tuple or tuple struct index");
2551 token::Literal(token::Float(n), _suf) => {
2553 let fstr = n.as_str();
2554 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2555 &format!("unexpected token: `{}`", n));
2556 err.span_label(self.prev_span, &"unexpected token");
2557 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2558 let float = match fstr.parse::<f64>().ok() {
2562 let sugg = pprust::to_string(|s| {
2563 use print::pprust::PrintState;
2564 use print::pp::word;
2567 word(&mut s.s, ".")?;
2568 s.print_usize(float.trunc() as usize)?;
2570 word(&mut s.s, ".")?;
2571 word(&mut s.s, fstr.splitn(2, ".").last().unwrap())
2573 err.span_suggestion(
2574 lo.to(self.prev_span),
2575 "try parenthesizing the first index",
2582 // FIXME Could factor this out into non_fatal_unexpected or something.
2583 let actual = self.this_token_to_string();
2584 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2586 let dot_span = self.prev_span;
2587 e = self.parse_dot_suffix(keywords::Invalid.ident(), dot_span, e, lo)?;
2592 if self.expr_is_complete(&e) { break; }
2595 token::OpenDelim(token::Paren) => {
2596 let es = self.parse_unspanned_seq(
2597 &token::OpenDelim(token::Paren),
2598 &token::CloseDelim(token::Paren),
2599 SeqSep::trailing_allowed(token::Comma),
2600 |p| Ok(p.parse_expr()?)
2602 hi = self.prev_span;
2604 let nd = self.mk_call(e, es);
2605 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2609 // Could be either an index expression or a slicing expression.
2610 token::OpenDelim(token::Bracket) => {
2612 let ix = self.parse_expr()?;
2614 self.expect(&token::CloseDelim(token::Bracket))?;
2615 let index = self.mk_index(e, ix);
2616 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2624 pub fn process_potential_macro_variable(&mut self) {
2625 let ident = match self.token {
2626 token::SubstNt(name) => {
2627 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2630 token::Interpolated(ref nt) => {
2631 self.meta_var_span = Some(self.span);
2633 token::NtIdent(ident) => ident,
2639 self.token = token::Ident(ident.node);
2640 self.span = ident.span;
2643 /// parse a single token tree from the input.
2644 pub fn parse_token_tree(&mut self) -> TokenTree {
2646 token::OpenDelim(..) => {
2647 let frame = mem::replace(&mut self.token_cursor.frame,
2648 self.token_cursor.stack.pop().unwrap());
2649 self.span = frame.span;
2651 TokenTree::Delimited(frame.span, Delimited {
2653 tts: frame.tree_cursor.original_stream().into(),
2656 token::CloseDelim(_) | token::Eof => unreachable!(),
2658 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2660 TokenTree::Token(span, token)
2665 // parse a stream of tokens into a list of TokenTree's,
2667 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2668 let mut tts = Vec::new();
2669 while self.token != token::Eof {
2670 tts.push(self.parse_token_tree());
2675 pub fn parse_tokens(&mut self) -> TokenStream {
2676 let mut result = Vec::new();
2679 token::Eof | token::CloseDelim(..) => break,
2680 _ => result.push(self.parse_token_tree().into()),
2683 TokenStream::concat(result)
2686 /// Parse a prefix-unary-operator expr
2687 pub fn parse_prefix_expr(&mut self,
2688 already_parsed_attrs: Option<ThinVec<Attribute>>)
2689 -> PResult<'a, P<Expr>> {
2690 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2692 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2693 let (hi, ex) = match self.token {
2696 let e = self.parse_prefix_expr(None);
2697 let (span, e) = self.interpolated_or_expr_span(e)?;
2698 (span, self.mk_unary(UnOp::Not, e))
2700 token::BinOp(token::Minus) => {
2702 let e = self.parse_prefix_expr(None);
2703 let (span, e) = self.interpolated_or_expr_span(e)?;
2704 (span, self.mk_unary(UnOp::Neg, e))
2706 token::BinOp(token::Star) => {
2708 let e = self.parse_prefix_expr(None);
2709 let (span, e) = self.interpolated_or_expr_span(e)?;
2710 (span, self.mk_unary(UnOp::Deref, e))
2712 token::BinOp(token::And) | token::AndAnd => {
2714 let m = self.parse_mutability();
2715 let e = self.parse_prefix_expr(None);
2716 let (span, e) = self.interpolated_or_expr_span(e)?;
2717 (span, ExprKind::AddrOf(m, e))
2719 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2721 let place = self.parse_expr_res(
2722 Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
2725 let blk = self.parse_block()?;
2726 let span = blk.span;
2727 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2728 (span, ExprKind::InPlace(place, blk_expr))
2730 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2732 let e = self.parse_prefix_expr(None);
2733 let (span, e) = self.interpolated_or_expr_span(e)?;
2734 (span, ExprKind::Box(e))
2736 _ => return self.parse_dot_or_call_expr(Some(attrs))
2738 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2741 /// Parse an associative expression
2743 /// This parses an expression accounting for associativity and precedence of the operators in
2745 pub fn parse_assoc_expr(&mut self,
2746 already_parsed_attrs: Option<ThinVec<Attribute>>)
2747 -> PResult<'a, P<Expr>> {
2748 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2751 /// Parse an associative expression with operators of at least `min_prec` precedence
2752 pub fn parse_assoc_expr_with(&mut self,
2755 -> PResult<'a, P<Expr>> {
2756 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2759 let attrs = match lhs {
2760 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2763 if self.token == token::DotDot || self.token == token::DotDotDot {
2764 return self.parse_prefix_range_expr(attrs);
2766 self.parse_prefix_expr(attrs)?
2770 if self.expr_is_complete(&lhs) {
2771 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2774 self.expected_tokens.push(TokenType::Operator);
2775 while let Some(op) = AssocOp::from_token(&self.token) {
2777 let lhs_span = if self.prev_token_kind == PrevTokenKind::Interpolated {
2783 let cur_op_span = self.span;
2784 let restrictions = if op.is_assign_like() {
2785 self.restrictions & Restrictions::RESTRICTION_NO_STRUCT_LITERAL
2789 if op.precedence() < min_prec {
2793 if op.is_comparison() {
2794 self.check_no_chained_comparison(&lhs, &op);
2797 if op == AssocOp::As {
2798 let rhs = self.parse_ty_no_plus()?;
2799 lhs = self.mk_expr(lhs_span.to(rhs.span), ExprKind::Cast(lhs, rhs), ThinVec::new());
2801 } else if op == AssocOp::Colon {
2802 let rhs = self.parse_ty_no_plus()?;
2803 lhs = self.mk_expr(lhs_span.to(rhs.span), ExprKind::Type(lhs, rhs), ThinVec::new());
2805 } else if op == AssocOp::DotDot || op == AssocOp::DotDotDot {
2806 // If we didn’t have to handle `x..`/`x...`, it would be pretty easy to
2807 // generalise it to the Fixity::None code.
2809 // We have 2 alternatives here: `x..y`/`x...y` and `x..`/`x...` The other
2810 // two variants are handled with `parse_prefix_range_expr` call above.
2811 let rhs = if self.is_at_start_of_range_notation_rhs() {
2812 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2813 LhsExpr::NotYetParsed)?)
2817 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2822 let limits = if op == AssocOp::DotDot {
2823 RangeLimits::HalfOpen
2828 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2829 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2833 let rhs = match op.fixity() {
2834 Fixity::Right => self.with_res(
2835 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2837 this.parse_assoc_expr_with(op.precedence(),
2838 LhsExpr::NotYetParsed)
2840 Fixity::Left => self.with_res(
2841 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2843 this.parse_assoc_expr_with(op.precedence() + 1,
2844 LhsExpr::NotYetParsed)
2846 // We currently have no non-associative operators that are not handled above by
2847 // the special cases. The code is here only for future convenience.
2848 Fixity::None => self.with_res(
2849 restrictions - Restrictions::RESTRICTION_STMT_EXPR,
2851 this.parse_assoc_expr_with(op.precedence() + 1,
2852 LhsExpr::NotYetParsed)
2856 let span = lhs_span.to(rhs.span);
2858 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2859 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2860 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2861 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2862 AssocOp::Greater | AssocOp::GreaterEqual => {
2863 let ast_op = op.to_ast_binop().unwrap();
2864 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2865 self.mk_expr(span, binary, ThinVec::new())
2868 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2870 self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
2871 AssocOp::AssignOp(k) => {
2873 token::Plus => BinOpKind::Add,
2874 token::Minus => BinOpKind::Sub,
2875 token::Star => BinOpKind::Mul,
2876 token::Slash => BinOpKind::Div,
2877 token::Percent => BinOpKind::Rem,
2878 token::Caret => BinOpKind::BitXor,
2879 token::And => BinOpKind::BitAnd,
2880 token::Or => BinOpKind::BitOr,
2881 token::Shl => BinOpKind::Shl,
2882 token::Shr => BinOpKind::Shr,
2884 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2885 self.mk_expr(span, aopexpr, ThinVec::new())
2887 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotDot => {
2888 self.bug("As, Colon, DotDot or DotDotDot branch reached")
2892 if op.fixity() == Fixity::None { break }
2897 /// Produce an error if comparison operators are chained (RFC #558).
2898 /// We only need to check lhs, not rhs, because all comparison ops
2899 /// have same precedence and are left-associative
2900 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2901 debug_assert!(outer_op.is_comparison());
2903 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2904 // respan to include both operators
2905 let op_span = op.span.to(self.span);
2906 let mut err = self.diagnostic().struct_span_err(op_span,
2907 "chained comparison operators require parentheses");
2908 if op.node == BinOpKind::Lt &&
2909 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
2910 *outer_op == AssocOp::Greater // even in a case like the following:
2911 { // Foo<Bar<Baz<Qux, ()>>>
2913 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2921 /// Parse prefix-forms of range notation: `..expr`, `..`, `...expr`
2922 fn parse_prefix_range_expr(&mut self,
2923 already_parsed_attrs: Option<ThinVec<Attribute>>)
2924 -> PResult<'a, P<Expr>> {
2925 debug_assert!(self.token == token::DotDot || self.token == token::DotDotDot);
2926 let tok = self.token.clone();
2927 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2929 let mut hi = self.span;
2931 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2932 // RHS must be parsed with more associativity than the dots.
2933 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
2934 Some(self.parse_assoc_expr_with(next_prec,
2935 LhsExpr::NotYetParsed)
2943 let limits = if tok == token::DotDot {
2944 RangeLimits::HalfOpen
2949 let r = try!(self.mk_range(None,
2952 Ok(self.mk_expr(lo.to(hi), r, attrs))
2955 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2956 if self.token.can_begin_expr() {
2957 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2958 if self.token == token::OpenDelim(token::Brace) {
2959 return !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL);
2967 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2968 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
2969 if self.check_keyword(keywords::Let) {
2970 return self.parse_if_let_expr(attrs);
2972 let lo = self.prev_span;
2973 let cond = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
2974 let thn = self.parse_block()?;
2975 let mut els: Option<P<Expr>> = None;
2976 let mut hi = thn.span;
2977 if self.eat_keyword(keywords::Else) {
2978 let elexpr = self.parse_else_expr()?;
2982 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
2985 /// Parse an 'if let' expression ('if' token already eaten)
2986 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
2987 -> PResult<'a, P<Expr>> {
2988 let lo = self.prev_span;
2989 self.expect_keyword(keywords::Let)?;
2990 let pat = self.parse_pat()?;
2991 self.expect(&token::Eq)?;
2992 let expr = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
2993 let thn = self.parse_block()?;
2994 let (hi, els) = if self.eat_keyword(keywords::Else) {
2995 let expr = self.parse_else_expr()?;
2996 (expr.span, Some(expr))
3000 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
3003 // `move |args| expr`
3004 pub fn parse_lambda_expr(&mut self,
3006 capture_clause: CaptureBy,
3007 attrs: ThinVec<Attribute>)
3008 -> PResult<'a, P<Expr>>
3010 let decl = self.parse_fn_block_decl()?;
3011 let decl_hi = self.prev_span;
3012 let body = match decl.output {
3013 FunctionRetTy::Default(_) => self.parse_expr()?,
3015 // If an explicit return type is given, require a
3016 // block to appear (RFC 968).
3017 let body_lo = self.span;
3018 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3024 ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3028 // `else` token already eaten
3029 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3030 if self.eat_keyword(keywords::If) {
3031 return self.parse_if_expr(ThinVec::new());
3033 let blk = self.parse_block()?;
3034 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3038 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3039 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3041 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3042 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3044 let pat = self.parse_pat()?;
3045 self.expect_keyword(keywords::In)?;
3046 let expr = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
3047 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3048 attrs.extend(iattrs);
3050 let hi = self.prev_span;
3051 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3054 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3055 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3057 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3058 if self.token.is_keyword(keywords::Let) {
3059 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3061 let cond = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
3062 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3063 attrs.extend(iattrs);
3064 let span = span_lo.to(body.span);
3065 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3068 /// Parse a 'while let' expression ('while' token already eaten)
3069 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3071 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3072 self.expect_keyword(keywords::Let)?;
3073 let pat = self.parse_pat()?;
3074 self.expect(&token::Eq)?;
3075 let expr = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL, None)?;
3076 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3077 attrs.extend(iattrs);
3078 let span = span_lo.to(body.span);
3079 return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3082 // parse `loop {...}`, `loop` token already eaten
3083 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3085 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3086 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3087 attrs.extend(iattrs);
3088 let span = span_lo.to(body.span);
3089 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3092 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3093 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3094 -> PResult<'a, P<Expr>>
3096 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3097 attrs.extend(iattrs);
3098 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3101 // `match` token already eaten
3102 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3103 let match_span = self.prev_span;
3104 let lo = self.prev_span;
3105 let discriminant = self.parse_expr_res(Restrictions::RESTRICTION_NO_STRUCT_LITERAL,
3107 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3108 if self.token == token::Token::Semi {
3109 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3113 attrs.extend(self.parse_inner_attributes()?);
3115 let mut arms: Vec<Arm> = Vec::new();
3116 while self.token != token::CloseDelim(token::Brace) {
3117 match self.parse_arm() {
3118 Ok(arm) => arms.push(arm),
3120 // Recover by skipping to the end of the block.
3122 self.recover_stmt();
3123 let span = lo.to(self.span);
3124 if self.token == token::CloseDelim(token::Brace) {
3127 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3133 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3136 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3137 maybe_whole!(self, NtArm, |x| x);
3139 let attrs = self.parse_outer_attributes()?;
3140 let pats = self.parse_pats()?;
3141 let mut guard = None;
3142 if self.eat_keyword(keywords::If) {
3143 guard = Some(self.parse_expr()?);
3145 self.expect(&token::FatArrow)?;
3146 let expr = self.parse_expr_res(Restrictions::RESTRICTION_STMT_EXPR, None)?;
3149 !classify::expr_is_simple_block(&expr)
3150 && self.token != token::CloseDelim(token::Brace);
3153 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3155 self.eat(&token::Comma);
3166 /// Parse an expression
3167 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3168 self.parse_expr_res(Restrictions::empty(), None)
3171 /// Evaluate the closure with restrictions in place.
3173 /// After the closure is evaluated, restrictions are reset.
3174 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3175 where F: FnOnce(&mut Self) -> T
3177 let old = self.restrictions;
3178 self.restrictions = r;
3180 self.restrictions = old;
3185 /// Parse an expression, subject to the given restrictions
3186 pub fn parse_expr_res(&mut self, r: Restrictions,
3187 already_parsed_attrs: Option<ThinVec<Attribute>>)
3188 -> PResult<'a, P<Expr>> {
3189 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3192 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3193 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3194 if self.check(&token::Eq) {
3196 Ok(Some(self.parse_expr()?))
3202 /// Parse patterns, separated by '|' s
3203 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3204 let mut pats = Vec::new();
3206 pats.push(self.parse_pat()?);
3207 if self.check(&token::BinOp(token::Or)) { self.bump();}
3208 else { return Ok(pats); }
3212 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3213 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3214 let mut fields = vec![];
3215 let mut ddpos = None;
3217 while !self.check(&token::CloseDelim(token::Paren)) {
3218 if ddpos.is_none() && self.eat(&token::DotDot) {
3219 ddpos = Some(fields.len());
3220 if self.eat(&token::Comma) {
3221 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3222 fields.push(self.parse_pat()?);
3224 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3225 // Emit a friendly error, ignore `..` and continue parsing
3226 self.span_err(self.prev_span, "`..` can only be used once per \
3227 tuple or tuple struct pattern");
3229 fields.push(self.parse_pat()?);
3232 if !self.check(&token::CloseDelim(token::Paren)) ||
3233 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3234 self.expect(&token::Comma)?;
3241 fn parse_pat_vec_elements(
3243 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3244 let mut before = Vec::new();
3245 let mut slice = None;
3246 let mut after = Vec::new();
3247 let mut first = true;
3248 let mut before_slice = true;
3250 while self.token != token::CloseDelim(token::Bracket) {
3254 self.expect(&token::Comma)?;
3256 if self.token == token::CloseDelim(token::Bracket)
3257 && (before_slice || !after.is_empty()) {
3263 if self.eat(&token::DotDot) {
3265 if self.check(&token::Comma) ||
3266 self.check(&token::CloseDelim(token::Bracket)) {
3267 slice = Some(P(ast::Pat {
3268 id: ast::DUMMY_NODE_ID,
3269 node: PatKind::Wild,
3272 before_slice = false;
3278 let subpat = self.parse_pat()?;
3279 if before_slice && self.eat(&token::DotDot) {
3280 slice = Some(subpat);
3281 before_slice = false;
3282 } else if before_slice {
3283 before.push(subpat);
3289 Ok((before, slice, after))
3292 /// Parse the fields of a struct-like pattern
3293 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3294 let mut fields = Vec::new();
3295 let mut etc = false;
3296 let mut first = true;
3297 while self.token != token::CloseDelim(token::Brace) {
3301 self.expect(&token::Comma)?;
3302 // accept trailing commas
3303 if self.check(&token::CloseDelim(token::Brace)) { break }
3306 let attrs = self.parse_outer_attributes()?;
3310 if self.check(&token::DotDot) {
3312 if self.token != token::CloseDelim(token::Brace) {
3313 let token_str = self.this_token_to_string();
3314 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3321 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3322 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3323 // Parsing a pattern of the form "fieldname: pat"
3324 let fieldname = self.parse_field_name()?;
3326 let pat = self.parse_pat()?;
3328 (pat, fieldname, false)
3330 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3331 let is_box = self.eat_keyword(keywords::Box);
3332 let boxed_span = self.span;
3333 let is_ref = self.eat_keyword(keywords::Ref);
3334 let is_mut = self.eat_keyword(keywords::Mut);
3335 let fieldname = self.parse_ident()?;
3336 hi = self.prev_span;
3338 let bind_type = match (is_ref, is_mut) {
3339 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3340 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3341 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3342 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3344 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3345 let fieldpat = P(ast::Pat{
3346 id: ast::DUMMY_NODE_ID,
3347 node: PatKind::Ident(bind_type, fieldpath, None),
3348 span: boxed_span.to(hi),
3351 let subpat = if is_box {
3353 id: ast::DUMMY_NODE_ID,
3354 node: PatKind::Box(fieldpat),
3360 (subpat, fieldname, true)
3363 fields.push(codemap::Spanned { span: lo.to(hi),
3364 node: ast::FieldPat {
3367 is_shorthand: is_shorthand,
3368 attrs: attrs.into(),
3372 return Ok((fields, etc));
3375 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3376 if self.token.is_path_start() {
3378 let (qself, path) = if self.eat_lt() {
3379 // Parse a qualified path
3381 self.parse_qualified_path(PathStyle::Expr)?;
3384 // Parse an unqualified path
3385 (None, self.parse_path(PathStyle::Expr)?)
3387 let hi = self.prev_span;
3388 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3390 self.parse_pat_literal_maybe_minus()
3394 // helper function to decide whether to parse as ident binding or to try to do
3395 // something more complex like range patterns
3396 fn parse_as_ident(&mut self) -> bool {
3397 self.look_ahead(1, |t| match *t {
3398 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3399 token::DotDotDot | token::ModSep | token::Not => Some(false),
3400 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3401 // range pattern branch
3402 token::DotDot => None,
3404 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3405 token::Comma | token::CloseDelim(token::Bracket) => true,
3410 /// Parse a pattern.
3411 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3412 maybe_whole!(self, NtPat, |x| x);
3417 token::Underscore => {
3420 pat = PatKind::Wild;
3422 token::BinOp(token::And) | token::AndAnd => {
3423 // Parse &pat / &mut pat
3425 let mutbl = self.parse_mutability();
3426 if let token::Lifetime(ident) = self.token {
3427 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3429 let subpat = self.parse_pat()?;
3430 pat = PatKind::Ref(subpat, mutbl);
3432 token::OpenDelim(token::Paren) => {
3433 // Parse (pat,pat,pat,...) as tuple pattern
3435 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3436 self.expect(&token::CloseDelim(token::Paren))?;
3437 pat = PatKind::Tuple(fields, ddpos);
3439 token::OpenDelim(token::Bracket) => {
3440 // Parse [pat,pat,...] as slice pattern
3442 let (before, slice, after) = self.parse_pat_vec_elements()?;
3443 self.expect(&token::CloseDelim(token::Bracket))?;
3444 pat = PatKind::Slice(before, slice, after);
3446 // At this point, token != _, &, &&, (, [
3447 _ => if self.eat_keyword(keywords::Mut) {
3448 // Parse mut ident @ pat
3449 pat = self.parse_pat_ident(BindingMode::ByValue(Mutability::Mutable))?;
3450 } else if self.eat_keyword(keywords::Ref) {
3451 // Parse ref ident @ pat / ref mut ident @ pat
3452 let mutbl = self.parse_mutability();
3453 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3454 } else if self.eat_keyword(keywords::Box) {
3456 let subpat = self.parse_pat()?;
3457 pat = PatKind::Box(subpat);
3458 } else if self.token.is_ident() && !self.token.is_any_keyword() &&
3459 self.parse_as_ident() {
3460 // Parse ident @ pat
3461 // This can give false positives and parse nullary enums,
3462 // they are dealt with later in resolve
3463 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3464 pat = self.parse_pat_ident(binding_mode)?;
3465 } else if self.token.is_path_start() {
3466 // Parse pattern starting with a path
3467 let (qself, path) = if self.eat_lt() {
3468 // Parse a qualified path
3469 let (qself, path) = self.parse_qualified_path(PathStyle::Expr)?;
3472 // Parse an unqualified path
3473 (None, self.parse_path(PathStyle::Expr)?)
3476 token::Not if qself.is_none() => {
3477 // Parse macro invocation
3479 let (_, tts) = self.expect_delimited_token_tree()?;
3480 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3481 pat = PatKind::Mac(mac);
3483 token::DotDotDot | token::DotDot => {
3484 let end_kind = match self.token {
3485 token::DotDot => RangeEnd::Excluded,
3486 token::DotDotDot => RangeEnd::Included,
3487 _ => panic!("can only parse `..` or `...` for ranges (checked above)"),
3490 let span = lo.to(self.prev_span);
3491 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3493 let end = self.parse_pat_range_end()?;
3494 pat = PatKind::Range(begin, end, end_kind);
3496 token::OpenDelim(token::Brace) => {
3497 if qself.is_some() {
3498 return Err(self.fatal("unexpected `{` after qualified path"));
3500 // Parse struct pattern
3502 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3504 self.recover_stmt();
3508 pat = PatKind::Struct(path, fields, etc);
3510 token::OpenDelim(token::Paren) => {
3511 if qself.is_some() {
3512 return Err(self.fatal("unexpected `(` after qualified path"));
3514 // Parse tuple struct or enum pattern
3516 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3517 self.expect(&token::CloseDelim(token::Paren))?;
3518 pat = PatKind::TupleStruct(path, fields, ddpos)
3520 _ => pat = PatKind::Path(qself, path),
3523 // Try to parse everything else as literal with optional minus
3524 match self.parse_pat_literal_maybe_minus() {
3526 if self.eat(&token::DotDotDot) {
3527 let end = self.parse_pat_range_end()?;
3528 pat = PatKind::Range(begin, end, RangeEnd::Included);
3529 } else if self.eat(&token::DotDot) {
3530 let end = self.parse_pat_range_end()?;
3531 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3533 pat = PatKind::Lit(begin);
3537 self.cancel(&mut err);
3538 let msg = format!("expected pattern, found {}", self.this_token_descr());
3539 return Err(self.fatal(&msg));
3546 id: ast::DUMMY_NODE_ID,
3548 span: lo.to(self.prev_span),
3552 /// Parse ident or ident @ pat
3553 /// used by the copy foo and ref foo patterns to give a good
3554 /// error message when parsing mistakes like ref foo(a,b)
3555 fn parse_pat_ident(&mut self,
3556 binding_mode: ast::BindingMode)
3557 -> PResult<'a, PatKind> {
3558 let ident_span = self.span;
3559 let ident = self.parse_ident()?;
3560 let name = codemap::Spanned{span: ident_span, node: ident};
3561 let sub = if self.eat(&token::At) {
3562 Some(self.parse_pat()?)
3567 // just to be friendly, if they write something like
3569 // we end up here with ( as the current token. This shortly
3570 // leads to a parse error. Note that if there is no explicit
3571 // binding mode then we do not end up here, because the lookahead
3572 // will direct us over to parse_enum_variant()
3573 if self.token == token::OpenDelim(token::Paren) {
3574 return Err(self.span_fatal(
3576 "expected identifier, found enum pattern"))
3579 Ok(PatKind::Ident(binding_mode, name, sub))
3582 /// Parse a local variable declaration
3583 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3585 let pat = self.parse_pat()?;
3588 if self.eat(&token::Colon) {
3589 ty = Some(self.parse_ty()?);
3591 let init = self.parse_initializer()?;
3596 id: ast::DUMMY_NODE_ID,
3597 span: lo.to(self.prev_span),
3602 /// Parse a structure field
3603 fn parse_name_and_ty(&mut self,
3606 attrs: Vec<Attribute>)
3607 -> PResult<'a, StructField> {
3608 let name = self.parse_ident()?;
3609 self.expect(&token::Colon)?;
3610 let ty = self.parse_ty()?;
3612 span: lo.to(self.prev_span),
3615 id: ast::DUMMY_NODE_ID,
3621 /// Emit an expected item after attributes error.
3622 fn expected_item_err(&self, attrs: &[Attribute]) {
3623 let message = match attrs.last() {
3624 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3625 _ => "expected item after attributes",
3628 self.span_err(self.prev_span, message);
3631 /// Parse a statement. This stops just before trailing semicolons on everything but items.
3632 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3633 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3634 Ok(self.parse_stmt_(true))
3637 // Eat tokens until we can be relatively sure we reached the end of the
3638 // statement. This is something of a best-effort heuristic.
3640 // We terminate when we find an unmatched `}` (without consuming it).
3641 fn recover_stmt(&mut self) {
3642 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
3645 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3646 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3647 // approximate - it can mean we break too early due to macros, but that
3648 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3650 // If `break_on_block` is `Break`, then we will stop consuming tokens
3651 // after finding (and consuming) a brace-delimited block.
3652 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
3653 let mut brace_depth = 0;
3654 let mut bracket_depth = 0;
3655 let mut in_block = false;
3656 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
3657 break_on_semi, break_on_block);
3659 debug!("recover_stmt_ loop {:?}", self.token);
3661 token::OpenDelim(token::DelimToken::Brace) => {
3664 if break_on_block == BlockMode::Break &&
3666 bracket_depth == 0 {
3670 token::OpenDelim(token::DelimToken::Bracket) => {
3674 token::CloseDelim(token::DelimToken::Brace) => {
3675 if brace_depth == 0 {
3676 debug!("recover_stmt_ return - close delim {:?}", self.token);
3681 if in_block && bracket_depth == 0 && brace_depth == 0 {
3682 debug!("recover_stmt_ return - block end {:?}", self.token);
3686 token::CloseDelim(token::DelimToken::Bracket) => {
3688 if bracket_depth < 0 {
3694 debug!("recover_stmt_ return - Eof");
3699 if break_on_semi == SemiColonMode::Break &&
3701 bracket_depth == 0 {
3702 debug!("recover_stmt_ return - Semi");
3713 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
3714 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
3716 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
3721 fn is_catch_expr(&mut self) -> bool {
3722 self.token.is_keyword(keywords::Do) &&
3723 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
3724 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
3726 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3727 !self.restrictions.contains(Restrictions::RESTRICTION_NO_STRUCT_LITERAL)
3730 fn is_union_item(&self) -> bool {
3731 self.token.is_keyword(keywords::Union) &&
3732 self.look_ahead(1, |t| t.is_ident() && !t.is_any_keyword())
3735 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility)
3736 -> PResult<'a, Option<P<Item>>> {
3739 token::Ident(ident) if ident.name == "macro_rules" => {
3740 if self.look_ahead(1, |t| *t == token::Not) {
3741 let prev_span = self.prev_span;
3742 self.complain_if_pub_macro(vis, prev_span);
3747 _ => return Ok(None),
3750 let id = self.parse_ident()?;
3751 let (delim, tts) = self.expect_delimited_token_tree()?;
3752 if delim != token::Brace {
3753 if !self.eat(&token::Semi) {
3754 let msg = "macros that expand to items must either be surrounded with braces \
3755 or followed by a semicolon";
3756 self.span_err(self.prev_span, msg);
3760 let span = lo.to(self.prev_span);
3761 let kind = ItemKind::MacroDef(tts);
3762 Ok(Some(self.mk_item(span, id, kind, Visibility::Inherited, attrs.to_owned())))
3765 fn parse_stmt_without_recovery(&mut self,
3766 macro_legacy_warnings: bool)
3767 -> PResult<'a, Option<Stmt>> {
3768 maybe_whole!(self, NtStmt, |x| Some(x));
3770 let attrs = self.parse_outer_attributes()?;
3773 Ok(Some(if self.eat_keyword(keywords::Let) {
3775 id: ast::DUMMY_NODE_ID,
3776 node: StmtKind::Local(self.parse_local(attrs.into())?),
3777 span: lo.to(self.prev_span),
3779 } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited)? {
3781 id: ast::DUMMY_NODE_ID,
3782 node: StmtKind::Item(macro_def),
3783 span: lo.to(self.prev_span),
3785 // Starts like a simple path, but not a union item.
3786 } else if self.token.is_path_start() &&
3787 !self.token.is_qpath_start() &&
3788 !self.is_union_item() {
3789 let pth = self.parse_path(PathStyle::Expr)?;
3791 if !self.eat(&token::Not) {
3792 let expr = if self.check(&token::OpenDelim(token::Brace)) {
3793 self.parse_struct_expr(lo, pth, ThinVec::new())?
3795 let hi = self.prev_span;
3796 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
3799 let expr = self.with_res(Restrictions::RESTRICTION_STMT_EXPR, |this| {
3800 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
3801 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
3804 return Ok(Some(Stmt {
3805 id: ast::DUMMY_NODE_ID,
3806 node: StmtKind::Expr(expr),
3807 span: lo.to(self.prev_span),
3811 // it's a macro invocation
3812 let id = match self.token {
3813 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
3814 _ => self.parse_ident()?,
3817 // check that we're pointing at delimiters (need to check
3818 // again after the `if`, because of `parse_ident`
3819 // consuming more tokens).
3820 let delim = match self.token {
3821 token::OpenDelim(delim) => delim,
3823 // we only expect an ident if we didn't parse one
3825 let ident_str = if id.name == keywords::Invalid.name() {
3830 let tok_str = self.this_token_to_string();
3831 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3837 let (_, tts) = self.expect_delimited_token_tree()?;
3838 let hi = self.prev_span;
3840 let style = if delim == token::Brace {
3841 MacStmtStyle::Braces
3843 MacStmtStyle::NoBraces
3846 if id.name == keywords::Invalid.name() {
3847 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
3848 let node = if delim == token::Brace ||
3849 self.token == token::Semi || self.token == token::Eof {
3850 StmtKind::Mac(P((mac, style, attrs.into())))
3852 // We used to incorrectly stop parsing macro-expanded statements here.
3853 // If the next token will be an error anyway but could have parsed with the
3854 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
3855 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
3856 // These can continue an expression, so we can't stop parsing and warn.
3857 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
3858 token::BinOp(token::Minus) | token::BinOp(token::Star) |
3859 token::BinOp(token::And) | token::BinOp(token::Or) |
3860 token::AndAnd | token::OrOr |
3861 token::DotDot | token::DotDotDot => false,
3864 self.warn_missing_semicolon();
3865 StmtKind::Mac(P((mac, style, attrs.into())))
3867 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
3868 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
3869 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
3873 id: ast::DUMMY_NODE_ID,
3878 // if it has a special ident, it's definitely an item
3880 // Require a semicolon or braces.
3881 if style != MacStmtStyle::Braces {
3882 if !self.eat(&token::Semi) {
3883 self.span_err(self.prev_span,
3884 "macros that expand to items must \
3885 either be surrounded with braces or \
3886 followed by a semicolon");
3889 let span = lo.to(hi);
3891 id: ast::DUMMY_NODE_ID,
3893 node: StmtKind::Item({
3895 span, id /*id is good here*/,
3896 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
3897 Visibility::Inherited,
3903 // FIXME: Bad copy of attrs
3904 let old_directory_ownership =
3905 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
3906 let item = self.parse_item_(attrs.clone(), false, true)?;
3907 self.directory.ownership = old_directory_ownership;
3910 id: ast::DUMMY_NODE_ID,
3911 span: lo.to(i.span),
3912 node: StmtKind::Item(i),
3915 let unused_attrs = |attrs: &[_], s: &mut Self| {
3916 if attrs.len() > 0 {
3917 if s.prev_token_kind == PrevTokenKind::DocComment {
3918 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
3920 s.span_err(s.span, "expected statement after outer attribute");
3925 // Do not attempt to parse an expression if we're done here.
3926 if self.token == token::Semi {
3927 unused_attrs(&attrs, self);
3932 if self.token == token::CloseDelim(token::Brace) {
3933 unused_attrs(&attrs, self);
3937 // Remainder are line-expr stmts.
3938 let e = self.parse_expr_res(
3939 Restrictions::RESTRICTION_STMT_EXPR, Some(attrs.into()))?;
3941 id: ast::DUMMY_NODE_ID,
3942 span: lo.to(e.span),
3943 node: StmtKind::Expr(e),
3950 /// Is this expression a successfully-parsed statement?
3951 fn expr_is_complete(&mut self, e: &Expr) -> bool {
3952 self.restrictions.contains(Restrictions::RESTRICTION_STMT_EXPR) &&
3953 !classify::expr_requires_semi_to_be_stmt(e)
3956 /// Parse a block. No inner attrs are allowed.
3957 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
3958 maybe_whole!(self, NtBlock, |x| x);
3962 if !self.eat(&token::OpenDelim(token::Brace)) {
3964 let tok = self.this_token_to_string();
3965 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
3967 // Check to see if the user has written something like
3972 // Which is valid in other languages, but not Rust.
3973 match self.parse_stmt_without_recovery(false) {
3975 let mut stmt_span = stmt.span;
3976 // expand the span to include the semicolon, if it exists
3977 if self.eat(&token::Semi) {
3978 stmt_span.hi = self.prev_span.hi;
3980 let sugg = pprust::to_string(|s| {
3981 use print::pprust::{PrintState, INDENT_UNIT};
3982 s.ibox(INDENT_UNIT)?;
3984 s.print_stmt(&stmt)?;
3985 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
3987 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
3990 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
3991 self.cancel(&mut e);
3998 self.parse_block_tail(lo, BlockCheckMode::Default)
4001 /// Parse a block. Inner attrs are allowed.
4002 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4003 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4006 self.expect(&token::OpenDelim(token::Brace))?;
4007 Ok((self.parse_inner_attributes()?,
4008 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4011 /// Parse the rest of a block expression or function body
4012 /// Precondition: already parsed the '{'.
4013 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4014 let mut stmts = vec![];
4016 while !self.eat(&token::CloseDelim(token::Brace)) {
4017 if let Some(stmt) = self.parse_full_stmt(false)? {
4019 } else if self.token == token::Eof {
4022 // Found only `;` or `}`.
4029 id: ast::DUMMY_NODE_ID,
4031 span: lo.to(self.prev_span),
4035 /// Parse a statement, including the trailing semicolon.
4036 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4037 let mut stmt = match self.parse_stmt_(macro_legacy_warnings) {
4039 None => return Ok(None),
4043 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4044 // expression without semicolon
4045 if classify::expr_requires_semi_to_be_stmt(expr) {
4046 // Just check for errors and recover; do not eat semicolon yet.
4048 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4051 self.recover_stmt();
4055 StmtKind::Local(..) => {
4056 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4057 if macro_legacy_warnings && self.token != token::Semi {
4058 self.warn_missing_semicolon();
4060 self.expect_one_of(&[token::Semi], &[])?;
4066 if self.eat(&token::Semi) {
4067 stmt = stmt.add_trailing_semicolon();
4070 stmt.span.hi = self.prev_span.hi;
4074 fn warn_missing_semicolon(&self) {
4075 self.diagnostic().struct_span_warn(self.span, {
4076 &format!("expected `;`, found `{}`", self.this_token_to_string())
4078 "This was erroneously allowed and will become a hard error in a future release"
4082 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4083 // BOUND = TY_BOUND | LT_BOUND
4084 // LT_BOUND = LIFETIME (e.g. `'a`)
4085 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4086 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4087 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4088 let mut bounds = Vec::new();
4090 let is_bound_start = self.check_path() || self.check_lifetime() ||
4091 self.check(&token::Question) ||
4092 self.check_keyword(keywords::For) ||
4093 self.check(&token::OpenDelim(token::Paren));
4095 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4096 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4097 if self.token.is_lifetime() {
4098 if let Some(question_span) = question {
4099 self.span_err(question_span,
4100 "`?` may only modify trait bounds, not lifetime bounds");
4102 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4105 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4106 let path = self.parse_path(PathStyle::Type)?;
4107 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4108 let modifier = if question.is_some() {
4109 TraitBoundModifier::Maybe
4111 TraitBoundModifier::None
4113 bounds.push(TraitTyParamBound(poly_trait, modifier));
4116 self.expect(&token::CloseDelim(token::Paren))?;
4117 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4118 self.span_err(self.prev_span,
4119 "parenthesized lifetime bounds are not supported");
4126 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4134 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4135 self.parse_ty_param_bounds_common(true)
4138 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4139 // BOUND = LT_BOUND (e.g. `'a`)
4140 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4141 let mut lifetimes = Vec::new();
4142 while self.check_lifetime() {
4143 lifetimes.push(self.expect_lifetime());
4145 if !self.eat(&token::BinOp(token::Plus)) {
4152 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4153 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4154 let span = self.span;
4155 let ident = self.parse_ident()?;
4157 // Parse optional colon and param bounds.
4158 let bounds = if self.eat(&token::Colon) {
4159 self.parse_ty_param_bounds()?
4164 let default = if self.eat(&token::Eq) {
4165 Some(self.parse_ty()?)
4171 attrs: preceding_attrs.into(),
4173 id: ast::DUMMY_NODE_ID,
4180 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4181 /// trailing comma and erroneous trailing attributes.
4182 pub fn parse_generic_params(&mut self) -> PResult<'a, (Vec<LifetimeDef>, Vec<TyParam>)> {
4183 let mut lifetime_defs = Vec::new();
4184 let mut ty_params = Vec::new();
4185 let mut seen_ty_param = false;
4187 let attrs = self.parse_outer_attributes()?;
4188 if self.check_lifetime() {
4189 let lifetime = self.expect_lifetime();
4190 // Parse lifetime parameter.
4191 let bounds = if self.eat(&token::Colon) {
4192 self.parse_lt_param_bounds()
4196 lifetime_defs.push(LifetimeDef {
4197 attrs: attrs.into(),
4202 self.span_err(self.prev_span,
4203 "lifetime parameters must be declared prior to type parameters");
4205 } else if self.check_ident() {
4206 // Parse type parameter.
4207 ty_params.push(self.parse_ty_param(attrs)?);
4208 seen_ty_param = true;
4210 // Check for trailing attributes and stop parsing.
4211 if !attrs.is_empty() {
4212 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4213 self.span_err(attrs[0].span,
4214 &format!("trailing attribute after {} parameters", param_kind));
4219 if !self.eat(&token::Comma) {
4223 Ok((lifetime_defs, ty_params))
4226 /// Parse a set of optional generic type parameter declarations. Where
4227 /// clauses are not parsed here, and must be added later via
4228 /// `parse_where_clause()`.
4230 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4231 /// | ( < lifetimes , typaramseq ( , )? > )
4232 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4233 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4234 maybe_whole!(self, NtGenerics, |x| x);
4236 let span_lo = self.span;
4238 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4241 lifetimes: lifetime_defs,
4242 ty_params: ty_params,
4243 where_clause: WhereClause {
4244 id: ast::DUMMY_NODE_ID,
4245 predicates: Vec::new(),
4247 span: span_lo.to(self.prev_span),
4250 Ok(ast::Generics::default())
4254 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4255 /// possibly including trailing comma.
4256 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4257 let mut lifetimes = Vec::new();
4258 let mut types = Vec::new();
4259 let mut bindings = Vec::new();
4260 let mut seen_type = false;
4261 let mut seen_binding = false;
4263 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4264 // Parse lifetime argument.
4265 lifetimes.push(self.expect_lifetime());
4266 if seen_type || seen_binding {
4267 self.span_err(self.prev_span,
4268 "lifetime parameters must be declared prior to type parameters");
4270 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4271 // Parse associated type binding.
4273 let ident = self.parse_ident()?;
4275 let ty = self.parse_ty()?;
4276 bindings.push(TypeBinding {
4277 id: ast::DUMMY_NODE_ID,
4280 span: lo.to(self.prev_span),
4282 seen_binding = true;
4283 } else if self.check_type() {
4284 // Parse type argument.
4285 types.push(self.parse_ty()?);
4287 self.span_err(types[types.len() - 1].span,
4288 "type parameters must be declared prior to associated type bindings");
4295 if !self.eat(&token::Comma) {
4299 Ok((lifetimes, types, bindings))
4302 /// Parses an optional `where` clause and places it in `generics`.
4305 /// where T : Trait<U, V> + 'b, 'a : 'b
4307 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4308 maybe_whole!(self, NtWhereClause, |x| x);
4310 let mut where_clause = WhereClause {
4311 id: ast::DUMMY_NODE_ID,
4312 predicates: Vec::new(),
4315 if !self.eat_keyword(keywords::Where) {
4316 return Ok(where_clause);
4319 // This is a temporary future proofing.
4321 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4322 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4323 // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4324 if token::Lt == self.token {
4325 let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4326 if ident_or_lifetime {
4327 let gt_comma_or_colon = self.look_ahead(2, |t| {
4328 *t == token::Gt || *t == token::Comma || *t == token::Colon
4330 if gt_comma_or_colon {
4331 self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4338 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4339 let lifetime = self.expect_lifetime();
4340 // Bounds starting with a colon are mandatory, but possibly empty.
4341 self.expect(&token::Colon)?;
4342 let bounds = self.parse_lt_param_bounds();
4343 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4344 ast::WhereRegionPredicate {
4345 span: lo.to(self.prev_span),
4350 } else if self.check_type() {
4351 // Parse optional `for<'a, 'b>`.
4352 // This `for` is parsed greedily and applies to the whole predicate,
4353 // the bounded type can have its own `for` applying only to it.
4354 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4355 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4356 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4357 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4359 // Parse type with mandatory colon and (possibly empty) bounds,
4360 // or with mandatory equality sign and the second type.
4361 let ty = self.parse_ty()?;
4362 if self.eat(&token::Colon) {
4363 let bounds = self.parse_ty_param_bounds()?;
4364 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4365 ast::WhereBoundPredicate {
4366 span: lo.to(self.prev_span),
4367 bound_lifetimes: lifetime_defs,
4372 // FIXME: Decide what should be used here, `=` or `==`.
4373 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4374 let rhs_ty = self.parse_ty()?;
4375 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4376 ast::WhereEqPredicate {
4377 span: lo.to(self.prev_span),
4380 id: ast::DUMMY_NODE_ID,
4384 return self.unexpected();
4390 if !self.eat(&token::Comma) {
4398 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4399 -> PResult<'a, (Vec<Arg> , bool)> {
4401 let mut variadic = false;
4402 let args: Vec<Option<Arg>> =
4403 self.parse_unspanned_seq(
4404 &token::OpenDelim(token::Paren),
4405 &token::CloseDelim(token::Paren),
4406 SeqSep::trailing_allowed(token::Comma),
4408 if p.token == token::DotDotDot {
4411 if p.token != token::CloseDelim(token::Paren) {
4414 "`...` must be last in argument list for variadic function");
4419 "only foreign functions are allowed to be variadic");
4424 match p.parse_arg_general(named_args) {
4425 Ok(arg) => Ok(Some(arg)),
4428 let lo = p.prev_span;
4429 // Skip every token until next possible arg or end.
4430 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4431 // Create a placeholder argument for proper arg count (#34264).
4432 let span = lo.to(p.prev_span);
4433 Ok(Some(dummy_arg(span)))
4440 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4442 if variadic && args.is_empty() {
4444 "variadic function must be declared with at least one named argument");
4447 Ok((args, variadic))
4450 /// Parse the argument list and result type of a function declaration
4451 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4453 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4454 let ret_ty = self.parse_ret_ty()?;
4463 /// Returns the parsed optional self argument and whether a self shortcut was used.
4464 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4465 let expect_ident = |this: &mut Self| match this.token {
4466 // Preserve hygienic context.
4467 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4470 let isolated_self = |this: &mut Self, n| {
4471 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4472 this.look_ahead(n + 1, |t| t != &token::ModSep)
4475 // Parse optional self parameter of a method.
4476 // Only a limited set of initial token sequences is considered self parameters, anything
4477 // else is parsed as a normal function parameter list, so some lookahead is required.
4478 let eself_lo = self.span;
4479 let (eself, eself_ident) = match self.token {
4480 token::BinOp(token::And) => {
4486 if isolated_self(self, 1) {
4488 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4489 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4490 isolated_self(self, 2) {
4493 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4494 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4495 isolated_self(self, 2) {
4497 let lt = self.expect_lifetime();
4498 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4499 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4500 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4501 isolated_self(self, 3) {
4503 let lt = self.expect_lifetime();
4505 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4510 token::BinOp(token::Star) => {
4515 // Emit special error for `self` cases.
4516 if isolated_self(self, 1) {
4518 self.span_err(self.span, "cannot pass `self` by raw pointer");
4519 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4520 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4521 isolated_self(self, 2) {
4524 self.span_err(self.span, "cannot pass `self` by raw pointer");
4525 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4530 token::Ident(..) => {
4531 if isolated_self(self, 0) {
4534 let eself_ident = expect_ident(self);
4535 if self.eat(&token::Colon) {
4536 let ty = self.parse_ty()?;
4537 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4539 (SelfKind::Value(Mutability::Immutable), eself_ident)
4541 } else if self.token.is_keyword(keywords::Mut) &&
4542 isolated_self(self, 1) {
4546 let eself_ident = expect_ident(self);
4547 if self.eat(&token::Colon) {
4548 let ty = self.parse_ty()?;
4549 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4551 (SelfKind::Value(Mutability::Mutable), eself_ident)
4557 _ => return Ok(None),
4560 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
4561 Ok(Some(Arg::from_self(eself, eself_ident)))
4564 /// Parse the parameter list and result type of a function that may have a `self` parameter.
4565 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
4566 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4568 self.expect(&token::OpenDelim(token::Paren))?;
4570 // Parse optional self argument
4571 let self_arg = self.parse_self_arg()?;
4573 // Parse the rest of the function parameter list.
4574 let sep = SeqSep::trailing_allowed(token::Comma);
4575 let fn_inputs = if let Some(self_arg) = self_arg {
4576 if self.check(&token::CloseDelim(token::Paren)) {
4578 } else if self.eat(&token::Comma) {
4579 let mut fn_inputs = vec![self_arg];
4580 fn_inputs.append(&mut self.parse_seq_to_before_end(
4581 &token::CloseDelim(token::Paren), sep, parse_arg_fn)
4585 return self.unexpected();
4588 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4591 // Parse closing paren and return type.
4592 self.expect(&token::CloseDelim(token::Paren))?;
4595 output: self.parse_ret_ty()?,
4600 // parse the |arg, arg| header on a lambda
4601 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4602 let inputs_captures = {
4603 if self.eat(&token::OrOr) {
4606 self.expect(&token::BinOp(token::Or))?;
4607 let args = self.parse_seq_to_before_end(
4608 &token::BinOp(token::Or),
4609 SeqSep::trailing_allowed(token::Comma),
4610 |p| p.parse_fn_block_arg()
4616 let output = self.parse_ret_ty()?;
4619 inputs: inputs_captures,
4625 /// Parse the name and optional generic types of a function header.
4626 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4627 let id = self.parse_ident()?;
4628 let generics = self.parse_generics()?;
4632 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
4633 attrs: Vec<Attribute>) -> P<Item> {
4637 id: ast::DUMMY_NODE_ID,
4644 /// Parse an item-position function declaration.
4645 fn parse_item_fn(&mut self,
4647 constness: Spanned<Constness>,
4649 -> PResult<'a, ItemInfo> {
4650 let (ident, mut generics) = self.parse_fn_header()?;
4651 let decl = self.parse_fn_decl(false)?;
4652 generics.where_clause = self.parse_where_clause()?;
4653 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4654 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4657 /// true if we are looking at `const ID`, false for things like `const fn` etc
4658 pub fn is_const_item(&mut self) -> bool {
4659 self.token.is_keyword(keywords::Const) &&
4660 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4661 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4664 /// parses all the "front matter" for a `fn` declaration, up to
4665 /// and including the `fn` keyword:
4669 /// - `const unsafe fn`
4672 pub fn parse_fn_front_matter(&mut self)
4673 -> PResult<'a, (Spanned<ast::Constness>,
4676 let is_const_fn = self.eat_keyword(keywords::Const);
4677 let const_span = self.prev_span;
4678 let unsafety = self.parse_unsafety()?;
4679 let (constness, unsafety, abi) = if is_const_fn {
4680 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
4682 let abi = if self.eat_keyword(keywords::Extern) {
4683 self.parse_opt_abi()?.unwrap_or(Abi::C)
4687 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
4689 self.expect_keyword(keywords::Fn)?;
4690 Ok((constness, unsafety, abi))
4693 /// Parse an impl item.
4694 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
4695 maybe_whole!(self, NtImplItem, |x| x);
4697 let mut attrs = self.parse_outer_attributes()?;
4699 let vis = self.parse_visibility(false)?;
4700 let defaultness = self.parse_defaultness()?;
4701 let (name, node) = if self.eat_keyword(keywords::Type) {
4702 let name = self.parse_ident()?;
4703 self.expect(&token::Eq)?;
4704 let typ = self.parse_ty()?;
4705 self.expect(&token::Semi)?;
4706 (name, ast::ImplItemKind::Type(typ))
4707 } else if self.is_const_item() {
4708 self.expect_keyword(keywords::Const)?;
4709 let name = self.parse_ident()?;
4710 self.expect(&token::Colon)?;
4711 let typ = self.parse_ty()?;
4712 self.expect(&token::Eq)?;
4713 let expr = self.parse_expr()?;
4714 self.expect(&token::Semi)?;
4715 (name, ast::ImplItemKind::Const(typ, expr))
4717 let (name, inner_attrs, node) = self.parse_impl_method(&vis, at_end)?;
4718 attrs.extend(inner_attrs);
4723 id: ast::DUMMY_NODE_ID,
4724 span: lo.to(self.prev_span),
4727 defaultness: defaultness,
4733 fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
4734 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
4739 fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
4741 Visibility::Inherited => Ok(()),
4743 let is_macro_rules: bool = match self.token {
4744 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
4748 let mut err = self.diagnostic()
4749 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
4750 err.help("did you mean #[macro_export]?");
4753 let mut err = self.diagnostic()
4754 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
4755 err.help("try adjusting the macro to put `pub` inside the invocation");
4762 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
4763 -> DiagnosticBuilder<'a>
4765 // Given this code `path(`, it seems like this is not
4766 // setting the visibility of a macro invocation, but rather
4767 // a mistyped method declaration.
4768 // Create a diagnostic pointing out that `fn` is missing.
4770 // x | pub path(&self) {
4771 // | ^ missing `fn`, `type`, or `const`
4773 // ^^ `sp` below will point to this
4774 let sp = prev_span.between(self.prev_span);
4775 let mut err = self.diagnostic().struct_span_err(
4777 &format!("missing `fn`, `type`, or `const` for {}-item declaration",
4779 err.span_label(sp, &"missing `fn`, `type`, or `const`");
4783 /// Parse a method or a macro invocation in a trait impl.
4784 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
4785 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4786 // code copied from parse_macro_use_or_failure... abstraction!
4787 if self.token.is_path_start() {
4790 let prev_span = self.prev_span;
4793 let pth = self.parse_path(PathStyle::Mod)?;
4794 if pth.segments.len() == 1 {
4795 if !self.eat(&token::Not) {
4796 return Err(self.missing_assoc_item_kind_err("impl", prev_span));
4799 self.expect(&token::Not)?;
4802 self.complain_if_pub_macro(&vis, prev_span);
4804 // eat a matched-delimiter token tree:
4806 let (delim, tts) = self.expect_delimited_token_tree()?;
4807 if delim != token::Brace {
4808 self.expect(&token::Semi)?
4811 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
4812 Ok((keywords::Invalid.ident(), vec![], ast::ImplItemKind::Macro(mac)))
4814 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
4815 let ident = self.parse_ident()?;
4816 let mut generics = self.parse_generics()?;
4817 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
4818 generics.where_clause = self.parse_where_clause()?;
4820 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4821 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4825 constness: constness,
4831 /// Parse trait Foo { ... }
4832 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4833 let ident = self.parse_ident()?;
4834 let mut tps = self.parse_generics()?;
4836 // Parse optional colon and supertrait bounds.
4837 let bounds = if self.eat(&token::Colon) {
4838 self.parse_ty_param_bounds()?
4843 tps.where_clause = self.parse_where_clause()?;
4845 self.expect(&token::OpenDelim(token::Brace))?;
4846 let mut trait_items = vec![];
4847 while !self.eat(&token::CloseDelim(token::Brace)) {
4848 let mut at_end = false;
4849 match self.parse_trait_item(&mut at_end) {
4850 Ok(item) => trait_items.push(item),
4854 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
4859 Ok((ident, ItemKind::Trait(unsafety, tps, bounds, trait_items), None))
4862 /// Parses items implementations variants
4863 /// impl<T> Foo { ... }
4864 /// impl<T> ToString for &'static T { ... }
4865 /// impl Send for .. {}
4866 fn parse_item_impl(&mut self, unsafety: ast::Unsafety) -> PResult<'a, ItemInfo> {
4867 let impl_span = self.span;
4869 // First, parse type parameters if necessary.
4870 let mut generics = self.parse_generics()?;
4872 // Special case: if the next identifier that follows is '(', don't
4873 // allow this to be parsed as a trait.
4874 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4876 let neg_span = self.span;
4877 let polarity = if self.eat(&token::Not) {
4878 ast::ImplPolarity::Negative
4880 ast::ImplPolarity::Positive
4884 let mut ty = self.parse_ty()?;
4886 // Parse traits, if necessary.
4887 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4888 // New-style trait. Reinterpret the type as a trait.
4890 TyKind::Path(None, ref path) => {
4892 path: (*path).clone(),
4897 self.span_err(ty.span, "not a trait");
4903 ast::ImplPolarity::Negative => {
4904 // This is a negated type implementation
4905 // `impl !MyType {}`, which is not allowed.
4906 self.span_err(neg_span, "inherent implementation can't be negated");
4913 if opt_trait.is_some() && self.eat(&token::DotDot) {
4914 if generics.is_parameterized() {
4915 self.span_err(impl_span, "default trait implementations are not \
4916 allowed to have generics");
4919 self.expect(&token::OpenDelim(token::Brace))?;
4920 self.expect(&token::CloseDelim(token::Brace))?;
4921 Ok((keywords::Invalid.ident(),
4922 ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
4924 if opt_trait.is_some() {
4925 ty = self.parse_ty()?;
4927 generics.where_clause = self.parse_where_clause()?;
4929 self.expect(&token::OpenDelim(token::Brace))?;
4930 let attrs = self.parse_inner_attributes()?;
4932 let mut impl_items = vec![];
4933 while !self.eat(&token::CloseDelim(token::Brace)) {
4934 let mut at_end = false;
4935 match self.parse_impl_item(&mut at_end) {
4936 Ok(item) => impl_items.push(item),
4940 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
4946 Ok((keywords::Invalid.ident(),
4947 ItemKind::Impl(unsafety, polarity, generics, opt_trait, ty, impl_items),
4952 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<LifetimeDef>> {
4953 if self.eat_keyword(keywords::For) {
4955 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4957 if !ty_params.is_empty() {
4958 self.span_err(ty_params[0].span,
4959 "only lifetime parameters can be used in this context");
4967 /// Parse struct Foo { ... }
4968 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
4969 let class_name = self.parse_ident()?;
4971 let mut generics = self.parse_generics()?;
4973 // There is a special case worth noting here, as reported in issue #17904.
4974 // If we are parsing a tuple struct it is the case that the where clause
4975 // should follow the field list. Like so:
4977 // struct Foo<T>(T) where T: Copy;
4979 // If we are parsing a normal record-style struct it is the case
4980 // that the where clause comes before the body, and after the generics.
4981 // So if we look ahead and see a brace or a where-clause we begin
4982 // parsing a record style struct.
4984 // Otherwise if we look ahead and see a paren we parse a tuple-style
4987 let vdata = if self.token.is_keyword(keywords::Where) {
4988 generics.where_clause = self.parse_where_clause()?;
4989 if self.eat(&token::Semi) {
4990 // If we see a: `struct Foo<T> where T: Copy;` style decl.
4991 VariantData::Unit(ast::DUMMY_NODE_ID)
4993 // If we see: `struct Foo<T> where T: Copy { ... }`
4994 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
4996 // No `where` so: `struct Foo<T>;`
4997 } else if self.eat(&token::Semi) {
4998 VariantData::Unit(ast::DUMMY_NODE_ID)
4999 // Record-style struct definition
5000 } else if self.token == token::OpenDelim(token::Brace) {
5001 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5002 // Tuple-style struct definition with optional where-clause.
5003 } else if self.token == token::OpenDelim(token::Paren) {
5004 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5005 generics.where_clause = self.parse_where_clause()?;
5006 self.expect(&token::Semi)?;
5009 let token_str = self.this_token_to_string();
5010 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5011 name, found `{}`", token_str)))
5014 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5017 /// Parse union Foo { ... }
5018 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5019 let class_name = self.parse_ident()?;
5021 let mut generics = self.parse_generics()?;
5023 let vdata = if self.token.is_keyword(keywords::Where) {
5024 generics.where_clause = self.parse_where_clause()?;
5025 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5026 } else if self.token == token::OpenDelim(token::Brace) {
5027 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5029 let token_str = self.this_token_to_string();
5030 return Err(self.fatal(&format!("expected `where` or `{{` after union \
5031 name, found `{}`", token_str)))
5034 Ok((class_name, ItemKind::Union(vdata, generics), None))
5037 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5038 let mut fields = Vec::new();
5039 if self.eat(&token::OpenDelim(token::Brace)) {
5040 while self.token != token::CloseDelim(token::Brace) {
5041 fields.push(self.parse_struct_decl_field().map_err(|e| {
5042 self.recover_stmt();
5043 self.eat(&token::CloseDelim(token::Brace));
5050 let token_str = self.this_token_to_string();
5051 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5059 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5060 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5061 // Unit like structs are handled in parse_item_struct function
5062 let fields = self.parse_unspanned_seq(
5063 &token::OpenDelim(token::Paren),
5064 &token::CloseDelim(token::Paren),
5065 SeqSep::trailing_allowed(token::Comma),
5067 let attrs = p.parse_outer_attributes()?;
5069 let vis = p.parse_visibility(true)?;
5070 let ty = p.parse_ty()?;
5072 span: lo.to(p.span),
5075 id: ast::DUMMY_NODE_ID,
5084 /// Parse a structure field declaration
5085 pub fn parse_single_struct_field(&mut self,
5088 attrs: Vec<Attribute> )
5089 -> PResult<'a, StructField> {
5090 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5095 token::CloseDelim(token::Brace) => {}
5096 token::DocComment(_) => return Err(self.span_fatal_err(self.span,
5097 Error::UselessDocComment)),
5098 _ => return Err(self.span_fatal_help(self.span,
5099 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5100 "struct fields should be separated by commas")),
5105 /// Parse an element of a struct definition
5106 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5107 let attrs = self.parse_outer_attributes()?;
5109 let vis = self.parse_visibility(false)?;
5110 self.parse_single_struct_field(lo, vis, attrs)
5113 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5114 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5115 /// a function definition, it's not a tuple struct field) and the contents within the parens
5116 /// isn't valid, emit a proper diagnostic.
5117 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5118 maybe_whole!(self, NtVis, |x| x);
5120 if !self.eat_keyword(keywords::Pub) {
5121 return Ok(Visibility::Inherited)
5124 if self.check(&token::OpenDelim(token::Paren)) {
5125 let start_span = self.span;
5126 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5127 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5128 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5129 // by the following tokens.
5130 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5133 self.bump(); // `crate`
5134 let vis = Visibility::Crate(self.prev_span);
5135 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5137 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5140 self.bump(); // `in`
5141 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5142 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5143 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5145 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5146 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5147 t.is_keyword(keywords::SelfValue)) {
5148 // `pub(self)` or `pub(super)`
5150 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5151 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5152 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5154 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5155 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5157 let msg = "incorrect visibility restriction";
5158 let suggestion = r##"some possible visibility restrictions are:
5159 `pub(crate)`: visible only on the current crate
5160 `pub(super)`: visible only in the current module's parent
5161 `pub(in path::to::module)`: visible only on the specified path"##;
5162 let path = self.parse_path(PathStyle::Mod)?;
5163 let path_span = self.prev_span;
5164 let help_msg = format!("to make this visible only to module `{}`, add `in` before \
5167 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5168 let sp = start_span.to(self.prev_span);
5169 let mut err = self.span_fatal_help(sp, &msg, &suggestion);
5170 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5171 err.emit(); // emit diagnostic, but continue with public visibility
5175 Ok(Visibility::Public)
5178 /// Parse defaultness: DEFAULT or nothing
5179 fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5180 if self.eat_contextual_keyword(keywords::Default.ident()) {
5181 Ok(Defaultness::Default)
5183 Ok(Defaultness::Final)
5187 /// Given a termination token, parse all of the items in a module
5188 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5189 let mut items = vec![];
5190 while let Some(item) = self.parse_item()? {
5194 if !self.eat(term) {
5195 let token_str = self.this_token_to_string();
5196 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5199 let hi = if self.span == syntax_pos::DUMMY_SP {
5206 inner: inner_lo.to(hi),
5211 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5212 let id = self.parse_ident()?;
5213 self.expect(&token::Colon)?;
5214 let ty = self.parse_ty()?;
5215 self.expect(&token::Eq)?;
5216 let e = self.parse_expr()?;
5217 self.expect(&token::Semi)?;
5218 let item = match m {
5219 Some(m) => ItemKind::Static(ty, m, e),
5220 None => ItemKind::Const(ty, e),
5222 Ok((id, item, None))
5225 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5226 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5227 let (in_cfg, outer_attrs) = {
5228 let mut strip_unconfigured = ::config::StripUnconfigured {
5230 should_test: false, // irrelevant
5231 features: None, // don't perform gated feature checking
5233 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5234 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5237 let id_span = self.span;
5238 let id = self.parse_ident()?;
5239 if self.check(&token::Semi) {
5242 // This mod is in an external file. Let's go get it!
5243 let ModulePathSuccess { path, directory_ownership, warn } =
5244 self.submod_path(id, &outer_attrs, id_span)?;
5245 let (module, mut attrs) =
5246 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5248 let attr = ast::Attribute {
5249 id: attr::mk_attr_id(),
5250 style: ast::AttrStyle::Outer,
5251 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5252 Ident::from_str("warn_directory_ownership")),
5253 tokens: TokenStream::empty(),
5254 is_sugared_doc: false,
5255 span: syntax_pos::DUMMY_SP,
5257 attr::mark_known(&attr);
5260 Ok((id, module, Some(attrs)))
5262 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5263 Ok((id, ItemKind::Mod(placeholder), None))
5266 let old_directory = self.directory.clone();
5267 self.push_directory(id, &outer_attrs);
5268 self.expect(&token::OpenDelim(token::Brace))?;
5269 let mod_inner_lo = self.span;
5270 let attrs = self.parse_inner_attributes()?;
5271 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5272 self.directory = old_directory;
5273 Ok((id, ItemKind::Mod(module), Some(attrs)))
5277 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5278 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5279 self.directory.path.push(&path.as_str());
5280 self.directory.ownership = DirectoryOwnership::Owned;
5282 self.directory.path.push(&id.name.as_str());
5286 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5287 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5290 /// Returns either a path to a module, or .
5291 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5292 let mod_name = id.to_string();
5293 let default_path_str = format!("{}.rs", mod_name);
5294 let secondary_path_str = format!("{}{}mod.rs", mod_name, path::MAIN_SEPARATOR);
5295 let default_path = dir_path.join(&default_path_str);
5296 let secondary_path = dir_path.join(&secondary_path_str);
5297 let default_exists = codemap.file_exists(&default_path);
5298 let secondary_exists = codemap.file_exists(&secondary_path);
5300 let result = match (default_exists, secondary_exists) {
5301 (true, false) => Ok(ModulePathSuccess {
5303 directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5306 (false, true) => Ok(ModulePathSuccess {
5307 path: secondary_path,
5308 directory_ownership: DirectoryOwnership::Owned,
5311 (false, false) => Err(Error::FileNotFoundForModule {
5312 mod_name: mod_name.clone(),
5313 default_path: default_path_str,
5314 secondary_path: secondary_path_str,
5315 dir_path: format!("{}", dir_path.display()),
5317 (true, true) => Err(Error::DuplicatePaths {
5318 mod_name: mod_name.clone(),
5319 default_path: default_path_str,
5320 secondary_path: secondary_path_str,
5326 path_exists: default_exists || secondary_exists,
5331 fn submod_path(&mut self,
5333 outer_attrs: &[ast::Attribute],
5334 id_sp: Span) -> PResult<'a, ModulePathSuccess> {
5335 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5336 return Ok(ModulePathSuccess {
5337 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5338 Some("mod.rs") => DirectoryOwnership::Owned,
5339 _ => DirectoryOwnership::UnownedViaMod(true),
5346 let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5348 if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5350 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5351 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5352 if paths.path_exists {
5353 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5355 err.span_note(id_sp, &msg);
5358 } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5360 if let Ok(result) = paths.result {
5361 return Ok(ModulePathSuccess { warn: true, ..result });
5364 let mut err = self.diagnostic().struct_span_err(id_sp,
5365 "cannot declare a new module at this location");
5366 let this_module = match self.directory.path.file_name() {
5367 Some(file_name) => file_name.to_str().unwrap().to_owned(),
5368 None => self.root_module_name.as_ref().unwrap().clone(),
5370 err.span_note(id_sp,
5371 &format!("maybe move this module `{0}` to its own directory \
5372 via `{0}{1}mod.rs`",
5374 path::MAIN_SEPARATOR));
5375 if paths.path_exists {
5376 err.span_note(id_sp,
5377 &format!("... or maybe `use` the module `{}` instead \
5378 of possibly redeclaring it",
5385 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5389 /// Read a module from a source file.
5390 fn eval_src_mod(&mut self,
5392 directory_ownership: DirectoryOwnership,
5395 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5396 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5397 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5398 let mut err = String::from("circular modules: ");
5399 let len = included_mod_stack.len();
5400 for p in &included_mod_stack[i.. len] {
5401 err.push_str(&p.to_string_lossy());
5402 err.push_str(" -> ");
5404 err.push_str(&path.to_string_lossy());
5405 return Err(self.span_fatal(id_sp, &err[..]));
5407 included_mod_stack.push(path.clone());
5408 drop(included_mod_stack);
5411 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5412 p0.cfg_mods = self.cfg_mods;
5413 let mod_inner_lo = p0.span;
5414 let mod_attrs = p0.parse_inner_attributes()?;
5415 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5416 self.sess.included_mod_stack.borrow_mut().pop();
5417 Ok((ast::ItemKind::Mod(m0), mod_attrs))
5420 /// Parse a function declaration from a foreign module
5421 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5422 -> PResult<'a, ForeignItem> {
5423 self.expect_keyword(keywords::Fn)?;
5425 let (ident, mut generics) = self.parse_fn_header()?;
5426 let decl = self.parse_fn_decl(true)?;
5427 generics.where_clause = self.parse_where_clause()?;
5429 self.expect(&token::Semi)?;
5430 Ok(ast::ForeignItem {
5433 node: ForeignItemKind::Fn(decl, generics),
5434 id: ast::DUMMY_NODE_ID,
5440 /// Parse a static item from a foreign module
5441 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5442 -> PResult<'a, ForeignItem> {
5443 self.expect_keyword(keywords::Static)?;
5444 let mutbl = self.eat_keyword(keywords::Mut);
5446 let ident = self.parse_ident()?;
5447 self.expect(&token::Colon)?;
5448 let ty = self.parse_ty()?;
5450 self.expect(&token::Semi)?;
5454 node: ForeignItemKind::Static(ty, mutbl),
5455 id: ast::DUMMY_NODE_ID,
5461 /// Parse extern crate links
5465 /// extern crate foo;
5466 /// extern crate bar as foo;
5467 fn parse_item_extern_crate(&mut self,
5469 visibility: Visibility,
5470 attrs: Vec<Attribute>)
5471 -> PResult<'a, P<Item>> {
5473 let crate_name = self.parse_ident()?;
5474 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
5475 (Some(crate_name.name), ident)
5479 self.expect(&token::Semi)?;
5481 let prev_span = self.prev_span;
5482 Ok(self.mk_item(lo.to(prev_span),
5484 ItemKind::ExternCrate(maybe_path),
5489 /// Parse `extern` for foreign ABIs
5492 /// `extern` is expected to have been
5493 /// consumed before calling this method
5499 fn parse_item_foreign_mod(&mut self,
5501 opt_abi: Option<abi::Abi>,
5502 visibility: Visibility,
5503 mut attrs: Vec<Attribute>)
5504 -> PResult<'a, P<Item>> {
5505 self.expect(&token::OpenDelim(token::Brace))?;
5507 let abi = opt_abi.unwrap_or(Abi::C);
5509 attrs.extend(self.parse_inner_attributes()?);
5511 let mut foreign_items = vec![];
5512 while let Some(item) = self.parse_foreign_item()? {
5513 foreign_items.push(item);
5515 self.expect(&token::CloseDelim(token::Brace))?;
5517 let prev_span = self.prev_span;
5518 let m = ast::ForeignMod {
5520 items: foreign_items
5522 let invalid = keywords::Invalid.ident();
5523 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
5526 /// Parse type Foo = Bar;
5527 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5528 let ident = self.parse_ident()?;
5529 let mut tps = self.parse_generics()?;
5530 tps.where_clause = self.parse_where_clause()?;
5531 self.expect(&token::Eq)?;
5532 let ty = self.parse_ty()?;
5533 self.expect(&token::Semi)?;
5534 Ok((ident, ItemKind::Ty(ty, tps), None))
5537 /// Parse the part of an "enum" decl following the '{'
5538 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5539 let mut variants = Vec::new();
5540 let mut all_nullary = true;
5541 let mut any_disr = None;
5542 while self.token != token::CloseDelim(token::Brace) {
5543 let variant_attrs = self.parse_outer_attributes()?;
5544 let vlo = self.span;
5547 let mut disr_expr = None;
5548 let ident = self.parse_ident()?;
5549 if self.check(&token::OpenDelim(token::Brace)) {
5550 // Parse a struct variant.
5551 all_nullary = false;
5552 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
5553 ast::DUMMY_NODE_ID);
5554 } else if self.check(&token::OpenDelim(token::Paren)) {
5555 all_nullary = false;
5556 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
5557 ast::DUMMY_NODE_ID);
5558 } else if self.eat(&token::Eq) {
5559 disr_expr = Some(self.parse_expr()?);
5560 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5561 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5563 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5566 let vr = ast::Variant_ {
5568 attrs: variant_attrs,
5570 disr_expr: disr_expr,
5572 variants.push(respan(vlo.to(self.prev_span), vr));
5574 if !self.eat(&token::Comma) { break; }
5576 self.expect(&token::CloseDelim(token::Brace))?;
5578 Some(disr_span) if !all_nullary =>
5579 self.span_err(disr_span,
5580 "discriminator values can only be used with a c-like enum"),
5584 Ok(ast::EnumDef { variants: variants })
5587 /// Parse an "enum" declaration
5588 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5589 let id = self.parse_ident()?;
5590 let mut generics = self.parse_generics()?;
5591 generics.where_clause = self.parse_where_clause()?;
5592 self.expect(&token::OpenDelim(token::Brace))?;
5594 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
5595 self.recover_stmt();
5596 self.eat(&token::CloseDelim(token::Brace));
5599 Ok((id, ItemKind::Enum(enum_definition, generics), None))
5602 /// Parses a string as an ABI spec on an extern type or module. Consumes
5603 /// the `extern` keyword, if one is found.
5604 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5606 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5608 self.expect_no_suffix(sp, "ABI spec", suf);
5610 match abi::lookup(&s.as_str()) {
5611 Some(abi) => Ok(Some(abi)),
5613 let prev_span = self.prev_span;
5616 &format!("invalid ABI: expected one of [{}], \
5618 abi::all_names().join(", "),
5629 /// Parse one of the items allowed by the flags.
5630 /// NB: this function no longer parses the items inside an
5632 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5633 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5634 maybe_whole!(self, NtItem, |item| {
5635 let mut item = item.unwrap();
5636 let mut attrs = attrs;
5637 mem::swap(&mut item.attrs, &mut attrs);
5638 item.attrs.extend(attrs);
5644 let visibility = self.parse_visibility(false)?;
5646 if self.eat_keyword(keywords::Use) {
5648 let item_ = ItemKind::Use(self.parse_view_path()?);
5649 self.expect(&token::Semi)?;
5651 let prev_span = self.prev_span;
5652 let invalid = keywords::Invalid.ident();
5653 let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
5654 return Ok(Some(item));
5657 if self.eat_keyword(keywords::Extern) {
5658 if self.eat_keyword(keywords::Crate) {
5659 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
5662 let opt_abi = self.parse_opt_abi()?;
5664 if self.eat_keyword(keywords::Fn) {
5665 // EXTERN FUNCTION ITEM
5666 let fn_span = self.prev_span;
5667 let abi = opt_abi.unwrap_or(Abi::C);
5668 let (ident, item_, extra_attrs) =
5669 self.parse_item_fn(Unsafety::Normal,
5670 respan(fn_span, Constness::NotConst),
5672 let prev_span = self.prev_span;
5673 let item = self.mk_item(lo.to(prev_span),
5677 maybe_append(attrs, extra_attrs));
5678 return Ok(Some(item));
5679 } else if self.check(&token::OpenDelim(token::Brace)) {
5680 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
5686 if self.eat_keyword(keywords::Static) {
5688 let m = if self.eat_keyword(keywords::Mut) {
5691 Mutability::Immutable
5693 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
5694 let prev_span = self.prev_span;
5695 let item = self.mk_item(lo.to(prev_span),
5699 maybe_append(attrs, extra_attrs));
5700 return Ok(Some(item));
5702 if self.eat_keyword(keywords::Const) {
5703 let const_span = self.prev_span;
5704 if self.check_keyword(keywords::Fn)
5705 || (self.check_keyword(keywords::Unsafe)
5706 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5707 // CONST FUNCTION ITEM
5708 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5714 let (ident, item_, extra_attrs) =
5715 self.parse_item_fn(unsafety,
5716 respan(const_span, Constness::Const),
5718 let prev_span = self.prev_span;
5719 let item = self.mk_item(lo.to(prev_span),
5723 maybe_append(attrs, extra_attrs));
5724 return Ok(Some(item));
5728 if self.eat_keyword(keywords::Mut) {
5729 let prev_span = self.prev_span;
5730 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
5731 .help("did you mean to declare a static?")
5734 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
5735 let prev_span = self.prev_span;
5736 let item = self.mk_item(lo.to(prev_span),
5740 maybe_append(attrs, extra_attrs));
5741 return Ok(Some(item));
5743 if self.check_keyword(keywords::Unsafe) &&
5744 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5746 // UNSAFE TRAIT ITEM
5747 self.expect_keyword(keywords::Unsafe)?;
5748 self.expect_keyword(keywords::Trait)?;
5749 let (ident, item_, extra_attrs) =
5750 self.parse_item_trait(ast::Unsafety::Unsafe)?;
5751 let prev_span = self.prev_span;
5752 let item = self.mk_item(lo.to(prev_span),
5756 maybe_append(attrs, extra_attrs));
5757 return Ok(Some(item));
5759 if self.check_keyword(keywords::Unsafe) &&
5760 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))
5763 self.expect_keyword(keywords::Unsafe)?;
5764 self.expect_keyword(keywords::Impl)?;
5765 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe)?;
5766 let prev_span = self.prev_span;
5767 let item = self.mk_item(lo.to(prev_span),
5771 maybe_append(attrs, extra_attrs));
5772 return Ok(Some(item));
5774 if self.check_keyword(keywords::Fn) {
5777 let fn_span = self.prev_span;
5778 let (ident, item_, extra_attrs) =
5779 self.parse_item_fn(Unsafety::Normal,
5780 respan(fn_span, Constness::NotConst),
5782 let prev_span = self.prev_span;
5783 let item = self.mk_item(lo.to(prev_span),
5787 maybe_append(attrs, extra_attrs));
5788 return Ok(Some(item));
5790 if self.check_keyword(keywords::Unsafe)
5791 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5792 // UNSAFE FUNCTION ITEM
5794 let abi = if self.eat_keyword(keywords::Extern) {
5795 self.parse_opt_abi()?.unwrap_or(Abi::C)
5799 self.expect_keyword(keywords::Fn)?;
5800 let fn_span = self.prev_span;
5801 let (ident, item_, extra_attrs) =
5802 self.parse_item_fn(Unsafety::Unsafe,
5803 respan(fn_span, Constness::NotConst),
5805 let prev_span = self.prev_span;
5806 let item = self.mk_item(lo.to(prev_span),
5810 maybe_append(attrs, extra_attrs));
5811 return Ok(Some(item));
5813 if self.eat_keyword(keywords::Mod) {
5815 let (ident, item_, extra_attrs) =
5816 self.parse_item_mod(&attrs[..])?;
5817 let prev_span = self.prev_span;
5818 let item = self.mk_item(lo.to(prev_span),
5822 maybe_append(attrs, extra_attrs));
5823 return Ok(Some(item));
5825 if self.eat_keyword(keywords::Type) {
5827 let (ident, item_, extra_attrs) = self.parse_item_type()?;
5828 let prev_span = self.prev_span;
5829 let item = self.mk_item(lo.to(prev_span),
5833 maybe_append(attrs, extra_attrs));
5834 return Ok(Some(item));
5836 if self.eat_keyword(keywords::Enum) {
5838 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
5839 let prev_span = self.prev_span;
5840 let item = self.mk_item(lo.to(prev_span),
5844 maybe_append(attrs, extra_attrs));
5845 return Ok(Some(item));
5847 if self.eat_keyword(keywords::Trait) {
5849 let (ident, item_, extra_attrs) =
5850 self.parse_item_trait(ast::Unsafety::Normal)?;
5851 let prev_span = self.prev_span;
5852 let item = self.mk_item(lo.to(prev_span),
5856 maybe_append(attrs, extra_attrs));
5857 return Ok(Some(item));
5859 if self.eat_keyword(keywords::Impl) {
5861 let (ident, item_, extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal)?;
5862 let prev_span = self.prev_span;
5863 let item = self.mk_item(lo.to(prev_span),
5867 maybe_append(attrs, extra_attrs));
5868 return Ok(Some(item));
5870 if self.eat_keyword(keywords::Struct) {
5872 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
5873 let prev_span = self.prev_span;
5874 let item = self.mk_item(lo.to(prev_span),
5878 maybe_append(attrs, extra_attrs));
5879 return Ok(Some(item));
5881 if self.is_union_item() {
5884 let (ident, item_, extra_attrs) = self.parse_item_union()?;
5885 let prev_span = self.prev_span;
5886 let item = self.mk_item(lo.to(prev_span),
5890 maybe_append(attrs, extra_attrs));
5891 return Ok(Some(item));
5893 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility)? {
5894 return Ok(Some(macro_def));
5897 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5900 /// Parse a foreign item.
5901 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
5902 let attrs = self.parse_outer_attributes()?;
5904 let visibility = self.parse_visibility(false)?;
5906 if self.check_keyword(keywords::Static) {
5907 // FOREIGN STATIC ITEM
5908 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
5910 if self.check_keyword(keywords::Fn) {
5911 // FOREIGN FUNCTION ITEM
5912 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
5915 // FIXME #5668: this will occur for a macro invocation:
5916 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
5918 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5924 /// This is the fall-through for parsing items.
5925 fn parse_macro_use_or_failure(
5927 attrs: Vec<Attribute> ,
5928 macros_allowed: bool,
5929 attributes_allowed: bool,
5931 visibility: Visibility
5932 ) -> PResult<'a, Option<P<Item>>> {
5933 if macros_allowed && self.token.is_path_start() {
5934 // MACRO INVOCATION ITEM
5936 let prev_span = self.prev_span;
5937 self.complain_if_pub_macro(&visibility, prev_span);
5939 let mac_lo = self.span;
5942 let pth = self.parse_path(PathStyle::Mod)?;
5943 self.expect(&token::Not)?;
5945 // a 'special' identifier (like what `macro_rules!` uses)
5946 // is optional. We should eventually unify invoc syntax
5948 let id = if self.token.is_ident() {
5951 keywords::Invalid.ident() // no special identifier
5953 // eat a matched-delimiter token tree:
5954 let (delim, tts) = self.expect_delimited_token_tree()?;
5955 if delim != token::Brace {
5956 if !self.eat(&token::Semi) {
5957 let prev_span = self.prev_span;
5958 self.span_err(prev_span,
5959 "macros that expand to items must either \
5960 be surrounded with braces or followed by \
5965 let hi = self.prev_span;
5966 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
5967 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
5968 return Ok(Some(item));
5971 // FAILURE TO PARSE ITEM
5973 Visibility::Inherited => {}
5975 let prev_span = self.prev_span;
5976 return Err(self.span_fatal(prev_span, "unmatched visibility `pub`"));
5980 if !attributes_allowed && !attrs.is_empty() {
5981 self.expected_item_err(&attrs);
5986 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
5987 let attrs = self.parse_outer_attributes()?;
5988 self.parse_item_(attrs, true, false)
5991 fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> {
5992 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
5993 &token::CloseDelim(token::Brace),
5994 SeqSep::trailing_allowed(token::Comma), |this| {
5996 let ident = if this.eat_keyword(keywords::SelfValue) {
5997 keywords::SelfValue.ident()
6001 let rename = this.parse_rename()?;
6002 let node = ast::PathListItem_ {
6005 id: ast::DUMMY_NODE_ID
6007 Ok(respan(lo.to(this.prev_span), node))
6012 fn is_import_coupler(&mut self) -> bool {
6013 self.check(&token::ModSep) &&
6014 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6015 *t == token::BinOp(token::Star))
6018 /// Matches ViewPath:
6019 /// MOD_SEP? non_global_path
6020 /// MOD_SEP? non_global_path as IDENT
6021 /// MOD_SEP? non_global_path MOD_SEP STAR
6022 /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE
6023 /// MOD_SEP? LBRACE item_seq RBRACE
6024 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
6026 if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) ||
6027 self.is_import_coupler() {
6028 // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`.
6029 self.eat(&token::ModSep);
6030 let prefix = ast::Path {
6031 segments: vec![PathSegment::crate_root()],
6032 span: lo.to(self.span),
6034 let view_path_kind = if self.eat(&token::BinOp(token::Star)) {
6035 ViewPathGlob(prefix)
6037 ViewPathList(prefix, self.parse_path_list_items()?)
6039 Ok(P(respan(lo.to(self.span), view_path_kind)))
6041 let prefix = self.parse_path(PathStyle::Mod)?.default_to_global();
6042 if self.is_import_coupler() {
6043 // `foo::bar::{a, b}` or `foo::bar::*`
6045 if self.check(&token::BinOp(token::Star)) {
6047 Ok(P(respan(lo.to(self.span), ViewPathGlob(prefix))))
6049 let items = self.parse_path_list_items()?;
6050 Ok(P(respan(lo.to(self.span), ViewPathList(prefix, items))))
6053 // `foo::bar` or `foo::bar as baz`
6054 let rename = self.parse_rename()?.
6055 unwrap_or(prefix.segments.last().unwrap().identifier);
6056 Ok(P(respan(lo.to(self.prev_span), ViewPathSimple(rename, prefix))))
6061 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6062 if self.eat_keyword(keywords::As) {
6063 self.parse_ident().map(Some)
6069 /// Parses a source module as a crate. This is the main
6070 /// entry point for the parser.
6071 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6074 attrs: self.parse_inner_attributes()?,
6075 module: self.parse_mod_items(&token::Eof, lo)?,
6076 span: lo.to(self.span),
6080 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6081 let ret = match self.token {
6082 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6083 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6090 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6091 match self.parse_optional_str() {
6092 Some((s, style, suf)) => {
6093 let sp = self.prev_span;
6094 self.expect_no_suffix(sp, "string literal", suf);
6097 _ => Err(self.fatal("expected string literal"))