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::{AngleBracketedParameterData, ParenthesizedParameterData, AttrStyle, BareFnTy};
13 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
15 use ast::{Mod, Arg, Arm, Attribute, BindingMode, TraitItemKind};
17 use ast::{BlockCheckMode, CaptureBy};
18 use ast::{Constness, Crate};
21 use ast::{Expr, ExprKind, RangeLimits};
22 use ast::{Field, FnDecl};
23 use ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
24 use ast::{Ident, ImplItem, Item, ItemKind};
25 use ast::{Lifetime, LifetimeDef, Lit, LitKind, UintTy};
27 use ast::MacStmtStyle;
29 use ast::{MutTy, Mutability};
30 use ast::{Pat, PatKind, PathSegment};
31 use ast::{PolyTraitRef, QSelf};
32 use ast::{Stmt, StmtKind};
33 use ast::{VariantData, StructField};
36 use ast::{TraitItem, TraitRef};
37 use ast::{Ty, TyKind, TypeBinding, TyParam, TyParamBounds};
38 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
39 use ast::{Visibility, WhereClause};
40 use ast::{BinOpKind, UnOp};
43 use codemap::{self, CodeMap, Spanned, respan};
44 use syntax_pos::{self, Span, BytePos};
45 use errors::{self, DiagnosticBuilder};
46 use parse::{self, classify, token};
47 use parse::common::SeqSep;
48 use parse::lexer::TokenAndSpan;
49 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
50 use parse::obsolete::ObsoleteSyntax;
51 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
52 use util::parser::{AssocOp, Fixity};
56 use tokenstream::{self, Delimited, ThinTokenStream, TokenTree, TokenStream};
57 use symbol::{Symbol, keywords};
61 use std::collections::HashSet;
63 use std::path::{self, Path, PathBuf};
67 pub flags Restrictions: u8 {
68 const RESTRICTION_STMT_EXPR = 1 << 0,
69 const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1,
73 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute> >);
75 /// How to parse a path.
76 #[derive(Copy, Clone, PartialEq)]
78 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
79 /// with something else. For example, in expressions `segment < ....` can be interpreted
80 /// as a comparison and `segment ( ....` can be interpreted as a function call.
81 /// In all such contexts the non-path interpretation is preferred by default for practical
82 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
83 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
85 /// In other contexts, notably in types, no ambiguity exists and paths can be written
86 /// without the disambiguator, e.g. `x<y>` - unambiguously a path.
87 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
89 /// A path with generic arguments disallowed, e.g. `foo::bar::Baz`, used in imports,
90 /// visibilities or attributes.
91 /// Technically, this variant is unnecessary and e.g. `Expr` can be used instead
92 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
93 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
94 /// tokens when something goes wrong.
98 #[derive(Clone, Copy, Debug, PartialEq)]
99 pub enum SemiColonMode {
104 #[derive(Clone, Copy, Debug, PartialEq)]
110 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
111 /// dropped into the token stream, which happens while parsing the result of
112 /// macro expansion). Placement of these is not as complex as I feared it would
113 /// be. The important thing is to make sure that lookahead doesn't balk at
114 /// `token::Interpolated` tokens.
115 macro_rules! maybe_whole_expr {
117 if let token::Interpolated(nt) = $p.token.clone() {
119 token::NtExpr(ref e) => {
121 return Ok((*e).clone());
123 token::NtPath(ref path) => {
126 let kind = ExprKind::Path(None, (*path).clone());
127 return Ok($p.mk_expr(span, kind, ThinVec::new()));
129 token::NtBlock(ref block) => {
132 let kind = ExprKind::Block((*block).clone());
133 return Ok($p.mk_expr(span, kind, ThinVec::new()));
141 /// As maybe_whole_expr, but for things other than expressions
142 macro_rules! maybe_whole {
143 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
144 if let token::Interpolated(nt) = $p.token.clone() {
145 if let token::$constructor($x) = nt.0.clone() {
153 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
155 if let Some(ref attrs) = rhs {
156 lhs.extend(attrs.iter().cloned())
161 #[derive(Debug, Clone, Copy, PartialEq)]
172 /* ident is handled by common.rs */
175 pub struct Parser<'a> {
176 pub sess: &'a ParseSess,
177 /// the current token:
178 pub token: token::Token,
179 /// the span of the current token:
181 /// the span of the previous token:
182 pub meta_var_span: Option<Span>,
184 /// the previous token kind
185 prev_token_kind: PrevTokenKind,
186 pub restrictions: Restrictions,
187 /// The set of seen errors about obsolete syntax. Used to suppress
188 /// extra detail when the same error is seen twice
189 pub obsolete_set: HashSet<ObsoleteSyntax>,
190 /// Used to determine the path to externally loaded source files
191 pub directory: Directory,
192 /// Whether to parse sub-modules in other files.
193 pub recurse_into_file_modules: bool,
194 /// Name of the root module this parser originated from. If `None`, then the
195 /// name is not known. This does not change while the parser is descending
196 /// into modules, and sub-parsers have new values for this name.
197 pub root_module_name: Option<String>,
198 pub expected_tokens: Vec<TokenType>,
199 token_cursor: TokenCursor,
200 pub desugar_doc_comments: bool,
201 /// Whether we should configure out of line modules as we parse.
208 frame: TokenCursorFrame,
209 stack: Vec<TokenCursorFrame>,
213 struct TokenCursorFrame {
214 delim: token::DelimToken,
217 tree_cursor: tokenstream::Cursor,
219 last_token: LastToken,
222 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
223 /// by the parser, and then that's transitively used to record the tokens that
224 /// each parse AST item is created with.
226 /// Right now this has two states, either collecting tokens or not collecting
227 /// tokens. If we're collecting tokens we just save everything off into a local
228 /// `Vec`. This should eventually though likely save tokens from the original
229 /// token stream and just use slicing of token streams to avoid creation of a
230 /// whole new vector.
232 /// The second state is where we're passively not recording tokens, but the last
233 /// token is still tracked for when we want to start recording tokens. This
234 /// "last token" means that when we start recording tokens we'll want to ensure
235 /// that this, the first token, is included in the output.
237 /// You can find some more example usage of this in the `collect_tokens` method
241 Collecting(Vec<TokenTree>),
242 Was(Option<TokenTree>),
245 impl TokenCursorFrame {
246 fn new(sp: Span, delimited: &Delimited) -> Self {
248 delim: delimited.delim,
250 open_delim: delimited.delim == token::NoDelim,
251 tree_cursor: delimited.stream().into_trees(),
252 close_delim: delimited.delim == token::NoDelim,
253 last_token: LastToken::Was(None),
259 fn next(&mut self) -> TokenAndSpan {
261 let tree = if !self.frame.open_delim {
262 self.frame.open_delim = true;
263 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
264 .open_tt(self.frame.span)
265 } else if let Some(tree) = self.frame.tree_cursor.next() {
267 } else if !self.frame.close_delim {
268 self.frame.close_delim = true;
269 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
270 .close_tt(self.frame.span)
271 } else if let Some(frame) = self.stack.pop() {
275 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
278 match self.frame.last_token {
279 LastToken::Collecting(ref mut v) => v.push(tree.clone()),
280 LastToken::Was(ref mut t) => *t = Some(tree.clone()),
284 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
285 TokenTree::Delimited(sp, ref delimited) => {
286 let frame = TokenCursorFrame::new(sp, delimited);
287 self.stack.push(mem::replace(&mut self.frame, frame));
293 fn next_desugared(&mut self) -> TokenAndSpan {
294 let (sp, name) = match self.next() {
295 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
299 let stripped = strip_doc_comment_decoration(&name.as_str());
301 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
302 // required to wrap the text.
303 let mut num_of_hashes = 0;
305 for ch in stripped.chars() {
308 '#' if count > 0 => count + 1,
311 num_of_hashes = cmp::max(num_of_hashes, count);
314 let body = TokenTree::Delimited(sp, Delimited {
315 delim: token::Bracket,
316 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"))),
317 TokenTree::Token(sp, token::Eq),
318 TokenTree::Token(sp, token::Literal(
319 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
320 .iter().cloned().collect::<TokenStream>().into(),
323 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
324 delim: token::NoDelim,
325 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
326 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
327 .iter().cloned().collect::<TokenStream>().into()
329 [TokenTree::Token(sp, token::Pound), body]
330 .iter().cloned().collect::<TokenStream>().into()
338 #[derive(PartialEq, Eq, Clone)]
341 Keyword(keywords::Keyword),
350 fn to_string(&self) -> String {
352 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
353 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
354 TokenType::Operator => "an operator".to_string(),
355 TokenType::Lifetime => "lifetime".to_string(),
356 TokenType::Ident => "identifier".to_string(),
357 TokenType::Path => "path".to_string(),
358 TokenType::Type => "type".to_string(),
363 fn is_ident_or_underscore(t: &token::Token) -> bool {
364 t.is_ident() || *t == token::Underscore
367 /// Information about the path to a module.
368 pub struct ModulePath {
370 pub path_exists: bool,
371 pub result: Result<ModulePathSuccess, Error>,
374 pub struct ModulePathSuccess {
376 pub directory_ownership: DirectoryOwnership,
380 pub struct ModulePathError {
382 pub help_msg: String,
386 FileNotFoundForModule {
388 default_path: String,
389 secondary_path: String,
394 default_path: String,
395 secondary_path: String,
398 InclusiveRangeWithNoEnd,
402 pub fn span_err(self, sp: Span, handler: &errors::Handler) -> DiagnosticBuilder {
404 Error::FileNotFoundForModule { ref mod_name,
408 let mut err = struct_span_err!(handler, sp, E0583,
409 "file not found for module `{}`", mod_name);
410 err.help(&format!("name the file either {} or {} inside the directory {:?}",
416 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
417 let mut err = struct_span_err!(handler, sp, E0584,
418 "file for module `{}` found at both {} and {}",
422 err.help("delete or rename one of them to remove the ambiguity");
425 Error::UselessDocComment => {
426 let mut err = struct_span_err!(handler, sp, E0585,
427 "found a documentation comment that doesn't document anything");
428 err.help("doc comments must come before what they document, maybe a comment was \
429 intended with `//`?");
432 Error::InclusiveRangeWithNoEnd => {
433 let mut err = struct_span_err!(handler, sp, E0586,
434 "inclusive range with no end");
435 err.help("inclusive ranges must be bounded at the end (`...b` or `a...b`)");
445 AttributesParsed(ThinVec<Attribute>),
446 AlreadyParsed(P<Expr>),
449 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
450 fn from(o: Option<ThinVec<Attribute>>) -> Self {
451 if let Some(attrs) = o {
452 LhsExpr::AttributesParsed(attrs)
454 LhsExpr::NotYetParsed
459 impl From<P<Expr>> for LhsExpr {
460 fn from(expr: P<Expr>) -> Self {
461 LhsExpr::AlreadyParsed(expr)
465 /// Create a placeholder argument.
466 fn dummy_arg(span: Span) -> Arg {
467 let spanned = Spanned {
469 node: keywords::Invalid.ident()
472 id: ast::DUMMY_NODE_ID,
473 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), spanned, None),
479 id: ast::DUMMY_NODE_ID
481 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
484 impl<'a> Parser<'a> {
485 pub fn new(sess: &'a ParseSess,
487 directory: Option<Directory>,
488 recurse_into_file_modules: bool,
489 desugar_doc_comments: bool)
491 let mut parser = Parser {
493 token: token::Underscore,
494 span: syntax_pos::DUMMY_SP,
495 prev_span: syntax_pos::DUMMY_SP,
497 prev_token_kind: PrevTokenKind::Other,
498 restrictions: Restrictions::empty(),
499 obsolete_set: HashSet::new(),
500 recurse_into_file_modules,
501 directory: Directory { path: PathBuf::new(), ownership: DirectoryOwnership::Owned },
502 root_module_name: None,
503 expected_tokens: Vec::new(),
504 token_cursor: TokenCursor {
505 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
506 delim: token::NoDelim,
511 desugar_doc_comments,
515 let tok = parser.next_tok();
516 parser.token = tok.tok;
517 parser.span = tok.sp;
519 if let Some(directory) = directory {
520 parser.directory = directory;
521 } else if parser.span != syntax_pos::DUMMY_SP {
522 parser.directory.path = PathBuf::from(sess.codemap().span_to_filename(parser.span));
523 parser.directory.path.pop();
526 parser.process_potential_macro_variable();
530 fn next_tok(&mut self) -> TokenAndSpan {
531 let mut next = if self.desugar_doc_comments {
532 self.token_cursor.next_desugared()
534 self.token_cursor.next()
536 if next.sp == syntax_pos::DUMMY_SP {
537 next.sp = self.prev_span;
542 /// Convert a token to a string using self's reader
543 pub fn token_to_string(token: &token::Token) -> String {
544 pprust::token_to_string(token)
547 /// Convert the current token to a string using self's reader
548 pub fn this_token_to_string(&self) -> String {
549 Parser::token_to_string(&self.token)
552 pub fn this_token_descr(&self) -> String {
553 let prefix = match &self.token {
554 t if t.is_special_ident() => "reserved identifier ",
555 t if t.is_used_keyword() => "keyword ",
556 t if t.is_unused_keyword() => "reserved keyword ",
559 format!("{}`{}`", prefix, self.this_token_to_string())
562 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
563 let token_str = Parser::token_to_string(t);
564 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
567 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
568 match self.expect_one_of(&[], &[]) {
570 Ok(_) => unreachable!(),
574 /// Expect and consume the token t. Signal an error if
575 /// the next token is not t.
576 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
577 if self.expected_tokens.is_empty() {
578 if self.token == *t {
582 let token_str = Parser::token_to_string(t);
583 let this_token_str = self.this_token_to_string();
584 Err(self.fatal(&format!("expected `{}`, found `{}`",
589 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
593 /// Expect next token to be edible or inedible token. If edible,
594 /// then consume it; if inedible, then return without consuming
595 /// anything. Signal a fatal error if next token is unexpected.
596 pub fn expect_one_of(&mut self,
597 edible: &[token::Token],
598 inedible: &[token::Token]) -> PResult<'a, ()>{
599 fn tokens_to_string(tokens: &[TokenType]) -> String {
600 let mut i = tokens.iter();
601 // This might be a sign we need a connect method on Iterator.
603 .map_or("".to_string(), |t| t.to_string());
604 i.enumerate().fold(b, |mut b, (i, a)| {
605 if tokens.len() > 2 && i == tokens.len() - 2 {
607 } else if tokens.len() == 2 && i == tokens.len() - 2 {
612 b.push_str(&a.to_string());
616 if edible.contains(&self.token) {
619 } else if inedible.contains(&self.token) {
620 // leave it in the input
623 let mut expected = edible.iter()
624 .map(|x| TokenType::Token(x.clone()))
625 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
626 .chain(self.expected_tokens.iter().cloned())
627 .collect::<Vec<_>>();
628 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
630 let expect = tokens_to_string(&expected[..]);
631 let actual = self.this_token_to_string();
632 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
633 let short_expect = if expected.len() > 6 {
634 format!("{} possible tokens", expected.len())
638 (format!("expected one of {}, found `{}`", expect, actual),
639 (self.prev_span.next_point(), format!("expected one of {} here", short_expect)))
640 } else if expected.is_empty() {
641 (format!("unexpected token: `{}`", actual),
642 (self.prev_span, "unexpected token after this".to_string()))
644 (format!("expected {}, found `{}`", expect, actual),
645 (self.prev_span.next_point(), format!("expected {} here", expect)))
647 let mut err = self.fatal(&msg_exp);
648 let sp = if self.token == token::Token::Eof {
649 // This is EOF, don't want to point at the following char, but rather the last token
654 if self.span.contains(sp) {
655 err.span_label(self.span, label_exp);
657 err.span_label(sp, label_exp);
658 err.span_label(self.span, "unexpected token");
664 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
665 fn interpolated_or_expr_span(&self,
666 expr: PResult<'a, P<Expr>>)
667 -> PResult<'a, (Span, P<Expr>)> {
669 if self.prev_token_kind == PrevTokenKind::Interpolated {
677 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
680 if self.token.is_reserved_ident() {
681 self.span_err(self.span, &format!("expected identifier, found {}",
682 self.this_token_descr()));
688 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
689 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
691 let mut err = self.fatal(&format!("expected identifier, found `{}`",
692 self.this_token_to_string()));
693 if self.token == token::Underscore {
694 err.note("`_` is a wildcard pattern, not an identifier");
702 /// Check if the next token is `tok`, and return `true` if so.
704 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
706 pub fn check(&mut self, tok: &token::Token) -> bool {
707 let is_present = self.token == *tok;
708 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
712 /// Consume token 'tok' if it exists. Returns true if the given
713 /// token was present, false otherwise.
714 pub fn eat(&mut self, tok: &token::Token) -> bool {
715 let is_present = self.check(tok);
716 if is_present { self.bump() }
720 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
721 self.expected_tokens.push(TokenType::Keyword(kw));
722 self.token.is_keyword(kw)
725 /// If the next token is the given keyword, eat it and return
726 /// true. Otherwise, return false.
727 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
728 if self.check_keyword(kw) {
736 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
737 if self.token.is_keyword(kw) {
745 /// If the given word is not a keyword, signal an error.
746 /// If the next token is not the given word, signal an error.
747 /// Otherwise, eat it.
748 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
749 if !self.eat_keyword(kw) {
756 fn check_ident(&mut self) -> bool {
757 if self.token.is_ident() {
760 self.expected_tokens.push(TokenType::Ident);
765 fn check_path(&mut self) -> bool {
766 if self.token.is_path_start() {
769 self.expected_tokens.push(TokenType::Path);
774 fn check_type(&mut self) -> bool {
775 if self.token.can_begin_type() {
778 self.expected_tokens.push(TokenType::Type);
783 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
784 /// `&` and continue. If an `&` is not seen, signal an error.
785 fn expect_and(&mut self) -> PResult<'a, ()> {
786 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
788 token::BinOp(token::And) => {
793 let span = self.span.with_lo(self.span.lo() + BytePos(1));
794 Ok(self.bump_with(token::BinOp(token::And), span))
796 _ => self.unexpected()
800 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
802 None => {/* everything ok */}
804 let text = suf.as_str();
806 self.span_bug(sp, "found empty literal suffix in Some")
808 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
813 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
814 /// `<` and continue. If a `<` is not seen, return false.
816 /// This is meant to be used when parsing generics on a path to get the
818 fn eat_lt(&mut self) -> bool {
819 self.expected_tokens.push(TokenType::Token(token::Lt));
825 token::BinOp(token::Shl) => {
826 let span = self.span.with_lo(self.span.lo() + BytePos(1));
827 self.bump_with(token::Lt, span);
834 fn expect_lt(&mut self) -> PResult<'a, ()> {
842 /// Expect and consume a GT. if a >> is seen, replace it
843 /// with a single > and continue. If a GT is not seen,
845 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
846 self.expected_tokens.push(TokenType::Token(token::Gt));
852 token::BinOp(token::Shr) => {
853 let span = self.span.with_lo(self.span.lo() + BytePos(1));
854 Ok(self.bump_with(token::Gt, span))
856 token::BinOpEq(token::Shr) => {
857 let span = self.span.with_lo(self.span.lo() + BytePos(1));
858 Ok(self.bump_with(token::Ge, span))
861 let span = self.span.with_lo(self.span.lo() + BytePos(1));
862 Ok(self.bump_with(token::Eq, span))
864 _ => self.unexpected()
868 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
869 sep: Option<token::Token>,
871 -> PResult<'a, (Vec<T>, bool)>
872 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
874 let mut v = Vec::new();
875 // This loop works by alternating back and forth between parsing types
876 // and commas. For example, given a string `A, B,>`, the parser would
877 // first parse `A`, then a comma, then `B`, then a comma. After that it
878 // would encounter a `>` and stop. This lets the parser handle trailing
879 // commas in generic parameters, because it can stop either after
880 // parsing a type or after parsing a comma.
882 if self.check(&token::Gt)
883 || self.token == token::BinOp(token::Shr)
884 || self.token == token::Ge
885 || self.token == token::BinOpEq(token::Shr) {
891 Some(result) => v.push(result),
892 None => return Ok((v, true))
895 if let Some(t) = sep.as_ref() {
901 return Ok((v, false));
904 /// Parse a sequence bracketed by '<' and '>', stopping
906 pub fn parse_seq_to_before_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 (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
913 |p| Ok(Some(f(p)?)))?;
918 pub fn parse_seq_to_gt<T, F>(&mut self,
919 sep: Option<token::Token>,
921 -> PResult<'a, Vec<T>> where
922 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
924 let v = self.parse_seq_to_before_gt(sep, f)?;
929 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
930 sep: Option<token::Token>,
932 -> PResult<'a, (Vec<T>, bool)> where
933 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
935 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
939 return Ok((v, returned));
942 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
943 /// passes through any errors encountered. Used for error recovery.
944 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
945 let handler = self.diagnostic();
947 self.parse_seq_to_before_tokens(kets,
949 |p| Ok(p.parse_token_tree()),
950 |mut e| handler.cancel(&mut e));
953 /// Parse a sequence, including the closing delimiter. The function
954 /// f must consume tokens until reaching the next separator or
956 pub fn parse_seq_to_end<T, F>(&mut self,
960 -> PResult<'a, Vec<T>> where
961 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
963 let val = self.parse_seq_to_before_end(ket, sep, f);
968 /// Parse a sequence, not including the closing delimiter. The function
969 /// f must consume tokens until reaching the next separator or
971 pub fn parse_seq_to_before_end<T, F>(&mut self,
976 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
978 self.parse_seq_to_before_tokens(&[ket], sep, f, |mut e| e.emit())
981 // `fe` is an error handler.
982 fn parse_seq_to_before_tokens<T, F, Fe>(&mut self,
983 kets: &[&token::Token],
988 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
989 Fe: FnMut(DiagnosticBuilder)
991 let mut first: bool = true;
993 while !kets.contains(&&self.token) {
995 token::CloseDelim(..) | token::Eof => break,
998 if let Some(ref t) = sep.sep {
1002 if let Err(e) = self.expect(t) {
1008 if sep.trailing_sep_allowed && kets.iter().any(|k| self.check(k)) {
1024 /// Parse a sequence, including the closing delimiter. The function
1025 /// f must consume tokens until reaching the next separator or
1026 /// closing bracket.
1027 pub fn parse_unspanned_seq<T, F>(&mut self,
1032 -> PResult<'a, Vec<T>> where
1033 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1036 let result = self.parse_seq_to_before_end(ket, sep, f);
1037 if self.token == *ket {
1043 // NB: Do not use this function unless you actually plan to place the
1044 // spanned list in the AST.
1045 pub fn parse_seq<T, F>(&mut self,
1050 -> PResult<'a, Spanned<Vec<T>>> where
1051 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1055 let result = self.parse_seq_to_before_end(ket, sep, f);
1058 Ok(respan(lo.to(hi), result))
1061 /// Advance the parser by one token
1062 pub fn bump(&mut self) {
1063 if self.prev_token_kind == PrevTokenKind::Eof {
1064 // Bumping after EOF is a bad sign, usually an infinite loop.
1065 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1068 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1070 // Record last token kind for possible error recovery.
1071 self.prev_token_kind = match self.token {
1072 token::DocComment(..) => PrevTokenKind::DocComment,
1073 token::Comma => PrevTokenKind::Comma,
1074 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1075 token::Interpolated(..) => PrevTokenKind::Interpolated,
1076 token::Eof => PrevTokenKind::Eof,
1077 token::Ident(..) => PrevTokenKind::Ident,
1078 _ => PrevTokenKind::Other,
1081 let next = self.next_tok();
1082 self.span = next.sp;
1083 self.token = next.tok;
1084 self.expected_tokens.clear();
1085 // check after each token
1086 self.process_potential_macro_variable();
1089 /// Advance the parser using provided token as a next one. Use this when
1090 /// consuming a part of a token. For example a single `<` from `<<`.
1091 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1092 self.prev_span = self.span.with_hi(span.lo());
1093 // It would be incorrect to record the kind of the current token, but
1094 // fortunately for tokens currently using `bump_with`, the
1095 // prev_token_kind will be of no use anyway.
1096 self.prev_token_kind = PrevTokenKind::Other;
1099 self.expected_tokens.clear();
1102 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1103 F: FnOnce(&token::Token) -> R,
1106 return f(&self.token)
1109 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1110 Some(tree) => match tree {
1111 TokenTree::Token(_, tok) => tok,
1112 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1114 None => token::CloseDelim(self.token_cursor.frame.delim),
1117 fn look_ahead_span(&self, dist: usize) -> Span {
1122 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1123 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1124 None => self.look_ahead_span(dist - 1),
1127 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1128 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1130 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1131 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1133 pub fn span_fatal_err(&self, sp: Span, err: Error) -> DiagnosticBuilder<'a> {
1134 err.span_err(sp, self.diagnostic())
1136 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1137 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1141 pub fn bug(&self, m: &str) -> ! {
1142 self.sess.span_diagnostic.span_bug(self.span, m)
1144 pub fn warn(&self, m: &str) {
1145 self.sess.span_diagnostic.span_warn(self.span, m)
1147 pub fn span_warn(&self, sp: Span, m: &str) {
1148 self.sess.span_diagnostic.span_warn(sp, m)
1150 pub fn span_err(&self, sp: Span, m: &str) {
1151 self.sess.span_diagnostic.span_err(sp, m)
1153 pub fn span_err_help(&self, sp: Span, m: &str, h: &str) {
1154 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1158 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1159 self.sess.span_diagnostic.span_bug(sp, m)
1161 pub fn abort_if_errors(&self) {
1162 self.sess.span_diagnostic.abort_if_errors();
1165 fn cancel(&self, err: &mut DiagnosticBuilder) {
1166 self.sess.span_diagnostic.cancel(err)
1169 pub fn diagnostic(&self) -> &'a errors::Handler {
1170 &self.sess.span_diagnostic
1173 /// Is the current token one of the keywords that signals a bare function
1175 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1176 self.check_keyword(keywords::Fn) ||
1177 self.check_keyword(keywords::Unsafe) ||
1178 self.check_keyword(keywords::Extern)
1181 fn get_label(&mut self) -> ast::Ident {
1183 token::Lifetime(ref ident) => *ident,
1184 _ => self.bug("not a lifetime"),
1188 /// parse a TyKind::BareFn type:
1189 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<LifetimeDef>)
1190 -> PResult<'a, TyKind> {
1193 [unsafe] [extern "ABI"] fn (S) -> T
1203 let unsafety = self.parse_unsafety()?;
1204 let abi = if self.eat_keyword(keywords::Extern) {
1205 self.parse_opt_abi()?.unwrap_or(Abi::C)
1210 self.expect_keyword(keywords::Fn)?;
1211 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1212 let ret_ty = self.parse_ret_ty()?;
1213 let decl = P(FnDecl {
1218 Ok(TyKind::BareFn(P(BareFnTy {
1221 lifetimes: lifetime_defs,
1226 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1227 if self.eat_keyword(keywords::Unsafe) {
1228 return Ok(Unsafety::Unsafe);
1230 return Ok(Unsafety::Normal);
1234 /// Parse the items in a trait declaration
1235 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1236 maybe_whole!(self, NtTraitItem, |x| x);
1237 let attrs = self.parse_outer_attributes()?;
1238 let (mut item, tokens) = self.collect_tokens(|this| {
1239 this.parse_trait_item_(at_end, attrs)
1241 // See `parse_item` for why this clause is here.
1242 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1243 item.tokens = Some(tokens);
1248 fn parse_trait_item_(&mut self,
1250 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1253 let (name, node) = if self.eat_keyword(keywords::Type) {
1254 let TyParam {ident, bounds, default, ..} = self.parse_ty_param(vec![])?;
1255 self.expect(&token::Semi)?;
1256 (ident, TraitItemKind::Type(bounds, default))
1257 } else if self.is_const_item() {
1258 self.expect_keyword(keywords::Const)?;
1259 let ident = self.parse_ident()?;
1260 self.expect(&token::Colon)?;
1261 let ty = self.parse_ty()?;
1262 let default = if self.check(&token::Eq) {
1264 let expr = self.parse_expr()?;
1265 self.expect(&token::Semi)?;
1268 self.expect(&token::Semi)?;
1271 (ident, TraitItemKind::Const(ty, default))
1272 } else if self.token.is_path_start() {
1273 // trait item macro.
1274 // code copied from parse_macro_use_or_failure... abstraction!
1275 let prev_span = self.prev_span;
1277 let pth = self.parse_path(PathStyle::Mod)?;
1279 if pth.segments.len() == 1 {
1280 if !self.eat(&token::Not) {
1281 return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1284 self.expect(&token::Not)?;
1287 // eat a matched-delimiter token tree:
1288 let (delim, tts) = self.expect_delimited_token_tree()?;
1289 if delim != token::Brace {
1290 self.expect(&token::Semi)?
1293 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1294 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac))
1296 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
1298 let ident = self.parse_ident()?;
1299 let mut generics = self.parse_generics()?;
1301 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1302 // This is somewhat dubious; We don't want to allow
1303 // argument names to be left off if there is a
1305 p.parse_arg_general(false)
1308 generics.where_clause = self.parse_where_clause()?;
1309 let sig = ast::MethodSig {
1317 let body = match self.token {
1321 debug!("parse_trait_methods(): parsing required method");
1324 token::OpenDelim(token::Brace) => {
1325 debug!("parse_trait_methods(): parsing provided method");
1327 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1328 attrs.extend(inner_attrs.iter().cloned());
1332 let token_str = self.this_token_to_string();
1333 return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1336 (ident, ast::TraitItemKind::Method(sig, body))
1340 id: ast::DUMMY_NODE_ID,
1344 span: lo.to(self.prev_span),
1349 /// Parse optional return type [ -> TY ] in function decl
1350 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1351 if self.eat(&token::RArrow) {
1352 Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
1354 Ok(FunctionRetTy::Default(self.span.with_hi(self.span.lo())))
1359 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1360 self.parse_ty_common(true)
1363 /// Parse a type in restricted contexts where `+` is not permitted.
1364 /// Example 1: `&'a TYPE`
1365 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1366 /// Example 2: `value1 as TYPE + value2`
1367 /// `+` is prohibited to avoid interactions with expression grammar.
1368 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1369 self.parse_ty_common(false)
1372 fn parse_ty_common(&mut self, allow_plus: bool) -> PResult<'a, P<Ty>> {
1373 maybe_whole!(self, NtTy, |x| x);
1376 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1377 // `(TYPE)` is a parenthesized type.
1378 // `(TYPE,)` is a tuple with a single field of type TYPE.
1379 let mut ts = vec![];
1380 let mut last_comma = false;
1381 while self.token != token::CloseDelim(token::Paren) {
1382 ts.push(self.parse_ty()?);
1383 if self.eat(&token::Comma) {
1390 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1391 self.expect(&token::CloseDelim(token::Paren))?;
1393 if ts.len() == 1 && !last_comma {
1394 let ty = ts.into_iter().nth(0).unwrap().unwrap();
1395 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1397 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1398 TyKind::Path(None, ref path) if maybe_bounds => {
1399 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1401 TyKind::TraitObject(ref bounds)
1402 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1403 let path = match bounds[0] {
1404 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1405 _ => self.bug("unexpected lifetime bound"),
1407 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1410 _ => TyKind::Paren(P(ty))
1415 } else if self.eat(&token::Not) {
1418 } else if self.eat(&token::BinOp(token::Star)) {
1420 TyKind::Ptr(self.parse_ptr()?)
1421 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1423 let t = self.parse_ty()?;
1424 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1425 let t = match self.maybe_parse_fixed_length_of_vec()? {
1426 None => TyKind::Slice(t),
1427 Some(suffix) => TyKind::Array(t, suffix),
1429 self.expect(&token::CloseDelim(token::Bracket))?;
1431 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1434 self.parse_borrowed_pointee()?
1435 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1437 // In order to not be ambiguous, the type must be surrounded by parens.
1438 self.expect(&token::OpenDelim(token::Paren))?;
1439 let e = self.parse_expr()?;
1440 self.expect(&token::CloseDelim(token::Paren))?;
1442 } else if self.eat(&token::Underscore) {
1443 // A type to be inferred `_`
1445 } else if self.eat_lt() {
1447 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1448 TyKind::Path(Some(qself), path)
1449 } else if self.token.is_path_start() {
1451 let path = self.parse_path(PathStyle::Type)?;
1452 if self.eat(&token::Not) {
1453 // Macro invocation in type position
1454 let (_, tts) = self.expect_delimited_token_tree()?;
1455 TyKind::Mac(respan(lo.to(self.span), Mac_ { path: path, tts: tts }))
1457 // Just a type path or bound list (trait object type) starting with a trait.
1459 // `Trait1 + Trait2 + 'a`
1460 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1461 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1463 TyKind::Path(None, path)
1466 } else if self.token_is_bare_fn_keyword() {
1467 // Function pointer type
1468 self.parse_ty_bare_fn(Vec::new())?
1469 } else if self.check_keyword(keywords::For) {
1470 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1471 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1472 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1474 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1475 if self.token_is_bare_fn_keyword() {
1476 self.parse_ty_bare_fn(lifetime_defs)?
1478 let path = self.parse_path(PathStyle::Type)?;
1479 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1480 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1482 } else if self.eat_keyword(keywords::Impl) {
1483 // FIXME: figure out priority of `+` in `impl Trait1 + Trait2` (#34511).
1484 TyKind::ImplTrait(self.parse_ty_param_bounds()?)
1485 } else if self.check(&token::Question) ||
1486 self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)){
1487 // Bound list (trait object type)
1488 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?)
1490 let msg = format!("expected type, found {}", self.this_token_descr());
1491 return Err(self.fatal(&msg));
1494 let span = lo.to(self.prev_span);
1495 let ty = Ty { node: node, span: span, id: ast::DUMMY_NODE_ID };
1497 // Try to recover from use of `+` with incorrect priority.
1498 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1503 fn parse_remaining_bounds(&mut self, lifetime_defs: Vec<LifetimeDef>, path: ast::Path,
1504 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1505 let poly_trait_ref = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
1506 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1509 bounds.append(&mut self.parse_ty_param_bounds()?);
1511 Ok(TyKind::TraitObject(bounds))
1514 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1515 // Do not add `+` to expected tokens.
1516 if !allow_plus || self.token != token::BinOp(token::Plus) {
1521 let bounds = self.parse_ty_param_bounds()?;
1522 let sum_span = ty.span.to(self.prev_span);
1524 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1525 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1528 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1529 let sum_with_parens = pprust::to_string(|s| {
1530 use print::pprust::PrintState;
1533 s.print_opt_lifetime(lifetime)?;
1534 s.print_mutability(mut_ty.mutbl)?;
1536 s.print_type(&mut_ty.ty)?;
1537 s.print_bounds(" +", &bounds)?;
1540 err.span_suggestion(sum_span, "try adding parentheses", sum_with_parens);
1542 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1543 err.span_label(sum_span, "perhaps you forgot parentheses?");
1546 err.span_label(sum_span, "expected a path");
1553 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1554 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1555 let mutbl = self.parse_mutability();
1556 let ty = self.parse_ty_no_plus()?;
1557 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1560 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1561 let mutbl = if self.eat_keyword(keywords::Mut) {
1563 } else if self.eat_keyword(keywords::Const) {
1564 Mutability::Immutable
1566 let span = self.prev_span;
1568 "expected mut or const in raw pointer type (use \
1569 `*mut T` or `*const T` as appropriate)");
1570 Mutability::Immutable
1572 let t = self.parse_ty_no_plus()?;
1573 Ok(MutTy { ty: t, mutbl: mutbl })
1576 pub fn is_named_argument(&mut self) -> bool {
1577 let offset = match self.token {
1578 token::BinOp(token::And) |
1580 _ if self.token.is_keyword(keywords::Mut) => 1,
1584 debug!("parser is_named_argument offset:{}", offset);
1587 is_ident_or_underscore(&self.token)
1588 && self.look_ahead(1, |t| *t == token::Colon)
1590 self.look_ahead(offset, |t| is_ident_or_underscore(t))
1591 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1595 /// This version of parse arg doesn't necessarily require
1596 /// identifier names.
1597 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1598 maybe_whole!(self, NtArg, |x| x);
1600 let pat = if require_name || self.is_named_argument() {
1601 debug!("parse_arg_general parse_pat (require_name:{})",
1603 let pat = self.parse_pat()?;
1605 self.expect(&token::Colon)?;
1608 debug!("parse_arg_general ident_to_pat");
1609 let sp = self.prev_span;
1610 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1612 id: ast::DUMMY_NODE_ID,
1613 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1619 let t = self.parse_ty()?;
1624 id: ast::DUMMY_NODE_ID,
1628 /// Parse a single function argument
1629 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1630 self.parse_arg_general(true)
1633 /// Parse an argument in a lambda header e.g. |arg, arg|
1634 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1635 let pat = self.parse_pat()?;
1636 let t = if self.eat(&token::Colon) {
1640 id: ast::DUMMY_NODE_ID,
1641 node: TyKind::Infer,
1648 id: ast::DUMMY_NODE_ID
1652 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1653 if self.eat(&token::Semi) {
1654 Ok(Some(self.parse_expr()?))
1660 /// Matches token_lit = LIT_INTEGER | ...
1661 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1662 let out = match self.token {
1663 token::Interpolated(ref nt) => match nt.0 {
1664 token::NtExpr(ref v) => match v.node {
1665 ExprKind::Lit(ref lit) => { lit.node.clone() }
1666 _ => { return self.unexpected_last(&self.token); }
1668 _ => { return self.unexpected_last(&self.token); }
1670 token::Literal(lit, suf) => {
1671 let diag = Some((self.span, &self.sess.span_diagnostic));
1672 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1676 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1681 _ => { return self.unexpected_last(&self.token); }
1688 /// Matches lit = true | false | token_lit
1689 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1691 let lit = if self.eat_keyword(keywords::True) {
1693 } else if self.eat_keyword(keywords::False) {
1694 LitKind::Bool(false)
1696 let lit = self.parse_lit_token()?;
1699 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1702 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1703 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1704 maybe_whole_expr!(self);
1706 let minus_lo = self.span;
1707 let minus_present = self.eat(&token::BinOp(token::Minus));
1709 let literal = P(self.parse_lit()?);
1710 let hi = self.prev_span;
1711 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1714 let minus_hi = self.prev_span;
1715 let unary = self.mk_unary(UnOp::Neg, expr);
1716 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1722 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1724 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1728 _ => self.parse_ident(),
1732 /// Parses qualified path.
1733 /// Assumes that the leading `<` has been parsed already.
1735 /// `qualified_path = <type [as trait_ref]>::path`
1739 /// `<T as U>::F::a<S>` (without disambiguator)
1740 /// `<T as U>::F::a::<S>` (with disambiguator)
1741 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1742 let lo = self.prev_span;
1743 let ty = self.parse_ty()?;
1744 let mut path = if self.eat_keyword(keywords::As) {
1745 self.parse_path(PathStyle::Type)?
1747 ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP }
1749 self.expect(&token::Gt)?;
1750 self.expect(&token::ModSep)?;
1752 let qself = QSelf { ty, position: path.segments.len() };
1753 self.parse_path_segments(&mut path.segments, style, true)?;
1755 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1758 /// Parses simple paths.
1760 /// `path = [::] segment+`
1761 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1764 /// `a::b::C<D>` (without disambiguator)
1765 /// `a::b::C::<D>` (with disambiguator)
1766 /// `Fn(Args)` (without disambiguator)
1767 /// `Fn::(Args)` (with disambiguator)
1768 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1769 self.parse_path_common(style, true)
1772 pub fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1773 -> PResult<'a, ast::Path> {
1774 maybe_whole!(self, NtPath, |path| {
1775 if style == PathStyle::Mod &&
1776 path.segments.iter().any(|segment| segment.parameters.is_some()) {
1777 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1782 let lo = self.meta_var_span.unwrap_or(self.span);
1783 let mut segments = Vec::new();
1784 if self.eat(&token::ModSep) {
1785 segments.push(PathSegment::crate_root(lo));
1787 self.parse_path_segments(&mut segments, style, enable_warning)?;
1789 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1792 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1793 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1794 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1795 let meta_ident = match self.token {
1796 token::Interpolated(ref nt) => match nt.0 {
1797 token::NtMeta(ref meta) => match meta.node {
1798 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
1805 if let Some(ident) = meta_ident {
1807 return Ok(ast::Path::from_ident(self.prev_span, ident));
1809 self.parse_path(style)
1812 fn parse_path_segments(&mut self, segments: &mut Vec<PathSegment>, style: PathStyle,
1813 enable_warning: bool) -> PResult<'a, ()> {
1815 segments.push(self.parse_path_segment(style, enable_warning)?);
1817 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1823 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
1824 -> PResult<'a, PathSegment> {
1825 let ident_span = self.span;
1826 let ident = self.parse_path_segment_ident()?;
1828 let is_args_start = |token: &token::Token| match *token {
1829 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
1832 let check_args_start = |this: &mut Self| {
1833 this.expected_tokens.extend_from_slice(
1834 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1836 is_args_start(&this.token)
1839 Ok(if style == PathStyle::Type && check_args_start(self) ||
1840 style != PathStyle::Mod && self.check(&token::ModSep)
1841 && self.look_ahead(1, |t| is_args_start(t)) {
1842 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1844 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
1845 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
1846 .span_label(self.prev_span, "try removing `::`").emit();
1849 let parameters = if self.eat_lt() {
1851 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1853 let span = lo.to(self.prev_span);
1854 AngleBracketedParameterData { lifetimes, types, bindings, span }.into()
1858 let inputs = self.parse_seq_to_end(&token::CloseDelim(token::Paren),
1859 SeqSep::trailing_allowed(token::Comma),
1861 let output = if self.eat(&token::RArrow) {
1862 Some(self.parse_ty_no_plus()?)
1866 let span = lo.to(self.prev_span);
1867 ParenthesizedParameterData { inputs, output, span }.into()
1870 PathSegment { identifier: ident, span: ident_span, parameters }
1872 // Generic arguments are not found.
1873 PathSegment::from_ident(ident, ident_span)
1877 fn check_lifetime(&mut self) -> bool {
1878 self.expected_tokens.push(TokenType::Lifetime);
1879 self.token.is_lifetime()
1882 /// Parse single lifetime 'a or panic.
1883 fn expect_lifetime(&mut self) -> Lifetime {
1885 token::Lifetime(ident) => {
1886 let ident_span = self.span;
1888 Lifetime { ident: ident, span: ident_span, id: ast::DUMMY_NODE_ID }
1890 _ => self.span_bug(self.span, "not a lifetime")
1894 /// Parse mutability (`mut` or nothing).
1895 fn parse_mutability(&mut self) -> Mutability {
1896 if self.eat_keyword(keywords::Mut) {
1899 Mutability::Immutable
1903 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1904 if let token::Literal(token::Integer(name), None) = self.token {
1906 Ok(Ident::with_empty_ctxt(name))
1912 /// Parse ident (COLON expr)?
1913 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1914 let attrs = self.parse_outer_attributes()?;
1918 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1919 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1920 let fieldname = self.parse_field_name()?;
1922 hi = self.prev_span;
1923 (fieldname, self.parse_expr()?, false)
1925 let fieldname = self.parse_ident()?;
1926 hi = self.prev_span;
1928 // Mimic `x: x` for the `x` field shorthand.
1929 let path = ast::Path::from_ident(lo.to(hi), fieldname);
1930 (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
1933 ident: respan(lo.to(hi), fieldname),
1934 span: lo.to(expr.span),
1937 attrs: attrs.into(),
1941 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1943 id: ast::DUMMY_NODE_ID,
1946 attrs: attrs.into(),
1950 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
1951 ExprKind::Unary(unop, expr)
1954 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1955 ExprKind::Binary(binop, lhs, rhs)
1958 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
1959 ExprKind::Call(f, args)
1962 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
1963 ExprKind::Index(expr, idx)
1966 pub fn mk_range(&mut self,
1967 start: Option<P<Expr>>,
1968 end: Option<P<Expr>>,
1969 limits: RangeLimits)
1970 -> PResult<'a, ast::ExprKind> {
1971 if end.is_none() && limits == RangeLimits::Closed {
1972 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
1974 Ok(ExprKind::Range(start, end, limits))
1978 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
1979 ExprKind::TupField(expr, idx)
1982 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1983 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1984 ExprKind::AssignOp(binop, lhs, rhs)
1987 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
1989 id: ast::DUMMY_NODE_ID,
1990 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
1996 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
1997 let span = &self.span;
1998 let lv_lit = P(codemap::Spanned {
1999 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2004 id: ast::DUMMY_NODE_ID,
2005 node: ExprKind::Lit(lv_lit),
2011 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2013 token::OpenDelim(delim) => match self.parse_token_tree() {
2014 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2015 _ => unreachable!(),
2017 _ => Err(self.fatal("expected open delimiter")),
2021 /// At the bottom (top?) of the precedence hierarchy,
2022 /// parse things like parenthesized exprs,
2023 /// macros, return, etc.
2025 /// NB: This does not parse outer attributes,
2026 /// and is private because it only works
2027 /// correctly if called from parse_dot_or_call_expr().
2028 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2029 maybe_whole_expr!(self);
2031 // Outer attributes are already parsed and will be
2032 // added to the return value after the fact.
2034 // Therefore, prevent sub-parser from parsing
2035 // attributes by giving them a empty "already parsed" list.
2036 let mut attrs = ThinVec::new();
2039 let mut hi = self.span;
2043 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2045 token::OpenDelim(token::Paren) => {
2048 attrs.extend(self.parse_inner_attributes()?);
2050 // (e) is parenthesized e
2051 // (e,) is a tuple with only one field, e
2052 let mut es = vec![];
2053 let mut trailing_comma = false;
2054 while self.token != token::CloseDelim(token::Paren) {
2055 es.push(self.parse_expr()?);
2056 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2057 if self.check(&token::Comma) {
2058 trailing_comma = true;
2062 trailing_comma = false;
2068 hi = self.prev_span;
2069 let span = lo.to(hi);
2070 return if es.len() == 1 && !trailing_comma {
2071 Ok(self.mk_expr(span, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2073 Ok(self.mk_expr(span, ExprKind::Tup(es), attrs))
2076 token::OpenDelim(token::Brace) => {
2077 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2079 token::BinOp(token::Or) | token::OrOr => {
2081 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2083 token::OpenDelim(token::Bracket) => {
2086 attrs.extend(self.parse_inner_attributes()?);
2088 if self.check(&token::CloseDelim(token::Bracket)) {
2091 ex = ExprKind::Array(Vec::new());
2094 let first_expr = self.parse_expr()?;
2095 if self.check(&token::Semi) {
2096 // Repeating array syntax: [ 0; 512 ]
2098 let count = self.parse_expr()?;
2099 self.expect(&token::CloseDelim(token::Bracket))?;
2100 ex = ExprKind::Repeat(first_expr, count);
2101 } else if self.check(&token::Comma) {
2102 // Vector with two or more elements.
2104 let remaining_exprs = self.parse_seq_to_end(
2105 &token::CloseDelim(token::Bracket),
2106 SeqSep::trailing_allowed(token::Comma),
2107 |p| Ok(p.parse_expr()?)
2109 let mut exprs = vec![first_expr];
2110 exprs.extend(remaining_exprs);
2111 ex = ExprKind::Array(exprs);
2113 // Vector with one element.
2114 self.expect(&token::CloseDelim(token::Bracket))?;
2115 ex = ExprKind::Array(vec![first_expr]);
2118 hi = self.prev_span;
2122 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2124 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2126 if self.eat_keyword(keywords::Move) {
2127 let lo = self.prev_span;
2128 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2130 if self.eat_keyword(keywords::If) {
2131 return self.parse_if_expr(attrs);
2133 if self.eat_keyword(keywords::For) {
2134 let lo = self.prev_span;
2135 return self.parse_for_expr(None, lo, attrs);
2137 if self.eat_keyword(keywords::While) {
2138 let lo = self.prev_span;
2139 return self.parse_while_expr(None, lo, attrs);
2141 if self.token.is_lifetime() {
2142 let label = Spanned { node: self.get_label(),
2146 self.expect(&token::Colon)?;
2147 if self.eat_keyword(keywords::While) {
2148 return self.parse_while_expr(Some(label), lo, attrs)
2150 if self.eat_keyword(keywords::For) {
2151 return self.parse_for_expr(Some(label), lo, attrs)
2153 if self.eat_keyword(keywords::Loop) {
2154 return self.parse_loop_expr(Some(label), lo, attrs)
2156 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2158 if self.eat_keyword(keywords::Loop) {
2159 let lo = self.prev_span;
2160 return self.parse_loop_expr(None, lo, attrs);
2162 if self.eat_keyword(keywords::Continue) {
2163 let ex = if self.token.is_lifetime() {
2164 let ex = ExprKind::Continue(Some(Spanned{
2165 node: self.get_label(),
2171 ExprKind::Continue(None)
2173 let hi = self.prev_span;
2174 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2176 if self.eat_keyword(keywords::Match) {
2177 return self.parse_match_expr(attrs);
2179 if self.eat_keyword(keywords::Unsafe) {
2180 return self.parse_block_expr(
2182 BlockCheckMode::Unsafe(ast::UserProvided),
2185 if self.is_catch_expr() {
2187 assert!(self.eat_keyword(keywords::Do));
2188 assert!(self.eat_keyword(keywords::Catch));
2189 return self.parse_catch_expr(lo, attrs);
2191 if self.eat_keyword(keywords::Return) {
2192 if self.token.can_begin_expr() {
2193 let e = self.parse_expr()?;
2195 ex = ExprKind::Ret(Some(e));
2197 ex = ExprKind::Ret(None);
2199 } else if self.eat_keyword(keywords::Break) {
2200 let lt = if self.token.is_lifetime() {
2201 let spanned_lt = Spanned {
2202 node: self.get_label(),
2210 let e = if self.token.can_begin_expr()
2211 && !(self.token == token::OpenDelim(token::Brace)
2212 && self.restrictions.contains(
2213 RESTRICTION_NO_STRUCT_LITERAL)) {
2214 Some(self.parse_expr()?)
2218 ex = ExprKind::Break(lt, e);
2219 hi = self.prev_span;
2220 } else if self.eat_keyword(keywords::Yield) {
2221 if self.token.can_begin_expr() {
2222 let e = self.parse_expr()?;
2224 ex = ExprKind::Yield(Some(e));
2226 ex = ExprKind::Yield(None);
2228 } else if self.token.is_keyword(keywords::Let) {
2229 // Catch this syntax error here, instead of in `parse_ident`, so
2230 // that we can explicitly mention that let is not to be used as an expression
2231 let mut db = self.fatal("expected expression, found statement (`let`)");
2232 db.note("variable declaration using `let` is a statement");
2234 } else if self.token.is_path_start() {
2235 let pth = self.parse_path(PathStyle::Expr)?;
2237 // `!`, as an operator, is prefix, so we know this isn't that
2238 if self.eat(&token::Not) {
2239 // MACRO INVOCATION expression
2240 let (_, tts) = self.expect_delimited_token_tree()?;
2241 let hi = self.prev_span;
2242 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2244 if self.check(&token::OpenDelim(token::Brace)) {
2245 // This is a struct literal, unless we're prohibited
2246 // from parsing struct literals here.
2247 let prohibited = self.restrictions.contains(
2248 RESTRICTION_NO_STRUCT_LITERAL
2251 return self.parse_struct_expr(lo, pth, attrs);
2256 ex = ExprKind::Path(None, pth);
2258 match self.parse_lit() {
2261 ex = ExprKind::Lit(P(lit));
2264 self.cancel(&mut err);
2265 let msg = format!("expected expression, found {}",
2266 self.this_token_descr());
2267 return Err(self.fatal(&msg));
2274 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2277 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2278 -> PResult<'a, P<Expr>> {
2280 let mut fields = Vec::new();
2281 let mut base = None;
2283 attrs.extend(self.parse_inner_attributes()?);
2285 while self.token != token::CloseDelim(token::Brace) {
2286 if self.eat(&token::DotDot) {
2287 match self.parse_expr() {
2293 self.recover_stmt();
2299 match self.parse_field() {
2300 Ok(f) => fields.push(f),
2303 self.recover_stmt();
2308 match self.expect_one_of(&[token::Comma],
2309 &[token::CloseDelim(token::Brace)]) {
2313 self.recover_stmt();
2319 let span = lo.to(self.span);
2320 self.expect(&token::CloseDelim(token::Brace))?;
2321 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2324 fn parse_or_use_outer_attributes(&mut self,
2325 already_parsed_attrs: Option<ThinVec<Attribute>>)
2326 -> PResult<'a, ThinVec<Attribute>> {
2327 if let Some(attrs) = already_parsed_attrs {
2330 self.parse_outer_attributes().map(|a| a.into())
2334 /// Parse a block or unsafe block
2335 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2336 outer_attrs: ThinVec<Attribute>)
2337 -> PResult<'a, P<Expr>> {
2338 self.expect(&token::OpenDelim(token::Brace))?;
2340 let mut attrs = outer_attrs;
2341 attrs.extend(self.parse_inner_attributes()?);
2343 let blk = self.parse_block_tail(lo, blk_mode)?;
2344 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2347 /// parse a.b or a(13) or a[4] or just a
2348 pub fn parse_dot_or_call_expr(&mut self,
2349 already_parsed_attrs: Option<ThinVec<Attribute>>)
2350 -> PResult<'a, P<Expr>> {
2351 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2353 let b = self.parse_bottom_expr();
2354 let (span, b) = self.interpolated_or_expr_span(b)?;
2355 self.parse_dot_or_call_expr_with(b, span, attrs)
2358 pub fn parse_dot_or_call_expr_with(&mut self,
2361 mut attrs: ThinVec<Attribute>)
2362 -> PResult<'a, P<Expr>> {
2363 // Stitch the list of outer attributes onto the return value.
2364 // A little bit ugly, but the best way given the current code
2366 self.parse_dot_or_call_expr_with_(e0, lo)
2368 expr.map(|mut expr| {
2369 attrs.extend::<Vec<_>>(expr.attrs.into());
2372 ExprKind::If(..) | ExprKind::IfLet(..) => {
2373 if !expr.attrs.is_empty() {
2374 // Just point to the first attribute in there...
2375 let span = expr.attrs[0].span;
2378 "attributes are not yet allowed on `if` \
2389 // Assuming we have just parsed `.`, continue parsing into an expression.
2390 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2391 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2392 Ok(match self.token {
2393 token::OpenDelim(token::Paren) => {
2394 // Method call `expr.f()`
2395 let mut args = self.parse_unspanned_seq(
2396 &token::OpenDelim(token::Paren),
2397 &token::CloseDelim(token::Paren),
2398 SeqSep::trailing_allowed(token::Comma),
2399 |p| Ok(p.parse_expr()?)
2401 args.insert(0, self_arg);
2403 let span = lo.to(self.prev_span);
2404 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2407 // Field access `expr.f`
2408 if let Some(parameters) = segment.parameters {
2409 self.span_err(parameters.span(),
2410 "field expressions may not have generic arguments");
2413 let span = lo.to(self.prev_span);
2414 let ident = respan(segment.span, segment.identifier);
2415 self.mk_expr(span, ExprKind::Field(self_arg, ident), ThinVec::new())
2420 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2425 while self.eat(&token::Question) {
2426 let hi = self.prev_span;
2427 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2431 if self.eat(&token::Dot) {
2433 token::Ident(..) => {
2434 e = self.parse_dot_suffix(e, lo)?;
2436 token::Literal(token::Integer(n), suf) => {
2439 // A tuple index may not have a suffix
2440 self.expect_no_suffix(sp, "tuple index", suf);
2442 let dot_span = self.prev_span;
2446 let index = n.as_str().parse::<usize>().ok();
2449 let id = respan(dot_span.to(hi), n);
2450 let field = self.mk_tup_field(e, id);
2451 e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2454 let prev_span = self.prev_span;
2455 self.span_err(prev_span, "invalid tuple or tuple struct index");
2459 token::Literal(token::Float(n), _suf) => {
2461 let fstr = n.as_str();
2462 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2463 &format!("unexpected token: `{}`", n));
2464 err.span_label(self.prev_span, "unexpected token");
2465 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2466 let float = match fstr.parse::<f64>().ok() {
2470 let sugg = pprust::to_string(|s| {
2471 use print::pprust::PrintState;
2475 s.print_usize(float.trunc() as usize)?;
2478 s.s.word(fstr.splitn(2, ".").last().unwrap())
2480 err.span_suggestion(
2481 lo.to(self.prev_span),
2482 "try parenthesizing the first index",
2489 // FIXME Could factor this out into non_fatal_unexpected or something.
2490 let actual = self.this_token_to_string();
2491 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2496 if self.expr_is_complete(&e) { break; }
2499 token::OpenDelim(token::Paren) => {
2500 let es = self.parse_unspanned_seq(
2501 &token::OpenDelim(token::Paren),
2502 &token::CloseDelim(token::Paren),
2503 SeqSep::trailing_allowed(token::Comma),
2504 |p| Ok(p.parse_expr()?)
2506 hi = self.prev_span;
2508 let nd = self.mk_call(e, es);
2509 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2513 // Could be either an index expression or a slicing expression.
2514 token::OpenDelim(token::Bracket) => {
2516 let ix = self.parse_expr()?;
2518 self.expect(&token::CloseDelim(token::Bracket))?;
2519 let index = self.mk_index(e, ix);
2520 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2528 pub fn process_potential_macro_variable(&mut self) {
2529 let ident = match self.token {
2530 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2531 self.look_ahead(1, |t| t.is_ident()) => {
2533 let name = match self.token { token::Ident(ident) => ident, _ => unreachable!() };
2534 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2537 token::Interpolated(ref nt) => {
2538 self.meta_var_span = Some(self.span);
2540 token::NtIdent(ident) => ident,
2546 self.token = token::Ident(ident.node);
2547 self.span = ident.span;
2550 /// parse a single token tree from the input.
2551 pub fn parse_token_tree(&mut self) -> TokenTree {
2553 token::OpenDelim(..) => {
2554 let frame = mem::replace(&mut self.token_cursor.frame,
2555 self.token_cursor.stack.pop().unwrap());
2556 self.span = frame.span;
2558 TokenTree::Delimited(frame.span, Delimited {
2560 tts: frame.tree_cursor.original_stream().into(),
2563 token::CloseDelim(_) | token::Eof => unreachable!(),
2565 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2567 TokenTree::Token(span, token)
2572 // parse a stream of tokens into a list of TokenTree's,
2574 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2575 let mut tts = Vec::new();
2576 while self.token != token::Eof {
2577 tts.push(self.parse_token_tree());
2582 pub fn parse_tokens(&mut self) -> TokenStream {
2583 let mut result = Vec::new();
2586 token::Eof | token::CloseDelim(..) => break,
2587 _ => result.push(self.parse_token_tree().into()),
2590 TokenStream::concat(result)
2593 /// Parse a prefix-unary-operator expr
2594 pub fn parse_prefix_expr(&mut self,
2595 already_parsed_attrs: Option<ThinVec<Attribute>>)
2596 -> PResult<'a, P<Expr>> {
2597 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2599 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2600 let (hi, ex) = match self.token {
2603 let e = self.parse_prefix_expr(None);
2604 let (span, e) = self.interpolated_or_expr_span(e)?;
2605 (span, self.mk_unary(UnOp::Not, e))
2607 // Suggest `!` for bitwise negation when encountering a `~`
2610 let e = self.parse_prefix_expr(None);
2611 let (span, e) = self.interpolated_or_expr_span(e)?;
2612 let span_of_tilde = lo;
2613 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2614 "`~` can not be used as a unary operator");
2615 err.span_label(span_of_tilde, "did you mean `!`?");
2616 err.help("use `!` instead of `~` if you meant to perform bitwise negation");
2618 (span, self.mk_unary(UnOp::Not, e))
2620 token::BinOp(token::Minus) => {
2622 let e = self.parse_prefix_expr(None);
2623 let (span, e) = self.interpolated_or_expr_span(e)?;
2624 (span, self.mk_unary(UnOp::Neg, e))
2626 token::BinOp(token::Star) => {
2628 let e = self.parse_prefix_expr(None);
2629 let (span, e) = self.interpolated_or_expr_span(e)?;
2630 (span, self.mk_unary(UnOp::Deref, e))
2632 token::BinOp(token::And) | token::AndAnd => {
2634 let m = self.parse_mutability();
2635 let e = self.parse_prefix_expr(None);
2636 let (span, e) = self.interpolated_or_expr_span(e)?;
2637 (span, ExprKind::AddrOf(m, e))
2639 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2641 let place = self.parse_expr_res(
2642 RESTRICTION_NO_STRUCT_LITERAL,
2645 let blk = self.parse_block()?;
2646 let span = blk.span;
2647 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2648 (span, ExprKind::InPlace(place, blk_expr))
2650 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2652 let e = self.parse_prefix_expr(None);
2653 let (span, e) = self.interpolated_or_expr_span(e)?;
2654 (span, ExprKind::Box(e))
2656 _ => return self.parse_dot_or_call_expr(Some(attrs))
2658 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2661 /// Parse an associative expression
2663 /// This parses an expression accounting for associativity and precedence of the operators in
2665 pub fn parse_assoc_expr(&mut self,
2666 already_parsed_attrs: Option<ThinVec<Attribute>>)
2667 -> PResult<'a, P<Expr>> {
2668 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2671 /// Parse an associative expression with operators of at least `min_prec` precedence
2672 pub fn parse_assoc_expr_with(&mut self,
2675 -> PResult<'a, P<Expr>> {
2676 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2679 let attrs = match lhs {
2680 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2683 if self.token == token::DotDot || self.token == token::DotDotDot {
2684 return self.parse_prefix_range_expr(attrs);
2686 self.parse_prefix_expr(attrs)?
2690 if self.expr_is_complete(&lhs) {
2691 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2694 self.expected_tokens.push(TokenType::Operator);
2695 while let Some(op) = AssocOp::from_token(&self.token) {
2697 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2698 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2699 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2700 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2701 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2702 (PrevTokenKind::Interpolated, _) => self.prev_span,
2703 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2704 if path.segments.len() == 1 => self.prev_span,
2708 let cur_op_span = self.span;
2709 let restrictions = if op.is_assign_like() {
2710 self.restrictions & RESTRICTION_NO_STRUCT_LITERAL
2714 if op.precedence() < min_prec {
2718 if op.is_comparison() {
2719 self.check_no_chained_comparison(&lhs, &op);
2722 if op == AssocOp::As {
2723 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2725 } else if op == AssocOp::Colon {
2726 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2729 err.span_label(self.span,
2730 "expecting a type here because of type ascription");
2731 let cm = self.sess.codemap();
2732 let cur_pos = cm.lookup_char_pos(self.span.lo());
2733 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
2734 if cur_pos.line != op_pos.line {
2735 err.span_suggestion_short(cur_op_span,
2736 "did you mean to use `;` here?",
2743 } else if op == AssocOp::DotDot || op == AssocOp::DotDotDot {
2744 // If we didn’t have to handle `x..`/`x...`, it would be pretty easy to
2745 // generalise it to the Fixity::None code.
2747 // We have 2 alternatives here: `x..y`/`x...y` and `x..`/`x...` The other
2748 // two variants are handled with `parse_prefix_range_expr` call above.
2749 let rhs = if self.is_at_start_of_range_notation_rhs() {
2750 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2751 LhsExpr::NotYetParsed)?)
2755 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2760 let limits = if op == AssocOp::DotDot {
2761 RangeLimits::HalfOpen
2766 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2767 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2771 let rhs = match op.fixity() {
2772 Fixity::Right => self.with_res(
2773 restrictions - RESTRICTION_STMT_EXPR,
2775 this.parse_assoc_expr_with(op.precedence(),
2776 LhsExpr::NotYetParsed)
2778 Fixity::Left => self.with_res(
2779 restrictions - RESTRICTION_STMT_EXPR,
2781 this.parse_assoc_expr_with(op.precedence() + 1,
2782 LhsExpr::NotYetParsed)
2784 // We currently have no non-associative operators that are not handled above by
2785 // the special cases. The code is here only for future convenience.
2786 Fixity::None => self.with_res(
2787 restrictions - RESTRICTION_STMT_EXPR,
2789 this.parse_assoc_expr_with(op.precedence() + 1,
2790 LhsExpr::NotYetParsed)
2794 let span = lhs_span.to(rhs.span);
2796 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2797 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2798 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2799 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2800 AssocOp::Greater | AssocOp::GreaterEqual => {
2801 let ast_op = op.to_ast_binop().unwrap();
2802 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2803 self.mk_expr(span, binary, ThinVec::new())
2806 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2808 self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
2809 AssocOp::AssignOp(k) => {
2811 token::Plus => BinOpKind::Add,
2812 token::Minus => BinOpKind::Sub,
2813 token::Star => BinOpKind::Mul,
2814 token::Slash => BinOpKind::Div,
2815 token::Percent => BinOpKind::Rem,
2816 token::Caret => BinOpKind::BitXor,
2817 token::And => BinOpKind::BitAnd,
2818 token::Or => BinOpKind::BitOr,
2819 token::Shl => BinOpKind::Shl,
2820 token::Shr => BinOpKind::Shr,
2822 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2823 self.mk_expr(span, aopexpr, ThinVec::new())
2825 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotDot => {
2826 self.bug("As, Colon, DotDot or DotDotDot branch reached")
2830 if op.fixity() == Fixity::None { break }
2835 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
2836 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
2837 -> PResult<'a, P<Expr>> {
2838 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
2839 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
2842 // Save the state of the parser before parsing type normally, in case there is a
2843 // LessThan comparison after this cast.
2844 let parser_snapshot_before_type = self.clone();
2845 match self.parse_ty_no_plus() {
2847 Ok(mk_expr(self, rhs))
2849 Err(mut type_err) => {
2850 // Rewind to before attempting to parse the type with generics, to recover
2851 // from situations like `x as usize < y` in which we first tried to parse
2852 // `usize < y` as a type with generic arguments.
2853 let parser_snapshot_after_type = self.clone();
2854 mem::replace(self, parser_snapshot_before_type);
2856 match self.parse_path(PathStyle::Expr) {
2858 // Successfully parsed the type path leaving a `<` yet to parse.
2861 // Report non-fatal diagnostics, keep `x as usize` as an expression
2862 // in AST and continue parsing.
2863 let msg = format!("`<` is interpreted as a start of generic \
2864 arguments for `{}`, not a comparison", path);
2865 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
2866 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
2867 "interpreted as generic arguments");
2868 err.span_label(self.span, "not interpreted as comparison");
2870 let expr = mk_expr(self, P(Ty {
2872 node: TyKind::Path(None, path),
2873 id: ast::DUMMY_NODE_ID
2876 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
2877 .unwrap_or(pprust::expr_to_string(&expr));
2878 err.span_suggestion(expr.span,
2879 "try comparing the casted value",
2880 format!("({})", expr_str));
2885 Err(mut path_err) => {
2886 // Couldn't parse as a path, return original error and parser state.
2888 mem::replace(self, parser_snapshot_after_type);
2896 /// Produce an error if comparison operators are chained (RFC #558).
2897 /// We only need to check lhs, not rhs, because all comparison ops
2898 /// have same precedence and are left-associative
2899 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2900 debug_assert!(outer_op.is_comparison(),
2901 "check_no_chained_comparison: {:?} is not comparison",
2904 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2905 // respan to include both operators
2906 let op_span = op.span.to(self.span);
2907 let mut err = self.diagnostic().struct_span_err(op_span,
2908 "chained comparison operators require parentheses");
2909 if op.node == BinOpKind::Lt &&
2910 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
2911 *outer_op == AssocOp::Greater // even in a case like the following:
2912 { // Foo<Bar<Baz<Qux, ()>>>
2914 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2922 /// Parse prefix-forms of range notation: `..expr`, `..`, `...expr`
2923 fn parse_prefix_range_expr(&mut self,
2924 already_parsed_attrs: Option<ThinVec<Attribute>>)
2925 -> PResult<'a, P<Expr>> {
2926 debug_assert!(self.token == token::DotDot || self.token == token::DotDotDot,
2927 "parse_prefix_range_expr: token {:?} is not DotDot or DotDotDot",
2929 let tok = self.token.clone();
2930 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2932 let mut hi = self.span;
2934 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2935 // RHS must be parsed with more associativity than the dots.
2936 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
2937 Some(self.parse_assoc_expr_with(next_prec,
2938 LhsExpr::NotYetParsed)
2946 let limits = if tok == token::DotDot {
2947 RangeLimits::HalfOpen
2952 let r = try!(self.mk_range(None,
2955 Ok(self.mk_expr(lo.to(hi), r, attrs))
2958 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2959 if self.token.can_begin_expr() {
2960 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2961 if self.token == token::OpenDelim(token::Brace) {
2962 return !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL);
2970 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2971 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
2972 if self.check_keyword(keywords::Let) {
2973 return self.parse_if_let_expr(attrs);
2975 let lo = self.prev_span;
2976 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
2978 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
2979 // verify that the last statement is either an implicit return (no `;`) or an explicit
2980 // return. This won't catch blocks with an explicit `return`, but that would be caught by
2981 // the dead code lint.
2982 if self.eat_keyword(keywords::Else) || !cond.returns() {
2983 let sp = lo.next_point();
2984 let mut err = self.diagnostic()
2985 .struct_span_err(sp, "missing condition for `if` statemement");
2986 err.span_label(sp, "expected if condition here");
2989 let thn = self.parse_block()?;
2990 let mut els: Option<P<Expr>> = None;
2991 let mut hi = thn.span;
2992 if self.eat_keyword(keywords::Else) {
2993 let elexpr = self.parse_else_expr()?;
2997 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3000 /// Parse an 'if let' expression ('if' token already eaten)
3001 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3002 -> PResult<'a, P<Expr>> {
3003 let lo = self.prev_span;
3004 self.expect_keyword(keywords::Let)?;
3005 let pat = self.parse_pat()?;
3006 self.expect(&token::Eq)?;
3007 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3008 let thn = self.parse_block()?;
3009 let (hi, els) = if self.eat_keyword(keywords::Else) {
3010 let expr = self.parse_else_expr()?;
3011 (expr.span, Some(expr))
3015 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
3018 // `move |args| expr`
3019 pub fn parse_lambda_expr(&mut self,
3021 capture_clause: CaptureBy,
3022 attrs: ThinVec<Attribute>)
3023 -> PResult<'a, P<Expr>>
3025 let decl = self.parse_fn_block_decl()?;
3026 let decl_hi = self.prev_span;
3027 let body = match decl.output {
3028 FunctionRetTy::Default(_) => {
3029 let restrictions = self.restrictions - RESTRICTION_STMT_EXPR;
3030 self.parse_expr_res(restrictions, None)?
3033 // If an explicit return type is given, require a
3034 // block to appear (RFC 968).
3035 let body_lo = self.span;
3036 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3042 ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3046 // `else` token already eaten
3047 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3048 if self.eat_keyword(keywords::If) {
3049 return self.parse_if_expr(ThinVec::new());
3051 let blk = self.parse_block()?;
3052 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3056 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3057 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3059 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3060 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3062 let pat = self.parse_pat()?;
3063 self.expect_keyword(keywords::In)?;
3064 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3065 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3066 attrs.extend(iattrs);
3068 let hi = self.prev_span;
3069 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3072 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3073 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3075 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3076 if self.token.is_keyword(keywords::Let) {
3077 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3079 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3080 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3081 attrs.extend(iattrs);
3082 let span = span_lo.to(body.span);
3083 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3086 /// Parse a 'while let' expression ('while' token already eaten)
3087 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3089 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3090 self.expect_keyword(keywords::Let)?;
3091 let pat = self.parse_pat()?;
3092 self.expect(&token::Eq)?;
3093 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3094 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3095 attrs.extend(iattrs);
3096 let span = span_lo.to(body.span);
3097 return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3100 // parse `loop {...}`, `loop` token already eaten
3101 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3103 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3104 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3105 attrs.extend(iattrs);
3106 let span = span_lo.to(body.span);
3107 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3110 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3111 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3112 -> PResult<'a, P<Expr>>
3114 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3115 attrs.extend(iattrs);
3116 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3119 // `match` token already eaten
3120 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3121 let match_span = self.prev_span;
3122 let lo = self.prev_span;
3123 let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL,
3125 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3126 if self.token == token::Token::Semi {
3127 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3131 attrs.extend(self.parse_inner_attributes()?);
3133 let mut arms: Vec<Arm> = Vec::new();
3134 while self.token != token::CloseDelim(token::Brace) {
3135 match self.parse_arm() {
3136 Ok(arm) => arms.push(arm),
3138 // Recover by skipping to the end of the block.
3140 self.recover_stmt();
3141 let span = lo.to(self.span);
3142 if self.token == token::CloseDelim(token::Brace) {
3145 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3151 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3154 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3155 maybe_whole!(self, NtArm, |x| x);
3157 let attrs = self.parse_outer_attributes()?;
3158 // Allow a '|' before the pats (RFC 1925)
3159 let beginning_vert = if self.eat(&token::BinOp(token::Or)) {
3160 Some(self.prev_span)
3164 let pats = self.parse_pats()?;
3165 let guard = if self.eat_keyword(keywords::If) {
3166 Some(self.parse_expr()?)
3170 self.expect(&token::FatArrow)?;
3171 let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR, None)?;
3173 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3174 && self.token != token::CloseDelim(token::Brace);
3177 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3179 self.eat(&token::Comma);
3191 /// Parse an expression
3192 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3193 self.parse_expr_res(Restrictions::empty(), None)
3196 /// Evaluate the closure with restrictions in place.
3198 /// After the closure is evaluated, restrictions are reset.
3199 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3200 where F: FnOnce(&mut Self) -> T
3202 let old = self.restrictions;
3203 self.restrictions = r;
3205 self.restrictions = old;
3210 /// Parse an expression, subject to the given restrictions
3211 pub fn parse_expr_res(&mut self, r: Restrictions,
3212 already_parsed_attrs: Option<ThinVec<Attribute>>)
3213 -> PResult<'a, P<Expr>> {
3214 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3217 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3218 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3219 if self.check(&token::Eq) {
3221 Ok(Some(self.parse_expr()?))
3227 /// Parse patterns, separated by '|' s
3228 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3229 let mut pats = Vec::new();
3231 pats.push(self.parse_pat()?);
3232 if self.check(&token::BinOp(token::Or)) { self.bump();}
3233 else { return Ok(pats); }
3237 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3238 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3239 let mut fields = vec![];
3240 let mut ddpos = None;
3242 while !self.check(&token::CloseDelim(token::Paren)) {
3243 if ddpos.is_none() && self.eat(&token::DotDot) {
3244 ddpos = Some(fields.len());
3245 if self.eat(&token::Comma) {
3246 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3247 fields.push(self.parse_pat()?);
3249 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3250 // Emit a friendly error, ignore `..` and continue parsing
3251 self.span_err(self.prev_span, "`..` can only be used once per \
3252 tuple or tuple struct pattern");
3254 fields.push(self.parse_pat()?);
3257 if !self.check(&token::CloseDelim(token::Paren)) ||
3258 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3259 self.expect(&token::Comma)?;
3266 fn parse_pat_vec_elements(
3268 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3269 let mut before = Vec::new();
3270 let mut slice = None;
3271 let mut after = Vec::new();
3272 let mut first = true;
3273 let mut before_slice = true;
3275 while self.token != token::CloseDelim(token::Bracket) {
3279 self.expect(&token::Comma)?;
3281 if self.token == token::CloseDelim(token::Bracket)
3282 && (before_slice || !after.is_empty()) {
3288 if self.eat(&token::DotDot) {
3290 if self.check(&token::Comma) ||
3291 self.check(&token::CloseDelim(token::Bracket)) {
3292 slice = Some(P(ast::Pat {
3293 id: ast::DUMMY_NODE_ID,
3294 node: PatKind::Wild,
3297 before_slice = false;
3303 let subpat = self.parse_pat()?;
3304 if before_slice && self.eat(&token::DotDot) {
3305 slice = Some(subpat);
3306 before_slice = false;
3307 } else if before_slice {
3308 before.push(subpat);
3314 Ok((before, slice, after))
3317 /// Parse the fields of a struct-like pattern
3318 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3319 let mut fields = Vec::new();
3320 let mut etc = false;
3321 let mut first = true;
3322 while self.token != token::CloseDelim(token::Brace) {
3326 self.expect(&token::Comma)?;
3327 // accept trailing commas
3328 if self.check(&token::CloseDelim(token::Brace)) { break }
3331 let attrs = self.parse_outer_attributes()?;
3335 if self.check(&token::DotDot) {
3337 if self.token != token::CloseDelim(token::Brace) {
3338 let token_str = self.this_token_to_string();
3339 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3346 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3347 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3348 // Parsing a pattern of the form "fieldname: pat"
3349 let fieldname = self.parse_field_name()?;
3351 let pat = self.parse_pat()?;
3353 (pat, fieldname, false)
3355 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3356 let is_box = self.eat_keyword(keywords::Box);
3357 let boxed_span = self.span;
3358 let is_ref = self.eat_keyword(keywords::Ref);
3359 let is_mut = self.eat_keyword(keywords::Mut);
3360 let fieldname = self.parse_ident()?;
3361 hi = self.prev_span;
3363 let bind_type = match (is_ref, is_mut) {
3364 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3365 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3366 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3367 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3369 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3370 let fieldpat = P(ast::Pat{
3371 id: ast::DUMMY_NODE_ID,
3372 node: PatKind::Ident(bind_type, fieldpath, None),
3373 span: boxed_span.to(hi),
3376 let subpat = if is_box {
3378 id: ast::DUMMY_NODE_ID,
3379 node: PatKind::Box(fieldpat),
3385 (subpat, fieldname, true)
3388 fields.push(codemap::Spanned { span: lo.to(hi),
3389 node: ast::FieldPat {
3393 attrs: attrs.into(),
3397 return Ok((fields, etc));
3400 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3401 if self.token.is_path_start() {
3403 let (qself, path) = if self.eat_lt() {
3404 // Parse a qualified path
3405 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3408 // Parse an unqualified path
3409 (None, self.parse_path(PathStyle::Expr)?)
3411 let hi = self.prev_span;
3412 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3414 self.parse_pat_literal_maybe_minus()
3418 // helper function to decide whether to parse as ident binding or to try to do
3419 // something more complex like range patterns
3420 fn parse_as_ident(&mut self) -> bool {
3421 self.look_ahead(1, |t| match *t {
3422 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3423 token::DotDotDot | token::ModSep | token::Not => Some(false),
3424 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3425 // range pattern branch
3426 token::DotDot => None,
3428 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3429 token::Comma | token::CloseDelim(token::Bracket) => true,
3434 /// Parse a pattern.
3435 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3436 maybe_whole!(self, NtPat, |x| x);
3441 token::Underscore => {
3444 pat = PatKind::Wild;
3446 token::BinOp(token::And) | token::AndAnd => {
3447 // Parse &pat / &mut pat
3449 let mutbl = self.parse_mutability();
3450 if let token::Lifetime(ident) = self.token {
3451 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3453 let subpat = self.parse_pat()?;
3454 pat = PatKind::Ref(subpat, mutbl);
3456 token::OpenDelim(token::Paren) => {
3457 // Parse (pat,pat,pat,...) as tuple pattern
3459 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3460 self.expect(&token::CloseDelim(token::Paren))?;
3461 pat = PatKind::Tuple(fields, ddpos);
3463 token::OpenDelim(token::Bracket) => {
3464 // Parse [pat,pat,...] as slice pattern
3466 let (before, slice, after) = self.parse_pat_vec_elements()?;
3467 self.expect(&token::CloseDelim(token::Bracket))?;
3468 pat = PatKind::Slice(before, slice, after);
3470 // At this point, token != _, &, &&, (, [
3471 _ => if self.eat_keyword(keywords::Mut) {
3472 // Parse mut ident @ pat / mut ref ident @ pat
3473 let mutref_span = self.prev_span.to(self.span);
3474 let binding_mode = if self.eat_keyword(keywords::Ref) {
3476 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3477 .span_suggestion(mutref_span, "try switching the order", "ref mut".into())
3479 BindingMode::ByRef(Mutability::Mutable)
3481 BindingMode::ByValue(Mutability::Mutable)
3483 pat = self.parse_pat_ident(binding_mode)?;
3484 } else if self.eat_keyword(keywords::Ref) {
3485 // Parse ref ident @ pat / ref mut ident @ pat
3486 let mutbl = self.parse_mutability();
3487 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3488 } else if self.eat_keyword(keywords::Box) {
3490 let subpat = self.parse_pat()?;
3491 pat = PatKind::Box(subpat);
3492 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3493 self.parse_as_ident() {
3494 // Parse ident @ pat
3495 // This can give false positives and parse nullary enums,
3496 // they are dealt with later in resolve
3497 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3498 pat = self.parse_pat_ident(binding_mode)?;
3499 } else if self.token.is_path_start() {
3500 // Parse pattern starting with a path
3501 let (qself, path) = if self.eat_lt() {
3502 // Parse a qualified path
3503 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3506 // Parse an unqualified path
3507 (None, self.parse_path(PathStyle::Expr)?)
3510 token::Not if qself.is_none() => {
3511 // Parse macro invocation
3513 let (_, tts) = self.expect_delimited_token_tree()?;
3514 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3515 pat = PatKind::Mac(mac);
3517 token::DotDotDot | token::DotDot => {
3518 let end_kind = match self.token {
3519 token::DotDot => RangeEnd::Excluded,
3520 token::DotDotDot => RangeEnd::Included,
3521 _ => panic!("can only parse `..` or `...` for ranges (checked above)"),
3524 let span = lo.to(self.prev_span);
3525 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3527 let end = self.parse_pat_range_end()?;
3528 pat = PatKind::Range(begin, end, end_kind);
3530 token::OpenDelim(token::Brace) => {
3531 if qself.is_some() {
3532 return Err(self.fatal("unexpected `{` after qualified path"));
3534 // Parse struct pattern
3536 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3538 self.recover_stmt();
3542 pat = PatKind::Struct(path, fields, etc);
3544 token::OpenDelim(token::Paren) => {
3545 if qself.is_some() {
3546 return Err(self.fatal("unexpected `(` after qualified path"));
3548 // Parse tuple struct or enum pattern
3550 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3551 self.expect(&token::CloseDelim(token::Paren))?;
3552 pat = PatKind::TupleStruct(path, fields, ddpos)
3554 _ => pat = PatKind::Path(qself, path),
3557 // Try to parse everything else as literal with optional minus
3558 match self.parse_pat_literal_maybe_minus() {
3560 if self.eat(&token::DotDotDot) {
3561 let end = self.parse_pat_range_end()?;
3562 pat = PatKind::Range(begin, end, RangeEnd::Included);
3563 } else if self.eat(&token::DotDot) {
3564 let end = self.parse_pat_range_end()?;
3565 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3567 pat = PatKind::Lit(begin);
3571 self.cancel(&mut err);
3572 let msg = format!("expected pattern, found {}", self.this_token_descr());
3573 return Err(self.fatal(&msg));
3580 id: ast::DUMMY_NODE_ID,
3582 span: lo.to(self.prev_span),
3586 /// Parse ident or ident @ pat
3587 /// used by the copy foo and ref foo patterns to give a good
3588 /// error message when parsing mistakes like ref foo(a,b)
3589 fn parse_pat_ident(&mut self,
3590 binding_mode: ast::BindingMode)
3591 -> PResult<'a, PatKind> {
3592 let ident_span = self.span;
3593 let ident = self.parse_ident()?;
3594 let name = codemap::Spanned{span: ident_span, node: ident};
3595 let sub = if self.eat(&token::At) {
3596 Some(self.parse_pat()?)
3601 // just to be friendly, if they write something like
3603 // we end up here with ( as the current token. This shortly
3604 // leads to a parse error. Note that if there is no explicit
3605 // binding mode then we do not end up here, because the lookahead
3606 // will direct us over to parse_enum_variant()
3607 if self.token == token::OpenDelim(token::Paren) {
3608 return Err(self.span_fatal(
3610 "expected identifier, found enum pattern"))
3613 Ok(PatKind::Ident(binding_mode, name, sub))
3616 /// Parse a local variable declaration
3617 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3618 let lo = self.prev_span;
3619 let pat = self.parse_pat()?;
3621 let ty = if self.eat(&token::Colon) {
3622 Some(self.parse_ty()?)
3626 let init = self.parse_initializer()?;
3631 id: ast::DUMMY_NODE_ID,
3632 span: lo.to(self.prev_span),
3637 /// Parse a structure field
3638 fn parse_name_and_ty(&mut self,
3641 attrs: Vec<Attribute>)
3642 -> PResult<'a, StructField> {
3643 let name = self.parse_ident()?;
3644 self.expect(&token::Colon)?;
3645 let ty = self.parse_ty()?;
3647 span: lo.to(self.prev_span),
3650 id: ast::DUMMY_NODE_ID,
3656 /// Emit an expected item after attributes error.
3657 fn expected_item_err(&self, attrs: &[Attribute]) {
3658 let message = match attrs.last() {
3659 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3660 _ => "expected item after attributes",
3663 self.span_err(self.prev_span, message);
3666 /// Parse a statement. This stops just before trailing semicolons on everything but items.
3667 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3668 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3669 Ok(self.parse_stmt_(true))
3672 // Eat tokens until we can be relatively sure we reached the end of the
3673 // statement. This is something of a best-effort heuristic.
3675 // We terminate when we find an unmatched `}` (without consuming it).
3676 fn recover_stmt(&mut self) {
3677 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
3680 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3681 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3682 // approximate - it can mean we break too early due to macros, but that
3683 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3685 // If `break_on_block` is `Break`, then we will stop consuming tokens
3686 // after finding (and consuming) a brace-delimited block.
3687 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
3688 let mut brace_depth = 0;
3689 let mut bracket_depth = 0;
3690 let mut in_block = false;
3691 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
3692 break_on_semi, break_on_block);
3694 debug!("recover_stmt_ loop {:?}", self.token);
3696 token::OpenDelim(token::DelimToken::Brace) => {
3699 if break_on_block == BlockMode::Break &&
3701 bracket_depth == 0 {
3705 token::OpenDelim(token::DelimToken::Bracket) => {
3709 token::CloseDelim(token::DelimToken::Brace) => {
3710 if brace_depth == 0 {
3711 debug!("recover_stmt_ return - close delim {:?}", self.token);
3716 if in_block && bracket_depth == 0 && brace_depth == 0 {
3717 debug!("recover_stmt_ return - block end {:?}", self.token);
3721 token::CloseDelim(token::DelimToken::Bracket) => {
3723 if bracket_depth < 0 {
3729 debug!("recover_stmt_ return - Eof");
3734 if break_on_semi == SemiColonMode::Break &&
3736 bracket_depth == 0 {
3737 debug!("recover_stmt_ return - Semi");
3748 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
3749 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
3751 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
3756 fn is_catch_expr(&mut self) -> bool {
3757 self.token.is_keyword(keywords::Do) &&
3758 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
3759 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
3761 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3762 !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL)
3765 fn is_union_item(&self) -> bool {
3766 self.token.is_keyword(keywords::Union) &&
3767 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
3770 fn is_defaultness(&self) -> bool {
3771 // `pub` is included for better error messages
3772 self.token.is_keyword(keywords::Default) &&
3773 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
3774 t.is_keyword(keywords::Const) ||
3775 t.is_keyword(keywords::Fn) ||
3776 t.is_keyword(keywords::Unsafe) ||
3777 t.is_keyword(keywords::Extern) ||
3778 t.is_keyword(keywords::Type) ||
3779 t.is_keyword(keywords::Pub))
3782 fn eat_defaultness(&mut self) -> bool {
3783 let is_defaultness = self.is_defaultness();
3787 self.expected_tokens.push(TokenType::Keyword(keywords::Default));
3792 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility)
3793 -> PResult<'a, Option<P<Item>>> {
3795 let (ident, def) = match self.token {
3796 token::Ident(ident) if ident.name == keywords::Macro.name() => {
3798 let ident = self.parse_ident()?;
3799 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
3800 match self.parse_token_tree() {
3801 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
3802 _ => unreachable!(),
3804 } else if self.check(&token::OpenDelim(token::Paren)) {
3805 let args = self.parse_token_tree();
3806 let body = if self.check(&token::OpenDelim(token::Brace)) {
3807 self.parse_token_tree()
3812 TokenStream::concat(vec![
3814 TokenTree::Token(lo.to(self.prev_span), token::FatArrow).into(),
3822 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
3824 token::Ident(ident) if ident.name == "macro_rules" &&
3825 self.look_ahead(1, |t| *t == token::Not) => {
3826 let prev_span = self.prev_span;
3827 self.complain_if_pub_macro(vis, prev_span);
3831 let ident = self.parse_ident()?;
3832 let (delim, tokens) = self.expect_delimited_token_tree()?;
3833 if delim != token::Brace {
3834 if !self.eat(&token::Semi) {
3835 let msg = "macros that expand to items must either \
3836 be surrounded with braces or followed by a semicolon";
3837 self.span_err(self.prev_span, msg);
3841 (ident, ast::MacroDef { tokens: tokens, legacy: true })
3843 _ => return Ok(None),
3846 let span = lo.to(self.prev_span);
3847 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
3850 fn parse_stmt_without_recovery(&mut self,
3851 macro_legacy_warnings: bool)
3852 -> PResult<'a, Option<Stmt>> {
3853 maybe_whole!(self, NtStmt, |x| Some(x));
3855 let attrs = self.parse_outer_attributes()?;
3858 Ok(Some(if self.eat_keyword(keywords::Let) {
3860 id: ast::DUMMY_NODE_ID,
3861 node: StmtKind::Local(self.parse_local(attrs.into())?),
3862 span: lo.to(self.prev_span),
3864 } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited)? {
3866 id: ast::DUMMY_NODE_ID,
3867 node: StmtKind::Item(macro_def),
3868 span: lo.to(self.prev_span),
3870 // Starts like a simple path, but not a union item.
3871 } else if self.token.is_path_start() &&
3872 !self.token.is_qpath_start() &&
3873 !self.is_union_item() {
3874 let pth = self.parse_path(PathStyle::Expr)?;
3876 if !self.eat(&token::Not) {
3877 let expr = if self.check(&token::OpenDelim(token::Brace)) {
3878 self.parse_struct_expr(lo, pth, ThinVec::new())?
3880 let hi = self.prev_span;
3881 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
3884 let expr = self.with_res(RESTRICTION_STMT_EXPR, |this| {
3885 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
3886 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
3889 return Ok(Some(Stmt {
3890 id: ast::DUMMY_NODE_ID,
3891 node: StmtKind::Expr(expr),
3892 span: lo.to(self.prev_span),
3896 // it's a macro invocation
3897 let id = match self.token {
3898 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
3899 _ => self.parse_ident()?,
3902 // check that we're pointing at delimiters (need to check
3903 // again after the `if`, because of `parse_ident`
3904 // consuming more tokens).
3905 let delim = match self.token {
3906 token::OpenDelim(delim) => delim,
3908 // we only expect an ident if we didn't parse one
3910 let ident_str = if id.name == keywords::Invalid.name() {
3915 let tok_str = self.this_token_to_string();
3916 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3922 let (_, tts) = self.expect_delimited_token_tree()?;
3923 let hi = self.prev_span;
3925 let style = if delim == token::Brace {
3926 MacStmtStyle::Braces
3928 MacStmtStyle::NoBraces
3931 if id.name == keywords::Invalid.name() {
3932 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
3933 let node = if delim == token::Brace ||
3934 self.token == token::Semi || self.token == token::Eof {
3935 StmtKind::Mac(P((mac, style, attrs.into())))
3937 // We used to incorrectly stop parsing macro-expanded statements here.
3938 // If the next token will be an error anyway but could have parsed with the
3939 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
3940 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
3941 // These can continue an expression, so we can't stop parsing and warn.
3942 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
3943 token::BinOp(token::Minus) | token::BinOp(token::Star) |
3944 token::BinOp(token::And) | token::BinOp(token::Or) |
3945 token::AndAnd | token::OrOr |
3946 token::DotDot | token::DotDotDot => false,
3949 self.warn_missing_semicolon();
3950 StmtKind::Mac(P((mac, style, attrs.into())))
3952 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
3953 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
3954 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
3958 id: ast::DUMMY_NODE_ID,
3963 // if it has a special ident, it's definitely an item
3965 // Require a semicolon or braces.
3966 if style != MacStmtStyle::Braces {
3967 if !self.eat(&token::Semi) {
3968 self.span_err(self.prev_span,
3969 "macros that expand to items must \
3970 either be surrounded with braces or \
3971 followed by a semicolon");
3974 let span = lo.to(hi);
3976 id: ast::DUMMY_NODE_ID,
3978 node: StmtKind::Item({
3980 span, id /*id is good here*/,
3981 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
3982 Visibility::Inherited,
3988 // FIXME: Bad copy of attrs
3989 let old_directory_ownership =
3990 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
3991 let item = self.parse_item_(attrs.clone(), false, true)?;
3992 self.directory.ownership = old_directory_ownership;
3996 id: ast::DUMMY_NODE_ID,
3997 span: lo.to(i.span),
3998 node: StmtKind::Item(i),
4001 let unused_attrs = |attrs: &[_], s: &mut Self| {
4002 if !attrs.is_empty() {
4003 if s.prev_token_kind == PrevTokenKind::DocComment {
4004 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4006 s.span_err(s.span, "expected statement after outer attribute");
4011 // Do not attempt to parse an expression if we're done here.
4012 if self.token == token::Semi {
4013 unused_attrs(&attrs, self);
4018 if self.token == token::CloseDelim(token::Brace) {
4019 unused_attrs(&attrs, self);
4023 // Remainder are line-expr stmts.
4024 let e = self.parse_expr_res(
4025 RESTRICTION_STMT_EXPR, Some(attrs.into()))?;
4027 id: ast::DUMMY_NODE_ID,
4028 span: lo.to(e.span),
4029 node: StmtKind::Expr(e),
4036 /// Is this expression a successfully-parsed statement?
4037 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4038 self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
4039 !classify::expr_requires_semi_to_be_stmt(e)
4042 /// Parse a block. No inner attrs are allowed.
4043 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4044 maybe_whole!(self, NtBlock, |x| x);
4048 if !self.eat(&token::OpenDelim(token::Brace)) {
4050 let tok = self.this_token_to_string();
4051 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4053 // Check to see if the user has written something like
4058 // Which is valid in other languages, but not Rust.
4059 match self.parse_stmt_without_recovery(false) {
4061 let mut stmt_span = stmt.span;
4062 // expand the span to include the semicolon, if it exists
4063 if self.eat(&token::Semi) {
4064 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4066 let sugg = pprust::to_string(|s| {
4067 use print::pprust::{PrintState, INDENT_UNIT};
4068 s.ibox(INDENT_UNIT)?;
4070 s.print_stmt(&stmt)?;
4071 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4073 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4076 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4077 self.cancel(&mut e);
4084 self.parse_block_tail(lo, BlockCheckMode::Default)
4087 /// Parse a block. Inner attrs are allowed.
4088 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4089 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4092 self.expect(&token::OpenDelim(token::Brace))?;
4093 Ok((self.parse_inner_attributes()?,
4094 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4097 /// Parse the rest of a block expression or function body
4098 /// Precondition: already parsed the '{'.
4099 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4100 let mut stmts = vec![];
4102 while !self.eat(&token::CloseDelim(token::Brace)) {
4103 if let Some(stmt) = self.parse_full_stmt(false)? {
4105 } else if self.token == token::Eof {
4108 // Found only `;` or `}`.
4115 id: ast::DUMMY_NODE_ID,
4117 span: lo.to(self.prev_span),
4121 /// Parse a statement, including the trailing semicolon.
4122 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4123 let mut stmt = match self.parse_stmt_(macro_legacy_warnings) {
4125 None => return Ok(None),
4129 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4130 // expression without semicolon
4131 if classify::expr_requires_semi_to_be_stmt(expr) {
4132 // Just check for errors and recover; do not eat semicolon yet.
4134 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4137 self.recover_stmt();
4141 StmtKind::Local(..) => {
4142 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4143 if macro_legacy_warnings && self.token != token::Semi {
4144 self.warn_missing_semicolon();
4146 self.expect_one_of(&[token::Semi], &[])?;
4152 if self.eat(&token::Semi) {
4153 stmt = stmt.add_trailing_semicolon();
4156 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4160 fn warn_missing_semicolon(&self) {
4161 self.diagnostic().struct_span_warn(self.span, {
4162 &format!("expected `;`, found `{}`", self.this_token_to_string())
4164 "This was erroneously allowed and will become a hard error in a future release"
4168 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4169 // BOUND = TY_BOUND | LT_BOUND
4170 // LT_BOUND = LIFETIME (e.g. `'a`)
4171 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4172 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4173 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4174 let mut bounds = Vec::new();
4176 let is_bound_start = self.check_path() || self.check_lifetime() ||
4177 self.check(&token::Question) ||
4178 self.check_keyword(keywords::For) ||
4179 self.check(&token::OpenDelim(token::Paren));
4181 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4182 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4183 if self.token.is_lifetime() {
4184 if let Some(question_span) = question {
4185 self.span_err(question_span,
4186 "`?` may only modify trait bounds, not lifetime bounds");
4188 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4191 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4192 let path = self.parse_path(PathStyle::Type)?;
4193 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4194 let modifier = if question.is_some() {
4195 TraitBoundModifier::Maybe
4197 TraitBoundModifier::None
4199 bounds.push(TraitTyParamBound(poly_trait, modifier));
4202 self.expect(&token::CloseDelim(token::Paren))?;
4203 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4204 self.span_err(self.prev_span,
4205 "parenthesized lifetime bounds are not supported");
4212 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4220 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4221 self.parse_ty_param_bounds_common(true)
4224 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4225 // BOUND = LT_BOUND (e.g. `'a`)
4226 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4227 let mut lifetimes = Vec::new();
4228 while self.check_lifetime() {
4229 lifetimes.push(self.expect_lifetime());
4231 if !self.eat(&token::BinOp(token::Plus)) {
4238 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4239 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4240 let span = self.span;
4241 let ident = self.parse_ident()?;
4243 // Parse optional colon and param bounds.
4244 let bounds = if self.eat(&token::Colon) {
4245 self.parse_ty_param_bounds()?
4250 let default = if self.eat(&token::Eq) {
4251 Some(self.parse_ty()?)
4257 attrs: preceding_attrs.into(),
4259 id: ast::DUMMY_NODE_ID,
4266 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4267 /// trailing comma and erroneous trailing attributes.
4268 pub fn parse_generic_params(&mut self) -> PResult<'a, (Vec<LifetimeDef>, Vec<TyParam>)> {
4269 let mut lifetime_defs = Vec::new();
4270 let mut ty_params = Vec::new();
4271 let mut seen_ty_param = false;
4273 let attrs = self.parse_outer_attributes()?;
4274 if self.check_lifetime() {
4275 let lifetime = self.expect_lifetime();
4276 // Parse lifetime parameter.
4277 let bounds = if self.eat(&token::Colon) {
4278 self.parse_lt_param_bounds()
4282 lifetime_defs.push(LifetimeDef {
4283 attrs: attrs.into(),
4288 self.span_err(self.prev_span,
4289 "lifetime parameters must be declared prior to type parameters");
4291 } else if self.check_ident() {
4292 // Parse type parameter.
4293 ty_params.push(self.parse_ty_param(attrs)?);
4294 seen_ty_param = true;
4296 // Check for trailing attributes and stop parsing.
4297 if !attrs.is_empty() {
4298 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4299 self.span_err(attrs[0].span,
4300 &format!("trailing attribute after {} parameters", param_kind));
4305 if !self.eat(&token::Comma) {
4309 Ok((lifetime_defs, ty_params))
4312 /// Parse a set of optional generic type parameter declarations. Where
4313 /// clauses are not parsed here, and must be added later via
4314 /// `parse_where_clause()`.
4316 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4317 /// | ( < lifetimes , typaramseq ( , )? > )
4318 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4319 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4320 maybe_whole!(self, NtGenerics, |x| x);
4322 let span_lo = self.span;
4324 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4327 lifetimes: lifetime_defs,
4329 where_clause: WhereClause {
4330 id: ast::DUMMY_NODE_ID,
4331 predicates: Vec::new(),
4332 span: syntax_pos::DUMMY_SP,
4334 span: span_lo.to(self.prev_span),
4337 Ok(ast::Generics::default())
4341 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4342 /// possibly including trailing comma.
4343 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4344 let mut lifetimes = Vec::new();
4345 let mut types = Vec::new();
4346 let mut bindings = Vec::new();
4347 let mut seen_type = false;
4348 let mut seen_binding = false;
4350 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4351 // Parse lifetime argument.
4352 lifetimes.push(self.expect_lifetime());
4353 if seen_type || seen_binding {
4354 self.span_err(self.prev_span,
4355 "lifetime parameters must be declared prior to type parameters");
4357 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4358 // Parse associated type binding.
4360 let ident = self.parse_ident()?;
4362 let ty = self.parse_ty()?;
4363 bindings.push(TypeBinding {
4364 id: ast::DUMMY_NODE_ID,
4367 span: lo.to(self.prev_span),
4369 seen_binding = true;
4370 } else if self.check_type() {
4371 // Parse type argument.
4372 types.push(self.parse_ty()?);
4374 self.span_err(types[types.len() - 1].span,
4375 "type parameters must be declared prior to associated type bindings");
4382 if !self.eat(&token::Comma) {
4386 Ok((lifetimes, types, bindings))
4389 /// Parses an optional `where` clause and places it in `generics`.
4391 /// ```ignore (only-for-syntax-highlight)
4392 /// where T : Trait<U, V> + 'b, 'a : 'b
4394 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4395 maybe_whole!(self, NtWhereClause, |x| x);
4397 let mut where_clause = WhereClause {
4398 id: ast::DUMMY_NODE_ID,
4399 predicates: Vec::new(),
4400 span: syntax_pos::DUMMY_SP,
4403 if !self.eat_keyword(keywords::Where) {
4404 return Ok(where_clause);
4406 let lo = self.prev_span;
4408 // This is a temporary future proofing.
4410 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4411 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4412 // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4413 if token::Lt == self.token {
4414 let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4415 if ident_or_lifetime {
4416 let gt_comma_or_colon = self.look_ahead(2, |t| {
4417 *t == token::Gt || *t == token::Comma || *t == token::Colon
4419 if gt_comma_or_colon {
4420 self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4427 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4428 let lifetime = self.expect_lifetime();
4429 // Bounds starting with a colon are mandatory, but possibly empty.
4430 self.expect(&token::Colon)?;
4431 let bounds = self.parse_lt_param_bounds();
4432 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4433 ast::WhereRegionPredicate {
4434 span: lo.to(self.prev_span),
4439 } else if self.check_type() {
4440 // Parse optional `for<'a, 'b>`.
4441 // This `for` is parsed greedily and applies to the whole predicate,
4442 // the bounded type can have its own `for` applying only to it.
4443 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4444 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4445 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4446 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4448 // Parse type with mandatory colon and (possibly empty) bounds,
4449 // or with mandatory equality sign and the second type.
4450 let ty = self.parse_ty()?;
4451 if self.eat(&token::Colon) {
4452 let bounds = self.parse_ty_param_bounds()?;
4453 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4454 ast::WhereBoundPredicate {
4455 span: lo.to(self.prev_span),
4456 bound_lifetimes: lifetime_defs,
4461 // FIXME: Decide what should be used here, `=` or `==`.
4462 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4463 let rhs_ty = self.parse_ty()?;
4464 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4465 ast::WhereEqPredicate {
4466 span: lo.to(self.prev_span),
4469 id: ast::DUMMY_NODE_ID,
4473 return self.unexpected();
4479 if !self.eat(&token::Comma) {
4484 where_clause.span = lo.to(self.prev_span);
4488 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4489 -> PResult<'a, (Vec<Arg> , bool)> {
4491 let mut variadic = false;
4492 let args: Vec<Option<Arg>> =
4493 self.parse_unspanned_seq(
4494 &token::OpenDelim(token::Paren),
4495 &token::CloseDelim(token::Paren),
4496 SeqSep::trailing_allowed(token::Comma),
4498 if p.token == token::DotDotDot {
4501 if p.token != token::CloseDelim(token::Paren) {
4504 "`...` must be last in argument list for variadic function");
4509 "only foreign functions are allowed to be variadic");
4514 match p.parse_arg_general(named_args) {
4515 Ok(arg) => Ok(Some(arg)),
4518 let lo = p.prev_span;
4519 // Skip every token until next possible arg or end.
4520 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4521 // Create a placeholder argument for proper arg count (#34264).
4522 let span = lo.to(p.prev_span);
4523 Ok(Some(dummy_arg(span)))
4530 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4532 if variadic && args.is_empty() {
4534 "variadic function must be declared with at least one named argument");
4537 Ok((args, variadic))
4540 /// Parse the argument list and result type of a function declaration
4541 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4543 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4544 let ret_ty = self.parse_ret_ty()?;
4553 /// Returns the parsed optional self argument and whether a self shortcut was used.
4554 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4555 let expect_ident = |this: &mut Self| match this.token {
4556 // Preserve hygienic context.
4557 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4560 let isolated_self = |this: &mut Self, n| {
4561 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4562 this.look_ahead(n + 1, |t| t != &token::ModSep)
4565 // Parse optional self parameter of a method.
4566 // Only a limited set of initial token sequences is considered self parameters, anything
4567 // else is parsed as a normal function parameter list, so some lookahead is required.
4568 let eself_lo = self.span;
4569 let (eself, eself_ident) = match self.token {
4570 token::BinOp(token::And) => {
4576 if isolated_self(self, 1) {
4578 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4579 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4580 isolated_self(self, 2) {
4583 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4584 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4585 isolated_self(self, 2) {
4587 let lt = self.expect_lifetime();
4588 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4589 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4590 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4591 isolated_self(self, 3) {
4593 let lt = self.expect_lifetime();
4595 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4600 token::BinOp(token::Star) => {
4605 // Emit special error for `self` cases.
4606 if isolated_self(self, 1) {
4608 self.span_err(self.span, "cannot pass `self` by raw pointer");
4609 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4610 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4611 isolated_self(self, 2) {
4614 self.span_err(self.span, "cannot pass `self` by raw pointer");
4615 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4620 token::Ident(..) => {
4621 if isolated_self(self, 0) {
4624 let eself_ident = expect_ident(self);
4625 if self.eat(&token::Colon) {
4626 let ty = self.parse_ty()?;
4627 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4629 (SelfKind::Value(Mutability::Immutable), eself_ident)
4631 } else if self.token.is_keyword(keywords::Mut) &&
4632 isolated_self(self, 1) {
4636 let eself_ident = expect_ident(self);
4637 if self.eat(&token::Colon) {
4638 let ty = self.parse_ty()?;
4639 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4641 (SelfKind::Value(Mutability::Mutable), eself_ident)
4647 _ => return Ok(None),
4650 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
4651 Ok(Some(Arg::from_self(eself, eself_ident)))
4654 /// Parse the parameter list and result type of a function that may have a `self` parameter.
4655 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
4656 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4658 self.expect(&token::OpenDelim(token::Paren))?;
4660 // Parse optional self argument
4661 let self_arg = self.parse_self_arg()?;
4663 // Parse the rest of the function parameter list.
4664 let sep = SeqSep::trailing_allowed(token::Comma);
4665 let fn_inputs = if let Some(self_arg) = self_arg {
4666 if self.check(&token::CloseDelim(token::Paren)) {
4668 } else if self.eat(&token::Comma) {
4669 let mut fn_inputs = vec![self_arg];
4670 fn_inputs.append(&mut self.parse_seq_to_before_end(
4671 &token::CloseDelim(token::Paren), sep, parse_arg_fn)
4675 return self.unexpected();
4678 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4681 // Parse closing paren and return type.
4682 self.expect(&token::CloseDelim(token::Paren))?;
4685 output: self.parse_ret_ty()?,
4690 // parse the |arg, arg| header on a lambda
4691 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4692 let inputs_captures = {
4693 if self.eat(&token::OrOr) {
4696 self.expect(&token::BinOp(token::Or))?;
4697 let args = self.parse_seq_to_before_end(
4698 &token::BinOp(token::Or),
4699 SeqSep::trailing_allowed(token::Comma),
4700 |p| p.parse_fn_block_arg()
4706 let output = self.parse_ret_ty()?;
4709 inputs: inputs_captures,
4715 /// Parse the name and optional generic types of a function header.
4716 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4717 let id = self.parse_ident()?;
4718 let generics = self.parse_generics()?;
4722 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
4723 attrs: Vec<Attribute>) -> P<Item> {
4727 id: ast::DUMMY_NODE_ID,
4735 /// Parse an item-position function declaration.
4736 fn parse_item_fn(&mut self,
4738 constness: Spanned<Constness>,
4740 -> PResult<'a, ItemInfo> {
4741 let (ident, mut generics) = self.parse_fn_header()?;
4742 let decl = self.parse_fn_decl(false)?;
4743 generics.where_clause = self.parse_where_clause()?;
4744 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4745 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4748 /// true if we are looking at `const ID`, false for things like `const fn` etc
4749 pub fn is_const_item(&mut self) -> bool {
4750 self.token.is_keyword(keywords::Const) &&
4751 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4752 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4755 /// parses all the "front matter" for a `fn` declaration, up to
4756 /// and including the `fn` keyword:
4760 /// - `const unsafe fn`
4763 pub fn parse_fn_front_matter(&mut self)
4764 -> PResult<'a, (Spanned<ast::Constness>,
4767 let is_const_fn = self.eat_keyword(keywords::Const);
4768 let const_span = self.prev_span;
4769 let unsafety = self.parse_unsafety()?;
4770 let (constness, unsafety, abi) = if is_const_fn {
4771 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
4773 let abi = if self.eat_keyword(keywords::Extern) {
4774 self.parse_opt_abi()?.unwrap_or(Abi::C)
4778 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
4780 self.expect_keyword(keywords::Fn)?;
4781 Ok((constness, unsafety, abi))
4784 /// Parse an impl item.
4785 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
4786 maybe_whole!(self, NtImplItem, |x| x);
4787 let attrs = self.parse_outer_attributes()?;
4788 let (mut item, tokens) = self.collect_tokens(|this| {
4789 this.parse_impl_item_(at_end, attrs)
4792 // See `parse_item` for why this clause is here.
4793 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
4794 item.tokens = Some(tokens);
4799 fn parse_impl_item_(&mut self,
4801 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
4803 let vis = self.parse_visibility(false)?;
4804 let defaultness = self.parse_defaultness()?;
4805 let (name, node) = if self.eat_keyword(keywords::Type) {
4806 let name = self.parse_ident()?;
4807 self.expect(&token::Eq)?;
4808 let typ = self.parse_ty()?;
4809 self.expect(&token::Semi)?;
4810 (name, ast::ImplItemKind::Type(typ))
4811 } else if self.is_const_item() {
4812 self.expect_keyword(keywords::Const)?;
4813 let name = self.parse_ident()?;
4814 self.expect(&token::Colon)?;
4815 let typ = self.parse_ty()?;
4816 self.expect(&token::Eq)?;
4817 let expr = self.parse_expr()?;
4818 self.expect(&token::Semi)?;
4819 (name, ast::ImplItemKind::Const(typ, expr))
4821 let (name, inner_attrs, node) = self.parse_impl_method(&vis, at_end)?;
4822 attrs.extend(inner_attrs);
4827 id: ast::DUMMY_NODE_ID,
4828 span: lo.to(self.prev_span),
4838 fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
4839 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
4844 fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
4846 Visibility::Inherited => Ok(()),
4848 let is_macro_rules: bool = match self.token {
4849 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
4853 let mut err = self.diagnostic()
4854 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
4855 err.help("did you mean #[macro_export]?");
4858 let mut err = self.diagnostic()
4859 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
4860 err.help("try adjusting the macro to put `pub` inside the invocation");
4867 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
4868 -> DiagnosticBuilder<'a>
4870 // Given this code `path(`, it seems like this is not
4871 // setting the visibility of a macro invocation, but rather
4872 // a mistyped method declaration.
4873 // Create a diagnostic pointing out that `fn` is missing.
4875 // x | pub path(&self) {
4876 // | ^ missing `fn`, `type`, or `const`
4878 // ^^ `sp` below will point to this
4879 let sp = prev_span.between(self.prev_span);
4880 let mut err = self.diagnostic().struct_span_err(
4882 &format!("missing `fn`, `type`, or `const` for {}-item declaration",
4884 err.span_label(sp, "missing `fn`, `type`, or `const`");
4888 /// Parse a method or a macro invocation in a trait impl.
4889 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
4890 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4891 // code copied from parse_macro_use_or_failure... abstraction!
4892 if self.token.is_path_start() {
4895 let prev_span = self.prev_span;
4898 let pth = self.parse_path(PathStyle::Mod)?;
4899 if pth.segments.len() == 1 {
4900 if !self.eat(&token::Not) {
4901 return Err(self.missing_assoc_item_kind_err("impl", prev_span));
4904 self.expect(&token::Not)?;
4907 self.complain_if_pub_macro(vis, prev_span);
4909 // eat a matched-delimiter token tree:
4911 let (delim, tts) = self.expect_delimited_token_tree()?;
4912 if delim != token::Brace {
4913 self.expect(&token::Semi)?
4916 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
4917 Ok((keywords::Invalid.ident(), vec![], ast::ImplItemKind::Macro(mac)))
4919 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
4920 let ident = self.parse_ident()?;
4921 let mut generics = self.parse_generics()?;
4922 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
4923 generics.where_clause = self.parse_where_clause()?;
4925 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4926 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4936 /// Parse trait Foo { ... }
4937 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4938 let ident = self.parse_ident()?;
4939 let mut tps = self.parse_generics()?;
4941 // Parse optional colon and supertrait bounds.
4942 let bounds = if self.eat(&token::Colon) {
4943 self.parse_ty_param_bounds()?
4948 tps.where_clause = self.parse_where_clause()?;
4950 self.expect(&token::OpenDelim(token::Brace))?;
4951 let mut trait_items = vec![];
4952 while !self.eat(&token::CloseDelim(token::Brace)) {
4953 let mut at_end = false;
4954 match self.parse_trait_item(&mut at_end) {
4955 Ok(item) => trait_items.push(item),
4959 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
4964 Ok((ident, ItemKind::Trait(unsafety, tps, bounds, trait_items), None))
4967 /// Parses items implementations variants
4968 /// impl<T> Foo { ... }
4969 /// impl<T> ToString for &'static T { ... }
4970 /// impl Send for .. {}
4971 fn parse_item_impl(&mut self,
4972 unsafety: ast::Unsafety,
4973 defaultness: Defaultness) -> PResult<'a, ItemInfo> {
4974 let impl_span = self.span;
4976 // First, parse type parameters if necessary.
4977 let mut generics = self.parse_generics()?;
4979 // Special case: if the next identifier that follows is '(', don't
4980 // allow this to be parsed as a trait.
4981 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4983 let neg_span = self.span;
4984 let polarity = if self.eat(&token::Not) {
4985 ast::ImplPolarity::Negative
4987 ast::ImplPolarity::Positive
4991 let mut ty = self.parse_ty()?;
4993 // Parse traits, if necessary.
4994 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4995 // New-style trait. Reinterpret the type as a trait.
4997 TyKind::Path(None, ref path) => {
4999 path: (*path).clone(),
5004 self.span_err(ty.span, "not a trait");
5009 if polarity == ast::ImplPolarity::Negative {
5010 // This is a negated type implementation
5011 // `impl !MyType {}`, which is not allowed.
5012 self.span_err(neg_span, "inherent implementation can't be negated");
5017 if opt_trait.is_some() && self.eat(&token::DotDot) {
5018 if generics.is_parameterized() {
5019 self.span_err(impl_span, "default trait implementations are not \
5020 allowed to have generics");
5023 if let ast::Defaultness::Default = defaultness {
5024 self.span_err(impl_span, "`default impl` is not allowed for \
5025 default trait implementations");
5028 self.expect(&token::OpenDelim(token::Brace))?;
5029 self.expect(&token::CloseDelim(token::Brace))?;
5030 Ok((keywords::Invalid.ident(),
5031 ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
5033 if opt_trait.is_some() {
5034 ty = self.parse_ty()?;
5036 generics.where_clause = self.parse_where_clause()?;
5038 self.expect(&token::OpenDelim(token::Brace))?;
5039 let attrs = self.parse_inner_attributes()?;
5041 let mut impl_items = vec![];
5042 while !self.eat(&token::CloseDelim(token::Brace)) {
5043 let mut at_end = false;
5044 match self.parse_impl_item(&mut at_end) {
5045 Ok(item) => impl_items.push(item),
5049 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5055 Ok((keywords::Invalid.ident(),
5056 ItemKind::Impl(unsafety, polarity, defaultness, generics, opt_trait, ty, impl_items),
5061 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<LifetimeDef>> {
5062 if self.eat_keyword(keywords::For) {
5064 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
5066 if !ty_params.is_empty() {
5067 self.span_err(ty_params[0].span,
5068 "only lifetime parameters can be used in this context");
5076 /// Parse struct Foo { ... }
5077 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5078 let class_name = self.parse_ident()?;
5080 let mut generics = self.parse_generics()?;
5082 // There is a special case worth noting here, as reported in issue #17904.
5083 // If we are parsing a tuple struct it is the case that the where clause
5084 // should follow the field list. Like so:
5086 // struct Foo<T>(T) where T: Copy;
5088 // If we are parsing a normal record-style struct it is the case
5089 // that the where clause comes before the body, and after the generics.
5090 // So if we look ahead and see a brace or a where-clause we begin
5091 // parsing a record style struct.
5093 // Otherwise if we look ahead and see a paren we parse a tuple-style
5096 let vdata = if self.token.is_keyword(keywords::Where) {
5097 generics.where_clause = self.parse_where_clause()?;
5098 if self.eat(&token::Semi) {
5099 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5100 VariantData::Unit(ast::DUMMY_NODE_ID)
5102 // If we see: `struct Foo<T> where T: Copy { ... }`
5103 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5105 // No `where` so: `struct Foo<T>;`
5106 } else if self.eat(&token::Semi) {
5107 VariantData::Unit(ast::DUMMY_NODE_ID)
5108 // Record-style struct definition
5109 } else if self.token == token::OpenDelim(token::Brace) {
5110 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5111 // Tuple-style struct definition with optional where-clause.
5112 } else if self.token == token::OpenDelim(token::Paren) {
5113 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5114 generics.where_clause = self.parse_where_clause()?;
5115 self.expect(&token::Semi)?;
5118 let token_str = self.this_token_to_string();
5119 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5120 name, found `{}`", token_str)))
5123 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5126 /// Parse union Foo { ... }
5127 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5128 let class_name = self.parse_ident()?;
5130 let mut generics = self.parse_generics()?;
5132 let vdata = if self.token.is_keyword(keywords::Where) {
5133 generics.where_clause = self.parse_where_clause()?;
5134 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5135 } else if self.token == token::OpenDelim(token::Brace) {
5136 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5138 let token_str = self.this_token_to_string();
5139 return Err(self.fatal(&format!("expected `where` or `{{` after union \
5140 name, found `{}`", token_str)))
5143 Ok((class_name, ItemKind::Union(vdata, generics), None))
5146 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5147 let mut fields = Vec::new();
5148 if self.eat(&token::OpenDelim(token::Brace)) {
5149 while self.token != token::CloseDelim(token::Brace) {
5150 fields.push(self.parse_struct_decl_field().map_err(|e| {
5151 self.recover_stmt();
5152 self.eat(&token::CloseDelim(token::Brace));
5159 let token_str = self.this_token_to_string();
5160 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5168 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5169 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5170 // Unit like structs are handled in parse_item_struct function
5171 let fields = self.parse_unspanned_seq(
5172 &token::OpenDelim(token::Paren),
5173 &token::CloseDelim(token::Paren),
5174 SeqSep::trailing_allowed(token::Comma),
5176 let attrs = p.parse_outer_attributes()?;
5178 let vis = p.parse_visibility(true)?;
5179 let ty = p.parse_ty()?;
5181 span: lo.to(p.span),
5184 id: ast::DUMMY_NODE_ID,
5193 /// Parse a structure field declaration
5194 pub fn parse_single_struct_field(&mut self,
5197 attrs: Vec<Attribute> )
5198 -> PResult<'a, StructField> {
5199 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5204 token::CloseDelim(token::Brace) => {}
5205 token::DocComment(_) => return Err(self.span_fatal_err(self.span,
5206 Error::UselessDocComment)),
5207 _ => return Err(self.span_fatal_help(self.span,
5208 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5209 "struct fields should be separated by commas")),
5214 /// Parse an element of a struct definition
5215 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5216 let attrs = self.parse_outer_attributes()?;
5218 let vis = self.parse_visibility(false)?;
5219 self.parse_single_struct_field(lo, vis, attrs)
5222 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5223 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5224 /// a function definition, it's not a tuple struct field) and the contents within the parens
5225 /// isn't valid, emit a proper diagnostic.
5226 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5227 maybe_whole!(self, NtVis, |x| x);
5229 if !self.eat_keyword(keywords::Pub) {
5230 return Ok(Visibility::Inherited)
5233 if self.check(&token::OpenDelim(token::Paren)) {
5234 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5235 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5236 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5237 // by the following tokens.
5238 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5241 self.bump(); // `crate`
5242 let vis = Visibility::Crate(self.prev_span);
5243 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5245 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5248 self.bump(); // `in`
5249 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5250 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5251 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5253 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5254 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5255 t.is_keyword(keywords::SelfValue)) {
5256 // `pub(self)` or `pub(super)`
5258 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5259 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5260 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5262 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5263 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5265 let msg = "incorrect visibility restriction";
5266 let suggestion = r##"some possible visibility restrictions are:
5267 `pub(crate)`: visible only on the current crate
5268 `pub(super)`: visible only in the current module's parent
5269 `pub(in path::to::module)`: visible only on the specified path"##;
5270 let path = self.parse_path(PathStyle::Mod)?;
5271 let path_span = self.prev_span;
5272 let help_msg = format!("make this visible only to module `{}` with `in`", path);
5273 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5274 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5275 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5276 err.emit(); // emit diagnostic, but continue with public visibility
5280 Ok(Visibility::Public)
5283 /// Parse defaultness: DEFAULT or nothing
5284 fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5285 if self.eat_defaultness() {
5286 Ok(Defaultness::Default)
5288 Ok(Defaultness::Final)
5292 /// Given a termination token, parse all of the items in a module
5293 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5294 let mut items = vec![];
5295 while let Some(item) = self.parse_item()? {
5299 if !self.eat(term) {
5300 let token_str = self.this_token_to_string();
5301 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5304 let hi = if self.span == syntax_pos::DUMMY_SP {
5311 inner: inner_lo.to(hi),
5316 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5317 let id = self.parse_ident()?;
5318 self.expect(&token::Colon)?;
5319 let ty = self.parse_ty()?;
5320 self.expect(&token::Eq)?;
5321 let e = self.parse_expr()?;
5322 self.expect(&token::Semi)?;
5323 let item = match m {
5324 Some(m) => ItemKind::Static(ty, m, e),
5325 None => ItemKind::Const(ty, e),
5327 Ok((id, item, None))
5330 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5331 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5332 let (in_cfg, outer_attrs) = {
5333 let mut strip_unconfigured = ::config::StripUnconfigured {
5335 should_test: false, // irrelevant
5336 features: None, // don't perform gated feature checking
5338 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5339 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5342 let id_span = self.span;
5343 let id = self.parse_ident()?;
5344 if self.check(&token::Semi) {
5346 if in_cfg && self.recurse_into_file_modules {
5347 // This mod is in an external file. Let's go get it!
5348 let ModulePathSuccess { path, directory_ownership, warn } =
5349 self.submod_path(id, &outer_attrs, id_span)?;
5350 let (module, mut attrs) =
5351 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5353 let attr = ast::Attribute {
5354 id: attr::mk_attr_id(),
5355 style: ast::AttrStyle::Outer,
5356 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5357 Ident::from_str("warn_directory_ownership")),
5358 tokens: TokenStream::empty(),
5359 is_sugared_doc: false,
5360 span: syntax_pos::DUMMY_SP,
5362 attr::mark_known(&attr);
5365 Ok((id, module, Some(attrs)))
5367 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5368 Ok((id, ItemKind::Mod(placeholder), None))
5371 let old_directory = self.directory.clone();
5372 self.push_directory(id, &outer_attrs);
5374 self.expect(&token::OpenDelim(token::Brace))?;
5375 let mod_inner_lo = self.span;
5376 let attrs = self.parse_inner_attributes()?;
5377 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5379 self.directory = old_directory;
5380 Ok((id, ItemKind::Mod(module), Some(attrs)))
5384 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5385 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5386 self.directory.path.push(&path.as_str());
5387 self.directory.ownership = DirectoryOwnership::Owned;
5389 self.directory.path.push(&id.name.as_str());
5393 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5394 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5397 /// Returns either a path to a module, or .
5398 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5399 let mod_name = id.to_string();
5400 let default_path_str = format!("{}.rs", mod_name);
5401 let secondary_path_str = format!("{}{}mod.rs", mod_name, path::MAIN_SEPARATOR);
5402 let default_path = dir_path.join(&default_path_str);
5403 let secondary_path = dir_path.join(&secondary_path_str);
5404 let default_exists = codemap.file_exists(&default_path);
5405 let secondary_exists = codemap.file_exists(&secondary_path);
5407 let result = match (default_exists, secondary_exists) {
5408 (true, false) => Ok(ModulePathSuccess {
5410 directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5413 (false, true) => Ok(ModulePathSuccess {
5414 path: secondary_path,
5415 directory_ownership: DirectoryOwnership::Owned,
5418 (false, false) => Err(Error::FileNotFoundForModule {
5419 mod_name: mod_name.clone(),
5420 default_path: default_path_str,
5421 secondary_path: secondary_path_str,
5422 dir_path: format!("{}", dir_path.display()),
5424 (true, true) => Err(Error::DuplicatePaths {
5425 mod_name: mod_name.clone(),
5426 default_path: default_path_str,
5427 secondary_path: secondary_path_str,
5433 path_exists: default_exists || secondary_exists,
5438 fn submod_path(&mut self,
5440 outer_attrs: &[ast::Attribute],
5442 -> PResult<'a, ModulePathSuccess> {
5443 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5444 return Ok(ModulePathSuccess {
5445 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5446 Some("mod.rs") => DirectoryOwnership::Owned,
5447 _ => DirectoryOwnership::UnownedViaMod(true),
5454 let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5456 if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5458 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5459 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5460 if paths.path_exists {
5461 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5463 err.span_note(id_sp, &msg);
5466 } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5468 if let Ok(result) = paths.result {
5469 return Ok(ModulePathSuccess { warn: true, ..result });
5472 let mut err = self.diagnostic().struct_span_err(id_sp,
5473 "cannot declare a new module at this location");
5474 if id_sp != syntax_pos::DUMMY_SP {
5475 let src_path = PathBuf::from(self.sess.codemap().span_to_filename(id_sp));
5476 if let Some(stem) = src_path.file_stem() {
5477 let mut dest_path = src_path.clone();
5478 dest_path.set_file_name(stem);
5479 dest_path.push("mod.rs");
5480 err.span_note(id_sp,
5481 &format!("maybe move this module `{}` to its own \
5482 directory via `{}`", src_path.to_string_lossy(),
5483 dest_path.to_string_lossy()));
5486 if paths.path_exists {
5487 err.span_note(id_sp,
5488 &format!("... or maybe `use` the module `{}` instead \
5489 of possibly redeclaring it",
5494 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5498 /// Read a module from a source file.
5499 fn eval_src_mod(&mut self,
5501 directory_ownership: DirectoryOwnership,
5504 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5505 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5506 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5507 let mut err = String::from("circular modules: ");
5508 let len = included_mod_stack.len();
5509 for p in &included_mod_stack[i.. len] {
5510 err.push_str(&p.to_string_lossy());
5511 err.push_str(" -> ");
5513 err.push_str(&path.to_string_lossy());
5514 return Err(self.span_fatal(id_sp, &err[..]));
5516 included_mod_stack.push(path.clone());
5517 drop(included_mod_stack);
5520 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5521 p0.cfg_mods = self.cfg_mods;
5522 let mod_inner_lo = p0.span;
5523 let mod_attrs = p0.parse_inner_attributes()?;
5524 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5525 self.sess.included_mod_stack.borrow_mut().pop();
5526 Ok((ast::ItemKind::Mod(m0), mod_attrs))
5529 /// Parse a function declaration from a foreign module
5530 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5531 -> PResult<'a, ForeignItem> {
5532 self.expect_keyword(keywords::Fn)?;
5534 let (ident, mut generics) = self.parse_fn_header()?;
5535 let decl = self.parse_fn_decl(true)?;
5536 generics.where_clause = self.parse_where_clause()?;
5538 self.expect(&token::Semi)?;
5539 Ok(ast::ForeignItem {
5542 node: ForeignItemKind::Fn(decl, generics),
5543 id: ast::DUMMY_NODE_ID,
5549 /// Parse a static item from a foreign module.
5550 /// Assumes that the `static` keyword is already parsed.
5551 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5552 -> PResult<'a, ForeignItem> {
5553 let mutbl = self.eat_keyword(keywords::Mut);
5554 let ident = self.parse_ident()?;
5555 self.expect(&token::Colon)?;
5556 let ty = self.parse_ty()?;
5558 self.expect(&token::Semi)?;
5562 node: ForeignItemKind::Static(ty, mutbl),
5563 id: ast::DUMMY_NODE_ID,
5569 /// Parse extern crate links
5573 /// extern crate foo;
5574 /// extern crate bar as foo;
5575 fn parse_item_extern_crate(&mut self,
5577 visibility: Visibility,
5578 attrs: Vec<Attribute>)
5579 -> PResult<'a, P<Item>> {
5581 let crate_name = self.parse_ident()?;
5582 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
5583 (Some(crate_name.name), ident)
5587 self.expect(&token::Semi)?;
5589 let prev_span = self.prev_span;
5590 Ok(self.mk_item(lo.to(prev_span),
5592 ItemKind::ExternCrate(maybe_path),
5597 /// Parse `extern` for foreign ABIs
5600 /// `extern` is expected to have been
5601 /// consumed before calling this method
5607 fn parse_item_foreign_mod(&mut self,
5609 opt_abi: Option<abi::Abi>,
5610 visibility: Visibility,
5611 mut attrs: Vec<Attribute>)
5612 -> PResult<'a, P<Item>> {
5613 self.expect(&token::OpenDelim(token::Brace))?;
5615 let abi = opt_abi.unwrap_or(Abi::C);
5617 attrs.extend(self.parse_inner_attributes()?);
5619 let mut foreign_items = vec![];
5620 while let Some(item) = self.parse_foreign_item()? {
5621 foreign_items.push(item);
5623 self.expect(&token::CloseDelim(token::Brace))?;
5625 let prev_span = self.prev_span;
5626 let m = ast::ForeignMod {
5628 items: foreign_items
5630 let invalid = keywords::Invalid.ident();
5631 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
5634 /// Parse type Foo = Bar;
5635 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5636 let ident = self.parse_ident()?;
5637 let mut tps = self.parse_generics()?;
5638 tps.where_clause = self.parse_where_clause()?;
5639 self.expect(&token::Eq)?;
5640 let ty = self.parse_ty()?;
5641 self.expect(&token::Semi)?;
5642 Ok((ident, ItemKind::Ty(ty, tps), None))
5645 /// Parse the part of an "enum" decl following the '{'
5646 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5647 let mut variants = Vec::new();
5648 let mut all_nullary = true;
5649 let mut any_disr = None;
5650 while self.token != token::CloseDelim(token::Brace) {
5651 let variant_attrs = self.parse_outer_attributes()?;
5652 let vlo = self.span;
5655 let mut disr_expr = None;
5656 let ident = self.parse_ident()?;
5657 if self.check(&token::OpenDelim(token::Brace)) {
5658 // Parse a struct variant.
5659 all_nullary = false;
5660 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
5661 ast::DUMMY_NODE_ID);
5662 } else if self.check(&token::OpenDelim(token::Paren)) {
5663 all_nullary = false;
5664 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
5665 ast::DUMMY_NODE_ID);
5666 } else if self.eat(&token::Eq) {
5667 disr_expr = Some(self.parse_expr()?);
5668 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5669 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5671 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5674 let vr = ast::Variant_ {
5676 attrs: variant_attrs,
5680 variants.push(respan(vlo.to(self.prev_span), vr));
5682 if !self.eat(&token::Comma) { break; }
5684 self.expect(&token::CloseDelim(token::Brace))?;
5686 Some(disr_span) if !all_nullary =>
5687 self.span_err(disr_span,
5688 "discriminator values can only be used with a c-like enum"),
5692 Ok(ast::EnumDef { variants: variants })
5695 /// Parse an "enum" declaration
5696 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5697 let id = self.parse_ident()?;
5698 let mut generics = self.parse_generics()?;
5699 generics.where_clause = self.parse_where_clause()?;
5700 self.expect(&token::OpenDelim(token::Brace))?;
5702 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
5703 self.recover_stmt();
5704 self.eat(&token::CloseDelim(token::Brace));
5707 Ok((id, ItemKind::Enum(enum_definition, generics), None))
5710 /// Parses a string as an ABI spec on an extern type or module. Consumes
5711 /// the `extern` keyword, if one is found.
5712 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5714 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5716 self.expect_no_suffix(sp, "ABI spec", suf);
5718 match abi::lookup(&s.as_str()) {
5719 Some(abi) => Ok(Some(abi)),
5721 let prev_span = self.prev_span;
5724 &format!("invalid ABI: expected one of [{}], \
5726 abi::all_names().join(", "),
5737 /// Parse one of the items allowed by the flags.
5738 /// NB: this function no longer parses the items inside an
5740 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5741 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5742 maybe_whole!(self, NtItem, |item| {
5743 let mut item = item.unwrap();
5744 let mut attrs = attrs;
5745 mem::swap(&mut item.attrs, &mut attrs);
5746 item.attrs.extend(attrs);
5752 let visibility = self.parse_visibility(false)?;
5754 if self.eat_keyword(keywords::Use) {
5756 let item_ = ItemKind::Use(self.parse_view_path()?);
5757 self.expect(&token::Semi)?;
5759 let prev_span = self.prev_span;
5760 let invalid = keywords::Invalid.ident();
5761 let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
5762 return Ok(Some(item));
5765 if self.eat_keyword(keywords::Extern) {
5766 if self.eat_keyword(keywords::Crate) {
5767 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
5770 let opt_abi = self.parse_opt_abi()?;
5772 if self.eat_keyword(keywords::Fn) {
5773 // EXTERN FUNCTION ITEM
5774 let fn_span = self.prev_span;
5775 let abi = opt_abi.unwrap_or(Abi::C);
5776 let (ident, item_, extra_attrs) =
5777 self.parse_item_fn(Unsafety::Normal,
5778 respan(fn_span, Constness::NotConst),
5780 let prev_span = self.prev_span;
5781 let item = self.mk_item(lo.to(prev_span),
5785 maybe_append(attrs, extra_attrs));
5786 return Ok(Some(item));
5787 } else if self.check(&token::OpenDelim(token::Brace)) {
5788 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
5794 if self.eat_keyword(keywords::Static) {
5796 let m = if self.eat_keyword(keywords::Mut) {
5799 Mutability::Immutable
5801 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
5802 let prev_span = self.prev_span;
5803 let item = self.mk_item(lo.to(prev_span),
5807 maybe_append(attrs, extra_attrs));
5808 return Ok(Some(item));
5810 if self.eat_keyword(keywords::Const) {
5811 let const_span = self.prev_span;
5812 if self.check_keyword(keywords::Fn)
5813 || (self.check_keyword(keywords::Unsafe)
5814 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5815 // CONST FUNCTION ITEM
5816 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5822 let (ident, item_, extra_attrs) =
5823 self.parse_item_fn(unsafety,
5824 respan(const_span, Constness::Const),
5826 let prev_span = self.prev_span;
5827 let item = self.mk_item(lo.to(prev_span),
5831 maybe_append(attrs, extra_attrs));
5832 return Ok(Some(item));
5836 if self.eat_keyword(keywords::Mut) {
5837 let prev_span = self.prev_span;
5838 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
5839 .help("did you mean to declare a static?")
5842 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
5843 let prev_span = self.prev_span;
5844 let item = self.mk_item(lo.to(prev_span),
5848 maybe_append(attrs, extra_attrs));
5849 return Ok(Some(item));
5851 if self.check_keyword(keywords::Unsafe) &&
5852 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5854 // UNSAFE TRAIT ITEM
5855 self.expect_keyword(keywords::Unsafe)?;
5856 self.expect_keyword(keywords::Trait)?;
5857 let (ident, item_, extra_attrs) =
5858 self.parse_item_trait(ast::Unsafety::Unsafe)?;
5859 let prev_span = self.prev_span;
5860 let item = self.mk_item(lo.to(prev_span),
5864 maybe_append(attrs, extra_attrs));
5865 return Ok(Some(item));
5867 if (self.check_keyword(keywords::Unsafe) &&
5868 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))) ||
5869 (self.check_keyword(keywords::Default) &&
5870 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) &&
5871 self.look_ahead(2, |t| t.is_keyword(keywords::Impl)))
5874 let defaultness = self.parse_defaultness()?;
5875 self.expect_keyword(keywords::Unsafe)?;
5876 self.expect_keyword(keywords::Impl)?;
5879 extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe, defaultness)?;
5880 let prev_span = self.prev_span;
5881 let item = self.mk_item(lo.to(prev_span),
5885 maybe_append(attrs, extra_attrs));
5886 return Ok(Some(item));
5888 if self.check_keyword(keywords::Fn) {
5891 let fn_span = self.prev_span;
5892 let (ident, item_, extra_attrs) =
5893 self.parse_item_fn(Unsafety::Normal,
5894 respan(fn_span, Constness::NotConst),
5896 let prev_span = self.prev_span;
5897 let item = self.mk_item(lo.to(prev_span),
5901 maybe_append(attrs, extra_attrs));
5902 return Ok(Some(item));
5904 if self.check_keyword(keywords::Unsafe)
5905 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5906 // UNSAFE FUNCTION ITEM
5908 let abi = if self.eat_keyword(keywords::Extern) {
5909 self.parse_opt_abi()?.unwrap_or(Abi::C)
5913 self.expect_keyword(keywords::Fn)?;
5914 let fn_span = self.prev_span;
5915 let (ident, item_, extra_attrs) =
5916 self.parse_item_fn(Unsafety::Unsafe,
5917 respan(fn_span, Constness::NotConst),
5919 let prev_span = self.prev_span;
5920 let item = self.mk_item(lo.to(prev_span),
5924 maybe_append(attrs, extra_attrs));
5925 return Ok(Some(item));
5927 if self.eat_keyword(keywords::Mod) {
5929 let (ident, item_, extra_attrs) =
5930 self.parse_item_mod(&attrs[..])?;
5931 let prev_span = self.prev_span;
5932 let item = self.mk_item(lo.to(prev_span),
5936 maybe_append(attrs, extra_attrs));
5937 return Ok(Some(item));
5939 if self.eat_keyword(keywords::Type) {
5941 let (ident, item_, extra_attrs) = self.parse_item_type()?;
5942 let prev_span = self.prev_span;
5943 let item = self.mk_item(lo.to(prev_span),
5947 maybe_append(attrs, extra_attrs));
5948 return Ok(Some(item));
5950 if self.eat_keyword(keywords::Enum) {
5952 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
5953 let prev_span = self.prev_span;
5954 let item = self.mk_item(lo.to(prev_span),
5958 maybe_append(attrs, extra_attrs));
5959 return Ok(Some(item));
5961 if self.eat_keyword(keywords::Trait) {
5963 let (ident, item_, extra_attrs) =
5964 self.parse_item_trait(ast::Unsafety::Normal)?;
5965 let prev_span = self.prev_span;
5966 let item = self.mk_item(lo.to(prev_span),
5970 maybe_append(attrs, extra_attrs));
5971 return Ok(Some(item));
5973 if (self.check_keyword(keywords::Impl)) ||
5974 (self.check_keyword(keywords::Default) &&
5975 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)))
5978 let defaultness = self.parse_defaultness()?;
5979 self.expect_keyword(keywords::Impl)?;
5982 extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal, defaultness)?;
5983 let prev_span = self.prev_span;
5984 let item = self.mk_item(lo.to(prev_span),
5988 maybe_append(attrs, extra_attrs));
5989 return Ok(Some(item));
5991 if self.eat_keyword(keywords::Struct) {
5993 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
5994 let prev_span = self.prev_span;
5995 let item = self.mk_item(lo.to(prev_span),
5999 maybe_append(attrs, extra_attrs));
6000 return Ok(Some(item));
6002 if self.is_union_item() {
6005 let (ident, item_, extra_attrs) = self.parse_item_union()?;
6006 let prev_span = self.prev_span;
6007 let item = self.mk_item(lo.to(prev_span),
6011 maybe_append(attrs, extra_attrs));
6012 return Ok(Some(item));
6014 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility)? {
6015 return Ok(Some(macro_def));
6018 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
6021 /// Parse a foreign item.
6022 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
6023 let attrs = self.parse_outer_attributes()?;
6025 let visibility = self.parse_visibility(false)?;
6027 // FOREIGN STATIC ITEM
6028 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
6029 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
6030 if self.token.is_keyword(keywords::Const) {
6032 .struct_span_err(self.span, "extern items cannot be `const`")
6033 .span_suggestion(self.span, "instead try using", "static".to_owned())
6036 self.bump(); // `static` or `const`
6037 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6039 // FOREIGN FUNCTION ITEM
6040 if self.check_keyword(keywords::Fn) {
6041 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6044 // FIXME #5668: this will occur for a macro invocation:
6045 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
6047 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
6053 /// This is the fall-through for parsing items.
6054 fn parse_macro_use_or_failure(
6056 attrs: Vec<Attribute> ,
6057 macros_allowed: bool,
6058 attributes_allowed: bool,
6060 visibility: Visibility
6061 ) -> PResult<'a, Option<P<Item>>> {
6062 if macros_allowed && self.token.is_path_start() {
6063 // MACRO INVOCATION ITEM
6065 let prev_span = self.prev_span;
6066 self.complain_if_pub_macro(&visibility, prev_span);
6068 let mac_lo = self.span;
6071 let pth = self.parse_path(PathStyle::Mod)?;
6072 self.expect(&token::Not)?;
6074 // a 'special' identifier (like what `macro_rules!` uses)
6075 // is optional. We should eventually unify invoc syntax
6077 let id = if self.token.is_ident() {
6080 keywords::Invalid.ident() // no special identifier
6082 // eat a matched-delimiter token tree:
6083 let (delim, tts) = self.expect_delimited_token_tree()?;
6084 if delim != token::Brace {
6085 if !self.eat(&token::Semi) {
6086 self.span_err(self.prev_span,
6087 "macros that expand to items must either \
6088 be surrounded with braces or followed by \
6093 let hi = self.prev_span;
6094 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6095 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6096 return Ok(Some(item));
6099 // FAILURE TO PARSE ITEM
6101 Visibility::Inherited => {}
6103 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
6107 if !attributes_allowed && !attrs.is_empty() {
6108 self.expected_item_err(&attrs);
6113 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
6114 where F: FnOnce(&mut Self) -> PResult<'a, R>
6116 // Record all tokens we parse when parsing this item.
6117 let mut tokens = Vec::new();
6118 match self.token_cursor.frame.last_token {
6119 LastToken::Collecting(_) => {
6120 panic!("cannot collect tokens recursively yet")
6122 LastToken::Was(ref mut last) => tokens.extend(last.take()),
6124 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
6125 let prev = self.token_cursor.stack.len();
6127 let last_token = if self.token_cursor.stack.len() == prev {
6128 &mut self.token_cursor.frame.last_token
6130 &mut self.token_cursor.stack[prev].last_token
6132 let mut tokens = match *last_token {
6133 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
6134 LastToken::Was(_) => panic!("our vector went away?"),
6137 // If we're not at EOF our current token wasn't actually consumed by
6138 // `f`, but it'll still be in our list that we pulled out. In that case
6140 if self.token == token::Eof {
6141 *last_token = LastToken::Was(None);
6143 *last_token = LastToken::Was(tokens.pop());
6146 Ok((ret?, tokens.into_iter().collect()))
6149 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6150 let attrs = self.parse_outer_attributes()?;
6152 let (ret, tokens) = self.collect_tokens(|this| {
6153 this.parse_item_(attrs, true, false)
6156 // Once we've parsed an item and recorded the tokens we got while
6157 // parsing we may want to store `tokens` into the item we're about to
6158 // return. Note, though, that we specifically didn't capture tokens
6159 // related to outer attributes. The `tokens` field here may later be
6160 // used with procedural macros to convert this item back into a token
6161 // stream, but during expansion we may be removing attributes as we go
6164 // If we've got inner attributes then the `tokens` we've got above holds
6165 // these inner attributes. If an inner attribute is expanded we won't
6166 // actually remove it from the token stream, so we'll just keep yielding
6167 // it (bad!). To work around this case for now we just avoid recording
6168 // `tokens` if we detect any inner attributes. This should help keep
6169 // expansion correct, but we should fix this bug one day!
6172 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6173 i.tokens = Some(tokens);
6180 fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> {
6181 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
6182 &token::CloseDelim(token::Brace),
6183 SeqSep::trailing_allowed(token::Comma), |this| {
6185 let ident = if this.eat_keyword(keywords::SelfValue) {
6186 keywords::SelfValue.ident()
6190 let rename = this.parse_rename()?;
6191 let node = ast::PathListItem_ {
6194 id: ast::DUMMY_NODE_ID
6196 Ok(respan(lo.to(this.prev_span), node))
6201 fn is_import_coupler(&mut self) -> bool {
6202 self.check(&token::ModSep) &&
6203 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6204 *t == token::BinOp(token::Star))
6207 /// Matches ViewPath:
6208 /// MOD_SEP? non_global_path
6209 /// MOD_SEP? non_global_path as IDENT
6210 /// MOD_SEP? non_global_path MOD_SEP STAR
6211 /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE
6212 /// MOD_SEP? LBRACE item_seq RBRACE
6213 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
6215 if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) ||
6216 self.is_import_coupler() {
6217 // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`.
6218 self.eat(&token::ModSep);
6219 let prefix = ast::Path {
6220 segments: vec![PathSegment::crate_root(lo)],
6221 span: lo.to(self.span),
6223 let view_path_kind = if self.eat(&token::BinOp(token::Star)) {
6224 ViewPathGlob(prefix)
6226 ViewPathList(prefix, self.parse_path_list_items()?)
6228 Ok(P(respan(lo.to(self.span), view_path_kind)))
6230 let prefix = self.parse_path(PathStyle::Mod)?.default_to_global();
6231 if self.is_import_coupler() {
6232 // `foo::bar::{a, b}` or `foo::bar::*`
6234 if self.check(&token::BinOp(token::Star)) {
6236 Ok(P(respan(lo.to(self.span), ViewPathGlob(prefix))))
6238 let items = self.parse_path_list_items()?;
6239 Ok(P(respan(lo.to(self.span), ViewPathList(prefix, items))))
6242 // `foo::bar` or `foo::bar as baz`
6243 let rename = self.parse_rename()?.
6244 unwrap_or(prefix.segments.last().unwrap().identifier);
6245 Ok(P(respan(lo.to(self.prev_span), ViewPathSimple(rename, prefix))))
6250 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6251 if self.eat_keyword(keywords::As) {
6252 self.parse_ident().map(Some)
6258 /// Parses a source module as a crate. This is the main
6259 /// entry point for the parser.
6260 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6263 attrs: self.parse_inner_attributes()?,
6264 module: self.parse_mod_items(&token::Eof, lo)?,
6265 span: lo.to(self.span),
6269 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6270 let ret = match self.token {
6271 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6272 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6279 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6280 match self.parse_optional_str() {
6281 Some((s, style, suf)) => {
6282 let sp = self.prev_span;
6283 self.expect_no_suffix(sp, "string literal", suf);
6286 _ => Err(self.fatal("expected string literal"))