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 struct Restrictions: u8 {
68 const STMT_EXPR = 1 << 0;
69 const 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 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
485 enum TokenExpectType {
490 impl<'a> Parser<'a> {
491 pub fn new(sess: &'a ParseSess,
493 directory: Option<Directory>,
494 recurse_into_file_modules: bool,
495 desugar_doc_comments: bool)
497 let mut parser = Parser {
499 token: token::Underscore,
500 span: syntax_pos::DUMMY_SP,
501 prev_span: syntax_pos::DUMMY_SP,
503 prev_token_kind: PrevTokenKind::Other,
504 restrictions: Restrictions::empty(),
505 obsolete_set: HashSet::new(),
506 recurse_into_file_modules,
507 directory: Directory { path: PathBuf::new(), ownership: DirectoryOwnership::Owned },
508 root_module_name: None,
509 expected_tokens: Vec::new(),
510 token_cursor: TokenCursor {
511 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
512 delim: token::NoDelim,
517 desugar_doc_comments,
521 let tok = parser.next_tok();
522 parser.token = tok.tok;
523 parser.span = tok.sp;
525 if let Some(directory) = directory {
526 parser.directory = directory;
527 } else if parser.span != syntax_pos::DUMMY_SP {
528 parser.directory.path = PathBuf::from(sess.codemap().span_to_filename(parser.span));
529 parser.directory.path.pop();
532 parser.process_potential_macro_variable();
536 fn next_tok(&mut self) -> TokenAndSpan {
537 let mut next = if self.desugar_doc_comments {
538 self.token_cursor.next_desugared()
540 self.token_cursor.next()
542 if next.sp == syntax_pos::DUMMY_SP {
543 next.sp = self.prev_span;
548 /// Convert a token to a string using self's reader
549 pub fn token_to_string(token: &token::Token) -> String {
550 pprust::token_to_string(token)
553 /// Convert the current token to a string using self's reader
554 pub fn this_token_to_string(&self) -> String {
555 Parser::token_to_string(&self.token)
558 pub fn this_token_descr(&self) -> String {
559 let prefix = match &self.token {
560 t if t.is_special_ident() => "reserved identifier ",
561 t if t.is_used_keyword() => "keyword ",
562 t if t.is_unused_keyword() => "reserved keyword ",
565 format!("{}`{}`", prefix, self.this_token_to_string())
568 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
569 let token_str = Parser::token_to_string(t);
570 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
573 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
574 match self.expect_one_of(&[], &[]) {
576 Ok(_) => unreachable!(),
580 /// Expect and consume the token t. Signal an error if
581 /// the next token is not t.
582 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
583 if self.expected_tokens.is_empty() {
584 if self.token == *t {
588 let token_str = Parser::token_to_string(t);
589 let this_token_str = self.this_token_to_string();
590 Err(self.fatal(&format!("expected `{}`, found `{}`",
595 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
599 /// Expect next token to be edible or inedible token. If edible,
600 /// then consume it; if inedible, then return without consuming
601 /// anything. Signal a fatal error if next token is unexpected.
602 pub fn expect_one_of(&mut self,
603 edible: &[token::Token],
604 inedible: &[token::Token]) -> PResult<'a, ()>{
605 fn tokens_to_string(tokens: &[TokenType]) -> String {
606 let mut i = tokens.iter();
607 // This might be a sign we need a connect method on Iterator.
609 .map_or("".to_string(), |t| t.to_string());
610 i.enumerate().fold(b, |mut b, (i, a)| {
611 if tokens.len() > 2 && i == tokens.len() - 2 {
613 } else if tokens.len() == 2 && i == tokens.len() - 2 {
618 b.push_str(&a.to_string());
622 if edible.contains(&self.token) {
625 } else if inedible.contains(&self.token) {
626 // leave it in the input
629 let mut expected = edible.iter()
630 .map(|x| TokenType::Token(x.clone()))
631 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
632 .chain(self.expected_tokens.iter().cloned())
633 .collect::<Vec<_>>();
634 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
636 let expect = tokens_to_string(&expected[..]);
637 let actual = self.this_token_to_string();
638 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
639 let short_expect = if expected.len() > 6 {
640 format!("{} possible tokens", expected.len())
644 (format!("expected one of {}, found `{}`", expect, actual),
645 (self.prev_span.next_point(), format!("expected one of {} here", short_expect)))
646 } else if expected.is_empty() {
647 (format!("unexpected token: `{}`", actual),
648 (self.prev_span, "unexpected token after this".to_string()))
650 (format!("expected {}, found `{}`", expect, actual),
651 (self.prev_span.next_point(), format!("expected {} here", expect)))
653 let mut err = self.fatal(&msg_exp);
654 let sp = if self.token == token::Token::Eof {
655 // This is EOF, don't want to point at the following char, but rather the last token
660 if self.span.contains(sp) {
661 err.span_label(self.span, label_exp);
663 err.span_label(sp, label_exp);
664 err.span_label(self.span, "unexpected token");
670 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
671 fn interpolated_or_expr_span(&self,
672 expr: PResult<'a, P<Expr>>)
673 -> PResult<'a, (Span, P<Expr>)> {
675 if self.prev_token_kind == PrevTokenKind::Interpolated {
683 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
686 if self.token.is_reserved_ident() {
687 self.span_err(self.span, &format!("expected identifier, found {}",
688 self.this_token_descr()));
694 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
695 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
697 let mut err = self.fatal(&format!("expected identifier, found `{}`",
698 self.this_token_to_string()));
699 if self.token == token::Underscore {
700 err.note("`_` is a wildcard pattern, not an identifier");
708 /// Check if the next token is `tok`, and return `true` if so.
710 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
712 pub fn check(&mut self, tok: &token::Token) -> bool {
713 let is_present = self.token == *tok;
714 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
718 /// Consume token 'tok' if it exists. Returns true if the given
719 /// token was present, false otherwise.
720 pub fn eat(&mut self, tok: &token::Token) -> bool {
721 let is_present = self.check(tok);
722 if is_present { self.bump() }
726 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
727 self.expected_tokens.push(TokenType::Keyword(kw));
728 self.token.is_keyword(kw)
731 /// If the next token is the given keyword, eat it and return
732 /// true. Otherwise, return false.
733 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
734 if self.check_keyword(kw) {
742 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
743 if self.token.is_keyword(kw) {
751 /// If the given word is not a keyword, signal an error.
752 /// If the next token is not the given word, signal an error.
753 /// Otherwise, eat it.
754 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
755 if !self.eat_keyword(kw) {
762 fn check_ident(&mut self) -> bool {
763 if self.token.is_ident() {
766 self.expected_tokens.push(TokenType::Ident);
771 fn check_path(&mut self) -> bool {
772 if self.token.is_path_start() {
775 self.expected_tokens.push(TokenType::Path);
780 fn check_type(&mut self) -> bool {
781 if self.token.can_begin_type() {
784 self.expected_tokens.push(TokenType::Type);
789 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
790 /// `&` and continue. If an `&` is not seen, signal an error.
791 fn expect_and(&mut self) -> PResult<'a, ()> {
792 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
794 token::BinOp(token::And) => {
799 let span = self.span.with_lo(self.span.lo() + BytePos(1));
800 Ok(self.bump_with(token::BinOp(token::And), span))
802 _ => self.unexpected()
806 /// Expect and consume an `|`. If `||` is seen, replace it with a single
807 /// `|` and continue. If an `|` is not seen, signal an error.
808 fn expect_or(&mut self) -> PResult<'a, ()> {
809 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
811 token::BinOp(token::Or) => {
816 let span = self.span.with_lo(self.span.lo() + BytePos(1));
817 Ok(self.bump_with(token::BinOp(token::Or), span))
819 _ => self.unexpected()
823 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
825 None => {/* everything ok */}
827 let text = suf.as_str();
829 self.span_bug(sp, "found empty literal suffix in Some")
831 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
836 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
837 /// `<` and continue. If a `<` is not seen, return false.
839 /// This is meant to be used when parsing generics on a path to get the
841 fn eat_lt(&mut self) -> bool {
842 self.expected_tokens.push(TokenType::Token(token::Lt));
848 token::BinOp(token::Shl) => {
849 let span = self.span.with_lo(self.span.lo() + BytePos(1));
850 self.bump_with(token::Lt, span);
857 fn expect_lt(&mut self) -> PResult<'a, ()> {
865 /// Expect and consume a GT. if a >> is seen, replace it
866 /// with a single > and continue. If a GT is not seen,
868 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
869 self.expected_tokens.push(TokenType::Token(token::Gt));
875 token::BinOp(token::Shr) => {
876 let span = self.span.with_lo(self.span.lo() + BytePos(1));
877 Ok(self.bump_with(token::Gt, span))
879 token::BinOpEq(token::Shr) => {
880 let span = self.span.with_lo(self.span.lo() + BytePos(1));
881 Ok(self.bump_with(token::Ge, span))
884 let span = self.span.with_lo(self.span.lo() + BytePos(1));
885 Ok(self.bump_with(token::Eq, span))
887 _ => self.unexpected()
891 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
892 sep: Option<token::Token>,
894 -> PResult<'a, (Vec<T>, bool)>
895 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
897 let mut v = Vec::new();
898 // This loop works by alternating back and forth between parsing types
899 // and commas. For example, given a string `A, B,>`, the parser would
900 // first parse `A`, then a comma, then `B`, then a comma. After that it
901 // would encounter a `>` and stop. This lets the parser handle trailing
902 // commas in generic parameters, because it can stop either after
903 // parsing a type or after parsing a comma.
905 if self.check(&token::Gt)
906 || self.token == token::BinOp(token::Shr)
907 || self.token == token::Ge
908 || self.token == token::BinOpEq(token::Shr) {
914 Some(result) => v.push(result),
915 None => return Ok((v, true))
918 if let Some(t) = sep.as_ref() {
924 return Ok((v, false));
927 /// Parse a sequence bracketed by '<' and '>', stopping
929 pub fn parse_seq_to_before_gt<T, F>(&mut self,
930 sep: Option<token::Token>,
932 -> PResult<'a, Vec<T>> where
933 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
935 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
936 |p| Ok(Some(f(p)?)))?;
941 pub fn parse_seq_to_gt<T, F>(&mut self,
942 sep: Option<token::Token>,
944 -> PResult<'a, Vec<T>> where
945 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
947 let v = self.parse_seq_to_before_gt(sep, f)?;
952 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
953 sep: Option<token::Token>,
955 -> PResult<'a, (Vec<T>, bool)> where
956 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
958 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
962 return Ok((v, returned));
965 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
966 /// passes through any errors encountered. Used for error recovery.
967 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
968 let handler = self.diagnostic();
970 self.parse_seq_to_before_tokens(kets,
972 TokenExpectType::Expect,
973 |p| Ok(p.parse_token_tree()),
974 |mut e| handler.cancel(&mut e));
977 /// Parse a sequence, including the closing delimiter. The function
978 /// f must consume tokens until reaching the next separator or
980 pub fn parse_seq_to_end<T, F>(&mut self,
984 -> PResult<'a, Vec<T>> where
985 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
987 let val = self.parse_seq_to_before_end(ket, sep, f);
992 /// Parse a sequence, not including the closing delimiter. The function
993 /// f must consume tokens until reaching the next separator or
995 pub fn parse_seq_to_before_end<T, F>(&mut self,
1000 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1002 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f, |mut e| e.emit())
1005 // `fe` is an error handler.
1006 fn parse_seq_to_before_tokens<T, F, Fe>(&mut self,
1007 kets: &[&token::Token],
1009 expect: TokenExpectType,
1013 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1014 Fe: FnMut(DiagnosticBuilder)
1016 let mut first: bool = true;
1018 while !kets.contains(&&self.token) {
1020 token::CloseDelim(..) | token::Eof => break,
1023 if let Some(ref t) = sep.sep {
1027 if let Err(e) = self.expect(t) {
1033 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1035 TokenExpectType::Expect => self.check(k),
1036 TokenExpectType::NoExpect => self.token == **k,
1054 /// Parse a sequence, including the closing delimiter. The function
1055 /// f must consume tokens until reaching the next separator or
1056 /// closing bracket.
1057 pub fn parse_unspanned_seq<T, F>(&mut self,
1062 -> PResult<'a, Vec<T>> where
1063 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1066 let result = self.parse_seq_to_before_end(ket, sep, f);
1067 if self.token == *ket {
1073 // NB: Do not use this function unless you actually plan to place the
1074 // spanned list in the AST.
1075 pub fn parse_seq<T, F>(&mut self,
1080 -> PResult<'a, Spanned<Vec<T>>> where
1081 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1085 let result = self.parse_seq_to_before_end(ket, sep, f);
1088 Ok(respan(lo.to(hi), result))
1091 /// Advance the parser by one token
1092 pub fn bump(&mut self) {
1093 if self.prev_token_kind == PrevTokenKind::Eof {
1094 // Bumping after EOF is a bad sign, usually an infinite loop.
1095 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1098 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1100 // Record last token kind for possible error recovery.
1101 self.prev_token_kind = match self.token {
1102 token::DocComment(..) => PrevTokenKind::DocComment,
1103 token::Comma => PrevTokenKind::Comma,
1104 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1105 token::Interpolated(..) => PrevTokenKind::Interpolated,
1106 token::Eof => PrevTokenKind::Eof,
1107 token::Ident(..) => PrevTokenKind::Ident,
1108 _ => PrevTokenKind::Other,
1111 let next = self.next_tok();
1112 self.span = next.sp;
1113 self.token = next.tok;
1114 self.expected_tokens.clear();
1115 // check after each token
1116 self.process_potential_macro_variable();
1119 /// Advance the parser using provided token as a next one. Use this when
1120 /// consuming a part of a token. For example a single `<` from `<<`.
1121 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1122 self.prev_span = self.span.with_hi(span.lo());
1123 // It would be incorrect to record the kind of the current token, but
1124 // fortunately for tokens currently using `bump_with`, the
1125 // prev_token_kind will be of no use anyway.
1126 self.prev_token_kind = PrevTokenKind::Other;
1129 self.expected_tokens.clear();
1132 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1133 F: FnOnce(&token::Token) -> R,
1136 return f(&self.token)
1139 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1140 Some(tree) => match tree {
1141 TokenTree::Token(_, tok) => tok,
1142 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1144 None => token::CloseDelim(self.token_cursor.frame.delim),
1147 fn look_ahead_span(&self, dist: usize) -> Span {
1152 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1153 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1154 None => self.look_ahead_span(dist - 1),
1157 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1158 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1160 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1161 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1163 pub fn span_fatal_err(&self, sp: Span, err: Error) -> DiagnosticBuilder<'a> {
1164 err.span_err(sp, self.diagnostic())
1166 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1167 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1171 pub fn bug(&self, m: &str) -> ! {
1172 self.sess.span_diagnostic.span_bug(self.span, m)
1174 pub fn warn(&self, m: &str) {
1175 self.sess.span_diagnostic.span_warn(self.span, m)
1177 pub fn span_warn(&self, sp: Span, m: &str) {
1178 self.sess.span_diagnostic.span_warn(sp, m)
1180 pub fn span_err(&self, sp: Span, m: &str) {
1181 self.sess.span_diagnostic.span_err(sp, m)
1183 pub fn span_err_help(&self, sp: Span, m: &str, h: &str) {
1184 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1188 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1189 self.sess.span_diagnostic.span_bug(sp, m)
1191 pub fn abort_if_errors(&self) {
1192 self.sess.span_diagnostic.abort_if_errors();
1195 fn cancel(&self, err: &mut DiagnosticBuilder) {
1196 self.sess.span_diagnostic.cancel(err)
1199 pub fn diagnostic(&self) -> &'a errors::Handler {
1200 &self.sess.span_diagnostic
1203 /// Is the current token one of the keywords that signals a bare function
1205 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1206 self.check_keyword(keywords::Fn) ||
1207 self.check_keyword(keywords::Unsafe) ||
1208 self.check_keyword(keywords::Extern)
1211 fn get_label(&mut self) -> ast::Ident {
1213 token::Lifetime(ref ident) => *ident,
1214 _ => self.bug("not a lifetime"),
1218 /// parse a TyKind::BareFn type:
1219 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<LifetimeDef>)
1220 -> PResult<'a, TyKind> {
1223 [unsafe] [extern "ABI"] fn (S) -> T
1233 let unsafety = self.parse_unsafety()?;
1234 let abi = if self.eat_keyword(keywords::Extern) {
1235 self.parse_opt_abi()?.unwrap_or(Abi::C)
1240 self.expect_keyword(keywords::Fn)?;
1241 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1242 let ret_ty = self.parse_ret_ty()?;
1243 let decl = P(FnDecl {
1248 Ok(TyKind::BareFn(P(BareFnTy {
1251 lifetimes: lifetime_defs,
1256 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1257 if self.eat_keyword(keywords::Unsafe) {
1258 return Ok(Unsafety::Unsafe);
1260 return Ok(Unsafety::Normal);
1264 /// Parse the items in a trait declaration
1265 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1266 maybe_whole!(self, NtTraitItem, |x| x);
1267 let attrs = self.parse_outer_attributes()?;
1268 let (mut item, tokens) = self.collect_tokens(|this| {
1269 this.parse_trait_item_(at_end, attrs)
1271 // See `parse_item` for why this clause is here.
1272 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1273 item.tokens = Some(tokens);
1278 fn parse_trait_item_(&mut self,
1280 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1283 let (name, node) = if self.eat_keyword(keywords::Type) {
1284 let TyParam {ident, bounds, default, ..} = self.parse_ty_param(vec![])?;
1285 self.expect(&token::Semi)?;
1286 (ident, TraitItemKind::Type(bounds, default))
1287 } else if self.is_const_item() {
1288 self.expect_keyword(keywords::Const)?;
1289 let ident = self.parse_ident()?;
1290 self.expect(&token::Colon)?;
1291 let ty = self.parse_ty()?;
1292 let default = if self.check(&token::Eq) {
1294 let expr = self.parse_expr()?;
1295 self.expect(&token::Semi)?;
1298 self.expect(&token::Semi)?;
1301 (ident, TraitItemKind::Const(ty, default))
1302 } else if self.token.is_path_start() {
1303 // trait item macro.
1304 // code copied from parse_macro_use_or_failure... abstraction!
1305 let prev_span = self.prev_span;
1307 let pth = self.parse_path(PathStyle::Mod)?;
1309 if pth.segments.len() == 1 {
1310 if !self.eat(&token::Not) {
1311 return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1314 self.expect(&token::Not)?;
1317 // eat a matched-delimiter token tree:
1318 let (delim, tts) = self.expect_delimited_token_tree()?;
1319 if delim != token::Brace {
1320 self.expect(&token::Semi)?
1323 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1324 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac))
1326 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
1328 let ident = self.parse_ident()?;
1329 let mut generics = self.parse_generics()?;
1331 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1332 // This is somewhat dubious; We don't want to allow
1333 // argument names to be left off if there is a
1335 p.parse_arg_general(false)
1338 generics.where_clause = self.parse_where_clause()?;
1339 let sig = ast::MethodSig {
1347 let body = match self.token {
1351 debug!("parse_trait_methods(): parsing required method");
1354 token::OpenDelim(token::Brace) => {
1355 debug!("parse_trait_methods(): parsing provided method");
1357 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1358 attrs.extend(inner_attrs.iter().cloned());
1362 let token_str = self.this_token_to_string();
1363 return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1366 (ident, ast::TraitItemKind::Method(sig, body))
1370 id: ast::DUMMY_NODE_ID,
1374 span: lo.to(self.prev_span),
1379 /// Parse optional return type [ -> TY ] in function decl
1380 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1381 if self.eat(&token::RArrow) {
1382 Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
1384 Ok(FunctionRetTy::Default(self.span.with_hi(self.span.lo())))
1389 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1390 self.parse_ty_common(true)
1393 /// Parse a type in restricted contexts where `+` is not permitted.
1394 /// Example 1: `&'a TYPE`
1395 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1396 /// Example 2: `value1 as TYPE + value2`
1397 /// `+` is prohibited to avoid interactions with expression grammar.
1398 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1399 self.parse_ty_common(false)
1402 fn parse_ty_common(&mut self, allow_plus: bool) -> PResult<'a, P<Ty>> {
1403 maybe_whole!(self, NtTy, |x| x);
1406 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1407 // `(TYPE)` is a parenthesized type.
1408 // `(TYPE,)` is a tuple with a single field of type TYPE.
1409 let mut ts = vec![];
1410 let mut last_comma = false;
1411 while self.token != token::CloseDelim(token::Paren) {
1412 ts.push(self.parse_ty()?);
1413 if self.eat(&token::Comma) {
1420 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1421 self.expect(&token::CloseDelim(token::Paren))?;
1423 if ts.len() == 1 && !last_comma {
1424 let ty = ts.into_iter().nth(0).unwrap().unwrap();
1425 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1427 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1428 TyKind::Path(None, ref path) if maybe_bounds => {
1429 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1431 TyKind::TraitObject(ref bounds)
1432 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1433 let path = match bounds[0] {
1434 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1435 _ => self.bug("unexpected lifetime bound"),
1437 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1440 _ => TyKind::Paren(P(ty))
1445 } else if self.eat(&token::Not) {
1448 } else if self.eat(&token::BinOp(token::Star)) {
1450 TyKind::Ptr(self.parse_ptr()?)
1451 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1453 let t = self.parse_ty()?;
1454 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1455 let t = match self.maybe_parse_fixed_length_of_vec()? {
1456 None => TyKind::Slice(t),
1457 Some(suffix) => TyKind::Array(t, suffix),
1459 self.expect(&token::CloseDelim(token::Bracket))?;
1461 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1464 self.parse_borrowed_pointee()?
1465 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1467 // In order to not be ambiguous, the type must be surrounded by parens.
1468 self.expect(&token::OpenDelim(token::Paren))?;
1469 let e = self.parse_expr()?;
1470 self.expect(&token::CloseDelim(token::Paren))?;
1472 } else if self.eat(&token::Underscore) {
1473 // A type to be inferred `_`
1475 } else if self.eat_lt() {
1477 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1478 TyKind::Path(Some(qself), path)
1479 } else if self.token.is_path_start() {
1481 let path = self.parse_path(PathStyle::Type)?;
1482 if self.eat(&token::Not) {
1483 // Macro invocation in type position
1484 let (_, tts) = self.expect_delimited_token_tree()?;
1485 TyKind::Mac(respan(lo.to(self.span), Mac_ { path: path, tts: tts }))
1487 // Just a type path or bound list (trait object type) starting with a trait.
1489 // `Trait1 + Trait2 + 'a`
1490 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1491 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1493 TyKind::Path(None, path)
1496 } else if self.token_is_bare_fn_keyword() {
1497 // Function pointer type
1498 self.parse_ty_bare_fn(Vec::new())?
1499 } else if self.check_keyword(keywords::For) {
1500 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1501 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1502 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1504 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1505 if self.token_is_bare_fn_keyword() {
1506 self.parse_ty_bare_fn(lifetime_defs)?
1508 let path = self.parse_path(PathStyle::Type)?;
1509 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1510 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1512 } else if self.eat_keyword(keywords::Impl) {
1513 // FIXME: figure out priority of `+` in `impl Trait1 + Trait2` (#34511).
1514 TyKind::ImplTrait(self.parse_ty_param_bounds()?)
1515 } else if self.check(&token::Question) ||
1516 self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)){
1517 // Bound list (trait object type)
1518 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?)
1520 let msg = format!("expected type, found {}", self.this_token_descr());
1521 return Err(self.fatal(&msg));
1524 let span = lo.to(self.prev_span);
1525 let ty = Ty { node: node, span: span, id: ast::DUMMY_NODE_ID };
1527 // Try to recover from use of `+` with incorrect priority.
1528 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1533 fn parse_remaining_bounds(&mut self, lifetime_defs: Vec<LifetimeDef>, path: ast::Path,
1534 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1535 let poly_trait_ref = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
1536 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1539 bounds.append(&mut self.parse_ty_param_bounds()?);
1541 Ok(TyKind::TraitObject(bounds))
1544 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1545 // Do not add `+` to expected tokens.
1546 if !allow_plus || self.token != token::BinOp(token::Plus) {
1551 let bounds = self.parse_ty_param_bounds()?;
1552 let sum_span = ty.span.to(self.prev_span);
1554 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1555 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1558 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1559 let sum_with_parens = pprust::to_string(|s| {
1560 use print::pprust::PrintState;
1563 s.print_opt_lifetime(lifetime)?;
1564 s.print_mutability(mut_ty.mutbl)?;
1566 s.print_type(&mut_ty.ty)?;
1567 s.print_bounds(" +", &bounds)?;
1570 err.span_suggestion(sum_span, "try adding parentheses", sum_with_parens);
1572 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1573 err.span_label(sum_span, "perhaps you forgot parentheses?");
1576 err.span_label(sum_span, "expected a path");
1583 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1584 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1585 let mutbl = self.parse_mutability();
1586 let ty = self.parse_ty_no_plus()?;
1587 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1590 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1591 let mutbl = if self.eat_keyword(keywords::Mut) {
1593 } else if self.eat_keyword(keywords::Const) {
1594 Mutability::Immutable
1596 let span = self.prev_span;
1598 "expected mut or const in raw pointer type (use \
1599 `*mut T` or `*const T` as appropriate)");
1600 Mutability::Immutable
1602 let t = self.parse_ty_no_plus()?;
1603 Ok(MutTy { ty: t, mutbl: mutbl })
1606 pub fn is_named_argument(&mut self) -> bool {
1607 let offset = match self.token {
1608 token::BinOp(token::And) |
1610 _ if self.token.is_keyword(keywords::Mut) => 1,
1614 debug!("parser is_named_argument offset:{}", offset);
1617 is_ident_or_underscore(&self.token)
1618 && self.look_ahead(1, |t| *t == token::Colon)
1620 self.look_ahead(offset, |t| is_ident_or_underscore(t))
1621 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1625 /// This version of parse arg doesn't necessarily require
1626 /// identifier names.
1627 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1628 maybe_whole!(self, NtArg, |x| x);
1630 let pat = if require_name || self.is_named_argument() {
1631 debug!("parse_arg_general parse_pat (require_name:{})",
1633 let pat = self.parse_pat()?;
1635 self.expect(&token::Colon)?;
1638 debug!("parse_arg_general ident_to_pat");
1639 let sp = self.prev_span;
1640 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1642 id: ast::DUMMY_NODE_ID,
1643 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1649 let t = self.parse_ty()?;
1654 id: ast::DUMMY_NODE_ID,
1658 /// Parse a single function argument
1659 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1660 self.parse_arg_general(true)
1663 /// Parse an argument in a lambda header e.g. |arg, arg|
1664 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1665 let pat = self.parse_pat()?;
1666 let t = if self.eat(&token::Colon) {
1670 id: ast::DUMMY_NODE_ID,
1671 node: TyKind::Infer,
1678 id: ast::DUMMY_NODE_ID
1682 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1683 if self.eat(&token::Semi) {
1684 Ok(Some(self.parse_expr()?))
1690 /// Matches token_lit = LIT_INTEGER | ...
1691 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1692 let out = match self.token {
1693 token::Interpolated(ref nt) => match nt.0 {
1694 token::NtExpr(ref v) => match v.node {
1695 ExprKind::Lit(ref lit) => { lit.node.clone() }
1696 _ => { return self.unexpected_last(&self.token); }
1698 _ => { return self.unexpected_last(&self.token); }
1700 token::Literal(lit, suf) => {
1701 let diag = Some((self.span, &self.sess.span_diagnostic));
1702 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1706 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1711 _ => { return self.unexpected_last(&self.token); }
1718 /// Matches lit = true | false | token_lit
1719 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1721 let lit = if self.eat_keyword(keywords::True) {
1723 } else if self.eat_keyword(keywords::False) {
1724 LitKind::Bool(false)
1726 let lit = self.parse_lit_token()?;
1729 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1732 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1733 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1734 maybe_whole_expr!(self);
1736 let minus_lo = self.span;
1737 let minus_present = self.eat(&token::BinOp(token::Minus));
1739 let literal = P(self.parse_lit()?);
1740 let hi = self.prev_span;
1741 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1744 let minus_hi = self.prev_span;
1745 let unary = self.mk_unary(UnOp::Neg, expr);
1746 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1752 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1754 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1758 _ => self.parse_ident(),
1762 /// Parses qualified path.
1763 /// Assumes that the leading `<` has been parsed already.
1765 /// `qualified_path = <type [as trait_ref]>::path`
1769 /// `<T as U>::F::a<S>` (without disambiguator)
1770 /// `<T as U>::F::a::<S>` (with disambiguator)
1771 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1772 let lo = self.prev_span;
1773 let ty = self.parse_ty()?;
1774 let mut path = if self.eat_keyword(keywords::As) {
1775 self.parse_path(PathStyle::Type)?
1777 ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP }
1779 self.expect(&token::Gt)?;
1780 self.expect(&token::ModSep)?;
1782 let qself = QSelf { ty, position: path.segments.len() };
1783 self.parse_path_segments(&mut path.segments, style, true)?;
1785 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1788 /// Parses simple paths.
1790 /// `path = [::] segment+`
1791 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1794 /// `a::b::C<D>` (without disambiguator)
1795 /// `a::b::C::<D>` (with disambiguator)
1796 /// `Fn(Args)` (without disambiguator)
1797 /// `Fn::(Args)` (with disambiguator)
1798 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1799 self.parse_path_common(style, true)
1802 pub fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1803 -> PResult<'a, ast::Path> {
1804 maybe_whole!(self, NtPath, |path| {
1805 if style == PathStyle::Mod &&
1806 path.segments.iter().any(|segment| segment.parameters.is_some()) {
1807 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1812 let lo = self.meta_var_span.unwrap_or(self.span);
1813 let mut segments = Vec::new();
1814 if self.eat(&token::ModSep) {
1815 segments.push(PathSegment::crate_root(lo));
1817 self.parse_path_segments(&mut segments, style, enable_warning)?;
1819 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1822 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1823 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1824 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1825 let meta_ident = match self.token {
1826 token::Interpolated(ref nt) => match nt.0 {
1827 token::NtMeta(ref meta) => match meta.node {
1828 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
1835 if let Some(ident) = meta_ident {
1837 return Ok(ast::Path::from_ident(self.prev_span, ident));
1839 self.parse_path(style)
1842 fn parse_path_segments(&mut self, segments: &mut Vec<PathSegment>, style: PathStyle,
1843 enable_warning: bool) -> PResult<'a, ()> {
1845 segments.push(self.parse_path_segment(style, enable_warning)?);
1847 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1853 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
1854 -> PResult<'a, PathSegment> {
1855 let ident_span = self.span;
1856 let ident = self.parse_path_segment_ident()?;
1858 let is_args_start = |token: &token::Token| match *token {
1859 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
1862 let check_args_start = |this: &mut Self| {
1863 this.expected_tokens.extend_from_slice(
1864 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1866 is_args_start(&this.token)
1869 Ok(if style == PathStyle::Type && check_args_start(self) ||
1870 style != PathStyle::Mod && self.check(&token::ModSep)
1871 && self.look_ahead(1, |t| is_args_start(t)) {
1872 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1874 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
1875 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
1876 .span_label(self.prev_span, "try removing `::`").emit();
1879 let parameters = if self.eat_lt() {
1881 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1883 let span = lo.to(self.prev_span);
1884 AngleBracketedParameterData { lifetimes, types, bindings, span }.into()
1888 let inputs = self.parse_seq_to_end(&token::CloseDelim(token::Paren),
1889 SeqSep::trailing_allowed(token::Comma),
1891 let output = if self.eat(&token::RArrow) {
1892 Some(self.parse_ty_no_plus()?)
1896 let span = lo.to(self.prev_span);
1897 ParenthesizedParameterData { inputs, output, span }.into()
1900 PathSegment { identifier: ident, span: ident_span, parameters }
1902 // Generic arguments are not found.
1903 PathSegment::from_ident(ident, ident_span)
1907 fn check_lifetime(&mut self) -> bool {
1908 self.expected_tokens.push(TokenType::Lifetime);
1909 self.token.is_lifetime()
1912 /// Parse single lifetime 'a or panic.
1913 fn expect_lifetime(&mut self) -> Lifetime {
1915 token::Lifetime(ident) => {
1916 let ident_span = self.span;
1918 Lifetime { ident: ident, span: ident_span, id: ast::DUMMY_NODE_ID }
1920 _ => self.span_bug(self.span, "not a lifetime")
1924 /// Parse mutability (`mut` or nothing).
1925 fn parse_mutability(&mut self) -> Mutability {
1926 if self.eat_keyword(keywords::Mut) {
1929 Mutability::Immutable
1933 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1934 if let token::Literal(token::Integer(name), None) = self.token {
1936 Ok(Ident::with_empty_ctxt(name))
1942 /// Parse ident (COLON expr)?
1943 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1944 let attrs = self.parse_outer_attributes()?;
1948 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1949 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1950 let fieldname = self.parse_field_name()?;
1952 hi = self.prev_span;
1953 (fieldname, self.parse_expr()?, false)
1955 let fieldname = self.parse_ident()?;
1956 hi = self.prev_span;
1958 // Mimic `x: x` for the `x` field shorthand.
1959 let path = ast::Path::from_ident(lo.to(hi), fieldname);
1960 (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
1963 ident: respan(lo.to(hi), fieldname),
1964 span: lo.to(expr.span),
1967 attrs: attrs.into(),
1971 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1973 id: ast::DUMMY_NODE_ID,
1976 attrs: attrs.into(),
1980 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
1981 ExprKind::Unary(unop, expr)
1984 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1985 ExprKind::Binary(binop, lhs, rhs)
1988 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
1989 ExprKind::Call(f, args)
1992 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
1993 ExprKind::Index(expr, idx)
1996 pub fn mk_range(&mut self,
1997 start: Option<P<Expr>>,
1998 end: Option<P<Expr>>,
1999 limits: RangeLimits)
2000 -> PResult<'a, ast::ExprKind> {
2001 if end.is_none() && limits == RangeLimits::Closed {
2002 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2004 Ok(ExprKind::Range(start, end, limits))
2008 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2009 ExprKind::TupField(expr, idx)
2012 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2013 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2014 ExprKind::AssignOp(binop, lhs, rhs)
2017 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2019 id: ast::DUMMY_NODE_ID,
2020 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2026 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2027 let span = &self.span;
2028 let lv_lit = P(codemap::Spanned {
2029 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2034 id: ast::DUMMY_NODE_ID,
2035 node: ExprKind::Lit(lv_lit),
2041 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2043 token::OpenDelim(delim) => match self.parse_token_tree() {
2044 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2045 _ => unreachable!(),
2047 _ => Err(self.fatal("expected open delimiter")),
2051 /// At the bottom (top?) of the precedence hierarchy,
2052 /// parse things like parenthesized exprs,
2053 /// macros, return, etc.
2055 /// NB: This does not parse outer attributes,
2056 /// and is private because it only works
2057 /// correctly if called from parse_dot_or_call_expr().
2058 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2059 maybe_whole_expr!(self);
2061 // Outer attributes are already parsed and will be
2062 // added to the return value after the fact.
2064 // Therefore, prevent sub-parser from parsing
2065 // attributes by giving them a empty "already parsed" list.
2066 let mut attrs = ThinVec::new();
2069 let mut hi = self.span;
2073 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2075 token::OpenDelim(token::Paren) => {
2078 attrs.extend(self.parse_inner_attributes()?);
2080 // (e) is parenthesized e
2081 // (e,) is a tuple with only one field, e
2082 let mut es = vec![];
2083 let mut trailing_comma = false;
2084 while self.token != token::CloseDelim(token::Paren) {
2085 es.push(self.parse_expr()?);
2086 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2087 if self.check(&token::Comma) {
2088 trailing_comma = true;
2092 trailing_comma = false;
2098 hi = self.prev_span;
2099 let span = lo.to(hi);
2100 return if es.len() == 1 && !trailing_comma {
2101 Ok(self.mk_expr(span, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2103 Ok(self.mk_expr(span, ExprKind::Tup(es), attrs))
2106 token::OpenDelim(token::Brace) => {
2107 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2109 token::BinOp(token::Or) | token::OrOr => {
2111 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2113 token::OpenDelim(token::Bracket) => {
2116 attrs.extend(self.parse_inner_attributes()?);
2118 if self.check(&token::CloseDelim(token::Bracket)) {
2121 ex = ExprKind::Array(Vec::new());
2124 let first_expr = self.parse_expr()?;
2125 if self.check(&token::Semi) {
2126 // Repeating array syntax: [ 0; 512 ]
2128 let count = self.parse_expr()?;
2129 self.expect(&token::CloseDelim(token::Bracket))?;
2130 ex = ExprKind::Repeat(first_expr, count);
2131 } else if self.check(&token::Comma) {
2132 // Vector with two or more elements.
2134 let remaining_exprs = self.parse_seq_to_end(
2135 &token::CloseDelim(token::Bracket),
2136 SeqSep::trailing_allowed(token::Comma),
2137 |p| Ok(p.parse_expr()?)
2139 let mut exprs = vec![first_expr];
2140 exprs.extend(remaining_exprs);
2141 ex = ExprKind::Array(exprs);
2143 // Vector with one element.
2144 self.expect(&token::CloseDelim(token::Bracket))?;
2145 ex = ExprKind::Array(vec![first_expr]);
2148 hi = self.prev_span;
2152 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2154 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2156 if self.eat_keyword(keywords::Move) {
2157 let lo = self.prev_span;
2158 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2160 if self.eat_keyword(keywords::If) {
2161 return self.parse_if_expr(attrs);
2163 if self.eat_keyword(keywords::For) {
2164 let lo = self.prev_span;
2165 return self.parse_for_expr(None, lo, attrs);
2167 if self.eat_keyword(keywords::While) {
2168 let lo = self.prev_span;
2169 return self.parse_while_expr(None, lo, attrs);
2171 if self.token.is_lifetime() {
2172 let label = Spanned { node: self.get_label(),
2176 self.expect(&token::Colon)?;
2177 if self.eat_keyword(keywords::While) {
2178 return self.parse_while_expr(Some(label), lo, attrs)
2180 if self.eat_keyword(keywords::For) {
2181 return self.parse_for_expr(Some(label), lo, attrs)
2183 if self.eat_keyword(keywords::Loop) {
2184 return self.parse_loop_expr(Some(label), lo, attrs)
2186 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2188 if self.eat_keyword(keywords::Loop) {
2189 let lo = self.prev_span;
2190 return self.parse_loop_expr(None, lo, attrs);
2192 if self.eat_keyword(keywords::Continue) {
2193 let ex = if self.token.is_lifetime() {
2194 let ex = ExprKind::Continue(Some(Spanned{
2195 node: self.get_label(),
2201 ExprKind::Continue(None)
2203 let hi = self.prev_span;
2204 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2206 if self.eat_keyword(keywords::Match) {
2207 return self.parse_match_expr(attrs);
2209 if self.eat_keyword(keywords::Unsafe) {
2210 return self.parse_block_expr(
2212 BlockCheckMode::Unsafe(ast::UserProvided),
2215 if self.is_catch_expr() {
2217 assert!(self.eat_keyword(keywords::Do));
2218 assert!(self.eat_keyword(keywords::Catch));
2219 return self.parse_catch_expr(lo, attrs);
2221 if self.eat_keyword(keywords::Return) {
2222 if self.token.can_begin_expr() {
2223 let e = self.parse_expr()?;
2225 ex = ExprKind::Ret(Some(e));
2227 ex = ExprKind::Ret(None);
2229 } else if self.eat_keyword(keywords::Break) {
2230 let lt = if self.token.is_lifetime() {
2231 let spanned_lt = Spanned {
2232 node: self.get_label(),
2240 let e = if self.token.can_begin_expr()
2241 && !(self.token == token::OpenDelim(token::Brace)
2242 && self.restrictions.contains(
2243 Restrictions::NO_STRUCT_LITERAL)) {
2244 Some(self.parse_expr()?)
2248 ex = ExprKind::Break(lt, e);
2249 hi = self.prev_span;
2250 } else if self.eat_keyword(keywords::Yield) {
2251 if self.token.can_begin_expr() {
2252 let e = self.parse_expr()?;
2254 ex = ExprKind::Yield(Some(e));
2256 ex = ExprKind::Yield(None);
2258 } else if self.token.is_keyword(keywords::Let) {
2259 // Catch this syntax error here, instead of in `parse_ident`, so
2260 // that we can explicitly mention that let is not to be used as an expression
2261 let mut db = self.fatal("expected expression, found statement (`let`)");
2262 db.note("variable declaration using `let` is a statement");
2264 } else if self.token.is_path_start() {
2265 let pth = self.parse_path(PathStyle::Expr)?;
2267 // `!`, as an operator, is prefix, so we know this isn't that
2268 if self.eat(&token::Not) {
2269 // MACRO INVOCATION expression
2270 let (_, tts) = self.expect_delimited_token_tree()?;
2271 let hi = self.prev_span;
2272 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2274 if self.check(&token::OpenDelim(token::Brace)) {
2275 // This is a struct literal, unless we're prohibited
2276 // from parsing struct literals here.
2277 let prohibited = self.restrictions.contains(
2278 Restrictions::NO_STRUCT_LITERAL
2281 return self.parse_struct_expr(lo, pth, attrs);
2286 ex = ExprKind::Path(None, pth);
2288 match self.parse_lit() {
2291 ex = ExprKind::Lit(P(lit));
2294 self.cancel(&mut err);
2295 let msg = format!("expected expression, found {}",
2296 self.this_token_descr());
2297 return Err(self.fatal(&msg));
2304 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2307 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2308 -> PResult<'a, P<Expr>> {
2310 let mut fields = Vec::new();
2311 let mut base = None;
2313 attrs.extend(self.parse_inner_attributes()?);
2315 while self.token != token::CloseDelim(token::Brace) {
2316 if self.eat(&token::DotDot) {
2317 match self.parse_expr() {
2323 self.recover_stmt();
2329 match self.parse_field() {
2330 Ok(f) => fields.push(f),
2333 self.recover_stmt();
2338 match self.expect_one_of(&[token::Comma],
2339 &[token::CloseDelim(token::Brace)]) {
2343 self.recover_stmt();
2349 let span = lo.to(self.span);
2350 self.expect(&token::CloseDelim(token::Brace))?;
2351 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2354 fn parse_or_use_outer_attributes(&mut self,
2355 already_parsed_attrs: Option<ThinVec<Attribute>>)
2356 -> PResult<'a, ThinVec<Attribute>> {
2357 if let Some(attrs) = already_parsed_attrs {
2360 self.parse_outer_attributes().map(|a| a.into())
2364 /// Parse a block or unsafe block
2365 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2366 outer_attrs: ThinVec<Attribute>)
2367 -> PResult<'a, P<Expr>> {
2368 self.expect(&token::OpenDelim(token::Brace))?;
2370 let mut attrs = outer_attrs;
2371 attrs.extend(self.parse_inner_attributes()?);
2373 let blk = self.parse_block_tail(lo, blk_mode)?;
2374 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2377 /// parse a.b or a(13) or a[4] or just a
2378 pub fn parse_dot_or_call_expr(&mut self,
2379 already_parsed_attrs: Option<ThinVec<Attribute>>)
2380 -> PResult<'a, P<Expr>> {
2381 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2383 let b = self.parse_bottom_expr();
2384 let (span, b) = self.interpolated_or_expr_span(b)?;
2385 self.parse_dot_or_call_expr_with(b, span, attrs)
2388 pub fn parse_dot_or_call_expr_with(&mut self,
2391 mut attrs: ThinVec<Attribute>)
2392 -> PResult<'a, P<Expr>> {
2393 // Stitch the list of outer attributes onto the return value.
2394 // A little bit ugly, but the best way given the current code
2396 self.parse_dot_or_call_expr_with_(e0, lo)
2398 expr.map(|mut expr| {
2399 attrs.extend::<Vec<_>>(expr.attrs.into());
2402 ExprKind::If(..) | ExprKind::IfLet(..) => {
2403 if !expr.attrs.is_empty() {
2404 // Just point to the first attribute in there...
2405 let span = expr.attrs[0].span;
2408 "attributes are not yet allowed on `if` \
2419 // Assuming we have just parsed `.`, continue parsing into an expression.
2420 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2421 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2422 Ok(match self.token {
2423 token::OpenDelim(token::Paren) => {
2424 // Method call `expr.f()`
2425 let mut args = self.parse_unspanned_seq(
2426 &token::OpenDelim(token::Paren),
2427 &token::CloseDelim(token::Paren),
2428 SeqSep::trailing_allowed(token::Comma),
2429 |p| Ok(p.parse_expr()?)
2431 args.insert(0, self_arg);
2433 let span = lo.to(self.prev_span);
2434 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2437 // Field access `expr.f`
2438 if let Some(parameters) = segment.parameters {
2439 self.span_err(parameters.span(),
2440 "field expressions may not have generic arguments");
2443 let span = lo.to(self.prev_span);
2444 let ident = respan(segment.span, segment.identifier);
2445 self.mk_expr(span, ExprKind::Field(self_arg, ident), ThinVec::new())
2450 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2455 while self.eat(&token::Question) {
2456 let hi = self.prev_span;
2457 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2461 if self.eat(&token::Dot) {
2463 token::Ident(..) => {
2464 e = self.parse_dot_suffix(e, lo)?;
2466 token::Literal(token::Integer(n), suf) => {
2469 // A tuple index may not have a suffix
2470 self.expect_no_suffix(sp, "tuple index", suf);
2472 let dot_span = self.prev_span;
2476 let index = n.as_str().parse::<usize>().ok();
2479 let id = respan(dot_span.to(hi), n);
2480 let field = self.mk_tup_field(e, id);
2481 e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2484 let prev_span = self.prev_span;
2485 self.span_err(prev_span, "invalid tuple or tuple struct index");
2489 token::Literal(token::Float(n), _suf) => {
2491 let fstr = n.as_str();
2492 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2493 &format!("unexpected token: `{}`", n));
2494 err.span_label(self.prev_span, "unexpected token");
2495 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2496 let float = match fstr.parse::<f64>().ok() {
2500 let sugg = pprust::to_string(|s| {
2501 use print::pprust::PrintState;
2505 s.print_usize(float.trunc() as usize)?;
2508 s.s.word(fstr.splitn(2, ".").last().unwrap())
2510 err.span_suggestion(
2511 lo.to(self.prev_span),
2512 "try parenthesizing the first index",
2519 // FIXME Could factor this out into non_fatal_unexpected or something.
2520 let actual = self.this_token_to_string();
2521 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2526 if self.expr_is_complete(&e) { break; }
2529 token::OpenDelim(token::Paren) => {
2530 let es = self.parse_unspanned_seq(
2531 &token::OpenDelim(token::Paren),
2532 &token::CloseDelim(token::Paren),
2533 SeqSep::trailing_allowed(token::Comma),
2534 |p| Ok(p.parse_expr()?)
2536 hi = self.prev_span;
2538 let nd = self.mk_call(e, es);
2539 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2543 // Could be either an index expression or a slicing expression.
2544 token::OpenDelim(token::Bracket) => {
2546 let ix = self.parse_expr()?;
2548 self.expect(&token::CloseDelim(token::Bracket))?;
2549 let index = self.mk_index(e, ix);
2550 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2558 pub fn process_potential_macro_variable(&mut self) {
2559 let ident = match self.token {
2560 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2561 self.look_ahead(1, |t| t.is_ident()) => {
2563 let name = match self.token { token::Ident(ident) => ident, _ => unreachable!() };
2564 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2567 token::Interpolated(ref nt) => {
2568 self.meta_var_span = Some(self.span);
2570 token::NtIdent(ident) => ident,
2576 self.token = token::Ident(ident.node);
2577 self.span = ident.span;
2580 /// parse a single token tree from the input.
2581 pub fn parse_token_tree(&mut self) -> TokenTree {
2583 token::OpenDelim(..) => {
2584 let frame = mem::replace(&mut self.token_cursor.frame,
2585 self.token_cursor.stack.pop().unwrap());
2586 self.span = frame.span;
2588 TokenTree::Delimited(frame.span, Delimited {
2590 tts: frame.tree_cursor.original_stream().into(),
2593 token::CloseDelim(_) | token::Eof => unreachable!(),
2595 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2597 TokenTree::Token(span, token)
2602 // parse a stream of tokens into a list of TokenTree's,
2604 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2605 let mut tts = Vec::new();
2606 while self.token != token::Eof {
2607 tts.push(self.parse_token_tree());
2612 pub fn parse_tokens(&mut self) -> TokenStream {
2613 let mut result = Vec::new();
2616 token::Eof | token::CloseDelim(..) => break,
2617 _ => result.push(self.parse_token_tree().into()),
2620 TokenStream::concat(result)
2623 /// Parse a prefix-unary-operator expr
2624 pub fn parse_prefix_expr(&mut self,
2625 already_parsed_attrs: Option<ThinVec<Attribute>>)
2626 -> PResult<'a, P<Expr>> {
2627 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2629 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2630 let (hi, ex) = match self.token {
2633 let e = self.parse_prefix_expr(None);
2634 let (span, e) = self.interpolated_or_expr_span(e)?;
2635 (lo.to(span), self.mk_unary(UnOp::Not, e))
2637 // Suggest `!` for bitwise negation when encountering a `~`
2640 let e = self.parse_prefix_expr(None);
2641 let (span, e) = self.interpolated_or_expr_span(e)?;
2642 let span_of_tilde = lo;
2643 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2644 "`~` can not be used as a unary operator");
2645 err.span_label(span_of_tilde, "did you mean `!`?");
2646 err.help("use `!` instead of `~` if you meant to perform bitwise negation");
2648 (lo.to(span), self.mk_unary(UnOp::Not, e))
2650 token::BinOp(token::Minus) => {
2652 let e = self.parse_prefix_expr(None);
2653 let (span, e) = self.interpolated_or_expr_span(e)?;
2654 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2656 token::BinOp(token::Star) => {
2658 let e = self.parse_prefix_expr(None);
2659 let (span, e) = self.interpolated_or_expr_span(e)?;
2660 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2662 token::BinOp(token::And) | token::AndAnd => {
2664 let m = self.parse_mutability();
2665 let e = self.parse_prefix_expr(None);
2666 let (span, e) = self.interpolated_or_expr_span(e)?;
2667 (lo.to(span), ExprKind::AddrOf(m, e))
2669 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2671 let place = self.parse_expr_res(
2672 Restrictions::NO_STRUCT_LITERAL,
2675 let blk = self.parse_block()?;
2676 let span = blk.span;
2677 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2678 (lo.to(span), ExprKind::InPlace(place, blk_expr))
2680 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2682 let e = self.parse_prefix_expr(None);
2683 let (span, e) = self.interpolated_or_expr_span(e)?;
2684 (lo.to(span), ExprKind::Box(e))
2686 _ => return self.parse_dot_or_call_expr(Some(attrs))
2688 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2691 /// Parse an associative expression
2693 /// This parses an expression accounting for associativity and precedence of the operators in
2695 pub fn parse_assoc_expr(&mut self,
2696 already_parsed_attrs: Option<ThinVec<Attribute>>)
2697 -> PResult<'a, P<Expr>> {
2698 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2701 /// Parse an associative expression with operators of at least `min_prec` precedence
2702 pub fn parse_assoc_expr_with(&mut self,
2705 -> PResult<'a, P<Expr>> {
2706 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2709 let attrs = match lhs {
2710 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2713 if self.token == token::DotDot || self.token == token::DotDotDot {
2714 return self.parse_prefix_range_expr(attrs);
2716 self.parse_prefix_expr(attrs)?
2720 if self.expr_is_complete(&lhs) {
2721 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2724 self.expected_tokens.push(TokenType::Operator);
2725 while let Some(op) = AssocOp::from_token(&self.token) {
2727 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2728 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2729 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2730 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2731 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2732 (PrevTokenKind::Interpolated, _) => self.prev_span,
2733 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2734 if path.segments.len() == 1 => self.prev_span,
2738 let cur_op_span = self.span;
2739 let restrictions = if op.is_assign_like() {
2740 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2744 if op.precedence() < min_prec {
2748 if op.is_comparison() {
2749 self.check_no_chained_comparison(&lhs, &op);
2752 if op == AssocOp::As {
2753 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2755 } else if op == AssocOp::Colon {
2756 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2759 err.span_label(self.span,
2760 "expecting a type here because of type ascription");
2761 let cm = self.sess.codemap();
2762 let cur_pos = cm.lookup_char_pos(self.span.lo());
2763 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
2764 if cur_pos.line != op_pos.line {
2765 err.span_suggestion_short(cur_op_span,
2766 "did you mean to use `;` here?",
2773 } else if op == AssocOp::DotDot || op == AssocOp::DotDotDot {
2774 // If we didn’t have to handle `x..`/`x...`, it would be pretty easy to
2775 // generalise it to the Fixity::None code.
2777 // We have 2 alternatives here: `x..y`/`x...y` and `x..`/`x...` The other
2778 // two variants are handled with `parse_prefix_range_expr` call above.
2779 let rhs = if self.is_at_start_of_range_notation_rhs() {
2780 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2781 LhsExpr::NotYetParsed)?)
2785 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2790 let limits = if op == AssocOp::DotDot {
2791 RangeLimits::HalfOpen
2796 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2797 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2801 let rhs = match op.fixity() {
2802 Fixity::Right => self.with_res(
2803 restrictions - Restrictions::STMT_EXPR,
2805 this.parse_assoc_expr_with(op.precedence(),
2806 LhsExpr::NotYetParsed)
2808 Fixity::Left => self.with_res(
2809 restrictions - Restrictions::STMT_EXPR,
2811 this.parse_assoc_expr_with(op.precedence() + 1,
2812 LhsExpr::NotYetParsed)
2814 // We currently have no non-associative operators that are not handled above by
2815 // the special cases. The code is here only for future convenience.
2816 Fixity::None => self.with_res(
2817 restrictions - Restrictions::STMT_EXPR,
2819 this.parse_assoc_expr_with(op.precedence() + 1,
2820 LhsExpr::NotYetParsed)
2824 let span = lhs_span.to(rhs.span);
2826 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2827 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2828 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2829 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2830 AssocOp::Greater | AssocOp::GreaterEqual => {
2831 let ast_op = op.to_ast_binop().unwrap();
2832 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2833 self.mk_expr(span, binary, ThinVec::new())
2836 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2838 self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
2839 AssocOp::AssignOp(k) => {
2841 token::Plus => BinOpKind::Add,
2842 token::Minus => BinOpKind::Sub,
2843 token::Star => BinOpKind::Mul,
2844 token::Slash => BinOpKind::Div,
2845 token::Percent => BinOpKind::Rem,
2846 token::Caret => BinOpKind::BitXor,
2847 token::And => BinOpKind::BitAnd,
2848 token::Or => BinOpKind::BitOr,
2849 token::Shl => BinOpKind::Shl,
2850 token::Shr => BinOpKind::Shr,
2852 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2853 self.mk_expr(span, aopexpr, ThinVec::new())
2855 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotDot => {
2856 self.bug("As, Colon, DotDot or DotDotDot branch reached")
2860 if op.fixity() == Fixity::None { break }
2865 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
2866 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
2867 -> PResult<'a, P<Expr>> {
2868 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
2869 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
2872 // Save the state of the parser before parsing type normally, in case there is a
2873 // LessThan comparison after this cast.
2874 let parser_snapshot_before_type = self.clone();
2875 match self.parse_ty_no_plus() {
2877 Ok(mk_expr(self, rhs))
2879 Err(mut type_err) => {
2880 // Rewind to before attempting to parse the type with generics, to recover
2881 // from situations like `x as usize < y` in which we first tried to parse
2882 // `usize < y` as a type with generic arguments.
2883 let parser_snapshot_after_type = self.clone();
2884 mem::replace(self, parser_snapshot_before_type);
2886 match self.parse_path(PathStyle::Expr) {
2888 // Successfully parsed the type path leaving a `<` yet to parse.
2891 // Report non-fatal diagnostics, keep `x as usize` as an expression
2892 // in AST and continue parsing.
2893 let msg = format!("`<` is interpreted as a start of generic \
2894 arguments for `{}`, not a comparison", path);
2895 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
2896 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
2897 "interpreted as generic arguments");
2898 err.span_label(self.span, "not interpreted as comparison");
2900 let expr = mk_expr(self, P(Ty {
2902 node: TyKind::Path(None, path),
2903 id: ast::DUMMY_NODE_ID
2906 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
2907 .unwrap_or(pprust::expr_to_string(&expr));
2908 err.span_suggestion(expr.span,
2909 "try comparing the casted value",
2910 format!("({})", expr_str));
2915 Err(mut path_err) => {
2916 // Couldn't parse as a path, return original error and parser state.
2918 mem::replace(self, parser_snapshot_after_type);
2926 /// Produce an error if comparison operators are chained (RFC #558).
2927 /// We only need to check lhs, not rhs, because all comparison ops
2928 /// have same precedence and are left-associative
2929 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2930 debug_assert!(outer_op.is_comparison(),
2931 "check_no_chained_comparison: {:?} is not comparison",
2934 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2935 // respan to include both operators
2936 let op_span = op.span.to(self.span);
2937 let mut err = self.diagnostic().struct_span_err(op_span,
2938 "chained comparison operators require parentheses");
2939 if op.node == BinOpKind::Lt &&
2940 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
2941 *outer_op == AssocOp::Greater // even in a case like the following:
2942 { // Foo<Bar<Baz<Qux, ()>>>
2944 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2952 /// Parse prefix-forms of range notation: `..expr`, `..`, `...expr`
2953 fn parse_prefix_range_expr(&mut self,
2954 already_parsed_attrs: Option<ThinVec<Attribute>>)
2955 -> PResult<'a, P<Expr>> {
2956 debug_assert!(self.token == token::DotDot || self.token == token::DotDotDot,
2957 "parse_prefix_range_expr: token {:?} is not DotDot or DotDotDot",
2959 let tok = self.token.clone();
2960 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2962 let mut hi = self.span;
2964 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2965 // RHS must be parsed with more associativity than the dots.
2966 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
2967 Some(self.parse_assoc_expr_with(next_prec,
2968 LhsExpr::NotYetParsed)
2976 let limits = if tok == token::DotDot {
2977 RangeLimits::HalfOpen
2982 let r = try!(self.mk_range(None,
2985 Ok(self.mk_expr(lo.to(hi), r, attrs))
2988 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2989 if self.token.can_begin_expr() {
2990 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2991 if self.token == token::OpenDelim(token::Brace) {
2992 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3000 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3001 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3002 if self.check_keyword(keywords::Let) {
3003 return self.parse_if_let_expr(attrs);
3005 let lo = self.prev_span;
3006 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3008 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3009 // verify that the last statement is either an implicit return (no `;`) or an explicit
3010 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3011 // the dead code lint.
3012 if self.eat_keyword(keywords::Else) || !cond.returns() {
3013 let sp = lo.next_point();
3014 let mut err = self.diagnostic()
3015 .struct_span_err(sp, "missing condition for `if` statemement");
3016 err.span_label(sp, "expected if condition here");
3019 let thn = self.parse_block()?;
3020 let mut els: Option<P<Expr>> = None;
3021 let mut hi = thn.span;
3022 if self.eat_keyword(keywords::Else) {
3023 let elexpr = self.parse_else_expr()?;
3027 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3030 /// Parse an 'if let' expression ('if' token already eaten)
3031 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3032 -> PResult<'a, P<Expr>> {
3033 let lo = self.prev_span;
3034 self.expect_keyword(keywords::Let)?;
3035 let pat = self.parse_pat()?;
3036 self.expect(&token::Eq)?;
3037 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3038 let thn = self.parse_block()?;
3039 let (hi, els) = if self.eat_keyword(keywords::Else) {
3040 let expr = self.parse_else_expr()?;
3041 (expr.span, Some(expr))
3045 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
3048 // `move |args| expr`
3049 pub fn parse_lambda_expr(&mut self,
3051 capture_clause: CaptureBy,
3052 attrs: ThinVec<Attribute>)
3053 -> PResult<'a, P<Expr>>
3055 let decl = self.parse_fn_block_decl()?;
3056 let decl_hi = self.prev_span;
3057 let body = match decl.output {
3058 FunctionRetTy::Default(_) => {
3059 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3060 self.parse_expr_res(restrictions, None)?
3063 // If an explicit return type is given, require a
3064 // block to appear (RFC 968).
3065 let body_lo = self.span;
3066 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3072 ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3076 // `else` token already eaten
3077 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3078 if self.eat_keyword(keywords::If) {
3079 return self.parse_if_expr(ThinVec::new());
3081 let blk = self.parse_block()?;
3082 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3086 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3087 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3089 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3090 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3092 let pat = self.parse_pat()?;
3093 self.expect_keyword(keywords::In)?;
3094 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3095 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3096 attrs.extend(iattrs);
3098 let hi = self.prev_span;
3099 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3102 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3103 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3105 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3106 if self.token.is_keyword(keywords::Let) {
3107 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3109 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3110 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3111 attrs.extend(iattrs);
3112 let span = span_lo.to(body.span);
3113 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3116 /// Parse a 'while let' expression ('while' token already eaten)
3117 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3119 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3120 self.expect_keyword(keywords::Let)?;
3121 let pat = self.parse_pat()?;
3122 self.expect(&token::Eq)?;
3123 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3124 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3125 attrs.extend(iattrs);
3126 let span = span_lo.to(body.span);
3127 return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3130 // parse `loop {...}`, `loop` token already eaten
3131 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3133 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3134 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3135 attrs.extend(iattrs);
3136 let span = span_lo.to(body.span);
3137 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3140 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3141 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3142 -> PResult<'a, P<Expr>>
3144 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3145 attrs.extend(iattrs);
3146 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3149 // `match` token already eaten
3150 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3151 let match_span = self.prev_span;
3152 let lo = self.prev_span;
3153 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3155 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3156 if self.token == token::Token::Semi {
3157 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3161 attrs.extend(self.parse_inner_attributes()?);
3163 let mut arms: Vec<Arm> = Vec::new();
3164 while self.token != token::CloseDelim(token::Brace) {
3165 match self.parse_arm() {
3166 Ok(arm) => arms.push(arm),
3168 // Recover by skipping to the end of the block.
3170 self.recover_stmt();
3171 let span = lo.to(self.span);
3172 if self.token == token::CloseDelim(token::Brace) {
3175 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3181 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3184 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3185 maybe_whole!(self, NtArm, |x| x);
3187 let attrs = self.parse_outer_attributes()?;
3188 // Allow a '|' before the pats (RFC 1925)
3189 let beginning_vert = if self.eat(&token::BinOp(token::Or)) {
3190 Some(self.prev_span)
3194 let pats = self.parse_pats()?;
3195 let guard = if self.eat_keyword(keywords::If) {
3196 Some(self.parse_expr()?)
3200 self.expect(&token::FatArrow)?;
3201 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)?;
3203 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3204 && self.token != token::CloseDelim(token::Brace);
3207 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3209 self.eat(&token::Comma);
3221 /// Parse an expression
3222 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3223 self.parse_expr_res(Restrictions::empty(), None)
3226 /// Evaluate the closure with restrictions in place.
3228 /// After the closure is evaluated, restrictions are reset.
3229 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3230 where F: FnOnce(&mut Self) -> T
3232 let old = self.restrictions;
3233 self.restrictions = r;
3235 self.restrictions = old;
3240 /// Parse an expression, subject to the given restrictions
3241 pub fn parse_expr_res(&mut self, r: Restrictions,
3242 already_parsed_attrs: Option<ThinVec<Attribute>>)
3243 -> PResult<'a, P<Expr>> {
3244 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3247 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3248 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3249 if self.check(&token::Eq) {
3251 Ok(Some(self.parse_expr()?))
3257 /// Parse patterns, separated by '|' s
3258 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3259 let mut pats = Vec::new();
3261 pats.push(self.parse_pat()?);
3262 if self.check(&token::BinOp(token::Or)) { self.bump();}
3263 else { return Ok(pats); }
3267 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3268 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3269 let mut fields = vec![];
3270 let mut ddpos = None;
3272 while !self.check(&token::CloseDelim(token::Paren)) {
3273 if ddpos.is_none() && self.eat(&token::DotDot) {
3274 ddpos = Some(fields.len());
3275 if self.eat(&token::Comma) {
3276 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3277 fields.push(self.parse_pat()?);
3279 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3280 // Emit a friendly error, ignore `..` and continue parsing
3281 self.span_err(self.prev_span, "`..` can only be used once per \
3282 tuple or tuple struct pattern");
3284 fields.push(self.parse_pat()?);
3287 if !self.check(&token::CloseDelim(token::Paren)) ||
3288 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3289 self.expect(&token::Comma)?;
3296 fn parse_pat_vec_elements(
3298 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3299 let mut before = Vec::new();
3300 let mut slice = None;
3301 let mut after = Vec::new();
3302 let mut first = true;
3303 let mut before_slice = true;
3305 while self.token != token::CloseDelim(token::Bracket) {
3309 self.expect(&token::Comma)?;
3311 if self.token == token::CloseDelim(token::Bracket)
3312 && (before_slice || !after.is_empty()) {
3318 if self.eat(&token::DotDot) {
3320 if self.check(&token::Comma) ||
3321 self.check(&token::CloseDelim(token::Bracket)) {
3322 slice = Some(P(ast::Pat {
3323 id: ast::DUMMY_NODE_ID,
3324 node: PatKind::Wild,
3327 before_slice = false;
3333 let subpat = self.parse_pat()?;
3334 if before_slice && self.eat(&token::DotDot) {
3335 slice = Some(subpat);
3336 before_slice = false;
3337 } else if before_slice {
3338 before.push(subpat);
3344 Ok((before, slice, after))
3347 /// Parse the fields of a struct-like pattern
3348 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3349 let mut fields = Vec::new();
3350 let mut etc = false;
3351 let mut first = true;
3352 while self.token != token::CloseDelim(token::Brace) {
3356 self.expect(&token::Comma)?;
3357 // accept trailing commas
3358 if self.check(&token::CloseDelim(token::Brace)) { break }
3361 let attrs = self.parse_outer_attributes()?;
3365 if self.check(&token::DotDot) {
3367 if self.token != token::CloseDelim(token::Brace) {
3368 let token_str = self.this_token_to_string();
3369 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3376 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3377 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3378 // Parsing a pattern of the form "fieldname: pat"
3379 let fieldname = self.parse_field_name()?;
3381 let pat = self.parse_pat()?;
3383 (pat, fieldname, false)
3385 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3386 let is_box = self.eat_keyword(keywords::Box);
3387 let boxed_span = self.span;
3388 let is_ref = self.eat_keyword(keywords::Ref);
3389 let is_mut = self.eat_keyword(keywords::Mut);
3390 let fieldname = self.parse_ident()?;
3391 hi = self.prev_span;
3393 let bind_type = match (is_ref, is_mut) {
3394 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3395 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3396 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3397 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3399 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3400 let fieldpat = P(ast::Pat{
3401 id: ast::DUMMY_NODE_ID,
3402 node: PatKind::Ident(bind_type, fieldpath, None),
3403 span: boxed_span.to(hi),
3406 let subpat = if is_box {
3408 id: ast::DUMMY_NODE_ID,
3409 node: PatKind::Box(fieldpat),
3415 (subpat, fieldname, true)
3418 fields.push(codemap::Spanned { span: lo.to(hi),
3419 node: ast::FieldPat {
3423 attrs: attrs.into(),
3427 return Ok((fields, etc));
3430 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3431 if self.token.is_path_start() {
3433 let (qself, path) = if self.eat_lt() {
3434 // Parse a qualified path
3435 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3438 // Parse an unqualified path
3439 (None, self.parse_path(PathStyle::Expr)?)
3441 let hi = self.prev_span;
3442 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3444 self.parse_pat_literal_maybe_minus()
3448 // helper function to decide whether to parse as ident binding or to try to do
3449 // something more complex like range patterns
3450 fn parse_as_ident(&mut self) -> bool {
3451 self.look_ahead(1, |t| match *t {
3452 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3453 token::DotDotDot | token::ModSep | token::Not => Some(false),
3454 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3455 // range pattern branch
3456 token::DotDot => None,
3458 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3459 token::Comma | token::CloseDelim(token::Bracket) => true,
3464 /// Parse a pattern.
3465 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3466 maybe_whole!(self, NtPat, |x| x);
3471 token::Underscore => {
3474 pat = PatKind::Wild;
3476 token::BinOp(token::And) | token::AndAnd => {
3477 // Parse &pat / &mut pat
3479 let mutbl = self.parse_mutability();
3480 if let token::Lifetime(ident) = self.token {
3481 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3483 let subpat = self.parse_pat()?;
3484 pat = PatKind::Ref(subpat, mutbl);
3486 token::OpenDelim(token::Paren) => {
3487 // Parse (pat,pat,pat,...) as tuple pattern
3489 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3490 self.expect(&token::CloseDelim(token::Paren))?;
3491 pat = PatKind::Tuple(fields, ddpos);
3493 token::OpenDelim(token::Bracket) => {
3494 // Parse [pat,pat,...] as slice pattern
3496 let (before, slice, after) = self.parse_pat_vec_elements()?;
3497 self.expect(&token::CloseDelim(token::Bracket))?;
3498 pat = PatKind::Slice(before, slice, after);
3500 // At this point, token != _, &, &&, (, [
3501 _ => if self.eat_keyword(keywords::Mut) {
3502 // Parse mut ident @ pat / mut ref ident @ pat
3503 let mutref_span = self.prev_span.to(self.span);
3504 let binding_mode = if self.eat_keyword(keywords::Ref) {
3506 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3507 .span_suggestion(mutref_span, "try switching the order", "ref mut".into())
3509 BindingMode::ByRef(Mutability::Mutable)
3511 BindingMode::ByValue(Mutability::Mutable)
3513 pat = self.parse_pat_ident(binding_mode)?;
3514 } else if self.eat_keyword(keywords::Ref) {
3515 // Parse ref ident @ pat / ref mut ident @ pat
3516 let mutbl = self.parse_mutability();
3517 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3518 } else if self.eat_keyword(keywords::Box) {
3520 let subpat = self.parse_pat()?;
3521 pat = PatKind::Box(subpat);
3522 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3523 self.parse_as_ident() {
3524 // Parse ident @ pat
3525 // This can give false positives and parse nullary enums,
3526 // they are dealt with later in resolve
3527 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3528 pat = self.parse_pat_ident(binding_mode)?;
3529 } else if self.token.is_path_start() {
3530 // Parse pattern starting with a path
3531 let (qself, path) = if self.eat_lt() {
3532 // Parse a qualified path
3533 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3536 // Parse an unqualified path
3537 (None, self.parse_path(PathStyle::Expr)?)
3540 token::Not if qself.is_none() => {
3541 // Parse macro invocation
3543 let (_, tts) = self.expect_delimited_token_tree()?;
3544 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3545 pat = PatKind::Mac(mac);
3547 token::DotDotDot | token::DotDot => {
3548 let end_kind = match self.token {
3549 token::DotDot => RangeEnd::Excluded,
3550 token::DotDotDot => RangeEnd::Included,
3551 _ => panic!("can only parse `..` or `...` for ranges (checked above)"),
3554 let span = lo.to(self.prev_span);
3555 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3557 let end = self.parse_pat_range_end()?;
3558 pat = PatKind::Range(begin, end, end_kind);
3560 token::OpenDelim(token::Brace) => {
3561 if qself.is_some() {
3562 return Err(self.fatal("unexpected `{` after qualified path"));
3564 // Parse struct pattern
3566 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3568 self.recover_stmt();
3572 pat = PatKind::Struct(path, fields, etc);
3574 token::OpenDelim(token::Paren) => {
3575 if qself.is_some() {
3576 return Err(self.fatal("unexpected `(` after qualified path"));
3578 // Parse tuple struct or enum pattern
3580 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3581 self.expect(&token::CloseDelim(token::Paren))?;
3582 pat = PatKind::TupleStruct(path, fields, ddpos)
3584 _ => pat = PatKind::Path(qself, path),
3587 // Try to parse everything else as literal with optional minus
3588 match self.parse_pat_literal_maybe_minus() {
3590 if self.eat(&token::DotDotDot) {
3591 let end = self.parse_pat_range_end()?;
3592 pat = PatKind::Range(begin, end, RangeEnd::Included);
3593 } else if self.eat(&token::DotDot) {
3594 let end = self.parse_pat_range_end()?;
3595 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3597 pat = PatKind::Lit(begin);
3601 self.cancel(&mut err);
3602 let msg = format!("expected pattern, found {}", self.this_token_descr());
3603 return Err(self.fatal(&msg));
3610 id: ast::DUMMY_NODE_ID,
3612 span: lo.to(self.prev_span),
3616 /// Parse ident or ident @ pat
3617 /// used by the copy foo and ref foo patterns to give a good
3618 /// error message when parsing mistakes like ref foo(a,b)
3619 fn parse_pat_ident(&mut self,
3620 binding_mode: ast::BindingMode)
3621 -> PResult<'a, PatKind> {
3622 let ident_span = self.span;
3623 let ident = self.parse_ident()?;
3624 let name = codemap::Spanned{span: ident_span, node: ident};
3625 let sub = if self.eat(&token::At) {
3626 Some(self.parse_pat()?)
3631 // just to be friendly, if they write something like
3633 // we end up here with ( as the current token. This shortly
3634 // leads to a parse error. Note that if there is no explicit
3635 // binding mode then we do not end up here, because the lookahead
3636 // will direct us over to parse_enum_variant()
3637 if self.token == token::OpenDelim(token::Paren) {
3638 return Err(self.span_fatal(
3640 "expected identifier, found enum pattern"))
3643 Ok(PatKind::Ident(binding_mode, name, sub))
3646 /// Parse a local variable declaration
3647 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3648 let lo = self.prev_span;
3649 let pat = self.parse_pat()?;
3651 let ty = if self.eat(&token::Colon) {
3652 Some(self.parse_ty()?)
3656 let init = self.parse_initializer()?;
3661 id: ast::DUMMY_NODE_ID,
3662 span: lo.to(self.prev_span),
3667 /// Parse a structure field
3668 fn parse_name_and_ty(&mut self,
3671 attrs: Vec<Attribute>)
3672 -> PResult<'a, StructField> {
3673 let name = self.parse_ident()?;
3674 self.expect(&token::Colon)?;
3675 let ty = self.parse_ty()?;
3677 span: lo.to(self.prev_span),
3680 id: ast::DUMMY_NODE_ID,
3686 /// Emit an expected item after attributes error.
3687 fn expected_item_err(&self, attrs: &[Attribute]) {
3688 let message = match attrs.last() {
3689 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3690 _ => "expected item after attributes",
3693 self.span_err(self.prev_span, message);
3696 /// Parse a statement. This stops just before trailing semicolons on everything but items.
3697 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3698 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3699 Ok(self.parse_stmt_(true))
3702 // Eat tokens until we can be relatively sure we reached the end of the
3703 // statement. This is something of a best-effort heuristic.
3705 // We terminate when we find an unmatched `}` (without consuming it).
3706 fn recover_stmt(&mut self) {
3707 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
3710 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3711 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3712 // approximate - it can mean we break too early due to macros, but that
3713 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3715 // If `break_on_block` is `Break`, then we will stop consuming tokens
3716 // after finding (and consuming) a brace-delimited block.
3717 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
3718 let mut brace_depth = 0;
3719 let mut bracket_depth = 0;
3720 let mut in_block = false;
3721 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
3722 break_on_semi, break_on_block);
3724 debug!("recover_stmt_ loop {:?}", self.token);
3726 token::OpenDelim(token::DelimToken::Brace) => {
3729 if break_on_block == BlockMode::Break &&
3731 bracket_depth == 0 {
3735 token::OpenDelim(token::DelimToken::Bracket) => {
3739 token::CloseDelim(token::DelimToken::Brace) => {
3740 if brace_depth == 0 {
3741 debug!("recover_stmt_ return - close delim {:?}", self.token);
3746 if in_block && bracket_depth == 0 && brace_depth == 0 {
3747 debug!("recover_stmt_ return - block end {:?}", self.token);
3751 token::CloseDelim(token::DelimToken::Bracket) => {
3753 if bracket_depth < 0 {
3759 debug!("recover_stmt_ return - Eof");
3764 if break_on_semi == SemiColonMode::Break &&
3766 bracket_depth == 0 {
3767 debug!("recover_stmt_ return - Semi");
3778 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
3779 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
3781 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
3786 fn is_catch_expr(&mut self) -> bool {
3787 self.token.is_keyword(keywords::Do) &&
3788 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
3789 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
3791 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3792 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
3795 fn is_union_item(&self) -> bool {
3796 self.token.is_keyword(keywords::Union) &&
3797 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
3800 fn is_defaultness(&self) -> bool {
3801 // `pub` is included for better error messages
3802 self.token.is_keyword(keywords::Default) &&
3803 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
3804 t.is_keyword(keywords::Const) ||
3805 t.is_keyword(keywords::Fn) ||
3806 t.is_keyword(keywords::Unsafe) ||
3807 t.is_keyword(keywords::Extern) ||
3808 t.is_keyword(keywords::Type) ||
3809 t.is_keyword(keywords::Pub))
3812 fn eat_defaultness(&mut self) -> bool {
3813 let is_defaultness = self.is_defaultness();
3817 self.expected_tokens.push(TokenType::Keyword(keywords::Default));
3822 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
3823 -> PResult<'a, Option<P<Item>>> {
3824 let token_lo = self.span;
3825 let (ident, def) = match self.token {
3826 token::Ident(ident) if ident.name == keywords::Macro.name() => {
3828 let ident = self.parse_ident()?;
3829 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
3830 match self.parse_token_tree() {
3831 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
3832 _ => unreachable!(),
3834 } else if self.check(&token::OpenDelim(token::Paren)) {
3835 let args = self.parse_token_tree();
3836 let body = if self.check(&token::OpenDelim(token::Brace)) {
3837 self.parse_token_tree()
3842 TokenStream::concat(vec![
3844 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
3852 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
3854 token::Ident(ident) if ident.name == "macro_rules" &&
3855 self.look_ahead(1, |t| *t == token::Not) => {
3856 let prev_span = self.prev_span;
3857 self.complain_if_pub_macro(vis, prev_span);
3861 let ident = self.parse_ident()?;
3862 let (delim, tokens) = self.expect_delimited_token_tree()?;
3863 if delim != token::Brace {
3864 if !self.eat(&token::Semi) {
3865 let msg = "macros that expand to items must either \
3866 be surrounded with braces or followed by a semicolon";
3867 self.span_err(self.prev_span, msg);
3871 (ident, ast::MacroDef { tokens: tokens, legacy: true })
3873 _ => return Ok(None),
3876 let span = lo.to(self.prev_span);
3877 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
3880 fn parse_stmt_without_recovery(&mut self,
3881 macro_legacy_warnings: bool)
3882 -> PResult<'a, Option<Stmt>> {
3883 maybe_whole!(self, NtStmt, |x| Some(x));
3885 let attrs = self.parse_outer_attributes()?;
3888 Ok(Some(if self.eat_keyword(keywords::Let) {
3890 id: ast::DUMMY_NODE_ID,
3891 node: StmtKind::Local(self.parse_local(attrs.into())?),
3892 span: lo.to(self.prev_span),
3894 } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited, lo)? {
3896 id: ast::DUMMY_NODE_ID,
3897 node: StmtKind::Item(macro_def),
3898 span: lo.to(self.prev_span),
3900 // Starts like a simple path, but not a union item.
3901 } else if self.token.is_path_start() &&
3902 !self.token.is_qpath_start() &&
3903 !self.is_union_item() {
3904 let pth = self.parse_path(PathStyle::Expr)?;
3906 if !self.eat(&token::Not) {
3907 let expr = if self.check(&token::OpenDelim(token::Brace)) {
3908 self.parse_struct_expr(lo, pth, ThinVec::new())?
3910 let hi = self.prev_span;
3911 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
3914 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
3915 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
3916 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
3919 return Ok(Some(Stmt {
3920 id: ast::DUMMY_NODE_ID,
3921 node: StmtKind::Expr(expr),
3922 span: lo.to(self.prev_span),
3926 // it's a macro invocation
3927 let id = match self.token {
3928 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
3929 _ => self.parse_ident()?,
3932 // check that we're pointing at delimiters (need to check
3933 // again after the `if`, because of `parse_ident`
3934 // consuming more tokens).
3935 let delim = match self.token {
3936 token::OpenDelim(delim) => delim,
3938 // we only expect an ident if we didn't parse one
3940 let ident_str = if id.name == keywords::Invalid.name() {
3945 let tok_str = self.this_token_to_string();
3946 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3952 let (_, tts) = self.expect_delimited_token_tree()?;
3953 let hi = self.prev_span;
3955 let style = if delim == token::Brace {
3956 MacStmtStyle::Braces
3958 MacStmtStyle::NoBraces
3961 if id.name == keywords::Invalid.name() {
3962 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
3963 let node = if delim == token::Brace ||
3964 self.token == token::Semi || self.token == token::Eof {
3965 StmtKind::Mac(P((mac, style, attrs.into())))
3967 // We used to incorrectly stop parsing macro-expanded statements here.
3968 // If the next token will be an error anyway but could have parsed with the
3969 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
3970 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
3971 // These can continue an expression, so we can't stop parsing and warn.
3972 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
3973 token::BinOp(token::Minus) | token::BinOp(token::Star) |
3974 token::BinOp(token::And) | token::BinOp(token::Or) |
3975 token::AndAnd | token::OrOr |
3976 token::DotDot | token::DotDotDot => false,
3979 self.warn_missing_semicolon();
3980 StmtKind::Mac(P((mac, style, attrs.into())))
3982 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
3983 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
3984 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
3988 id: ast::DUMMY_NODE_ID,
3993 // if it has a special ident, it's definitely an item
3995 // Require a semicolon or braces.
3996 if style != MacStmtStyle::Braces {
3997 if !self.eat(&token::Semi) {
3998 self.span_err(self.prev_span,
3999 "macros that expand to items must \
4000 either be surrounded with braces or \
4001 followed by a semicolon");
4004 let span = lo.to(hi);
4006 id: ast::DUMMY_NODE_ID,
4008 node: StmtKind::Item({
4010 span, id /*id is good here*/,
4011 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
4012 Visibility::Inherited,
4018 // FIXME: Bad copy of attrs
4019 let old_directory_ownership =
4020 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4021 let item = self.parse_item_(attrs.clone(), false, true)?;
4022 self.directory.ownership = old_directory_ownership;
4026 id: ast::DUMMY_NODE_ID,
4027 span: lo.to(i.span),
4028 node: StmtKind::Item(i),
4031 let unused_attrs = |attrs: &[_], s: &mut Self| {
4032 if !attrs.is_empty() {
4033 if s.prev_token_kind == PrevTokenKind::DocComment {
4034 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4036 s.span_err(s.span, "expected statement after outer attribute");
4041 // Do not attempt to parse an expression if we're done here.
4042 if self.token == token::Semi {
4043 unused_attrs(&attrs, self);
4048 if self.token == token::CloseDelim(token::Brace) {
4049 unused_attrs(&attrs, self);
4053 // Remainder are line-expr stmts.
4054 let e = self.parse_expr_res(
4055 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4057 id: ast::DUMMY_NODE_ID,
4058 span: lo.to(e.span),
4059 node: StmtKind::Expr(e),
4066 /// Is this expression a successfully-parsed statement?
4067 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4068 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4069 !classify::expr_requires_semi_to_be_stmt(e)
4072 /// Parse a block. No inner attrs are allowed.
4073 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4074 maybe_whole!(self, NtBlock, |x| x);
4078 if !self.eat(&token::OpenDelim(token::Brace)) {
4080 let tok = self.this_token_to_string();
4081 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4083 // Check to see if the user has written something like
4088 // Which is valid in other languages, but not Rust.
4089 match self.parse_stmt_without_recovery(false) {
4091 let mut stmt_span = stmt.span;
4092 // expand the span to include the semicolon, if it exists
4093 if self.eat(&token::Semi) {
4094 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4096 let sugg = pprust::to_string(|s| {
4097 use print::pprust::{PrintState, INDENT_UNIT};
4098 s.ibox(INDENT_UNIT)?;
4100 s.print_stmt(&stmt)?;
4101 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4103 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4106 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4107 self.cancel(&mut e);
4114 self.parse_block_tail(lo, BlockCheckMode::Default)
4117 /// Parse a block. Inner attrs are allowed.
4118 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4119 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4122 self.expect(&token::OpenDelim(token::Brace))?;
4123 Ok((self.parse_inner_attributes()?,
4124 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4127 /// Parse the rest of a block expression or function body
4128 /// Precondition: already parsed the '{'.
4129 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4130 let mut stmts = vec![];
4132 while !self.eat(&token::CloseDelim(token::Brace)) {
4133 if let Some(stmt) = self.parse_full_stmt(false)? {
4135 } else if self.token == token::Eof {
4138 // Found only `;` or `}`.
4145 id: ast::DUMMY_NODE_ID,
4147 span: lo.to(self.prev_span),
4151 /// Parse a statement, including the trailing semicolon.
4152 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4153 let mut stmt = match self.parse_stmt_(macro_legacy_warnings) {
4155 None => return Ok(None),
4159 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4160 // expression without semicolon
4161 if classify::expr_requires_semi_to_be_stmt(expr) {
4162 // Just check for errors and recover; do not eat semicolon yet.
4164 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4167 self.recover_stmt();
4171 StmtKind::Local(..) => {
4172 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4173 if macro_legacy_warnings && self.token != token::Semi {
4174 self.warn_missing_semicolon();
4176 self.expect_one_of(&[token::Semi], &[])?;
4182 if self.eat(&token::Semi) {
4183 stmt = stmt.add_trailing_semicolon();
4186 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4190 fn warn_missing_semicolon(&self) {
4191 self.diagnostic().struct_span_warn(self.span, {
4192 &format!("expected `;`, found `{}`", self.this_token_to_string())
4194 "This was erroneously allowed and will become a hard error in a future release"
4198 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4199 // BOUND = TY_BOUND | LT_BOUND
4200 // LT_BOUND = LIFETIME (e.g. `'a`)
4201 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4202 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4203 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4204 let mut bounds = Vec::new();
4206 let is_bound_start = self.check_path() || self.check_lifetime() ||
4207 self.check(&token::Question) ||
4208 self.check_keyword(keywords::For) ||
4209 self.check(&token::OpenDelim(token::Paren));
4211 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4212 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4213 if self.token.is_lifetime() {
4214 if let Some(question_span) = question {
4215 self.span_err(question_span,
4216 "`?` may only modify trait bounds, not lifetime bounds");
4218 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4221 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4222 let path = self.parse_path(PathStyle::Type)?;
4223 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4224 let modifier = if question.is_some() {
4225 TraitBoundModifier::Maybe
4227 TraitBoundModifier::None
4229 bounds.push(TraitTyParamBound(poly_trait, modifier));
4232 self.expect(&token::CloseDelim(token::Paren))?;
4233 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4234 self.span_err(self.prev_span,
4235 "parenthesized lifetime bounds are not supported");
4242 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4250 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4251 self.parse_ty_param_bounds_common(true)
4254 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4255 // BOUND = LT_BOUND (e.g. `'a`)
4256 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4257 let mut lifetimes = Vec::new();
4258 while self.check_lifetime() {
4259 lifetimes.push(self.expect_lifetime());
4261 if !self.eat(&token::BinOp(token::Plus)) {
4268 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4269 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4270 let span = self.span;
4271 let ident = self.parse_ident()?;
4273 // Parse optional colon and param bounds.
4274 let bounds = if self.eat(&token::Colon) {
4275 self.parse_ty_param_bounds()?
4280 let default = if self.eat(&token::Eq) {
4281 Some(self.parse_ty()?)
4287 attrs: preceding_attrs.into(),
4289 id: ast::DUMMY_NODE_ID,
4296 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4297 /// trailing comma and erroneous trailing attributes.
4298 pub fn parse_generic_params(&mut self) -> PResult<'a, (Vec<LifetimeDef>, Vec<TyParam>)> {
4299 let mut lifetime_defs = Vec::new();
4300 let mut ty_params = Vec::new();
4301 let mut seen_ty_param = false;
4303 let attrs = self.parse_outer_attributes()?;
4304 if self.check_lifetime() {
4305 let lifetime = self.expect_lifetime();
4306 // Parse lifetime parameter.
4307 let bounds = if self.eat(&token::Colon) {
4308 self.parse_lt_param_bounds()
4312 lifetime_defs.push(LifetimeDef {
4313 attrs: attrs.into(),
4318 self.span_err(self.prev_span,
4319 "lifetime parameters must be declared prior to type parameters");
4321 } else if self.check_ident() {
4322 // Parse type parameter.
4323 ty_params.push(self.parse_ty_param(attrs)?);
4324 seen_ty_param = true;
4326 // Check for trailing attributes and stop parsing.
4327 if !attrs.is_empty() {
4328 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4329 self.span_err(attrs[0].span,
4330 &format!("trailing attribute after {} parameters", param_kind));
4335 if !self.eat(&token::Comma) {
4339 Ok((lifetime_defs, ty_params))
4342 /// Parse a set of optional generic type parameter declarations. Where
4343 /// clauses are not parsed here, and must be added later via
4344 /// `parse_where_clause()`.
4346 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4347 /// | ( < lifetimes , typaramseq ( , )? > )
4348 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4349 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4350 maybe_whole!(self, NtGenerics, |x| x);
4352 let span_lo = self.span;
4354 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4357 lifetimes: lifetime_defs,
4359 where_clause: WhereClause {
4360 id: ast::DUMMY_NODE_ID,
4361 predicates: Vec::new(),
4362 span: syntax_pos::DUMMY_SP,
4364 span: span_lo.to(self.prev_span),
4367 Ok(ast::Generics::default())
4371 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4372 /// possibly including trailing comma.
4373 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4374 let mut lifetimes = Vec::new();
4375 let mut types = Vec::new();
4376 let mut bindings = Vec::new();
4377 let mut seen_type = false;
4378 let mut seen_binding = false;
4380 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4381 // Parse lifetime argument.
4382 lifetimes.push(self.expect_lifetime());
4383 if seen_type || seen_binding {
4384 self.span_err(self.prev_span,
4385 "lifetime parameters must be declared prior to type parameters");
4387 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4388 // Parse associated type binding.
4390 let ident = self.parse_ident()?;
4392 let ty = self.parse_ty()?;
4393 bindings.push(TypeBinding {
4394 id: ast::DUMMY_NODE_ID,
4397 span: lo.to(self.prev_span),
4399 seen_binding = true;
4400 } else if self.check_type() {
4401 // Parse type argument.
4402 types.push(self.parse_ty()?);
4404 self.span_err(types[types.len() - 1].span,
4405 "type parameters must be declared prior to associated type bindings");
4412 if !self.eat(&token::Comma) {
4416 Ok((lifetimes, types, bindings))
4419 /// Parses an optional `where` clause and places it in `generics`.
4421 /// ```ignore (only-for-syntax-highlight)
4422 /// where T : Trait<U, V> + 'b, 'a : 'b
4424 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4425 maybe_whole!(self, NtWhereClause, |x| x);
4427 let mut where_clause = WhereClause {
4428 id: ast::DUMMY_NODE_ID,
4429 predicates: Vec::new(),
4430 span: syntax_pos::DUMMY_SP,
4433 if !self.eat_keyword(keywords::Where) {
4434 return Ok(where_clause);
4436 let lo = self.prev_span;
4438 // This is a temporary future proofing.
4440 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4441 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4442 // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4443 if token::Lt == self.token {
4444 let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4445 if ident_or_lifetime {
4446 let gt_comma_or_colon = self.look_ahead(2, |t| {
4447 *t == token::Gt || *t == token::Comma || *t == token::Colon
4449 if gt_comma_or_colon {
4450 self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4457 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4458 let lifetime = self.expect_lifetime();
4459 // Bounds starting with a colon are mandatory, but possibly empty.
4460 self.expect(&token::Colon)?;
4461 let bounds = self.parse_lt_param_bounds();
4462 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4463 ast::WhereRegionPredicate {
4464 span: lo.to(self.prev_span),
4469 } else if self.check_type() {
4470 // Parse optional `for<'a, 'b>`.
4471 // This `for` is parsed greedily and applies to the whole predicate,
4472 // the bounded type can have its own `for` applying only to it.
4473 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4474 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4475 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4476 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4478 // Parse type with mandatory colon and (possibly empty) bounds,
4479 // or with mandatory equality sign and the second type.
4480 let ty = self.parse_ty()?;
4481 if self.eat(&token::Colon) {
4482 let bounds = self.parse_ty_param_bounds()?;
4483 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4484 ast::WhereBoundPredicate {
4485 span: lo.to(self.prev_span),
4486 bound_lifetimes: lifetime_defs,
4491 // FIXME: Decide what should be used here, `=` or `==`.
4492 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4493 let rhs_ty = self.parse_ty()?;
4494 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4495 ast::WhereEqPredicate {
4496 span: lo.to(self.prev_span),
4499 id: ast::DUMMY_NODE_ID,
4503 return self.unexpected();
4509 if !self.eat(&token::Comma) {
4514 where_clause.span = lo.to(self.prev_span);
4518 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4519 -> PResult<'a, (Vec<Arg> , bool)> {
4521 let mut variadic = false;
4522 let args: Vec<Option<Arg>> =
4523 self.parse_unspanned_seq(
4524 &token::OpenDelim(token::Paren),
4525 &token::CloseDelim(token::Paren),
4526 SeqSep::trailing_allowed(token::Comma),
4528 if p.token == token::DotDotDot {
4531 if p.token != token::CloseDelim(token::Paren) {
4534 "`...` must be last in argument list for variadic function");
4539 "only foreign functions are allowed to be variadic");
4544 match p.parse_arg_general(named_args) {
4545 Ok(arg) => Ok(Some(arg)),
4548 let lo = p.prev_span;
4549 // Skip every token until next possible arg or end.
4550 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4551 // Create a placeholder argument for proper arg count (#34264).
4552 let span = lo.to(p.prev_span);
4553 Ok(Some(dummy_arg(span)))
4560 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4562 if variadic && args.is_empty() {
4564 "variadic function must be declared with at least one named argument");
4567 Ok((args, variadic))
4570 /// Parse the argument list and result type of a function declaration
4571 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4573 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4574 let ret_ty = self.parse_ret_ty()?;
4583 /// Returns the parsed optional self argument and whether a self shortcut was used.
4584 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4585 let expect_ident = |this: &mut Self| match this.token {
4586 // Preserve hygienic context.
4587 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4590 let isolated_self = |this: &mut Self, n| {
4591 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4592 this.look_ahead(n + 1, |t| t != &token::ModSep)
4595 // Parse optional self parameter of a method.
4596 // Only a limited set of initial token sequences is considered self parameters, anything
4597 // else is parsed as a normal function parameter list, so some lookahead is required.
4598 let eself_lo = self.span;
4599 let (eself, eself_ident) = match self.token {
4600 token::BinOp(token::And) => {
4606 if isolated_self(self, 1) {
4608 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4609 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4610 isolated_self(self, 2) {
4613 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4614 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4615 isolated_self(self, 2) {
4617 let lt = self.expect_lifetime();
4618 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4619 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4620 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4621 isolated_self(self, 3) {
4623 let lt = self.expect_lifetime();
4625 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4630 token::BinOp(token::Star) => {
4635 // Emit special error for `self` cases.
4636 if isolated_self(self, 1) {
4638 self.span_err(self.span, "cannot pass `self` by raw pointer");
4639 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4640 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4641 isolated_self(self, 2) {
4644 self.span_err(self.span, "cannot pass `self` by raw pointer");
4645 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4650 token::Ident(..) => {
4651 if isolated_self(self, 0) {
4654 let eself_ident = expect_ident(self);
4655 if self.eat(&token::Colon) {
4656 let ty = self.parse_ty()?;
4657 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4659 (SelfKind::Value(Mutability::Immutable), eself_ident)
4661 } else if self.token.is_keyword(keywords::Mut) &&
4662 isolated_self(self, 1) {
4666 let eself_ident = expect_ident(self);
4667 if self.eat(&token::Colon) {
4668 let ty = self.parse_ty()?;
4669 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4671 (SelfKind::Value(Mutability::Mutable), eself_ident)
4677 _ => return Ok(None),
4680 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
4681 Ok(Some(Arg::from_self(eself, eself_ident)))
4684 /// Parse the parameter list and result type of a function that may have a `self` parameter.
4685 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
4686 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4688 self.expect(&token::OpenDelim(token::Paren))?;
4690 // Parse optional self argument
4691 let self_arg = self.parse_self_arg()?;
4693 // Parse the rest of the function parameter list.
4694 let sep = SeqSep::trailing_allowed(token::Comma);
4695 let fn_inputs = if let Some(self_arg) = self_arg {
4696 if self.check(&token::CloseDelim(token::Paren)) {
4698 } else if self.eat(&token::Comma) {
4699 let mut fn_inputs = vec![self_arg];
4700 fn_inputs.append(&mut self.parse_seq_to_before_end(
4701 &token::CloseDelim(token::Paren), sep, parse_arg_fn)
4705 return self.unexpected();
4708 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4711 // Parse closing paren and return type.
4712 self.expect(&token::CloseDelim(token::Paren))?;
4715 output: self.parse_ret_ty()?,
4720 // parse the |arg, arg| header on a lambda
4721 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4722 let inputs_captures = {
4723 if self.eat(&token::OrOr) {
4726 self.expect(&token::BinOp(token::Or))?;
4727 let args = self.parse_seq_to_before_tokens(
4728 &[&token::BinOp(token::Or), &token::OrOr],
4729 SeqSep::trailing_allowed(token::Comma),
4730 TokenExpectType::NoExpect,
4731 |p| p.parse_fn_block_arg(),
4738 let output = self.parse_ret_ty()?;
4741 inputs: inputs_captures,
4747 /// Parse the name and optional generic types of a function header.
4748 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4749 let id = self.parse_ident()?;
4750 let generics = self.parse_generics()?;
4754 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
4755 attrs: Vec<Attribute>) -> P<Item> {
4759 id: ast::DUMMY_NODE_ID,
4767 /// Parse an item-position function declaration.
4768 fn parse_item_fn(&mut self,
4770 constness: Spanned<Constness>,
4772 -> PResult<'a, ItemInfo> {
4773 let (ident, mut generics) = self.parse_fn_header()?;
4774 let decl = self.parse_fn_decl(false)?;
4775 generics.where_clause = self.parse_where_clause()?;
4776 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4777 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4780 /// true if we are looking at `const ID`, false for things like `const fn` etc
4781 pub fn is_const_item(&mut self) -> bool {
4782 self.token.is_keyword(keywords::Const) &&
4783 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4784 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4787 /// parses all the "front matter" for a `fn` declaration, up to
4788 /// and including the `fn` keyword:
4792 /// - `const unsafe fn`
4795 pub fn parse_fn_front_matter(&mut self)
4796 -> PResult<'a, (Spanned<ast::Constness>,
4799 let is_const_fn = self.eat_keyword(keywords::Const);
4800 let const_span = self.prev_span;
4801 let unsafety = self.parse_unsafety()?;
4802 let (constness, unsafety, abi) = if is_const_fn {
4803 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
4805 let abi = if self.eat_keyword(keywords::Extern) {
4806 self.parse_opt_abi()?.unwrap_or(Abi::C)
4810 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
4812 self.expect_keyword(keywords::Fn)?;
4813 Ok((constness, unsafety, abi))
4816 /// Parse an impl item.
4817 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
4818 maybe_whole!(self, NtImplItem, |x| x);
4819 let attrs = self.parse_outer_attributes()?;
4820 let (mut item, tokens) = self.collect_tokens(|this| {
4821 this.parse_impl_item_(at_end, attrs)
4824 // See `parse_item` for why this clause is here.
4825 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
4826 item.tokens = Some(tokens);
4831 fn parse_impl_item_(&mut self,
4833 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
4835 let vis = self.parse_visibility(false)?;
4836 let defaultness = self.parse_defaultness()?;
4837 let (name, node) = if self.eat_keyword(keywords::Type) {
4838 let name = self.parse_ident()?;
4839 self.expect(&token::Eq)?;
4840 let typ = self.parse_ty()?;
4841 self.expect(&token::Semi)?;
4842 (name, ast::ImplItemKind::Type(typ))
4843 } else if self.is_const_item() {
4844 self.expect_keyword(keywords::Const)?;
4845 let name = self.parse_ident()?;
4846 self.expect(&token::Colon)?;
4847 let typ = self.parse_ty()?;
4848 self.expect(&token::Eq)?;
4849 let expr = self.parse_expr()?;
4850 self.expect(&token::Semi)?;
4851 (name, ast::ImplItemKind::Const(typ, expr))
4853 let (name, inner_attrs, node) = self.parse_impl_method(&vis, at_end)?;
4854 attrs.extend(inner_attrs);
4859 id: ast::DUMMY_NODE_ID,
4860 span: lo.to(self.prev_span),
4870 fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
4871 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
4876 fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
4878 Visibility::Inherited => Ok(()),
4880 let is_macro_rules: bool = match self.token {
4881 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
4885 let mut err = self.diagnostic()
4886 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
4887 err.help("did you mean #[macro_export]?");
4890 let mut err = self.diagnostic()
4891 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
4892 err.help("try adjusting the macro to put `pub` inside the invocation");
4899 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
4900 -> DiagnosticBuilder<'a>
4902 // Given this code `path(`, it seems like this is not
4903 // setting the visibility of a macro invocation, but rather
4904 // a mistyped method declaration.
4905 // Create a diagnostic pointing out that `fn` is missing.
4907 // x | pub path(&self) {
4908 // | ^ missing `fn`, `type`, or `const`
4910 // ^^ `sp` below will point to this
4911 let sp = prev_span.between(self.prev_span);
4912 let mut err = self.diagnostic().struct_span_err(
4914 &format!("missing `fn`, `type`, or `const` for {}-item declaration",
4916 err.span_label(sp, "missing `fn`, `type`, or `const`");
4920 /// Parse a method or a macro invocation in a trait impl.
4921 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
4922 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4923 // code copied from parse_macro_use_or_failure... abstraction!
4924 if self.token.is_path_start() {
4927 let prev_span = self.prev_span;
4930 let pth = self.parse_path(PathStyle::Mod)?;
4931 if pth.segments.len() == 1 {
4932 if !self.eat(&token::Not) {
4933 return Err(self.missing_assoc_item_kind_err("impl", prev_span));
4936 self.expect(&token::Not)?;
4939 self.complain_if_pub_macro(vis, prev_span);
4941 // eat a matched-delimiter token tree:
4943 let (delim, tts) = self.expect_delimited_token_tree()?;
4944 if delim != token::Brace {
4945 self.expect(&token::Semi)?
4948 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
4949 Ok((keywords::Invalid.ident(), vec![], ast::ImplItemKind::Macro(mac)))
4951 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
4952 let ident = self.parse_ident()?;
4953 let mut generics = self.parse_generics()?;
4954 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
4955 generics.where_clause = self.parse_where_clause()?;
4957 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4958 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4968 /// Parse trait Foo { ... }
4969 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4970 let ident = self.parse_ident()?;
4971 let mut tps = self.parse_generics()?;
4973 // Parse optional colon and supertrait bounds.
4974 let bounds = if self.eat(&token::Colon) {
4975 self.parse_ty_param_bounds()?
4980 tps.where_clause = self.parse_where_clause()?;
4982 self.expect(&token::OpenDelim(token::Brace))?;
4983 let mut trait_items = vec![];
4984 while !self.eat(&token::CloseDelim(token::Brace)) {
4985 let mut at_end = false;
4986 match self.parse_trait_item(&mut at_end) {
4987 Ok(item) => trait_items.push(item),
4991 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
4996 Ok((ident, ItemKind::Trait(unsafety, tps, bounds, trait_items), None))
4999 /// Parses items implementations variants
5000 /// impl<T> Foo { ... }
5001 /// impl<T> ToString for &'static T { ... }
5002 /// impl Send for .. {}
5003 fn parse_item_impl(&mut self,
5004 unsafety: ast::Unsafety,
5005 defaultness: Defaultness) -> PResult<'a, ItemInfo> {
5006 let impl_span = self.span;
5008 // First, parse type parameters if necessary.
5009 let mut generics = self.parse_generics()?;
5011 // Special case: if the next identifier that follows is '(', don't
5012 // allow this to be parsed as a trait.
5013 let could_be_trait = self.token != token::OpenDelim(token::Paren);
5015 let neg_span = self.span;
5016 let polarity = if self.eat(&token::Not) {
5017 ast::ImplPolarity::Negative
5019 ast::ImplPolarity::Positive
5023 let mut ty = self.parse_ty()?;
5025 // Parse traits, if necessary.
5026 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
5027 // New-style trait. Reinterpret the type as a trait.
5029 TyKind::Path(None, ref path) => {
5031 path: (*path).clone(),
5036 self.span_err(ty.span, "not a trait");
5041 if polarity == ast::ImplPolarity::Negative {
5042 // This is a negated type implementation
5043 // `impl !MyType {}`, which is not allowed.
5044 self.span_err(neg_span, "inherent implementation can't be negated");
5049 if opt_trait.is_some() && self.eat(&token::DotDot) {
5050 if generics.is_parameterized() {
5051 self.span_err(impl_span, "default trait implementations are not \
5052 allowed to have generics");
5055 if let ast::Defaultness::Default = defaultness {
5056 self.span_err(impl_span, "`default impl` is not allowed for \
5057 default trait implementations");
5060 self.expect(&token::OpenDelim(token::Brace))?;
5061 self.expect(&token::CloseDelim(token::Brace))?;
5062 Ok((keywords::Invalid.ident(),
5063 ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
5065 if opt_trait.is_some() {
5066 ty = self.parse_ty()?;
5068 generics.where_clause = self.parse_where_clause()?;
5070 self.expect(&token::OpenDelim(token::Brace))?;
5071 let attrs = self.parse_inner_attributes()?;
5073 let mut impl_items = vec![];
5074 while !self.eat(&token::CloseDelim(token::Brace)) {
5075 let mut at_end = false;
5076 match self.parse_impl_item(&mut at_end) {
5077 Ok(item) => impl_items.push(item),
5081 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5087 Ok((keywords::Invalid.ident(),
5088 ItemKind::Impl(unsafety, polarity, defaultness, generics, opt_trait, ty, impl_items),
5093 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<LifetimeDef>> {
5094 if self.eat_keyword(keywords::For) {
5096 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
5098 if !ty_params.is_empty() {
5099 self.span_err(ty_params[0].span,
5100 "only lifetime parameters can be used in this context");
5108 /// Parse struct Foo { ... }
5109 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5110 let class_name = self.parse_ident()?;
5112 let mut generics = self.parse_generics()?;
5114 // There is a special case worth noting here, as reported in issue #17904.
5115 // If we are parsing a tuple struct it is the case that the where clause
5116 // should follow the field list. Like so:
5118 // struct Foo<T>(T) where T: Copy;
5120 // If we are parsing a normal record-style struct it is the case
5121 // that the where clause comes before the body, and after the generics.
5122 // So if we look ahead and see a brace or a where-clause we begin
5123 // parsing a record style struct.
5125 // Otherwise if we look ahead and see a paren we parse a tuple-style
5128 let vdata = if self.token.is_keyword(keywords::Where) {
5129 generics.where_clause = self.parse_where_clause()?;
5130 if self.eat(&token::Semi) {
5131 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5132 VariantData::Unit(ast::DUMMY_NODE_ID)
5134 // If we see: `struct Foo<T> where T: Copy { ... }`
5135 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5137 // No `where` so: `struct Foo<T>;`
5138 } else if self.eat(&token::Semi) {
5139 VariantData::Unit(ast::DUMMY_NODE_ID)
5140 // Record-style struct definition
5141 } else if self.token == token::OpenDelim(token::Brace) {
5142 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5143 // Tuple-style struct definition with optional where-clause.
5144 } else if self.token == token::OpenDelim(token::Paren) {
5145 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5146 generics.where_clause = self.parse_where_clause()?;
5147 self.expect(&token::Semi)?;
5150 let token_str = self.this_token_to_string();
5151 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5152 name, found `{}`", token_str)))
5155 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5158 /// Parse union Foo { ... }
5159 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5160 let class_name = self.parse_ident()?;
5162 let mut generics = self.parse_generics()?;
5164 let vdata = if self.token.is_keyword(keywords::Where) {
5165 generics.where_clause = self.parse_where_clause()?;
5166 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5167 } else if self.token == token::OpenDelim(token::Brace) {
5168 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5170 let token_str = self.this_token_to_string();
5171 return Err(self.fatal(&format!("expected `where` or `{{` after union \
5172 name, found `{}`", token_str)))
5175 Ok((class_name, ItemKind::Union(vdata, generics), None))
5178 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5179 let mut fields = Vec::new();
5180 if self.eat(&token::OpenDelim(token::Brace)) {
5181 while self.token != token::CloseDelim(token::Brace) {
5182 fields.push(self.parse_struct_decl_field().map_err(|e| {
5183 self.recover_stmt();
5184 self.eat(&token::CloseDelim(token::Brace));
5191 let token_str = self.this_token_to_string();
5192 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5200 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5201 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5202 // Unit like structs are handled in parse_item_struct function
5203 let fields = self.parse_unspanned_seq(
5204 &token::OpenDelim(token::Paren),
5205 &token::CloseDelim(token::Paren),
5206 SeqSep::trailing_allowed(token::Comma),
5208 let attrs = p.parse_outer_attributes()?;
5210 let vis = p.parse_visibility(true)?;
5211 let ty = p.parse_ty()?;
5213 span: lo.to(p.span),
5216 id: ast::DUMMY_NODE_ID,
5225 /// Parse a structure field declaration
5226 pub fn parse_single_struct_field(&mut self,
5229 attrs: Vec<Attribute> )
5230 -> PResult<'a, StructField> {
5231 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5236 token::CloseDelim(token::Brace) => {}
5237 token::DocComment(_) => return Err(self.span_fatal_err(self.span,
5238 Error::UselessDocComment)),
5239 _ => return Err(self.span_fatal_help(self.span,
5240 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5241 "struct fields should be separated by commas")),
5246 /// Parse an element of a struct definition
5247 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5248 let attrs = self.parse_outer_attributes()?;
5250 let vis = self.parse_visibility(false)?;
5251 self.parse_single_struct_field(lo, vis, attrs)
5254 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5255 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5256 /// a function definition, it's not a tuple struct field) and the contents within the parens
5257 /// isn't valid, emit a proper diagnostic.
5258 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5259 maybe_whole!(self, NtVis, |x| x);
5261 if !self.eat_keyword(keywords::Pub) {
5262 return Ok(Visibility::Inherited)
5265 if self.check(&token::OpenDelim(token::Paren)) {
5266 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5267 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5268 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5269 // by the following tokens.
5270 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5273 self.bump(); // `crate`
5274 let vis = Visibility::Crate(self.prev_span);
5275 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5277 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5280 self.bump(); // `in`
5281 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5282 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5283 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5285 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5286 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5287 t.is_keyword(keywords::SelfValue)) {
5288 // `pub(self)` or `pub(super)`
5290 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5291 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5292 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5294 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5295 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5297 let msg = "incorrect visibility restriction";
5298 let suggestion = r##"some possible visibility restrictions are:
5299 `pub(crate)`: visible only on the current crate
5300 `pub(super)`: visible only in the current module's parent
5301 `pub(in path::to::module)`: visible only on the specified path"##;
5302 let path = self.parse_path(PathStyle::Mod)?;
5303 let path_span = self.prev_span;
5304 let help_msg = format!("make this visible only to module `{}` with `in`", path);
5305 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5306 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5307 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5308 err.emit(); // emit diagnostic, but continue with public visibility
5312 Ok(Visibility::Public)
5315 /// Parse defaultness: DEFAULT or nothing
5316 fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5317 if self.eat_defaultness() {
5318 Ok(Defaultness::Default)
5320 Ok(Defaultness::Final)
5324 /// Given a termination token, parse all of the items in a module
5325 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5326 let mut items = vec![];
5327 while let Some(item) = self.parse_item()? {
5331 if !self.eat(term) {
5332 let token_str = self.this_token_to_string();
5333 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5336 let hi = if self.span == syntax_pos::DUMMY_SP {
5343 inner: inner_lo.to(hi),
5348 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5349 let id = self.parse_ident()?;
5350 self.expect(&token::Colon)?;
5351 let ty = self.parse_ty()?;
5352 self.expect(&token::Eq)?;
5353 let e = self.parse_expr()?;
5354 self.expect(&token::Semi)?;
5355 let item = match m {
5356 Some(m) => ItemKind::Static(ty, m, e),
5357 None => ItemKind::Const(ty, e),
5359 Ok((id, item, None))
5362 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5363 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5364 let (in_cfg, outer_attrs) = {
5365 let mut strip_unconfigured = ::config::StripUnconfigured {
5367 should_test: false, // irrelevant
5368 features: None, // don't perform gated feature checking
5370 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5371 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5374 let id_span = self.span;
5375 let id = self.parse_ident()?;
5376 if self.check(&token::Semi) {
5378 if in_cfg && self.recurse_into_file_modules {
5379 // This mod is in an external file. Let's go get it!
5380 let ModulePathSuccess { path, directory_ownership, warn } =
5381 self.submod_path(id, &outer_attrs, id_span)?;
5382 let (module, mut attrs) =
5383 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5385 let attr = ast::Attribute {
5386 id: attr::mk_attr_id(),
5387 style: ast::AttrStyle::Outer,
5388 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5389 Ident::from_str("warn_directory_ownership")),
5390 tokens: TokenStream::empty(),
5391 is_sugared_doc: false,
5392 span: syntax_pos::DUMMY_SP,
5394 attr::mark_known(&attr);
5397 Ok((id, module, Some(attrs)))
5399 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5400 Ok((id, ItemKind::Mod(placeholder), None))
5403 let old_directory = self.directory.clone();
5404 self.push_directory(id, &outer_attrs);
5406 self.expect(&token::OpenDelim(token::Brace))?;
5407 let mod_inner_lo = self.span;
5408 let attrs = self.parse_inner_attributes()?;
5409 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5411 self.directory = old_directory;
5412 Ok((id, ItemKind::Mod(module), Some(attrs)))
5416 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5417 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5418 self.directory.path.push(&path.as_str());
5419 self.directory.ownership = DirectoryOwnership::Owned;
5421 self.directory.path.push(&id.name.as_str());
5425 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5426 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5429 /// Returns either a path to a module, or .
5430 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5431 let mod_name = id.to_string();
5432 let default_path_str = format!("{}.rs", mod_name);
5433 let secondary_path_str = format!("{}{}mod.rs", mod_name, path::MAIN_SEPARATOR);
5434 let default_path = dir_path.join(&default_path_str);
5435 let secondary_path = dir_path.join(&secondary_path_str);
5436 let default_exists = codemap.file_exists(&default_path);
5437 let secondary_exists = codemap.file_exists(&secondary_path);
5439 let result = match (default_exists, secondary_exists) {
5440 (true, false) => Ok(ModulePathSuccess {
5442 directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5445 (false, true) => Ok(ModulePathSuccess {
5446 path: secondary_path,
5447 directory_ownership: DirectoryOwnership::Owned,
5450 (false, false) => Err(Error::FileNotFoundForModule {
5451 mod_name: mod_name.clone(),
5452 default_path: default_path_str,
5453 secondary_path: secondary_path_str,
5454 dir_path: format!("{}", dir_path.display()),
5456 (true, true) => Err(Error::DuplicatePaths {
5457 mod_name: mod_name.clone(),
5458 default_path: default_path_str,
5459 secondary_path: secondary_path_str,
5465 path_exists: default_exists || secondary_exists,
5470 fn submod_path(&mut self,
5472 outer_attrs: &[ast::Attribute],
5474 -> PResult<'a, ModulePathSuccess> {
5475 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5476 return Ok(ModulePathSuccess {
5477 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5478 Some("mod.rs") => DirectoryOwnership::Owned,
5479 _ => DirectoryOwnership::UnownedViaMod(true),
5486 let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5488 if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5490 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5491 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5492 if paths.path_exists {
5493 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5495 err.span_note(id_sp, &msg);
5498 } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5500 if let Ok(result) = paths.result {
5501 return Ok(ModulePathSuccess { warn: true, ..result });
5504 let mut err = self.diagnostic().struct_span_err(id_sp,
5505 "cannot declare a new module at this location");
5506 if id_sp != syntax_pos::DUMMY_SP {
5507 let src_path = PathBuf::from(self.sess.codemap().span_to_filename(id_sp));
5508 if let Some(stem) = src_path.file_stem() {
5509 let mut dest_path = src_path.clone();
5510 dest_path.set_file_name(stem);
5511 dest_path.push("mod.rs");
5512 err.span_note(id_sp,
5513 &format!("maybe move this module `{}` to its own \
5514 directory via `{}`", src_path.to_string_lossy(),
5515 dest_path.to_string_lossy()));
5518 if paths.path_exists {
5519 err.span_note(id_sp,
5520 &format!("... or maybe `use` the module `{}` instead \
5521 of possibly redeclaring it",
5526 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5530 /// Read a module from a source file.
5531 fn eval_src_mod(&mut self,
5533 directory_ownership: DirectoryOwnership,
5536 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5537 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5538 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5539 let mut err = String::from("circular modules: ");
5540 let len = included_mod_stack.len();
5541 for p in &included_mod_stack[i.. len] {
5542 err.push_str(&p.to_string_lossy());
5543 err.push_str(" -> ");
5545 err.push_str(&path.to_string_lossy());
5546 return Err(self.span_fatal(id_sp, &err[..]));
5548 included_mod_stack.push(path.clone());
5549 drop(included_mod_stack);
5552 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5553 p0.cfg_mods = self.cfg_mods;
5554 let mod_inner_lo = p0.span;
5555 let mod_attrs = p0.parse_inner_attributes()?;
5556 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5557 self.sess.included_mod_stack.borrow_mut().pop();
5558 Ok((ast::ItemKind::Mod(m0), mod_attrs))
5561 /// Parse a function declaration from a foreign module
5562 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5563 -> PResult<'a, ForeignItem> {
5564 self.expect_keyword(keywords::Fn)?;
5566 let (ident, mut generics) = self.parse_fn_header()?;
5567 let decl = self.parse_fn_decl(true)?;
5568 generics.where_clause = self.parse_where_clause()?;
5570 self.expect(&token::Semi)?;
5571 Ok(ast::ForeignItem {
5574 node: ForeignItemKind::Fn(decl, generics),
5575 id: ast::DUMMY_NODE_ID,
5581 /// Parse a static item from a foreign module.
5582 /// Assumes that the `static` keyword is already parsed.
5583 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5584 -> PResult<'a, ForeignItem> {
5585 let mutbl = self.eat_keyword(keywords::Mut);
5586 let ident = self.parse_ident()?;
5587 self.expect(&token::Colon)?;
5588 let ty = self.parse_ty()?;
5590 self.expect(&token::Semi)?;
5594 node: ForeignItemKind::Static(ty, mutbl),
5595 id: ast::DUMMY_NODE_ID,
5601 /// Parse extern crate links
5605 /// extern crate foo;
5606 /// extern crate bar as foo;
5607 fn parse_item_extern_crate(&mut self,
5609 visibility: Visibility,
5610 attrs: Vec<Attribute>)
5611 -> PResult<'a, P<Item>> {
5613 let crate_name = self.parse_ident()?;
5614 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
5615 (Some(crate_name.name), ident)
5619 self.expect(&token::Semi)?;
5621 let prev_span = self.prev_span;
5622 Ok(self.mk_item(lo.to(prev_span),
5624 ItemKind::ExternCrate(maybe_path),
5629 /// Parse `extern` for foreign ABIs
5632 /// `extern` is expected to have been
5633 /// consumed before calling this method
5639 fn parse_item_foreign_mod(&mut self,
5641 opt_abi: Option<abi::Abi>,
5642 visibility: Visibility,
5643 mut attrs: Vec<Attribute>)
5644 -> PResult<'a, P<Item>> {
5645 self.expect(&token::OpenDelim(token::Brace))?;
5647 let abi = opt_abi.unwrap_or(Abi::C);
5649 attrs.extend(self.parse_inner_attributes()?);
5651 let mut foreign_items = vec![];
5652 while let Some(item) = self.parse_foreign_item()? {
5653 foreign_items.push(item);
5655 self.expect(&token::CloseDelim(token::Brace))?;
5657 let prev_span = self.prev_span;
5658 let m = ast::ForeignMod {
5660 items: foreign_items
5662 let invalid = keywords::Invalid.ident();
5663 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
5666 /// Parse type Foo = Bar;
5667 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5668 let ident = self.parse_ident()?;
5669 let mut tps = self.parse_generics()?;
5670 tps.where_clause = self.parse_where_clause()?;
5671 self.expect(&token::Eq)?;
5672 let ty = self.parse_ty()?;
5673 self.expect(&token::Semi)?;
5674 Ok((ident, ItemKind::Ty(ty, tps), None))
5677 /// Parse the part of an "enum" decl following the '{'
5678 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5679 let mut variants = Vec::new();
5680 let mut all_nullary = true;
5681 let mut any_disr = None;
5682 while self.token != token::CloseDelim(token::Brace) {
5683 let variant_attrs = self.parse_outer_attributes()?;
5684 let vlo = self.span;
5687 let mut disr_expr = None;
5688 let ident = self.parse_ident()?;
5689 if self.check(&token::OpenDelim(token::Brace)) {
5690 // Parse a struct variant.
5691 all_nullary = false;
5692 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
5693 ast::DUMMY_NODE_ID);
5694 } else if self.check(&token::OpenDelim(token::Paren)) {
5695 all_nullary = false;
5696 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
5697 ast::DUMMY_NODE_ID);
5698 } else if self.eat(&token::Eq) {
5699 disr_expr = Some(self.parse_expr()?);
5700 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5701 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5703 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5706 let vr = ast::Variant_ {
5708 attrs: variant_attrs,
5712 variants.push(respan(vlo.to(self.prev_span), vr));
5714 if !self.eat(&token::Comma) { break; }
5716 self.expect(&token::CloseDelim(token::Brace))?;
5718 Some(disr_span) if !all_nullary =>
5719 self.span_err(disr_span,
5720 "discriminator values can only be used with a c-like enum"),
5724 Ok(ast::EnumDef { variants: variants })
5727 /// Parse an "enum" declaration
5728 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5729 let id = self.parse_ident()?;
5730 let mut generics = self.parse_generics()?;
5731 generics.where_clause = self.parse_where_clause()?;
5732 self.expect(&token::OpenDelim(token::Brace))?;
5734 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
5735 self.recover_stmt();
5736 self.eat(&token::CloseDelim(token::Brace));
5739 Ok((id, ItemKind::Enum(enum_definition, generics), None))
5742 /// Parses a string as an ABI spec on an extern type or module. Consumes
5743 /// the `extern` keyword, if one is found.
5744 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5746 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5748 self.expect_no_suffix(sp, "ABI spec", suf);
5750 match abi::lookup(&s.as_str()) {
5751 Some(abi) => Ok(Some(abi)),
5753 let prev_span = self.prev_span;
5756 &format!("invalid ABI: expected one of [{}], \
5758 abi::all_names().join(", "),
5769 /// Parse one of the items allowed by the flags.
5770 /// NB: this function no longer parses the items inside an
5772 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5773 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5774 maybe_whole!(self, NtItem, |item| {
5775 let mut item = item.unwrap();
5776 let mut attrs = attrs;
5777 mem::swap(&mut item.attrs, &mut attrs);
5778 item.attrs.extend(attrs);
5784 let visibility = self.parse_visibility(false)?;
5786 if self.eat_keyword(keywords::Use) {
5788 let item_ = ItemKind::Use(self.parse_view_path()?);
5789 self.expect(&token::Semi)?;
5791 let prev_span = self.prev_span;
5792 let invalid = keywords::Invalid.ident();
5793 let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
5794 return Ok(Some(item));
5797 if self.eat_keyword(keywords::Extern) {
5798 if self.eat_keyword(keywords::Crate) {
5799 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
5802 let opt_abi = self.parse_opt_abi()?;
5804 if self.eat_keyword(keywords::Fn) {
5805 // EXTERN FUNCTION ITEM
5806 let fn_span = self.prev_span;
5807 let abi = opt_abi.unwrap_or(Abi::C);
5808 let (ident, item_, extra_attrs) =
5809 self.parse_item_fn(Unsafety::Normal,
5810 respan(fn_span, Constness::NotConst),
5812 let prev_span = self.prev_span;
5813 let item = self.mk_item(lo.to(prev_span),
5817 maybe_append(attrs, extra_attrs));
5818 return Ok(Some(item));
5819 } else if self.check(&token::OpenDelim(token::Brace)) {
5820 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
5826 if self.eat_keyword(keywords::Static) {
5828 let m = if self.eat_keyword(keywords::Mut) {
5831 Mutability::Immutable
5833 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
5834 let prev_span = self.prev_span;
5835 let item = self.mk_item(lo.to(prev_span),
5839 maybe_append(attrs, extra_attrs));
5840 return Ok(Some(item));
5842 if self.eat_keyword(keywords::Const) {
5843 let const_span = self.prev_span;
5844 if self.check_keyword(keywords::Fn)
5845 || (self.check_keyword(keywords::Unsafe)
5846 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5847 // CONST FUNCTION ITEM
5848 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5854 let (ident, item_, extra_attrs) =
5855 self.parse_item_fn(unsafety,
5856 respan(const_span, Constness::Const),
5858 let prev_span = self.prev_span;
5859 let item = self.mk_item(lo.to(prev_span),
5863 maybe_append(attrs, extra_attrs));
5864 return Ok(Some(item));
5868 if self.eat_keyword(keywords::Mut) {
5869 let prev_span = self.prev_span;
5870 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
5871 .help("did you mean to declare a static?")
5874 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
5875 let prev_span = self.prev_span;
5876 let item = self.mk_item(lo.to(prev_span),
5880 maybe_append(attrs, extra_attrs));
5881 return Ok(Some(item));
5883 if self.check_keyword(keywords::Unsafe) &&
5884 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5886 // UNSAFE TRAIT ITEM
5887 self.expect_keyword(keywords::Unsafe)?;
5888 self.expect_keyword(keywords::Trait)?;
5889 let (ident, item_, extra_attrs) =
5890 self.parse_item_trait(ast::Unsafety::Unsafe)?;
5891 let prev_span = self.prev_span;
5892 let item = self.mk_item(lo.to(prev_span),
5896 maybe_append(attrs, extra_attrs));
5897 return Ok(Some(item));
5899 if (self.check_keyword(keywords::Unsafe) &&
5900 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))) ||
5901 (self.check_keyword(keywords::Default) &&
5902 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) &&
5903 self.look_ahead(2, |t| t.is_keyword(keywords::Impl)))
5906 let defaultness = self.parse_defaultness()?;
5907 self.expect_keyword(keywords::Unsafe)?;
5908 self.expect_keyword(keywords::Impl)?;
5911 extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe, defaultness)?;
5912 let prev_span = self.prev_span;
5913 let item = self.mk_item(lo.to(prev_span),
5917 maybe_append(attrs, extra_attrs));
5918 return Ok(Some(item));
5920 if self.check_keyword(keywords::Fn) {
5923 let fn_span = self.prev_span;
5924 let (ident, item_, extra_attrs) =
5925 self.parse_item_fn(Unsafety::Normal,
5926 respan(fn_span, Constness::NotConst),
5928 let prev_span = self.prev_span;
5929 let item = self.mk_item(lo.to(prev_span),
5933 maybe_append(attrs, extra_attrs));
5934 return Ok(Some(item));
5936 if self.check_keyword(keywords::Unsafe)
5937 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5938 // UNSAFE FUNCTION ITEM
5940 let abi = if self.eat_keyword(keywords::Extern) {
5941 self.parse_opt_abi()?.unwrap_or(Abi::C)
5945 self.expect_keyword(keywords::Fn)?;
5946 let fn_span = self.prev_span;
5947 let (ident, item_, extra_attrs) =
5948 self.parse_item_fn(Unsafety::Unsafe,
5949 respan(fn_span, Constness::NotConst),
5951 let prev_span = self.prev_span;
5952 let item = self.mk_item(lo.to(prev_span),
5956 maybe_append(attrs, extra_attrs));
5957 return Ok(Some(item));
5959 if self.eat_keyword(keywords::Mod) {
5961 let (ident, item_, extra_attrs) =
5962 self.parse_item_mod(&attrs[..])?;
5963 let prev_span = self.prev_span;
5964 let item = self.mk_item(lo.to(prev_span),
5968 maybe_append(attrs, extra_attrs));
5969 return Ok(Some(item));
5971 if self.eat_keyword(keywords::Type) {
5973 let (ident, item_, extra_attrs) = self.parse_item_type()?;
5974 let prev_span = self.prev_span;
5975 let item = self.mk_item(lo.to(prev_span),
5979 maybe_append(attrs, extra_attrs));
5980 return Ok(Some(item));
5982 if self.eat_keyword(keywords::Enum) {
5984 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
5985 let prev_span = self.prev_span;
5986 let item = self.mk_item(lo.to(prev_span),
5990 maybe_append(attrs, extra_attrs));
5991 return Ok(Some(item));
5993 if self.eat_keyword(keywords::Trait) {
5995 let (ident, item_, extra_attrs) =
5996 self.parse_item_trait(ast::Unsafety::Normal)?;
5997 let prev_span = self.prev_span;
5998 let item = self.mk_item(lo.to(prev_span),
6002 maybe_append(attrs, extra_attrs));
6003 return Ok(Some(item));
6005 if (self.check_keyword(keywords::Impl)) ||
6006 (self.check_keyword(keywords::Default) &&
6007 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)))
6010 let defaultness = self.parse_defaultness()?;
6011 self.expect_keyword(keywords::Impl)?;
6014 extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal, defaultness)?;
6015 let prev_span = self.prev_span;
6016 let item = self.mk_item(lo.to(prev_span),
6020 maybe_append(attrs, extra_attrs));
6021 return Ok(Some(item));
6023 if self.eat_keyword(keywords::Struct) {
6025 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6026 let prev_span = self.prev_span;
6027 let item = self.mk_item(lo.to(prev_span),
6031 maybe_append(attrs, extra_attrs));
6032 return Ok(Some(item));
6034 if self.is_union_item() {
6037 let (ident, item_, extra_attrs) = self.parse_item_union()?;
6038 let prev_span = self.prev_span;
6039 let item = self.mk_item(lo.to(prev_span),
6043 maybe_append(attrs, extra_attrs));
6044 return Ok(Some(item));
6046 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
6047 return Ok(Some(macro_def));
6050 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
6053 /// Parse a foreign item.
6054 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
6055 let attrs = self.parse_outer_attributes()?;
6057 let visibility = self.parse_visibility(false)?;
6059 // FOREIGN STATIC ITEM
6060 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
6061 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
6062 if self.token.is_keyword(keywords::Const) {
6064 .struct_span_err(self.span, "extern items cannot be `const`")
6065 .span_suggestion(self.span, "instead try using", "static".to_owned())
6068 self.bump(); // `static` or `const`
6069 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6071 // FOREIGN FUNCTION ITEM
6072 if self.check_keyword(keywords::Fn) {
6073 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6076 // FIXME #5668: this will occur for a macro invocation:
6077 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
6079 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
6085 /// This is the fall-through for parsing items.
6086 fn parse_macro_use_or_failure(
6088 attrs: Vec<Attribute> ,
6089 macros_allowed: bool,
6090 attributes_allowed: bool,
6092 visibility: Visibility
6093 ) -> PResult<'a, Option<P<Item>>> {
6094 if macros_allowed && self.token.is_path_start() {
6095 // MACRO INVOCATION ITEM
6097 let prev_span = self.prev_span;
6098 self.complain_if_pub_macro(&visibility, prev_span);
6100 let mac_lo = self.span;
6103 let pth = self.parse_path(PathStyle::Mod)?;
6104 self.expect(&token::Not)?;
6106 // a 'special' identifier (like what `macro_rules!` uses)
6107 // is optional. We should eventually unify invoc syntax
6109 let id = if self.token.is_ident() {
6112 keywords::Invalid.ident() // no special identifier
6114 // eat a matched-delimiter token tree:
6115 let (delim, tts) = self.expect_delimited_token_tree()?;
6116 if delim != token::Brace {
6117 if !self.eat(&token::Semi) {
6118 self.span_err(self.prev_span,
6119 "macros that expand to items must either \
6120 be surrounded with braces or followed by \
6125 let hi = self.prev_span;
6126 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6127 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6128 return Ok(Some(item));
6131 // FAILURE TO PARSE ITEM
6133 Visibility::Inherited => {}
6135 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
6139 if !attributes_allowed && !attrs.is_empty() {
6140 self.expected_item_err(&attrs);
6145 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
6146 where F: FnOnce(&mut Self) -> PResult<'a, R>
6148 // Record all tokens we parse when parsing this item.
6149 let mut tokens = Vec::new();
6150 match self.token_cursor.frame.last_token {
6151 LastToken::Collecting(_) => {
6152 panic!("cannot collect tokens recursively yet")
6154 LastToken::Was(ref mut last) => tokens.extend(last.take()),
6156 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
6157 let prev = self.token_cursor.stack.len();
6159 let last_token = if self.token_cursor.stack.len() == prev {
6160 &mut self.token_cursor.frame.last_token
6162 &mut self.token_cursor.stack[prev].last_token
6164 let mut tokens = match *last_token {
6165 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
6166 LastToken::Was(_) => panic!("our vector went away?"),
6169 // If we're not at EOF our current token wasn't actually consumed by
6170 // `f`, but it'll still be in our list that we pulled out. In that case
6172 if self.token == token::Eof {
6173 *last_token = LastToken::Was(None);
6175 *last_token = LastToken::Was(tokens.pop());
6178 Ok((ret?, tokens.into_iter().collect()))
6181 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6182 let attrs = self.parse_outer_attributes()?;
6184 let (ret, tokens) = self.collect_tokens(|this| {
6185 this.parse_item_(attrs, true, false)
6188 // Once we've parsed an item and recorded the tokens we got while
6189 // parsing we may want to store `tokens` into the item we're about to
6190 // return. Note, though, that we specifically didn't capture tokens
6191 // related to outer attributes. The `tokens` field here may later be
6192 // used with procedural macros to convert this item back into a token
6193 // stream, but during expansion we may be removing attributes as we go
6196 // If we've got inner attributes then the `tokens` we've got above holds
6197 // these inner attributes. If an inner attribute is expanded we won't
6198 // actually remove it from the token stream, so we'll just keep yielding
6199 // it (bad!). To work around this case for now we just avoid recording
6200 // `tokens` if we detect any inner attributes. This should help keep
6201 // expansion correct, but we should fix this bug one day!
6204 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6205 i.tokens = Some(tokens);
6212 fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> {
6213 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
6214 &token::CloseDelim(token::Brace),
6215 SeqSep::trailing_allowed(token::Comma), |this| {
6217 let ident = if this.eat_keyword(keywords::SelfValue) {
6218 keywords::SelfValue.ident()
6222 let rename = this.parse_rename()?;
6223 let node = ast::PathListItem_ {
6226 id: ast::DUMMY_NODE_ID
6228 Ok(respan(lo.to(this.prev_span), node))
6233 fn is_import_coupler(&mut self) -> bool {
6234 self.check(&token::ModSep) &&
6235 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6236 *t == token::BinOp(token::Star))
6239 /// Matches ViewPath:
6240 /// MOD_SEP? non_global_path
6241 /// MOD_SEP? non_global_path as IDENT
6242 /// MOD_SEP? non_global_path MOD_SEP STAR
6243 /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE
6244 /// MOD_SEP? LBRACE item_seq RBRACE
6245 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
6247 if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) ||
6248 self.is_import_coupler() {
6249 // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`.
6250 self.eat(&token::ModSep);
6251 let prefix = ast::Path {
6252 segments: vec![PathSegment::crate_root(lo)],
6253 span: lo.to(self.span),
6255 let view_path_kind = if self.eat(&token::BinOp(token::Star)) {
6256 ViewPathGlob(prefix)
6258 ViewPathList(prefix, self.parse_path_list_items()?)
6260 Ok(P(respan(lo.to(self.span), view_path_kind)))
6262 let prefix = self.parse_path(PathStyle::Mod)?.default_to_global();
6263 if self.is_import_coupler() {
6264 // `foo::bar::{a, b}` or `foo::bar::*`
6266 if self.check(&token::BinOp(token::Star)) {
6268 Ok(P(respan(lo.to(self.span), ViewPathGlob(prefix))))
6270 let items = self.parse_path_list_items()?;
6271 Ok(P(respan(lo.to(self.span), ViewPathList(prefix, items))))
6274 // `foo::bar` or `foo::bar as baz`
6275 let rename = self.parse_rename()?.
6276 unwrap_or(prefix.segments.last().unwrap().identifier);
6277 Ok(P(respan(lo.to(self.prev_span), ViewPathSimple(rename, prefix))))
6282 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6283 if self.eat_keyword(keywords::As) {
6284 self.parse_ident().map(Some)
6290 /// Parses a source module as a crate. This is the main
6291 /// entry point for the parser.
6292 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6295 attrs: self.parse_inner_attributes()?,
6296 module: self.parse_mod_items(&token::Eof, lo)?,
6297 span: lo.to(self.span),
6301 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6302 let ret = match self.token {
6303 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6304 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6311 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6312 match self.parse_optional_str() {
6313 Some((s, style, suf)) => {
6314 let sp = self.prev_span;
6315 self.expect_no_suffix(sp, "string literal", suf);
6318 _ => Err(self.fatal("expected string literal"))