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(_) => self.parse_expr()?,
3030 // If an explicit return type is given, require a
3031 // block to appear (RFC 968).
3032 let body_lo = self.span;
3033 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3039 ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3043 // `else` token already eaten
3044 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3045 if self.eat_keyword(keywords::If) {
3046 return self.parse_if_expr(ThinVec::new());
3048 let blk = self.parse_block()?;
3049 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3053 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3054 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3056 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3057 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3059 let pat = self.parse_pat()?;
3060 self.expect_keyword(keywords::In)?;
3061 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3062 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3063 attrs.extend(iattrs);
3065 let hi = self.prev_span;
3066 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3069 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3070 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3072 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3073 if self.token.is_keyword(keywords::Let) {
3074 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3076 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3077 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3078 attrs.extend(iattrs);
3079 let span = span_lo.to(body.span);
3080 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3083 /// Parse a 'while let' expression ('while' token already eaten)
3084 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3086 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3087 self.expect_keyword(keywords::Let)?;
3088 let pat = self.parse_pat()?;
3089 self.expect(&token::Eq)?;
3090 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3091 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3092 attrs.extend(iattrs);
3093 let span = span_lo.to(body.span);
3094 return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3097 // parse `loop {...}`, `loop` token already eaten
3098 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3100 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3101 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3102 attrs.extend(iattrs);
3103 let span = span_lo.to(body.span);
3104 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3107 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3108 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3109 -> PResult<'a, P<Expr>>
3111 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3112 attrs.extend(iattrs);
3113 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3116 // `match` token already eaten
3117 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3118 let match_span = self.prev_span;
3119 let lo = self.prev_span;
3120 let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL,
3122 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3123 if self.token == token::Token::Semi {
3124 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3128 attrs.extend(self.parse_inner_attributes()?);
3130 let mut arms: Vec<Arm> = Vec::new();
3131 while self.token != token::CloseDelim(token::Brace) {
3132 match self.parse_arm() {
3133 Ok(arm) => arms.push(arm),
3135 // Recover by skipping to the end of the block.
3137 self.recover_stmt();
3138 let span = lo.to(self.span);
3139 if self.token == token::CloseDelim(token::Brace) {
3142 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3148 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3151 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3152 maybe_whole!(self, NtArm, |x| x);
3154 let attrs = self.parse_outer_attributes()?;
3155 let pats = self.parse_pats()?;
3156 let guard = if self.eat_keyword(keywords::If) {
3157 Some(self.parse_expr()?)
3161 self.expect(&token::FatArrow)?;
3162 let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR, None)?;
3164 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3165 && self.token != token::CloseDelim(token::Brace);
3168 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3170 self.eat(&token::Comma);
3181 /// Parse an expression
3182 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3183 self.parse_expr_res(Restrictions::empty(), None)
3186 /// Evaluate the closure with restrictions in place.
3188 /// After the closure is evaluated, restrictions are reset.
3189 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3190 where F: FnOnce(&mut Self) -> T
3192 let old = self.restrictions;
3193 self.restrictions = r;
3195 self.restrictions = old;
3200 /// Parse an expression, subject to the given restrictions
3201 pub fn parse_expr_res(&mut self, r: Restrictions,
3202 already_parsed_attrs: Option<ThinVec<Attribute>>)
3203 -> PResult<'a, P<Expr>> {
3204 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3207 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3208 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3209 if self.check(&token::Eq) {
3211 Ok(Some(self.parse_expr()?))
3217 /// Parse patterns, separated by '|' s
3218 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3219 let mut pats = Vec::new();
3221 pats.push(self.parse_pat()?);
3222 if self.check(&token::BinOp(token::Or)) { self.bump();}
3223 else { return Ok(pats); }
3227 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3228 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3229 let mut fields = vec![];
3230 let mut ddpos = None;
3232 while !self.check(&token::CloseDelim(token::Paren)) {
3233 if ddpos.is_none() && self.eat(&token::DotDot) {
3234 ddpos = Some(fields.len());
3235 if self.eat(&token::Comma) {
3236 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3237 fields.push(self.parse_pat()?);
3239 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3240 // Emit a friendly error, ignore `..` and continue parsing
3241 self.span_err(self.prev_span, "`..` can only be used once per \
3242 tuple or tuple struct pattern");
3244 fields.push(self.parse_pat()?);
3247 if !self.check(&token::CloseDelim(token::Paren)) ||
3248 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3249 self.expect(&token::Comma)?;
3256 fn parse_pat_vec_elements(
3258 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3259 let mut before = Vec::new();
3260 let mut slice = None;
3261 let mut after = Vec::new();
3262 let mut first = true;
3263 let mut before_slice = true;
3265 while self.token != token::CloseDelim(token::Bracket) {
3269 self.expect(&token::Comma)?;
3271 if self.token == token::CloseDelim(token::Bracket)
3272 && (before_slice || !after.is_empty()) {
3278 if self.eat(&token::DotDot) {
3280 if self.check(&token::Comma) ||
3281 self.check(&token::CloseDelim(token::Bracket)) {
3282 slice = Some(P(ast::Pat {
3283 id: ast::DUMMY_NODE_ID,
3284 node: PatKind::Wild,
3287 before_slice = false;
3293 let subpat = self.parse_pat()?;
3294 if before_slice && self.eat(&token::DotDot) {
3295 slice = Some(subpat);
3296 before_slice = false;
3297 } else if before_slice {
3298 before.push(subpat);
3304 Ok((before, slice, after))
3307 /// Parse the fields of a struct-like pattern
3308 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3309 let mut fields = Vec::new();
3310 let mut etc = false;
3311 let mut first = true;
3312 while self.token != token::CloseDelim(token::Brace) {
3316 self.expect(&token::Comma)?;
3317 // accept trailing commas
3318 if self.check(&token::CloseDelim(token::Brace)) { break }
3321 let attrs = self.parse_outer_attributes()?;
3325 if self.check(&token::DotDot) {
3327 if self.token != token::CloseDelim(token::Brace) {
3328 let token_str = self.this_token_to_string();
3329 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3336 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3337 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3338 // Parsing a pattern of the form "fieldname: pat"
3339 let fieldname = self.parse_field_name()?;
3341 let pat = self.parse_pat()?;
3343 (pat, fieldname, false)
3345 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3346 let is_box = self.eat_keyword(keywords::Box);
3347 let boxed_span = self.span;
3348 let is_ref = self.eat_keyword(keywords::Ref);
3349 let is_mut = self.eat_keyword(keywords::Mut);
3350 let fieldname = self.parse_ident()?;
3351 hi = self.prev_span;
3353 let bind_type = match (is_ref, is_mut) {
3354 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3355 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3356 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3357 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3359 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3360 let fieldpat = P(ast::Pat{
3361 id: ast::DUMMY_NODE_ID,
3362 node: PatKind::Ident(bind_type, fieldpath, None),
3363 span: boxed_span.to(hi),
3366 let subpat = if is_box {
3368 id: ast::DUMMY_NODE_ID,
3369 node: PatKind::Box(fieldpat),
3375 (subpat, fieldname, true)
3378 fields.push(codemap::Spanned { span: lo.to(hi),
3379 node: ast::FieldPat {
3383 attrs: attrs.into(),
3387 return Ok((fields, etc));
3390 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3391 if self.token.is_path_start() {
3393 let (qself, path) = if self.eat_lt() {
3394 // Parse a qualified path
3395 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3398 // Parse an unqualified path
3399 (None, self.parse_path(PathStyle::Expr)?)
3401 let hi = self.prev_span;
3402 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3404 self.parse_pat_literal_maybe_minus()
3408 // helper function to decide whether to parse as ident binding or to try to do
3409 // something more complex like range patterns
3410 fn parse_as_ident(&mut self) -> bool {
3411 self.look_ahead(1, |t| match *t {
3412 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3413 token::DotDotDot | token::ModSep | token::Not => Some(false),
3414 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3415 // range pattern branch
3416 token::DotDot => None,
3418 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3419 token::Comma | token::CloseDelim(token::Bracket) => true,
3424 /// Parse a pattern.
3425 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3426 maybe_whole!(self, NtPat, |x| x);
3431 token::Underscore => {
3434 pat = PatKind::Wild;
3436 token::BinOp(token::And) | token::AndAnd => {
3437 // Parse &pat / &mut pat
3439 let mutbl = self.parse_mutability();
3440 if let token::Lifetime(ident) = self.token {
3441 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3443 let subpat = self.parse_pat()?;
3444 pat = PatKind::Ref(subpat, mutbl);
3446 token::OpenDelim(token::Paren) => {
3447 // Parse (pat,pat,pat,...) as tuple pattern
3449 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3450 self.expect(&token::CloseDelim(token::Paren))?;
3451 pat = PatKind::Tuple(fields, ddpos);
3453 token::OpenDelim(token::Bracket) => {
3454 // Parse [pat,pat,...] as slice pattern
3456 let (before, slice, after) = self.parse_pat_vec_elements()?;
3457 self.expect(&token::CloseDelim(token::Bracket))?;
3458 pat = PatKind::Slice(before, slice, after);
3460 // At this point, token != _, &, &&, (, [
3461 _ => if self.eat_keyword(keywords::Mut) {
3462 // Parse mut ident @ pat / mut ref ident @ pat
3463 let mutref_span = self.prev_span.to(self.span);
3464 let binding_mode = if self.eat_keyword(keywords::Ref) {
3466 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3467 .span_suggestion(mutref_span, "try switching the order", "ref mut".into())
3469 BindingMode::ByRef(Mutability::Mutable)
3471 BindingMode::ByValue(Mutability::Mutable)
3473 pat = self.parse_pat_ident(binding_mode)?;
3474 } else if self.eat_keyword(keywords::Ref) {
3475 // Parse ref ident @ pat / ref mut ident @ pat
3476 let mutbl = self.parse_mutability();
3477 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3478 } else if self.eat_keyword(keywords::Box) {
3480 let subpat = self.parse_pat()?;
3481 pat = PatKind::Box(subpat);
3482 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3483 self.parse_as_ident() {
3484 // Parse ident @ pat
3485 // This can give false positives and parse nullary enums,
3486 // they are dealt with later in resolve
3487 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3488 pat = self.parse_pat_ident(binding_mode)?;
3489 } else if self.token.is_path_start() {
3490 // Parse pattern starting with a path
3491 let (qself, path) = if self.eat_lt() {
3492 // Parse a qualified path
3493 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3496 // Parse an unqualified path
3497 (None, self.parse_path(PathStyle::Expr)?)
3500 token::Not if qself.is_none() => {
3501 // Parse macro invocation
3503 let (_, tts) = self.expect_delimited_token_tree()?;
3504 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3505 pat = PatKind::Mac(mac);
3507 token::DotDotDot | token::DotDot => {
3508 let end_kind = match self.token {
3509 token::DotDot => RangeEnd::Excluded,
3510 token::DotDotDot => RangeEnd::Included,
3511 _ => panic!("can only parse `..` or `...` for ranges (checked above)"),
3514 let span = lo.to(self.prev_span);
3515 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3517 let end = self.parse_pat_range_end()?;
3518 pat = PatKind::Range(begin, end, end_kind);
3520 token::OpenDelim(token::Brace) => {
3521 if qself.is_some() {
3522 return Err(self.fatal("unexpected `{` after qualified path"));
3524 // Parse struct pattern
3526 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3528 self.recover_stmt();
3532 pat = PatKind::Struct(path, fields, etc);
3534 token::OpenDelim(token::Paren) => {
3535 if qself.is_some() {
3536 return Err(self.fatal("unexpected `(` after qualified path"));
3538 // Parse tuple struct or enum pattern
3540 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3541 self.expect(&token::CloseDelim(token::Paren))?;
3542 pat = PatKind::TupleStruct(path, fields, ddpos)
3544 _ => pat = PatKind::Path(qself, path),
3547 // Try to parse everything else as literal with optional minus
3548 match self.parse_pat_literal_maybe_minus() {
3550 if self.eat(&token::DotDotDot) {
3551 let end = self.parse_pat_range_end()?;
3552 pat = PatKind::Range(begin, end, RangeEnd::Included);
3553 } else if self.eat(&token::DotDot) {
3554 let end = self.parse_pat_range_end()?;
3555 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3557 pat = PatKind::Lit(begin);
3561 self.cancel(&mut err);
3562 let msg = format!("expected pattern, found {}", self.this_token_descr());
3563 return Err(self.fatal(&msg));
3570 id: ast::DUMMY_NODE_ID,
3572 span: lo.to(self.prev_span),
3576 /// Parse ident or ident @ pat
3577 /// used by the copy foo and ref foo patterns to give a good
3578 /// error message when parsing mistakes like ref foo(a,b)
3579 fn parse_pat_ident(&mut self,
3580 binding_mode: ast::BindingMode)
3581 -> PResult<'a, PatKind> {
3582 let ident_span = self.span;
3583 let ident = self.parse_ident()?;
3584 let name = codemap::Spanned{span: ident_span, node: ident};
3585 let sub = if self.eat(&token::At) {
3586 Some(self.parse_pat()?)
3591 // just to be friendly, if they write something like
3593 // we end up here with ( as the current token. This shortly
3594 // leads to a parse error. Note that if there is no explicit
3595 // binding mode then we do not end up here, because the lookahead
3596 // will direct us over to parse_enum_variant()
3597 if self.token == token::OpenDelim(token::Paren) {
3598 return Err(self.span_fatal(
3600 "expected identifier, found enum pattern"))
3603 Ok(PatKind::Ident(binding_mode, name, sub))
3606 /// Parse a local variable declaration
3607 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3608 let lo = self.prev_span;
3609 let pat = self.parse_pat()?;
3611 let ty = if self.eat(&token::Colon) {
3612 Some(self.parse_ty()?)
3616 let init = self.parse_initializer()?;
3621 id: ast::DUMMY_NODE_ID,
3622 span: lo.to(self.prev_span),
3627 /// Parse a structure field
3628 fn parse_name_and_ty(&mut self,
3631 attrs: Vec<Attribute>)
3632 -> PResult<'a, StructField> {
3633 let name = self.parse_ident()?;
3634 self.expect(&token::Colon)?;
3635 let ty = self.parse_ty()?;
3637 span: lo.to(self.prev_span),
3640 id: ast::DUMMY_NODE_ID,
3646 /// Emit an expected item after attributes error.
3647 fn expected_item_err(&self, attrs: &[Attribute]) {
3648 let message = match attrs.last() {
3649 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3650 _ => "expected item after attributes",
3653 self.span_err(self.prev_span, message);
3656 /// Parse a statement. This stops just before trailing semicolons on everything but items.
3657 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3658 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3659 Ok(self.parse_stmt_(true))
3662 // Eat tokens until we can be relatively sure we reached the end of the
3663 // statement. This is something of a best-effort heuristic.
3665 // We terminate when we find an unmatched `}` (without consuming it).
3666 fn recover_stmt(&mut self) {
3667 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
3670 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3671 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3672 // approximate - it can mean we break too early due to macros, but that
3673 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3675 // If `break_on_block` is `Break`, then we will stop consuming tokens
3676 // after finding (and consuming) a brace-delimited block.
3677 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
3678 let mut brace_depth = 0;
3679 let mut bracket_depth = 0;
3680 let mut in_block = false;
3681 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
3682 break_on_semi, break_on_block);
3684 debug!("recover_stmt_ loop {:?}", self.token);
3686 token::OpenDelim(token::DelimToken::Brace) => {
3689 if break_on_block == BlockMode::Break &&
3691 bracket_depth == 0 {
3695 token::OpenDelim(token::DelimToken::Bracket) => {
3699 token::CloseDelim(token::DelimToken::Brace) => {
3700 if brace_depth == 0 {
3701 debug!("recover_stmt_ return - close delim {:?}", self.token);
3706 if in_block && bracket_depth == 0 && brace_depth == 0 {
3707 debug!("recover_stmt_ return - block end {:?}", self.token);
3711 token::CloseDelim(token::DelimToken::Bracket) => {
3713 if bracket_depth < 0 {
3719 debug!("recover_stmt_ return - Eof");
3724 if break_on_semi == SemiColonMode::Break &&
3726 bracket_depth == 0 {
3727 debug!("recover_stmt_ return - Semi");
3738 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
3739 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
3741 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
3746 fn is_catch_expr(&mut self) -> bool {
3747 self.token.is_keyword(keywords::Do) &&
3748 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
3749 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
3751 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3752 !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL)
3755 fn is_union_item(&self) -> bool {
3756 self.token.is_keyword(keywords::Union) &&
3757 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
3760 fn is_defaultness(&self) -> bool {
3761 // `pub` is included for better error messages
3762 self.token.is_keyword(keywords::Default) &&
3763 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
3764 t.is_keyword(keywords::Const) ||
3765 t.is_keyword(keywords::Fn) ||
3766 t.is_keyword(keywords::Unsafe) ||
3767 t.is_keyword(keywords::Extern) ||
3768 t.is_keyword(keywords::Type) ||
3769 t.is_keyword(keywords::Pub))
3772 fn eat_defaultness(&mut self) -> bool {
3773 let is_defaultness = self.is_defaultness();
3777 self.expected_tokens.push(TokenType::Keyword(keywords::Default));
3782 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility)
3783 -> PResult<'a, Option<P<Item>>> {
3785 let (ident, def) = match self.token {
3786 token::Ident(ident) if ident.name == keywords::Macro.name() => {
3788 let ident = self.parse_ident()?;
3789 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
3790 match self.parse_token_tree() {
3791 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
3792 _ => unreachable!(),
3794 } else if self.check(&token::OpenDelim(token::Paren)) {
3795 let args = self.parse_token_tree();
3796 let body = if self.check(&token::OpenDelim(token::Brace)) {
3797 self.parse_token_tree()
3802 TokenStream::concat(vec![
3804 TokenTree::Token(lo.to(self.prev_span), token::FatArrow).into(),
3812 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
3814 token::Ident(ident) if ident.name == "macro_rules" &&
3815 self.look_ahead(1, |t| *t == token::Not) => {
3816 let prev_span = self.prev_span;
3817 self.complain_if_pub_macro(vis, prev_span);
3821 let ident = self.parse_ident()?;
3822 let (delim, tokens) = self.expect_delimited_token_tree()?;
3823 if delim != token::Brace {
3824 if !self.eat(&token::Semi) {
3825 let msg = "macros that expand to items must either \
3826 be surrounded with braces or followed by a semicolon";
3827 self.span_err(self.prev_span, msg);
3831 (ident, ast::MacroDef { tokens: tokens, legacy: true })
3833 _ => return Ok(None),
3836 let span = lo.to(self.prev_span);
3837 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
3840 fn parse_stmt_without_recovery(&mut self,
3841 macro_legacy_warnings: bool)
3842 -> PResult<'a, Option<Stmt>> {
3843 maybe_whole!(self, NtStmt, |x| Some(x));
3845 let attrs = self.parse_outer_attributes()?;
3848 Ok(Some(if self.eat_keyword(keywords::Let) {
3850 id: ast::DUMMY_NODE_ID,
3851 node: StmtKind::Local(self.parse_local(attrs.into())?),
3852 span: lo.to(self.prev_span),
3854 } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited)? {
3856 id: ast::DUMMY_NODE_ID,
3857 node: StmtKind::Item(macro_def),
3858 span: lo.to(self.prev_span),
3860 // Starts like a simple path, but not a union item.
3861 } else if self.token.is_path_start() &&
3862 !self.token.is_qpath_start() &&
3863 !self.is_union_item() {
3864 let pth = self.parse_path(PathStyle::Expr)?;
3866 if !self.eat(&token::Not) {
3867 let expr = if self.check(&token::OpenDelim(token::Brace)) {
3868 self.parse_struct_expr(lo, pth, ThinVec::new())?
3870 let hi = self.prev_span;
3871 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
3874 let expr = self.with_res(RESTRICTION_STMT_EXPR, |this| {
3875 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
3876 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
3879 return Ok(Some(Stmt {
3880 id: ast::DUMMY_NODE_ID,
3881 node: StmtKind::Expr(expr),
3882 span: lo.to(self.prev_span),
3886 // it's a macro invocation
3887 let id = match self.token {
3888 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
3889 _ => self.parse_ident()?,
3892 // check that we're pointing at delimiters (need to check
3893 // again after the `if`, because of `parse_ident`
3894 // consuming more tokens).
3895 let delim = match self.token {
3896 token::OpenDelim(delim) => delim,
3898 // we only expect an ident if we didn't parse one
3900 let ident_str = if id.name == keywords::Invalid.name() {
3905 let tok_str = self.this_token_to_string();
3906 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3912 let (_, tts) = self.expect_delimited_token_tree()?;
3913 let hi = self.prev_span;
3915 let style = if delim == token::Brace {
3916 MacStmtStyle::Braces
3918 MacStmtStyle::NoBraces
3921 if id.name == keywords::Invalid.name() {
3922 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
3923 let node = if delim == token::Brace ||
3924 self.token == token::Semi || self.token == token::Eof {
3925 StmtKind::Mac(P((mac, style, attrs.into())))
3927 // We used to incorrectly stop parsing macro-expanded statements here.
3928 // If the next token will be an error anyway but could have parsed with the
3929 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
3930 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
3931 // These can continue an expression, so we can't stop parsing and warn.
3932 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
3933 token::BinOp(token::Minus) | token::BinOp(token::Star) |
3934 token::BinOp(token::And) | token::BinOp(token::Or) |
3935 token::AndAnd | token::OrOr |
3936 token::DotDot | token::DotDotDot => false,
3939 self.warn_missing_semicolon();
3940 StmtKind::Mac(P((mac, style, attrs.into())))
3942 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
3943 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
3944 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
3948 id: ast::DUMMY_NODE_ID,
3953 // if it has a special ident, it's definitely an item
3955 // Require a semicolon or braces.
3956 if style != MacStmtStyle::Braces {
3957 if !self.eat(&token::Semi) {
3958 self.span_err(self.prev_span,
3959 "macros that expand to items must \
3960 either be surrounded with braces or \
3961 followed by a semicolon");
3964 let span = lo.to(hi);
3966 id: ast::DUMMY_NODE_ID,
3968 node: StmtKind::Item({
3970 span, id /*id is good here*/,
3971 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
3972 Visibility::Inherited,
3978 // FIXME: Bad copy of attrs
3979 let old_directory_ownership =
3980 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
3981 let item = self.parse_item_(attrs.clone(), false, true)?;
3982 self.directory.ownership = old_directory_ownership;
3986 id: ast::DUMMY_NODE_ID,
3987 span: lo.to(i.span),
3988 node: StmtKind::Item(i),
3991 let unused_attrs = |attrs: &[_], s: &mut Self| {
3992 if !attrs.is_empty() {
3993 if s.prev_token_kind == PrevTokenKind::DocComment {
3994 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
3996 s.span_err(s.span, "expected statement after outer attribute");
4001 // Do not attempt to parse an expression if we're done here.
4002 if self.token == token::Semi {
4003 unused_attrs(&attrs, self);
4008 if self.token == token::CloseDelim(token::Brace) {
4009 unused_attrs(&attrs, self);
4013 // Remainder are line-expr stmts.
4014 let e = self.parse_expr_res(
4015 RESTRICTION_STMT_EXPR, Some(attrs.into()))?;
4017 id: ast::DUMMY_NODE_ID,
4018 span: lo.to(e.span),
4019 node: StmtKind::Expr(e),
4026 /// Is this expression a successfully-parsed statement?
4027 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4028 self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
4029 !classify::expr_requires_semi_to_be_stmt(e)
4032 /// Parse a block. No inner attrs are allowed.
4033 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4034 maybe_whole!(self, NtBlock, |x| x);
4038 if !self.eat(&token::OpenDelim(token::Brace)) {
4040 let tok = self.this_token_to_string();
4041 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4043 // Check to see if the user has written something like
4048 // Which is valid in other languages, but not Rust.
4049 match self.parse_stmt_without_recovery(false) {
4051 let mut stmt_span = stmt.span;
4052 // expand the span to include the semicolon, if it exists
4053 if self.eat(&token::Semi) {
4054 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4056 let sugg = pprust::to_string(|s| {
4057 use print::pprust::{PrintState, INDENT_UNIT};
4058 s.ibox(INDENT_UNIT)?;
4060 s.print_stmt(&stmt)?;
4061 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4063 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4066 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4067 self.cancel(&mut e);
4074 self.parse_block_tail(lo, BlockCheckMode::Default)
4077 /// Parse a block. Inner attrs are allowed.
4078 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4079 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4082 self.expect(&token::OpenDelim(token::Brace))?;
4083 Ok((self.parse_inner_attributes()?,
4084 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4087 /// Parse the rest of a block expression or function body
4088 /// Precondition: already parsed the '{'.
4089 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4090 let mut stmts = vec![];
4092 while !self.eat(&token::CloseDelim(token::Brace)) {
4093 if let Some(stmt) = self.parse_full_stmt(false)? {
4095 } else if self.token == token::Eof {
4098 // Found only `;` or `}`.
4105 id: ast::DUMMY_NODE_ID,
4107 span: lo.to(self.prev_span),
4111 /// Parse a statement, including the trailing semicolon.
4112 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4113 let mut stmt = match self.parse_stmt_(macro_legacy_warnings) {
4115 None => return Ok(None),
4119 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4120 // expression without semicolon
4121 if classify::expr_requires_semi_to_be_stmt(expr) {
4122 // Just check for errors and recover; do not eat semicolon yet.
4124 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4127 self.recover_stmt();
4131 StmtKind::Local(..) => {
4132 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4133 if macro_legacy_warnings && self.token != token::Semi {
4134 self.warn_missing_semicolon();
4136 self.expect_one_of(&[token::Semi], &[])?;
4142 if self.eat(&token::Semi) {
4143 stmt = stmt.add_trailing_semicolon();
4146 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4150 fn warn_missing_semicolon(&self) {
4151 self.diagnostic().struct_span_warn(self.span, {
4152 &format!("expected `;`, found `{}`", self.this_token_to_string())
4154 "This was erroneously allowed and will become a hard error in a future release"
4158 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4159 // BOUND = TY_BOUND | LT_BOUND
4160 // LT_BOUND = LIFETIME (e.g. `'a`)
4161 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4162 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4163 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4164 let mut bounds = Vec::new();
4166 let is_bound_start = self.check_path() || self.check_lifetime() ||
4167 self.check(&token::Question) ||
4168 self.check_keyword(keywords::For) ||
4169 self.check(&token::OpenDelim(token::Paren));
4171 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4172 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4173 if self.token.is_lifetime() {
4174 if let Some(question_span) = question {
4175 self.span_err(question_span,
4176 "`?` may only modify trait bounds, not lifetime bounds");
4178 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4181 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4182 let path = self.parse_path(PathStyle::Type)?;
4183 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4184 let modifier = if question.is_some() {
4185 TraitBoundModifier::Maybe
4187 TraitBoundModifier::None
4189 bounds.push(TraitTyParamBound(poly_trait, modifier));
4192 self.expect(&token::CloseDelim(token::Paren))?;
4193 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4194 self.span_err(self.prev_span,
4195 "parenthesized lifetime bounds are not supported");
4202 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4210 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4211 self.parse_ty_param_bounds_common(true)
4214 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4215 // BOUND = LT_BOUND (e.g. `'a`)
4216 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4217 let mut lifetimes = Vec::new();
4218 while self.check_lifetime() {
4219 lifetimes.push(self.expect_lifetime());
4221 if !self.eat(&token::BinOp(token::Plus)) {
4228 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4229 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4230 let span = self.span;
4231 let ident = self.parse_ident()?;
4233 // Parse optional colon and param bounds.
4234 let bounds = if self.eat(&token::Colon) {
4235 self.parse_ty_param_bounds()?
4240 let default = if self.eat(&token::Eq) {
4241 Some(self.parse_ty()?)
4247 attrs: preceding_attrs.into(),
4249 id: ast::DUMMY_NODE_ID,
4256 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4257 /// trailing comma and erroneous trailing attributes.
4258 pub fn parse_generic_params(&mut self) -> PResult<'a, (Vec<LifetimeDef>, Vec<TyParam>)> {
4259 let mut lifetime_defs = Vec::new();
4260 let mut ty_params = Vec::new();
4261 let mut seen_ty_param = false;
4263 let attrs = self.parse_outer_attributes()?;
4264 if self.check_lifetime() {
4265 let lifetime = self.expect_lifetime();
4266 // Parse lifetime parameter.
4267 let bounds = if self.eat(&token::Colon) {
4268 self.parse_lt_param_bounds()
4272 lifetime_defs.push(LifetimeDef {
4273 attrs: attrs.into(),
4278 self.span_err(self.prev_span,
4279 "lifetime parameters must be declared prior to type parameters");
4281 } else if self.check_ident() {
4282 // Parse type parameter.
4283 ty_params.push(self.parse_ty_param(attrs)?);
4284 seen_ty_param = true;
4286 // Check for trailing attributes and stop parsing.
4287 if !attrs.is_empty() {
4288 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4289 self.span_err(attrs[0].span,
4290 &format!("trailing attribute after {} parameters", param_kind));
4295 if !self.eat(&token::Comma) {
4299 Ok((lifetime_defs, ty_params))
4302 /// Parse a set of optional generic type parameter declarations. Where
4303 /// clauses are not parsed here, and must be added later via
4304 /// `parse_where_clause()`.
4306 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4307 /// | ( < lifetimes , typaramseq ( , )? > )
4308 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4309 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4310 maybe_whole!(self, NtGenerics, |x| x);
4312 let span_lo = self.span;
4314 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4317 lifetimes: lifetime_defs,
4319 where_clause: WhereClause {
4320 id: ast::DUMMY_NODE_ID,
4321 predicates: Vec::new(),
4322 span: syntax_pos::DUMMY_SP,
4324 span: span_lo.to(self.prev_span),
4327 Ok(ast::Generics::default())
4331 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4332 /// possibly including trailing comma.
4333 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4334 let mut lifetimes = Vec::new();
4335 let mut types = Vec::new();
4336 let mut bindings = Vec::new();
4337 let mut seen_type = false;
4338 let mut seen_binding = false;
4340 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4341 // Parse lifetime argument.
4342 lifetimes.push(self.expect_lifetime());
4343 if seen_type || seen_binding {
4344 self.span_err(self.prev_span,
4345 "lifetime parameters must be declared prior to type parameters");
4347 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4348 // Parse associated type binding.
4350 let ident = self.parse_ident()?;
4352 let ty = self.parse_ty()?;
4353 bindings.push(TypeBinding {
4354 id: ast::DUMMY_NODE_ID,
4357 span: lo.to(self.prev_span),
4359 seen_binding = true;
4360 } else if self.check_type() {
4361 // Parse type argument.
4362 types.push(self.parse_ty()?);
4364 self.span_err(types[types.len() - 1].span,
4365 "type parameters must be declared prior to associated type bindings");
4372 if !self.eat(&token::Comma) {
4376 Ok((lifetimes, types, bindings))
4379 /// Parses an optional `where` clause and places it in `generics`.
4381 /// ```ignore (only-for-syntax-highlight)
4382 /// where T : Trait<U, V> + 'b, 'a : 'b
4384 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4385 maybe_whole!(self, NtWhereClause, |x| x);
4387 let mut where_clause = WhereClause {
4388 id: ast::DUMMY_NODE_ID,
4389 predicates: Vec::new(),
4390 span: syntax_pos::DUMMY_SP,
4393 if !self.eat_keyword(keywords::Where) {
4394 return Ok(where_clause);
4396 let lo = self.prev_span;
4398 // This is a temporary future proofing.
4400 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4401 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4402 // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4403 if token::Lt == self.token {
4404 let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4405 if ident_or_lifetime {
4406 let gt_comma_or_colon = self.look_ahead(2, |t| {
4407 *t == token::Gt || *t == token::Comma || *t == token::Colon
4409 if gt_comma_or_colon {
4410 self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4417 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4418 let lifetime = self.expect_lifetime();
4419 // Bounds starting with a colon are mandatory, but possibly empty.
4420 self.expect(&token::Colon)?;
4421 let bounds = self.parse_lt_param_bounds();
4422 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4423 ast::WhereRegionPredicate {
4424 span: lo.to(self.prev_span),
4429 } else if self.check_type() {
4430 // Parse optional `for<'a, 'b>`.
4431 // This `for` is parsed greedily and applies to the whole predicate,
4432 // the bounded type can have its own `for` applying only to it.
4433 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4434 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4435 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4436 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4438 // Parse type with mandatory colon and (possibly empty) bounds,
4439 // or with mandatory equality sign and the second type.
4440 let ty = self.parse_ty()?;
4441 if self.eat(&token::Colon) {
4442 let bounds = self.parse_ty_param_bounds()?;
4443 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4444 ast::WhereBoundPredicate {
4445 span: lo.to(self.prev_span),
4446 bound_lifetimes: lifetime_defs,
4451 // FIXME: Decide what should be used here, `=` or `==`.
4452 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4453 let rhs_ty = self.parse_ty()?;
4454 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4455 ast::WhereEqPredicate {
4456 span: lo.to(self.prev_span),
4459 id: ast::DUMMY_NODE_ID,
4463 return self.unexpected();
4469 if !self.eat(&token::Comma) {
4474 where_clause.span = lo.to(self.prev_span);
4478 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4479 -> PResult<'a, (Vec<Arg> , bool)> {
4481 let mut variadic = false;
4482 let args: Vec<Option<Arg>> =
4483 self.parse_unspanned_seq(
4484 &token::OpenDelim(token::Paren),
4485 &token::CloseDelim(token::Paren),
4486 SeqSep::trailing_allowed(token::Comma),
4488 if p.token == token::DotDotDot {
4491 if p.token != token::CloseDelim(token::Paren) {
4494 "`...` must be last in argument list for variadic function");
4499 "only foreign functions are allowed to be variadic");
4504 match p.parse_arg_general(named_args) {
4505 Ok(arg) => Ok(Some(arg)),
4508 let lo = p.prev_span;
4509 // Skip every token until next possible arg or end.
4510 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4511 // Create a placeholder argument for proper arg count (#34264).
4512 let span = lo.to(p.prev_span);
4513 Ok(Some(dummy_arg(span)))
4520 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4522 if variadic && args.is_empty() {
4524 "variadic function must be declared with at least one named argument");
4527 Ok((args, variadic))
4530 /// Parse the argument list and result type of a function declaration
4531 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4533 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4534 let ret_ty = self.parse_ret_ty()?;
4543 /// Returns the parsed optional self argument and whether a self shortcut was used.
4544 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4545 let expect_ident = |this: &mut Self| match this.token {
4546 // Preserve hygienic context.
4547 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4550 let isolated_self = |this: &mut Self, n| {
4551 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4552 this.look_ahead(n + 1, |t| t != &token::ModSep)
4555 // Parse optional self parameter of a method.
4556 // Only a limited set of initial token sequences is considered self parameters, anything
4557 // else is parsed as a normal function parameter list, so some lookahead is required.
4558 let eself_lo = self.span;
4559 let (eself, eself_ident) = match self.token {
4560 token::BinOp(token::And) => {
4566 if isolated_self(self, 1) {
4568 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4569 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4570 isolated_self(self, 2) {
4573 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4574 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4575 isolated_self(self, 2) {
4577 let lt = self.expect_lifetime();
4578 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4579 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4580 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4581 isolated_self(self, 3) {
4583 let lt = self.expect_lifetime();
4585 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4590 token::BinOp(token::Star) => {
4595 // Emit special error for `self` cases.
4596 if isolated_self(self, 1) {
4598 self.span_err(self.span, "cannot pass `self` by raw pointer");
4599 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4600 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4601 isolated_self(self, 2) {
4604 self.span_err(self.span, "cannot pass `self` by raw pointer");
4605 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4610 token::Ident(..) => {
4611 if isolated_self(self, 0) {
4614 let eself_ident = expect_ident(self);
4615 if self.eat(&token::Colon) {
4616 let ty = self.parse_ty()?;
4617 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4619 (SelfKind::Value(Mutability::Immutable), eself_ident)
4621 } else if self.token.is_keyword(keywords::Mut) &&
4622 isolated_self(self, 1) {
4626 let eself_ident = expect_ident(self);
4627 if self.eat(&token::Colon) {
4628 let ty = self.parse_ty()?;
4629 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4631 (SelfKind::Value(Mutability::Mutable), eself_ident)
4637 _ => return Ok(None),
4640 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
4641 Ok(Some(Arg::from_self(eself, eself_ident)))
4644 /// Parse the parameter list and result type of a function that may have a `self` parameter.
4645 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
4646 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4648 self.expect(&token::OpenDelim(token::Paren))?;
4650 // Parse optional self argument
4651 let self_arg = self.parse_self_arg()?;
4653 // Parse the rest of the function parameter list.
4654 let sep = SeqSep::trailing_allowed(token::Comma);
4655 let fn_inputs = if let Some(self_arg) = self_arg {
4656 if self.check(&token::CloseDelim(token::Paren)) {
4658 } else if self.eat(&token::Comma) {
4659 let mut fn_inputs = vec![self_arg];
4660 fn_inputs.append(&mut self.parse_seq_to_before_end(
4661 &token::CloseDelim(token::Paren), sep, parse_arg_fn)
4665 return self.unexpected();
4668 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4671 // Parse closing paren and return type.
4672 self.expect(&token::CloseDelim(token::Paren))?;
4675 output: self.parse_ret_ty()?,
4680 // parse the |arg, arg| header on a lambda
4681 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4682 let inputs_captures = {
4683 if self.eat(&token::OrOr) {
4686 self.expect(&token::BinOp(token::Or))?;
4687 let args = self.parse_seq_to_before_end(
4688 &token::BinOp(token::Or),
4689 SeqSep::trailing_allowed(token::Comma),
4690 |p| p.parse_fn_block_arg()
4696 let output = self.parse_ret_ty()?;
4699 inputs: inputs_captures,
4705 /// Parse the name and optional generic types of a function header.
4706 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4707 let id = self.parse_ident()?;
4708 let generics = self.parse_generics()?;
4712 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
4713 attrs: Vec<Attribute>) -> P<Item> {
4717 id: ast::DUMMY_NODE_ID,
4725 /// Parse an item-position function declaration.
4726 fn parse_item_fn(&mut self,
4728 constness: Spanned<Constness>,
4730 -> PResult<'a, ItemInfo> {
4731 let (ident, mut generics) = self.parse_fn_header()?;
4732 let decl = self.parse_fn_decl(false)?;
4733 generics.where_clause = self.parse_where_clause()?;
4734 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4735 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4738 /// true if we are looking at `const ID`, false for things like `const fn` etc
4739 pub fn is_const_item(&mut self) -> bool {
4740 self.token.is_keyword(keywords::Const) &&
4741 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4742 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4745 /// parses all the "front matter" for a `fn` declaration, up to
4746 /// and including the `fn` keyword:
4750 /// - `const unsafe fn`
4753 pub fn parse_fn_front_matter(&mut self)
4754 -> PResult<'a, (Spanned<ast::Constness>,
4757 let is_const_fn = self.eat_keyword(keywords::Const);
4758 let const_span = self.prev_span;
4759 let unsafety = self.parse_unsafety()?;
4760 let (constness, unsafety, abi) = if is_const_fn {
4761 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
4763 let abi = if self.eat_keyword(keywords::Extern) {
4764 self.parse_opt_abi()?.unwrap_or(Abi::C)
4768 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
4770 self.expect_keyword(keywords::Fn)?;
4771 Ok((constness, unsafety, abi))
4774 /// Parse an impl item.
4775 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
4776 maybe_whole!(self, NtImplItem, |x| x);
4777 let attrs = self.parse_outer_attributes()?;
4778 let (mut item, tokens) = self.collect_tokens(|this| {
4779 this.parse_impl_item_(at_end, attrs)
4782 // See `parse_item` for why this clause is here.
4783 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
4784 item.tokens = Some(tokens);
4789 fn parse_impl_item_(&mut self,
4791 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
4793 let vis = self.parse_visibility(false)?;
4794 let defaultness = self.parse_defaultness()?;
4795 let (name, node) = if self.eat_keyword(keywords::Type) {
4796 let name = self.parse_ident()?;
4797 self.expect(&token::Eq)?;
4798 let typ = self.parse_ty()?;
4799 self.expect(&token::Semi)?;
4800 (name, ast::ImplItemKind::Type(typ))
4801 } else if self.is_const_item() {
4802 self.expect_keyword(keywords::Const)?;
4803 let name = self.parse_ident()?;
4804 self.expect(&token::Colon)?;
4805 let typ = self.parse_ty()?;
4806 self.expect(&token::Eq)?;
4807 let expr = self.parse_expr()?;
4808 self.expect(&token::Semi)?;
4809 (name, ast::ImplItemKind::Const(typ, expr))
4811 let (name, inner_attrs, node) = self.parse_impl_method(&vis, at_end)?;
4812 attrs.extend(inner_attrs);
4817 id: ast::DUMMY_NODE_ID,
4818 span: lo.to(self.prev_span),
4828 fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
4829 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
4834 fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
4836 Visibility::Inherited => Ok(()),
4838 let is_macro_rules: bool = match self.token {
4839 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
4843 let mut err = self.diagnostic()
4844 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
4845 err.help("did you mean #[macro_export]?");
4848 let mut err = self.diagnostic()
4849 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
4850 err.help("try adjusting the macro to put `pub` inside the invocation");
4857 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
4858 -> DiagnosticBuilder<'a>
4860 // Given this code `path(`, it seems like this is not
4861 // setting the visibility of a macro invocation, but rather
4862 // a mistyped method declaration.
4863 // Create a diagnostic pointing out that `fn` is missing.
4865 // x | pub path(&self) {
4866 // | ^ missing `fn`, `type`, or `const`
4868 // ^^ `sp` below will point to this
4869 let sp = prev_span.between(self.prev_span);
4870 let mut err = self.diagnostic().struct_span_err(
4872 &format!("missing `fn`, `type`, or `const` for {}-item declaration",
4874 err.span_label(sp, "missing `fn`, `type`, or `const`");
4878 /// Parse a method or a macro invocation in a trait impl.
4879 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
4880 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4881 // code copied from parse_macro_use_or_failure... abstraction!
4882 if self.token.is_path_start() {
4885 let prev_span = self.prev_span;
4888 let pth = self.parse_path(PathStyle::Mod)?;
4889 if pth.segments.len() == 1 {
4890 if !self.eat(&token::Not) {
4891 return Err(self.missing_assoc_item_kind_err("impl", prev_span));
4894 self.expect(&token::Not)?;
4897 self.complain_if_pub_macro(vis, prev_span);
4899 // eat a matched-delimiter token tree:
4901 let (delim, tts) = self.expect_delimited_token_tree()?;
4902 if delim != token::Brace {
4903 self.expect(&token::Semi)?
4906 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
4907 Ok((keywords::Invalid.ident(), vec![], ast::ImplItemKind::Macro(mac)))
4909 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
4910 let ident = self.parse_ident()?;
4911 let mut generics = self.parse_generics()?;
4912 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
4913 generics.where_clause = self.parse_where_clause()?;
4915 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4916 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4926 /// Parse trait Foo { ... }
4927 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4928 let ident = self.parse_ident()?;
4929 let mut tps = self.parse_generics()?;
4931 // Parse optional colon and supertrait bounds.
4932 let bounds = if self.eat(&token::Colon) {
4933 self.parse_ty_param_bounds()?
4938 tps.where_clause = self.parse_where_clause()?;
4940 self.expect(&token::OpenDelim(token::Brace))?;
4941 let mut trait_items = vec![];
4942 while !self.eat(&token::CloseDelim(token::Brace)) {
4943 let mut at_end = false;
4944 match self.parse_trait_item(&mut at_end) {
4945 Ok(item) => trait_items.push(item),
4949 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
4954 Ok((ident, ItemKind::Trait(unsafety, tps, bounds, trait_items), None))
4957 /// Parses items implementations variants
4958 /// impl<T> Foo { ... }
4959 /// impl<T> ToString for &'static T { ... }
4960 /// impl Send for .. {}
4961 fn parse_item_impl(&mut self,
4962 unsafety: ast::Unsafety,
4963 defaultness: Defaultness) -> PResult<'a, ItemInfo> {
4964 let impl_span = self.span;
4966 // First, parse type parameters if necessary.
4967 let mut generics = self.parse_generics()?;
4969 // Special case: if the next identifier that follows is '(', don't
4970 // allow this to be parsed as a trait.
4971 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4973 let neg_span = self.span;
4974 let polarity = if self.eat(&token::Not) {
4975 ast::ImplPolarity::Negative
4977 ast::ImplPolarity::Positive
4981 let mut ty = self.parse_ty()?;
4983 // Parse traits, if necessary.
4984 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4985 // New-style trait. Reinterpret the type as a trait.
4987 TyKind::Path(None, ref path) => {
4989 path: (*path).clone(),
4994 self.span_err(ty.span, "not a trait");
4999 if polarity == ast::ImplPolarity::Negative {
5000 // This is a negated type implementation
5001 // `impl !MyType {}`, which is not allowed.
5002 self.span_err(neg_span, "inherent implementation can't be negated");
5007 if opt_trait.is_some() && self.eat(&token::DotDot) {
5008 if generics.is_parameterized() {
5009 self.span_err(impl_span, "default trait implementations are not \
5010 allowed to have generics");
5013 if let ast::Defaultness::Default = defaultness {
5014 self.span_err(impl_span, "`default impl` is not allowed for \
5015 default trait implementations");
5018 self.expect(&token::OpenDelim(token::Brace))?;
5019 self.expect(&token::CloseDelim(token::Brace))?;
5020 Ok((keywords::Invalid.ident(),
5021 ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
5023 if opt_trait.is_some() {
5024 ty = self.parse_ty()?;
5026 generics.where_clause = self.parse_where_clause()?;
5028 self.expect(&token::OpenDelim(token::Brace))?;
5029 let attrs = self.parse_inner_attributes()?;
5031 let mut impl_items = vec![];
5032 while !self.eat(&token::CloseDelim(token::Brace)) {
5033 let mut at_end = false;
5034 match self.parse_impl_item(&mut at_end) {
5035 Ok(item) => impl_items.push(item),
5039 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5045 Ok((keywords::Invalid.ident(),
5046 ItemKind::Impl(unsafety, polarity, defaultness, generics, opt_trait, ty, impl_items),
5051 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<LifetimeDef>> {
5052 if self.eat_keyword(keywords::For) {
5054 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
5056 if !ty_params.is_empty() {
5057 self.span_err(ty_params[0].span,
5058 "only lifetime parameters can be used in this context");
5066 /// Parse struct Foo { ... }
5067 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5068 let class_name = self.parse_ident()?;
5070 let mut generics = self.parse_generics()?;
5072 // There is a special case worth noting here, as reported in issue #17904.
5073 // If we are parsing a tuple struct it is the case that the where clause
5074 // should follow the field list. Like so:
5076 // struct Foo<T>(T) where T: Copy;
5078 // If we are parsing a normal record-style struct it is the case
5079 // that the where clause comes before the body, and after the generics.
5080 // So if we look ahead and see a brace or a where-clause we begin
5081 // parsing a record style struct.
5083 // Otherwise if we look ahead and see a paren we parse a tuple-style
5086 let vdata = if self.token.is_keyword(keywords::Where) {
5087 generics.where_clause = self.parse_where_clause()?;
5088 if self.eat(&token::Semi) {
5089 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5090 VariantData::Unit(ast::DUMMY_NODE_ID)
5092 // If we see: `struct Foo<T> where T: Copy { ... }`
5093 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5095 // No `where` so: `struct Foo<T>;`
5096 } else if self.eat(&token::Semi) {
5097 VariantData::Unit(ast::DUMMY_NODE_ID)
5098 // Record-style struct definition
5099 } else if self.token == token::OpenDelim(token::Brace) {
5100 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5101 // Tuple-style struct definition with optional where-clause.
5102 } else if self.token == token::OpenDelim(token::Paren) {
5103 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5104 generics.where_clause = self.parse_where_clause()?;
5105 self.expect(&token::Semi)?;
5108 let token_str = self.this_token_to_string();
5109 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5110 name, found `{}`", token_str)))
5113 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5116 /// Parse union Foo { ... }
5117 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5118 let class_name = self.parse_ident()?;
5120 let mut generics = self.parse_generics()?;
5122 let vdata = if self.token.is_keyword(keywords::Where) {
5123 generics.where_clause = self.parse_where_clause()?;
5124 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5125 } else if self.token == token::OpenDelim(token::Brace) {
5126 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5128 let token_str = self.this_token_to_string();
5129 return Err(self.fatal(&format!("expected `where` or `{{` after union \
5130 name, found `{}`", token_str)))
5133 Ok((class_name, ItemKind::Union(vdata, generics), None))
5136 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5137 let mut fields = Vec::new();
5138 if self.eat(&token::OpenDelim(token::Brace)) {
5139 while self.token != token::CloseDelim(token::Brace) {
5140 fields.push(self.parse_struct_decl_field().map_err(|e| {
5141 self.recover_stmt();
5142 self.eat(&token::CloseDelim(token::Brace));
5149 let token_str = self.this_token_to_string();
5150 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5158 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5159 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5160 // Unit like structs are handled in parse_item_struct function
5161 let fields = self.parse_unspanned_seq(
5162 &token::OpenDelim(token::Paren),
5163 &token::CloseDelim(token::Paren),
5164 SeqSep::trailing_allowed(token::Comma),
5166 let attrs = p.parse_outer_attributes()?;
5168 let vis = p.parse_visibility(true)?;
5169 let ty = p.parse_ty()?;
5171 span: lo.to(p.span),
5174 id: ast::DUMMY_NODE_ID,
5183 /// Parse a structure field declaration
5184 pub fn parse_single_struct_field(&mut self,
5187 attrs: Vec<Attribute> )
5188 -> PResult<'a, StructField> {
5189 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5194 token::CloseDelim(token::Brace) => {}
5195 token::DocComment(_) => return Err(self.span_fatal_err(self.span,
5196 Error::UselessDocComment)),
5197 _ => return Err(self.span_fatal_help(self.span,
5198 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5199 "struct fields should be separated by commas")),
5204 /// Parse an element of a struct definition
5205 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5206 let attrs = self.parse_outer_attributes()?;
5208 let vis = self.parse_visibility(false)?;
5209 self.parse_single_struct_field(lo, vis, attrs)
5212 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5213 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5214 /// a function definition, it's not a tuple struct field) and the contents within the parens
5215 /// isn't valid, emit a proper diagnostic.
5216 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5217 maybe_whole!(self, NtVis, |x| x);
5219 if !self.eat_keyword(keywords::Pub) {
5220 return Ok(Visibility::Inherited)
5223 if self.check(&token::OpenDelim(token::Paren)) {
5224 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5225 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5226 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5227 // by the following tokens.
5228 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5231 self.bump(); // `crate`
5232 let vis = Visibility::Crate(self.prev_span);
5233 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5235 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5238 self.bump(); // `in`
5239 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5240 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5241 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5243 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5244 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5245 t.is_keyword(keywords::SelfValue)) {
5246 // `pub(self)` or `pub(super)`
5248 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5249 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5250 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5252 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5253 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5255 let msg = "incorrect visibility restriction";
5256 let suggestion = r##"some possible visibility restrictions are:
5257 `pub(crate)`: visible only on the current crate
5258 `pub(super)`: visible only in the current module's parent
5259 `pub(in path::to::module)`: visible only on the specified path"##;
5260 let path = self.parse_path(PathStyle::Mod)?;
5261 let path_span = self.prev_span;
5262 let help_msg = format!("make this visible only to module `{}` with `in`", path);
5263 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5264 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5265 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5266 err.emit(); // emit diagnostic, but continue with public visibility
5270 Ok(Visibility::Public)
5273 /// Parse defaultness: DEFAULT or nothing
5274 fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5275 if self.eat_defaultness() {
5276 Ok(Defaultness::Default)
5278 Ok(Defaultness::Final)
5282 /// Given a termination token, parse all of the items in a module
5283 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5284 let mut items = vec![];
5285 while let Some(item) = self.parse_item()? {
5289 if !self.eat(term) {
5290 let token_str = self.this_token_to_string();
5291 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5294 let hi = if self.span == syntax_pos::DUMMY_SP {
5301 inner: inner_lo.to(hi),
5306 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5307 let id = self.parse_ident()?;
5308 self.expect(&token::Colon)?;
5309 let ty = self.parse_ty()?;
5310 self.expect(&token::Eq)?;
5311 let e = self.parse_expr()?;
5312 self.expect(&token::Semi)?;
5313 let item = match m {
5314 Some(m) => ItemKind::Static(ty, m, e),
5315 None => ItemKind::Const(ty, e),
5317 Ok((id, item, None))
5320 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5321 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5322 let (in_cfg, outer_attrs) = {
5323 let mut strip_unconfigured = ::config::StripUnconfigured {
5325 should_test: false, // irrelevant
5326 features: None, // don't perform gated feature checking
5328 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5329 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5332 let id_span = self.span;
5333 let id = self.parse_ident()?;
5334 if self.check(&token::Semi) {
5336 if in_cfg && self.recurse_into_file_modules {
5337 // This mod is in an external file. Let's go get it!
5338 let ModulePathSuccess { path, directory_ownership, warn } =
5339 self.submod_path(id, &outer_attrs, id_span)?;
5340 let (module, mut attrs) =
5341 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5343 let attr = ast::Attribute {
5344 id: attr::mk_attr_id(),
5345 style: ast::AttrStyle::Outer,
5346 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5347 Ident::from_str("warn_directory_ownership")),
5348 tokens: TokenStream::empty(),
5349 is_sugared_doc: false,
5350 span: syntax_pos::DUMMY_SP,
5352 attr::mark_known(&attr);
5355 Ok((id, module, Some(attrs)))
5357 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5358 Ok((id, ItemKind::Mod(placeholder), None))
5361 let old_directory = self.directory.clone();
5362 self.push_directory(id, &outer_attrs);
5364 self.expect(&token::OpenDelim(token::Brace))?;
5365 let mod_inner_lo = self.span;
5366 let attrs = self.parse_inner_attributes()?;
5367 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5369 self.directory = old_directory;
5370 Ok((id, ItemKind::Mod(module), Some(attrs)))
5374 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5375 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5376 self.directory.path.push(&path.as_str());
5377 self.directory.ownership = DirectoryOwnership::Owned;
5379 self.directory.path.push(&id.name.as_str());
5383 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5384 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5387 /// Returns either a path to a module, or .
5388 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5389 let mod_name = id.to_string();
5390 let default_path_str = format!("{}.rs", mod_name);
5391 let secondary_path_str = format!("{}{}mod.rs", mod_name, path::MAIN_SEPARATOR);
5392 let default_path = dir_path.join(&default_path_str);
5393 let secondary_path = dir_path.join(&secondary_path_str);
5394 let default_exists = codemap.file_exists(&default_path);
5395 let secondary_exists = codemap.file_exists(&secondary_path);
5397 let result = match (default_exists, secondary_exists) {
5398 (true, false) => Ok(ModulePathSuccess {
5400 directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5403 (false, true) => Ok(ModulePathSuccess {
5404 path: secondary_path,
5405 directory_ownership: DirectoryOwnership::Owned,
5408 (false, false) => Err(Error::FileNotFoundForModule {
5409 mod_name: mod_name.clone(),
5410 default_path: default_path_str,
5411 secondary_path: secondary_path_str,
5412 dir_path: format!("{}", dir_path.display()),
5414 (true, true) => Err(Error::DuplicatePaths {
5415 mod_name: mod_name.clone(),
5416 default_path: default_path_str,
5417 secondary_path: secondary_path_str,
5423 path_exists: default_exists || secondary_exists,
5428 fn submod_path(&mut self,
5430 outer_attrs: &[ast::Attribute],
5432 -> PResult<'a, ModulePathSuccess> {
5433 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5434 return Ok(ModulePathSuccess {
5435 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5436 Some("mod.rs") => DirectoryOwnership::Owned,
5437 _ => DirectoryOwnership::UnownedViaMod(true),
5444 let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5446 if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5448 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5449 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5450 if paths.path_exists {
5451 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5453 err.span_note(id_sp, &msg);
5456 } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5458 if let Ok(result) = paths.result {
5459 return Ok(ModulePathSuccess { warn: true, ..result });
5462 let mut err = self.diagnostic().struct_span_err(id_sp,
5463 "cannot declare a new module at this location");
5464 if id_sp != syntax_pos::DUMMY_SP {
5465 let src_path = PathBuf::from(self.sess.codemap().span_to_filename(id_sp));
5466 if let Some(stem) = src_path.file_stem() {
5467 let mut dest_path = src_path.clone();
5468 dest_path.set_file_name(stem);
5469 dest_path.push("mod.rs");
5470 err.span_note(id_sp,
5471 &format!("maybe move this module `{}` to its own \
5472 directory via `{}`", src_path.to_string_lossy(),
5473 dest_path.to_string_lossy()));
5476 if paths.path_exists {
5477 err.span_note(id_sp,
5478 &format!("... or maybe `use` the module `{}` instead \
5479 of possibly redeclaring it",
5484 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5488 /// Read a module from a source file.
5489 fn eval_src_mod(&mut self,
5491 directory_ownership: DirectoryOwnership,
5494 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5495 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5496 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5497 let mut err = String::from("circular modules: ");
5498 let len = included_mod_stack.len();
5499 for p in &included_mod_stack[i.. len] {
5500 err.push_str(&p.to_string_lossy());
5501 err.push_str(" -> ");
5503 err.push_str(&path.to_string_lossy());
5504 return Err(self.span_fatal(id_sp, &err[..]));
5506 included_mod_stack.push(path.clone());
5507 drop(included_mod_stack);
5510 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5511 p0.cfg_mods = self.cfg_mods;
5512 let mod_inner_lo = p0.span;
5513 let mod_attrs = p0.parse_inner_attributes()?;
5514 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5515 self.sess.included_mod_stack.borrow_mut().pop();
5516 Ok((ast::ItemKind::Mod(m0), mod_attrs))
5519 /// Parse a function declaration from a foreign module
5520 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5521 -> PResult<'a, ForeignItem> {
5522 self.expect_keyword(keywords::Fn)?;
5524 let (ident, mut generics) = self.parse_fn_header()?;
5525 let decl = self.parse_fn_decl(true)?;
5526 generics.where_clause = self.parse_where_clause()?;
5528 self.expect(&token::Semi)?;
5529 Ok(ast::ForeignItem {
5532 node: ForeignItemKind::Fn(decl, generics),
5533 id: ast::DUMMY_NODE_ID,
5539 /// Parse a static item from a foreign module.
5540 /// Assumes that the `static` keyword is already parsed.
5541 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5542 -> PResult<'a, ForeignItem> {
5543 let mutbl = self.eat_keyword(keywords::Mut);
5544 let ident = self.parse_ident()?;
5545 self.expect(&token::Colon)?;
5546 let ty = self.parse_ty()?;
5548 self.expect(&token::Semi)?;
5552 node: ForeignItemKind::Static(ty, mutbl),
5553 id: ast::DUMMY_NODE_ID,
5559 /// Parse extern crate links
5563 /// extern crate foo;
5564 /// extern crate bar as foo;
5565 fn parse_item_extern_crate(&mut self,
5567 visibility: Visibility,
5568 attrs: Vec<Attribute>)
5569 -> PResult<'a, P<Item>> {
5571 let crate_name = self.parse_ident()?;
5572 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
5573 (Some(crate_name.name), ident)
5577 self.expect(&token::Semi)?;
5579 let prev_span = self.prev_span;
5580 Ok(self.mk_item(lo.to(prev_span),
5582 ItemKind::ExternCrate(maybe_path),
5587 /// Parse `extern` for foreign ABIs
5590 /// `extern` is expected to have been
5591 /// consumed before calling this method
5597 fn parse_item_foreign_mod(&mut self,
5599 opt_abi: Option<abi::Abi>,
5600 visibility: Visibility,
5601 mut attrs: Vec<Attribute>)
5602 -> PResult<'a, P<Item>> {
5603 self.expect(&token::OpenDelim(token::Brace))?;
5605 let abi = opt_abi.unwrap_or(Abi::C);
5607 attrs.extend(self.parse_inner_attributes()?);
5609 let mut foreign_items = vec![];
5610 while let Some(item) = self.parse_foreign_item()? {
5611 foreign_items.push(item);
5613 self.expect(&token::CloseDelim(token::Brace))?;
5615 let prev_span = self.prev_span;
5616 let m = ast::ForeignMod {
5618 items: foreign_items
5620 let invalid = keywords::Invalid.ident();
5621 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
5624 /// Parse type Foo = Bar;
5625 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5626 let ident = self.parse_ident()?;
5627 let mut tps = self.parse_generics()?;
5628 tps.where_clause = self.parse_where_clause()?;
5629 self.expect(&token::Eq)?;
5630 let ty = self.parse_ty()?;
5631 self.expect(&token::Semi)?;
5632 Ok((ident, ItemKind::Ty(ty, tps), None))
5635 /// Parse the part of an "enum" decl following the '{'
5636 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5637 let mut variants = Vec::new();
5638 let mut all_nullary = true;
5639 let mut any_disr = None;
5640 while self.token != token::CloseDelim(token::Brace) {
5641 let variant_attrs = self.parse_outer_attributes()?;
5642 let vlo = self.span;
5645 let mut disr_expr = None;
5646 let ident = self.parse_ident()?;
5647 if self.check(&token::OpenDelim(token::Brace)) {
5648 // Parse a struct variant.
5649 all_nullary = false;
5650 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
5651 ast::DUMMY_NODE_ID);
5652 } else if self.check(&token::OpenDelim(token::Paren)) {
5653 all_nullary = false;
5654 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
5655 ast::DUMMY_NODE_ID);
5656 } else if self.eat(&token::Eq) {
5657 disr_expr = Some(self.parse_expr()?);
5658 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5659 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5661 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5664 let vr = ast::Variant_ {
5666 attrs: variant_attrs,
5670 variants.push(respan(vlo.to(self.prev_span), vr));
5672 if !self.eat(&token::Comma) { break; }
5674 self.expect(&token::CloseDelim(token::Brace))?;
5676 Some(disr_span) if !all_nullary =>
5677 self.span_err(disr_span,
5678 "discriminator values can only be used with a c-like enum"),
5682 Ok(ast::EnumDef { variants: variants })
5685 /// Parse an "enum" declaration
5686 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5687 let id = self.parse_ident()?;
5688 let mut generics = self.parse_generics()?;
5689 generics.where_clause = self.parse_where_clause()?;
5690 self.expect(&token::OpenDelim(token::Brace))?;
5692 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
5693 self.recover_stmt();
5694 self.eat(&token::CloseDelim(token::Brace));
5697 Ok((id, ItemKind::Enum(enum_definition, generics), None))
5700 /// Parses a string as an ABI spec on an extern type or module. Consumes
5701 /// the `extern` keyword, if one is found.
5702 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5704 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5706 self.expect_no_suffix(sp, "ABI spec", suf);
5708 match abi::lookup(&s.as_str()) {
5709 Some(abi) => Ok(Some(abi)),
5711 let prev_span = self.prev_span;
5714 &format!("invalid ABI: expected one of [{}], \
5716 abi::all_names().join(", "),
5727 /// Parse one of the items allowed by the flags.
5728 /// NB: this function no longer parses the items inside an
5730 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5731 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5732 maybe_whole!(self, NtItem, |item| {
5733 let mut item = item.unwrap();
5734 let mut attrs = attrs;
5735 mem::swap(&mut item.attrs, &mut attrs);
5736 item.attrs.extend(attrs);
5742 let visibility = self.parse_visibility(false)?;
5744 if self.eat_keyword(keywords::Use) {
5746 let item_ = ItemKind::Use(self.parse_view_path()?);
5747 self.expect(&token::Semi)?;
5749 let prev_span = self.prev_span;
5750 let invalid = keywords::Invalid.ident();
5751 let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
5752 return Ok(Some(item));
5755 if self.eat_keyword(keywords::Extern) {
5756 if self.eat_keyword(keywords::Crate) {
5757 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
5760 let opt_abi = self.parse_opt_abi()?;
5762 if self.eat_keyword(keywords::Fn) {
5763 // EXTERN FUNCTION ITEM
5764 let fn_span = self.prev_span;
5765 let abi = opt_abi.unwrap_or(Abi::C);
5766 let (ident, item_, extra_attrs) =
5767 self.parse_item_fn(Unsafety::Normal,
5768 respan(fn_span, Constness::NotConst),
5770 let prev_span = self.prev_span;
5771 let item = self.mk_item(lo.to(prev_span),
5775 maybe_append(attrs, extra_attrs));
5776 return Ok(Some(item));
5777 } else if self.check(&token::OpenDelim(token::Brace)) {
5778 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
5784 if self.eat_keyword(keywords::Static) {
5786 let m = if self.eat_keyword(keywords::Mut) {
5789 Mutability::Immutable
5791 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
5792 let prev_span = self.prev_span;
5793 let item = self.mk_item(lo.to(prev_span),
5797 maybe_append(attrs, extra_attrs));
5798 return Ok(Some(item));
5800 if self.eat_keyword(keywords::Const) {
5801 let const_span = self.prev_span;
5802 if self.check_keyword(keywords::Fn)
5803 || (self.check_keyword(keywords::Unsafe)
5804 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5805 // CONST FUNCTION ITEM
5806 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5812 let (ident, item_, extra_attrs) =
5813 self.parse_item_fn(unsafety,
5814 respan(const_span, Constness::Const),
5816 let prev_span = self.prev_span;
5817 let item = self.mk_item(lo.to(prev_span),
5821 maybe_append(attrs, extra_attrs));
5822 return Ok(Some(item));
5826 if self.eat_keyword(keywords::Mut) {
5827 let prev_span = self.prev_span;
5828 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
5829 .help("did you mean to declare a static?")
5832 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
5833 let prev_span = self.prev_span;
5834 let item = self.mk_item(lo.to(prev_span),
5838 maybe_append(attrs, extra_attrs));
5839 return Ok(Some(item));
5841 if self.check_keyword(keywords::Unsafe) &&
5842 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5844 // UNSAFE TRAIT ITEM
5845 self.expect_keyword(keywords::Unsafe)?;
5846 self.expect_keyword(keywords::Trait)?;
5847 let (ident, item_, extra_attrs) =
5848 self.parse_item_trait(ast::Unsafety::Unsafe)?;
5849 let prev_span = self.prev_span;
5850 let item = self.mk_item(lo.to(prev_span),
5854 maybe_append(attrs, extra_attrs));
5855 return Ok(Some(item));
5857 if (self.check_keyword(keywords::Unsafe) &&
5858 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))) ||
5859 (self.check_keyword(keywords::Default) &&
5860 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) &&
5861 self.look_ahead(2, |t| t.is_keyword(keywords::Impl)))
5864 let defaultness = self.parse_defaultness()?;
5865 self.expect_keyword(keywords::Unsafe)?;
5866 self.expect_keyword(keywords::Impl)?;
5869 extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe, defaultness)?;
5870 let prev_span = self.prev_span;
5871 let item = self.mk_item(lo.to(prev_span),
5875 maybe_append(attrs, extra_attrs));
5876 return Ok(Some(item));
5878 if self.check_keyword(keywords::Fn) {
5881 let fn_span = self.prev_span;
5882 let (ident, item_, extra_attrs) =
5883 self.parse_item_fn(Unsafety::Normal,
5884 respan(fn_span, Constness::NotConst),
5886 let prev_span = self.prev_span;
5887 let item = self.mk_item(lo.to(prev_span),
5891 maybe_append(attrs, extra_attrs));
5892 return Ok(Some(item));
5894 if self.check_keyword(keywords::Unsafe)
5895 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5896 // UNSAFE FUNCTION ITEM
5898 let abi = if self.eat_keyword(keywords::Extern) {
5899 self.parse_opt_abi()?.unwrap_or(Abi::C)
5903 self.expect_keyword(keywords::Fn)?;
5904 let fn_span = self.prev_span;
5905 let (ident, item_, extra_attrs) =
5906 self.parse_item_fn(Unsafety::Unsafe,
5907 respan(fn_span, Constness::NotConst),
5909 let prev_span = self.prev_span;
5910 let item = self.mk_item(lo.to(prev_span),
5914 maybe_append(attrs, extra_attrs));
5915 return Ok(Some(item));
5917 if self.eat_keyword(keywords::Mod) {
5919 let (ident, item_, extra_attrs) =
5920 self.parse_item_mod(&attrs[..])?;
5921 let prev_span = self.prev_span;
5922 let item = self.mk_item(lo.to(prev_span),
5926 maybe_append(attrs, extra_attrs));
5927 return Ok(Some(item));
5929 if self.eat_keyword(keywords::Type) {
5931 let (ident, item_, extra_attrs) = self.parse_item_type()?;
5932 let prev_span = self.prev_span;
5933 let item = self.mk_item(lo.to(prev_span),
5937 maybe_append(attrs, extra_attrs));
5938 return Ok(Some(item));
5940 if self.eat_keyword(keywords::Enum) {
5942 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
5943 let prev_span = self.prev_span;
5944 let item = self.mk_item(lo.to(prev_span),
5948 maybe_append(attrs, extra_attrs));
5949 return Ok(Some(item));
5951 if self.eat_keyword(keywords::Trait) {
5953 let (ident, item_, extra_attrs) =
5954 self.parse_item_trait(ast::Unsafety::Normal)?;
5955 let prev_span = self.prev_span;
5956 let item = self.mk_item(lo.to(prev_span),
5960 maybe_append(attrs, extra_attrs));
5961 return Ok(Some(item));
5963 if (self.check_keyword(keywords::Impl)) ||
5964 (self.check_keyword(keywords::Default) &&
5965 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)))
5968 let defaultness = self.parse_defaultness()?;
5969 self.expect_keyword(keywords::Impl)?;
5972 extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal, defaultness)?;
5973 let prev_span = self.prev_span;
5974 let item = self.mk_item(lo.to(prev_span),
5978 maybe_append(attrs, extra_attrs));
5979 return Ok(Some(item));
5981 if self.eat_keyword(keywords::Struct) {
5983 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
5984 let prev_span = self.prev_span;
5985 let item = self.mk_item(lo.to(prev_span),
5989 maybe_append(attrs, extra_attrs));
5990 return Ok(Some(item));
5992 if self.is_union_item() {
5995 let (ident, item_, extra_attrs) = self.parse_item_union()?;
5996 let prev_span = self.prev_span;
5997 let item = self.mk_item(lo.to(prev_span),
6001 maybe_append(attrs, extra_attrs));
6002 return Ok(Some(item));
6004 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility)? {
6005 return Ok(Some(macro_def));
6008 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
6011 /// Parse a foreign item.
6012 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
6013 let attrs = self.parse_outer_attributes()?;
6015 let visibility = self.parse_visibility(false)?;
6017 // FOREIGN STATIC ITEM
6018 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
6019 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
6020 if self.token.is_keyword(keywords::Const) {
6022 .struct_span_err(self.span, "extern items cannot be `const`")
6023 .span_suggestion(self.span, "instead try using", "static".to_owned())
6026 self.bump(); // `static` or `const`
6027 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6029 // FOREIGN FUNCTION ITEM
6030 if self.check_keyword(keywords::Fn) {
6031 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6034 // FIXME #5668: this will occur for a macro invocation:
6035 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
6037 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
6043 /// This is the fall-through for parsing items.
6044 fn parse_macro_use_or_failure(
6046 attrs: Vec<Attribute> ,
6047 macros_allowed: bool,
6048 attributes_allowed: bool,
6050 visibility: Visibility
6051 ) -> PResult<'a, Option<P<Item>>> {
6052 if macros_allowed && self.token.is_path_start() {
6053 // MACRO INVOCATION ITEM
6055 let prev_span = self.prev_span;
6056 self.complain_if_pub_macro(&visibility, prev_span);
6058 let mac_lo = self.span;
6061 let pth = self.parse_path(PathStyle::Mod)?;
6062 self.expect(&token::Not)?;
6064 // a 'special' identifier (like what `macro_rules!` uses)
6065 // is optional. We should eventually unify invoc syntax
6067 let id = if self.token.is_ident() {
6070 keywords::Invalid.ident() // no special identifier
6072 // eat a matched-delimiter token tree:
6073 let (delim, tts) = self.expect_delimited_token_tree()?;
6074 if delim != token::Brace {
6075 if !self.eat(&token::Semi) {
6076 self.span_err(self.prev_span,
6077 "macros that expand to items must either \
6078 be surrounded with braces or followed by \
6083 let hi = self.prev_span;
6084 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6085 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6086 return Ok(Some(item));
6089 // FAILURE TO PARSE ITEM
6091 Visibility::Inherited => {}
6093 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
6097 if !attributes_allowed && !attrs.is_empty() {
6098 self.expected_item_err(&attrs);
6103 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
6104 where F: FnOnce(&mut Self) -> PResult<'a, R>
6106 // Record all tokens we parse when parsing this item.
6107 let mut tokens = Vec::new();
6108 match self.token_cursor.frame.last_token {
6109 LastToken::Collecting(_) => {
6110 panic!("cannot collect tokens recursively yet")
6112 LastToken::Was(ref mut last) => tokens.extend(last.take()),
6114 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
6115 let prev = self.token_cursor.stack.len();
6117 let last_token = if self.token_cursor.stack.len() == prev {
6118 &mut self.token_cursor.frame.last_token
6120 &mut self.token_cursor.stack[prev].last_token
6122 let mut tokens = match *last_token {
6123 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
6124 LastToken::Was(_) => panic!("our vector went away?"),
6127 // If we're not at EOF our current token wasn't actually consumed by
6128 // `f`, but it'll still be in our list that we pulled out. In that case
6130 if self.token == token::Eof {
6131 *last_token = LastToken::Was(None);
6133 *last_token = LastToken::Was(tokens.pop());
6136 Ok((ret?, tokens.into_iter().collect()))
6139 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6140 let attrs = self.parse_outer_attributes()?;
6142 let (ret, tokens) = self.collect_tokens(|this| {
6143 this.parse_item_(attrs, true, false)
6146 // Once we've parsed an item and recorded the tokens we got while
6147 // parsing we may want to store `tokens` into the item we're about to
6148 // return. Note, though, that we specifically didn't capture tokens
6149 // related to outer attributes. The `tokens` field here may later be
6150 // used with procedural macros to convert this item back into a token
6151 // stream, but during expansion we may be removing attributes as we go
6154 // If we've got inner attributes then the `tokens` we've got above holds
6155 // these inner attributes. If an inner attribute is expanded we won't
6156 // actually remove it from the token stream, so we'll just keep yielding
6157 // it (bad!). To work around this case for now we just avoid recording
6158 // `tokens` if we detect any inner attributes. This should help keep
6159 // expansion correct, but we should fix this bug one day!
6162 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6163 i.tokens = Some(tokens);
6170 fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> {
6171 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
6172 &token::CloseDelim(token::Brace),
6173 SeqSep::trailing_allowed(token::Comma), |this| {
6175 let ident = if this.eat_keyword(keywords::SelfValue) {
6176 keywords::SelfValue.ident()
6180 let rename = this.parse_rename()?;
6181 let node = ast::PathListItem_ {
6184 id: ast::DUMMY_NODE_ID
6186 Ok(respan(lo.to(this.prev_span), node))
6191 fn is_import_coupler(&mut self) -> bool {
6192 self.check(&token::ModSep) &&
6193 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6194 *t == token::BinOp(token::Star))
6197 /// Matches ViewPath:
6198 /// MOD_SEP? non_global_path
6199 /// MOD_SEP? non_global_path as IDENT
6200 /// MOD_SEP? non_global_path MOD_SEP STAR
6201 /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE
6202 /// MOD_SEP? LBRACE item_seq RBRACE
6203 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
6205 if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) ||
6206 self.is_import_coupler() {
6207 // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`.
6208 self.eat(&token::ModSep);
6209 let prefix = ast::Path {
6210 segments: vec![PathSegment::crate_root(lo)],
6211 span: lo.to(self.span),
6213 let view_path_kind = if self.eat(&token::BinOp(token::Star)) {
6214 ViewPathGlob(prefix)
6216 ViewPathList(prefix, self.parse_path_list_items()?)
6218 Ok(P(respan(lo.to(self.span), view_path_kind)))
6220 let prefix = self.parse_path(PathStyle::Mod)?.default_to_global();
6221 if self.is_import_coupler() {
6222 // `foo::bar::{a, b}` or `foo::bar::*`
6224 if self.check(&token::BinOp(token::Star)) {
6226 Ok(P(respan(lo.to(self.span), ViewPathGlob(prefix))))
6228 let items = self.parse_path_list_items()?;
6229 Ok(P(respan(lo.to(self.span), ViewPathList(prefix, items))))
6232 // `foo::bar` or `foo::bar as baz`
6233 let rename = self.parse_rename()?.
6234 unwrap_or(prefix.segments.last().unwrap().identifier);
6235 Ok(P(respan(lo.to(self.prev_span), ViewPathSimple(rename, prefix))))
6240 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6241 if self.eat_keyword(keywords::As) {
6242 self.parse_ident().map(Some)
6248 /// Parses a source module as a crate. This is the main
6249 /// entry point for the parser.
6250 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6253 attrs: self.parse_inner_attributes()?,
6254 module: self.parse_mod_items(&token::Eof, lo)?,
6255 span: lo.to(self.span),
6259 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6260 let ret = match self.token {
6261 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6262 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6269 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6270 match self.parse_optional_str() {
6271 Some((s, style, suf)) => {
6272 let sp = self.prev_span;
6273 self.expect_no_suffix(sp, "string literal", suf);
6276 _ => Err(self.fatal("expected string literal"))