1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use ast::{AngleBracketedParameterData, ParenthesizedParameterData, AttrStyle, BareFnTy};
13 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
15 use ast::{Mod, Arg, Arm, Attribute, BindingMode, TraitItemKind};
17 use ast::{BlockCheckMode, CaptureBy};
18 use ast::{Constness, Crate};
21 use ast::{Expr, ExprKind, RangeLimits};
22 use ast::{Field, FnDecl};
23 use ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
24 use ast::{Ident, ImplItem, Item, ItemKind};
25 use ast::{Lifetime, LifetimeDef, Lit, LitKind, UintTy};
27 use ast::MacStmtStyle;
29 use ast::{MutTy, Mutability};
30 use ast::{Pat, PatKind, PathSegment};
31 use ast::{PolyTraitRef, QSelf};
32 use ast::{Stmt, StmtKind};
33 use ast::{VariantData, StructField};
36 use ast::{TraitItem, TraitRef};
37 use ast::{Ty, TyKind, TypeBinding, TyParam, TyParamBounds};
38 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
39 use ast::{Visibility, WhereClause};
40 use ast::{BinOpKind, UnOp};
43 use codemap::{self, CodeMap, Spanned, respan};
44 use syntax_pos::{self, Span, BytePos};
45 use errors::{self, DiagnosticBuilder};
46 use parse::{self, classify, token};
47 use parse::common::SeqSep;
48 use parse::lexer::TokenAndSpan;
49 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
50 use parse::obsolete::ObsoleteSyntax;
51 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
52 use util::parser::{AssocOp, Fixity};
56 use tokenstream::{self, Delimited, ThinTokenStream, TokenTree, TokenStream};
57 use symbol::{Symbol, keywords};
61 use std::collections::HashSet;
63 use std::path::{self, Path, PathBuf};
67 pub flags Restrictions: u8 {
68 const RESTRICTION_STMT_EXPR = 1 << 0,
69 const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1,
73 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute> >);
75 /// How to parse a path.
76 #[derive(Copy, Clone, PartialEq)]
78 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
79 /// with something else. For example, in expressions `segment < ....` can be interpreted
80 /// as a comparison and `segment ( ....` can be interpreted as a function call.
81 /// In all such contexts the non-path interpretation is preferred by default for practical
82 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
83 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
85 /// In other contexts, notably in types, no ambiguity exists and paths can be written
86 /// without the disambiguator, e.g. `x<y>` - unambiguously a path.
87 /// Paths with disambiguators are rejected for now, but may be allowed in the future.
89 /// A path with generic arguments disallowed, e.g. `foo::bar::Baz`, used in imports,
90 /// visibilities or attributes.
91 /// Technically, this variant is unnecessary and e.g. `Expr` can be used instead
92 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
93 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
94 /// tokens when something goes wrong.
98 #[derive(Clone, Copy, Debug, PartialEq)]
99 pub enum SemiColonMode {
104 #[derive(Clone, Copy, Debug, PartialEq)]
110 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
111 /// dropped into the token stream, which happens while parsing the result of
112 /// macro expansion). Placement of these is not as complex as I feared it would
113 /// be. The important thing is to make sure that lookahead doesn't balk at
114 /// `token::Interpolated` tokens.
115 macro_rules! maybe_whole_expr {
117 if let token::Interpolated(nt) = $p.token.clone() {
119 token::NtExpr(ref e) => {
121 return Ok((*e).clone());
123 token::NtPath(ref path) => {
126 let kind = ExprKind::Path(None, (*path).clone());
127 return Ok($p.mk_expr(span, kind, ThinVec::new()));
129 token::NtBlock(ref block) => {
132 let kind = ExprKind::Block((*block).clone());
133 return Ok($p.mk_expr(span, kind, ThinVec::new()));
141 /// As maybe_whole_expr, but for things other than expressions
142 macro_rules! maybe_whole {
143 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
144 if let token::Interpolated(nt) = $p.token.clone() {
145 if let token::$constructor($x) = nt.0.clone() {
153 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
155 if let Some(ref attrs) = rhs {
156 lhs.extend(attrs.iter().cloned())
161 #[derive(Debug, Clone, Copy, PartialEq)]
172 /* ident is handled by common.rs */
175 pub struct Parser<'a> {
176 pub sess: &'a ParseSess,
177 /// the current token:
178 pub token: token::Token,
179 /// the span of the current token:
181 /// the span of the previous token:
182 pub meta_var_span: Option<Span>,
184 /// the previous token kind
185 prev_token_kind: PrevTokenKind,
186 pub restrictions: Restrictions,
187 /// The set of seen errors about obsolete syntax. Used to suppress
188 /// extra detail when the same error is seen twice
189 pub obsolete_set: HashSet<ObsoleteSyntax>,
190 /// Used to determine the path to externally loaded source files
191 pub directory: Directory,
192 /// Whether to parse sub-modules in other files.
193 pub recurse_into_file_modules: bool,
194 /// Name of the root module this parser originated from. If `None`, then the
195 /// name is not known. This does not change while the parser is descending
196 /// into modules, and sub-parsers have new values for this name.
197 pub root_module_name: Option<String>,
198 pub expected_tokens: Vec<TokenType>,
199 token_cursor: TokenCursor,
200 pub desugar_doc_comments: bool,
201 /// Whether we should configure out of line modules as we parse.
208 frame: TokenCursorFrame,
209 stack: Vec<TokenCursorFrame>,
213 struct TokenCursorFrame {
214 delim: token::DelimToken,
217 tree_cursor: tokenstream::Cursor,
219 last_token: LastToken,
222 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
223 /// by the parser, and then that's transitively used to record the tokens that
224 /// each parse AST item is created with.
226 /// Right now this has two states, either collecting tokens or not collecting
227 /// tokens. If we're collecting tokens we just save everything off into a local
228 /// `Vec`. This should eventually though likely save tokens from the original
229 /// token stream and just use slicing of token streams to avoid creation of a
230 /// whole new vector.
232 /// The second state is where we're passively not recording tokens, but the last
233 /// token is still tracked for when we want to start recording tokens. This
234 /// "last token" means that when we start recording tokens we'll want to ensure
235 /// that this, the first token, is included in the output.
237 /// You can find some more example usage of this in the `collect_tokens` method
241 Collecting(Vec<TokenTree>),
242 Was(Option<TokenTree>),
245 impl TokenCursorFrame {
246 fn new(sp: Span, delimited: &Delimited) -> Self {
248 delim: delimited.delim,
250 open_delim: delimited.delim == token::NoDelim,
251 tree_cursor: delimited.stream().into_trees(),
252 close_delim: delimited.delim == token::NoDelim,
253 last_token: LastToken::Was(None),
259 fn next(&mut self) -> TokenAndSpan {
261 let tree = if !self.frame.open_delim {
262 self.frame.open_delim = true;
263 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
264 .open_tt(self.frame.span)
265 } else if let Some(tree) = self.frame.tree_cursor.next() {
267 } else if !self.frame.close_delim {
268 self.frame.close_delim = true;
269 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
270 .close_tt(self.frame.span)
271 } else if let Some(frame) = self.stack.pop() {
275 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
278 match self.frame.last_token {
279 LastToken::Collecting(ref mut v) => v.push(tree.clone()),
280 LastToken::Was(ref mut t) => *t = Some(tree.clone()),
284 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
285 TokenTree::Delimited(sp, ref delimited) => {
286 let frame = TokenCursorFrame::new(sp, delimited);
287 self.stack.push(mem::replace(&mut self.frame, frame));
293 fn next_desugared(&mut self) -> TokenAndSpan {
294 let (sp, name) = match self.next() {
295 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
299 let stripped = strip_doc_comment_decoration(&name.as_str());
301 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
302 // required to wrap the text.
303 let mut num_of_hashes = 0;
305 for ch in stripped.chars() {
308 '#' if count > 0 => count + 1,
311 num_of_hashes = cmp::max(num_of_hashes, count);
314 let body = TokenTree::Delimited(sp, Delimited {
315 delim: token::Bracket,
316 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"))),
317 TokenTree::Token(sp, token::Eq),
318 TokenTree::Token(sp, token::Literal(
319 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
320 .iter().cloned().collect::<TokenStream>().into(),
323 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
324 delim: token::NoDelim,
325 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
326 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
327 .iter().cloned().collect::<TokenStream>().into()
329 [TokenTree::Token(sp, token::Pound), body]
330 .iter().cloned().collect::<TokenStream>().into()
338 #[derive(PartialEq, Eq, Clone)]
341 Keyword(keywords::Keyword),
350 fn to_string(&self) -> String {
352 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
353 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
354 TokenType::Operator => "an operator".to_string(),
355 TokenType::Lifetime => "lifetime".to_string(),
356 TokenType::Ident => "identifier".to_string(),
357 TokenType::Path => "path".to_string(),
358 TokenType::Type => "type".to_string(),
363 fn is_ident_or_underscore(t: &token::Token) -> bool {
364 t.is_ident() || *t == token::Underscore
367 /// Information about the path to a module.
368 pub struct ModulePath {
370 pub path_exists: bool,
371 pub result: Result<ModulePathSuccess, Error>,
374 pub struct ModulePathSuccess {
376 pub directory_ownership: DirectoryOwnership,
380 pub struct ModulePathError {
382 pub help_msg: String,
386 FileNotFoundForModule {
388 default_path: String,
389 secondary_path: String,
394 default_path: String,
395 secondary_path: String,
398 InclusiveRangeWithNoEnd,
402 pub fn span_err(self, sp: Span, handler: &errors::Handler) -> DiagnosticBuilder {
404 Error::FileNotFoundForModule { ref mod_name,
408 let mut err = struct_span_err!(handler, sp, E0583,
409 "file not found for module `{}`", mod_name);
410 err.help(&format!("name the file either {} or {} inside the directory {:?}",
416 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
417 let mut err = struct_span_err!(handler, sp, E0584,
418 "file for module `{}` found at both {} and {}",
422 err.help("delete or rename one of them to remove the ambiguity");
425 Error::UselessDocComment => {
426 let mut err = struct_span_err!(handler, sp, E0585,
427 "found a documentation comment that doesn't document anything");
428 err.help("doc comments must come before what they document, maybe a comment was \
429 intended with `//`?");
432 Error::InclusiveRangeWithNoEnd => {
433 let mut err = struct_span_err!(handler, sp, E0586,
434 "inclusive range with no end");
435 err.help("inclusive ranges must be bounded at the end (`...b` or `a...b`)");
445 AttributesParsed(ThinVec<Attribute>),
446 AlreadyParsed(P<Expr>),
449 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
450 fn from(o: Option<ThinVec<Attribute>>) -> Self {
451 if let Some(attrs) = o {
452 LhsExpr::AttributesParsed(attrs)
454 LhsExpr::NotYetParsed
459 impl From<P<Expr>> for LhsExpr {
460 fn from(expr: P<Expr>) -> Self {
461 LhsExpr::AlreadyParsed(expr)
465 /// Create a placeholder argument.
466 fn dummy_arg(span: Span) -> Arg {
467 let spanned = Spanned {
469 node: keywords::Invalid.ident()
472 id: ast::DUMMY_NODE_ID,
473 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), spanned, None),
479 id: ast::DUMMY_NODE_ID
481 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
484 impl<'a> Parser<'a> {
485 pub fn new(sess: &'a ParseSess,
487 directory: Option<Directory>,
488 recurse_into_file_modules: bool,
489 desugar_doc_comments: bool)
491 let mut parser = Parser {
493 token: token::Underscore,
494 span: syntax_pos::DUMMY_SP,
495 prev_span: syntax_pos::DUMMY_SP,
497 prev_token_kind: PrevTokenKind::Other,
498 restrictions: Restrictions::empty(),
499 obsolete_set: HashSet::new(),
500 recurse_into_file_modules: recurse_into_file_modules,
501 directory: Directory { path: PathBuf::new(), ownership: DirectoryOwnership::Owned },
502 root_module_name: None,
503 expected_tokens: Vec::new(),
504 token_cursor: TokenCursor {
505 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
506 delim: token::NoDelim,
511 desugar_doc_comments: desugar_doc_comments,
515 let tok = parser.next_tok();
516 parser.token = tok.tok;
517 parser.span = tok.sp;
519 if let Some(directory) = directory {
520 parser.directory = directory;
521 } else if parser.span != syntax_pos::DUMMY_SP {
522 parser.directory.path = PathBuf::from(sess.codemap().span_to_filename(parser.span));
523 parser.directory.path.pop();
526 parser.process_potential_macro_variable();
530 fn next_tok(&mut self) -> TokenAndSpan {
531 let mut next = if self.desugar_doc_comments {
532 self.token_cursor.next_desugared()
534 self.token_cursor.next()
536 if next.sp == syntax_pos::DUMMY_SP {
537 next.sp = self.prev_span;
542 /// Convert a token to a string using self's reader
543 pub fn token_to_string(token: &token::Token) -> String {
544 pprust::token_to_string(token)
547 /// Convert the current token to a string using self's reader
548 pub fn this_token_to_string(&self) -> String {
549 Parser::token_to_string(&self.token)
552 pub fn this_token_descr(&self) -> String {
553 let prefix = match &self.token {
554 t if t.is_special_ident() => "reserved identifier ",
555 t if t.is_used_keyword() => "keyword ",
556 t if t.is_unused_keyword() => "reserved keyword ",
559 format!("{}`{}`", prefix, self.this_token_to_string())
562 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
563 let token_str = Parser::token_to_string(t);
564 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
567 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
568 match self.expect_one_of(&[], &[]) {
570 Ok(_) => unreachable!(),
574 /// Expect and consume the token t. Signal an error if
575 /// the next token is not t.
576 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
577 if self.expected_tokens.is_empty() {
578 if self.token == *t {
582 let token_str = Parser::token_to_string(t);
583 let this_token_str = self.this_token_to_string();
584 Err(self.fatal(&format!("expected `{}`, found `{}`",
589 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
593 /// Expect next token to be edible or inedible token. If edible,
594 /// then consume it; if inedible, then return without consuming
595 /// anything. Signal a fatal error if next token is unexpected.
596 pub fn expect_one_of(&mut self,
597 edible: &[token::Token],
598 inedible: &[token::Token]) -> PResult<'a, ()>{
599 fn tokens_to_string(tokens: &[TokenType]) -> String {
600 let mut i = tokens.iter();
601 // This might be a sign we need a connect method on Iterator.
603 .map_or("".to_string(), |t| t.to_string());
604 i.enumerate().fold(b, |mut b, (i, a)| {
605 if tokens.len() > 2 && i == tokens.len() - 2 {
607 } else if tokens.len() == 2 && i == tokens.len() - 2 {
612 b.push_str(&a.to_string());
616 if edible.contains(&self.token) {
619 } else if inedible.contains(&self.token) {
620 // leave it in the input
623 let mut expected = edible.iter()
624 .map(|x| TokenType::Token(x.clone()))
625 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
626 .chain(self.expected_tokens.iter().cloned())
627 .collect::<Vec<_>>();
628 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
630 let expect = tokens_to_string(&expected[..]);
631 let actual = self.this_token_to_string();
632 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
633 let short_expect = if expected.len() > 6 {
634 format!("{} possible tokens", expected.len())
638 (format!("expected one of {}, found `{}`", expect, actual),
639 (self.prev_span.next_point(), format!("expected one of {} here", short_expect)))
640 } else if expected.is_empty() {
641 (format!("unexpected token: `{}`", actual),
642 (self.prev_span, "unexpected token after this".to_string()))
644 (format!("expected {}, found `{}`", expect, actual),
645 (self.prev_span.next_point(), format!("expected {} here", expect)))
647 let mut err = self.fatal(&msg_exp);
648 let sp = if self.token == token::Token::Eof {
649 // This is EOF, don't want to point at the following char, but rather the last token
654 if self.span.contains(sp) {
655 err.span_label(self.span, label_exp);
657 err.span_label(sp, label_exp);
658 err.span_label(self.span, "unexpected token");
664 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
665 fn interpolated_or_expr_span(&self,
666 expr: PResult<'a, P<Expr>>)
667 -> PResult<'a, (Span, P<Expr>)> {
669 if self.prev_token_kind == PrevTokenKind::Interpolated {
677 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
680 if self.token.is_reserved_ident() {
681 self.span_err(self.span, &format!("expected identifier, found {}",
682 self.this_token_descr()));
688 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
689 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
691 let mut err = self.fatal(&format!("expected identifier, found `{}`",
692 self.this_token_to_string()));
693 if self.token == token::Underscore {
694 err.note("`_` is a wildcard pattern, not an identifier");
702 /// Check if the next token is `tok`, and return `true` if so.
704 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
706 pub fn check(&mut self, tok: &token::Token) -> bool {
707 let is_present = self.token == *tok;
708 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
712 /// Consume token 'tok' if it exists. Returns true if the given
713 /// token was present, false otherwise.
714 pub fn eat(&mut self, tok: &token::Token) -> bool {
715 let is_present = self.check(tok);
716 if is_present { self.bump() }
720 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
721 self.expected_tokens.push(TokenType::Keyword(kw));
722 self.token.is_keyword(kw)
725 /// If the next token is the given keyword, eat it and return
726 /// true. Otherwise, return false.
727 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
728 if self.check_keyword(kw) {
736 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
737 if self.token.is_keyword(kw) {
745 /// If the given word is not a keyword, signal an error.
746 /// If the next token is not the given word, signal an error.
747 /// Otherwise, eat it.
748 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
749 if !self.eat_keyword(kw) {
756 fn check_ident(&mut self) -> bool {
757 if self.token.is_ident() {
760 self.expected_tokens.push(TokenType::Ident);
765 fn check_path(&mut self) -> bool {
766 if self.token.is_path_start() {
769 self.expected_tokens.push(TokenType::Path);
774 fn check_type(&mut self) -> bool {
775 if self.token.can_begin_type() {
778 self.expected_tokens.push(TokenType::Type);
783 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
784 /// `&` and continue. If an `&` is not seen, signal an error.
785 fn expect_and(&mut self) -> PResult<'a, ()> {
786 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
788 token::BinOp(token::And) => {
793 let span = self.span;
794 let lo = span.lo + BytePos(1);
795 Ok(self.bump_with(token::BinOp(token::And), Span { lo: lo, ..span }))
797 _ => self.unexpected()
801 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
803 None => {/* everything ok */}
805 let text = suf.as_str();
807 self.span_bug(sp, "found empty literal suffix in Some")
809 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
814 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
815 /// `<` and continue. If a `<` is not seen, return false.
817 /// This is meant to be used when parsing generics on a path to get the
819 fn eat_lt(&mut self) -> bool {
820 self.expected_tokens.push(TokenType::Token(token::Lt));
826 token::BinOp(token::Shl) => {
827 let span = self.span;
828 let lo = span.lo + BytePos(1);
829 self.bump_with(token::Lt, Span { lo: lo, ..span });
836 fn expect_lt(&mut self) -> PResult<'a, ()> {
844 /// Expect and consume a GT. if a >> is seen, replace it
845 /// with a single > and continue. If a GT is not seen,
847 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
848 self.expected_tokens.push(TokenType::Token(token::Gt));
854 token::BinOp(token::Shr) => {
855 let span = self.span;
856 let lo = span.lo + BytePos(1);
857 Ok(self.bump_with(token::Gt, Span { lo: lo, ..span }))
859 token::BinOpEq(token::Shr) => {
860 let span = self.span;
861 let lo = span.lo + BytePos(1);
862 Ok(self.bump_with(token::Ge, Span { lo: lo, ..span }))
865 let span = self.span;
866 let lo = span.lo + BytePos(1);
867 Ok(self.bump_with(token::Eq, Span { lo: lo, ..span }))
869 _ => self.unexpected()
873 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
874 sep: Option<token::Token>,
876 -> PResult<'a, (Vec<T>, bool)>
877 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
879 let mut v = Vec::new();
880 // This loop works by alternating back and forth between parsing types
881 // and commas. For example, given a string `A, B,>`, the parser would
882 // first parse `A`, then a comma, then `B`, then a comma. After that it
883 // would encounter a `>` and stop. This lets the parser handle trailing
884 // commas in generic parameters, because it can stop either after
885 // parsing a type or after parsing a comma.
887 if self.check(&token::Gt)
888 || self.token == token::BinOp(token::Shr)
889 || self.token == token::Ge
890 || self.token == token::BinOpEq(token::Shr) {
896 Some(result) => v.push(result),
897 None => return Ok((v, true))
900 if let Some(t) = sep.as_ref() {
906 return Ok((v, false));
909 /// Parse a sequence bracketed by '<' and '>', stopping
911 pub fn parse_seq_to_before_gt<T, F>(&mut self,
912 sep: Option<token::Token>,
914 -> PResult<'a, Vec<T>> where
915 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
917 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
918 |p| Ok(Some(f(p)?)))?;
923 pub fn parse_seq_to_gt<T, F>(&mut self,
924 sep: Option<token::Token>,
926 -> PResult<'a, Vec<T>> where
927 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
929 let v = self.parse_seq_to_before_gt(sep, f)?;
934 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
935 sep: Option<token::Token>,
937 -> PResult<'a, (Vec<T>, bool)> where
938 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
940 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
944 return Ok((v, returned));
947 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
948 /// passes through any errors encountered. Used for error recovery.
949 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
950 let handler = self.diagnostic();
952 self.parse_seq_to_before_tokens(kets,
954 |p| Ok(p.parse_token_tree()),
955 |mut e| handler.cancel(&mut e));
958 /// Parse a sequence, including the closing delimiter. The function
959 /// f must consume tokens until reaching the next separator or
961 pub fn parse_seq_to_end<T, F>(&mut self,
965 -> PResult<'a, Vec<T>> where
966 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
968 let val = self.parse_seq_to_before_end(ket, sep, f);
973 /// Parse a sequence, not including the closing delimiter. The function
974 /// f must consume tokens until reaching the next separator or
976 pub fn parse_seq_to_before_end<T, F>(&mut self,
981 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
983 self.parse_seq_to_before_tokens(&[ket], sep, f, |mut e| e.emit())
986 // `fe` is an error handler.
987 fn parse_seq_to_before_tokens<T, F, Fe>(&mut self,
988 kets: &[&token::Token],
993 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
994 Fe: FnMut(DiagnosticBuilder)
996 let mut first: bool = true;
998 while !kets.contains(&&self.token) {
1000 token::CloseDelim(..) | token::Eof => break,
1003 if let Some(ref t) = sep.sep {
1007 if let Err(e) = self.expect(t) {
1013 if sep.trailing_sep_allowed && kets.iter().any(|k| self.check(k)) {
1029 /// Parse a sequence, including the closing delimiter. The function
1030 /// f must consume tokens until reaching the next separator or
1031 /// closing bracket.
1032 pub fn parse_unspanned_seq<T, F>(&mut self,
1037 -> PResult<'a, Vec<T>> where
1038 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1041 let result = self.parse_seq_to_before_end(ket, sep, f);
1042 if self.token == *ket {
1048 // NB: Do not use this function unless you actually plan to place the
1049 // spanned list in the AST.
1050 pub fn parse_seq<T, F>(&mut self,
1055 -> PResult<'a, Spanned<Vec<T>>> where
1056 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1060 let result = self.parse_seq_to_before_end(ket, sep, f);
1063 Ok(respan(lo.to(hi), result))
1066 /// Advance the parser by one token
1067 pub fn bump(&mut self) {
1068 if self.prev_token_kind == PrevTokenKind::Eof {
1069 // Bumping after EOF is a bad sign, usually an infinite loop.
1070 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1073 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1075 // Record last token kind for possible error recovery.
1076 self.prev_token_kind = match self.token {
1077 token::DocComment(..) => PrevTokenKind::DocComment,
1078 token::Comma => PrevTokenKind::Comma,
1079 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1080 token::Interpolated(..) => PrevTokenKind::Interpolated,
1081 token::Eof => PrevTokenKind::Eof,
1082 token::Ident(..) => PrevTokenKind::Ident,
1083 _ => PrevTokenKind::Other,
1086 let next = self.next_tok();
1087 self.span = next.sp;
1088 self.token = next.tok;
1089 self.expected_tokens.clear();
1090 // check after each token
1091 self.process_potential_macro_variable();
1094 /// Advance the parser using provided token as a next one. Use this when
1095 /// consuming a part of a token. For example a single `<` from `<<`.
1096 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1097 self.prev_span = Span { hi: span.lo, ..self.span };
1098 // It would be incorrect to record the kind of the current token, but
1099 // fortunately for tokens currently using `bump_with`, the
1100 // prev_token_kind will be of no use anyway.
1101 self.prev_token_kind = PrevTokenKind::Other;
1104 self.expected_tokens.clear();
1107 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1108 F: FnOnce(&token::Token) -> R,
1111 return f(&self.token)
1114 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1115 Some(tree) => match tree {
1116 TokenTree::Token(_, tok) => tok,
1117 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1119 None => token::CloseDelim(self.token_cursor.frame.delim),
1122 fn look_ahead_span(&self, dist: usize) -> Span {
1127 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1128 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1129 None => self.look_ahead_span(dist - 1),
1132 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1133 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1135 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1136 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1138 pub fn span_fatal_err(&self, sp: Span, err: Error) -> DiagnosticBuilder<'a> {
1139 err.span_err(sp, self.diagnostic())
1141 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1142 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1146 pub fn bug(&self, m: &str) -> ! {
1147 self.sess.span_diagnostic.span_bug(self.span, m)
1149 pub fn warn(&self, m: &str) {
1150 self.sess.span_diagnostic.span_warn(self.span, m)
1152 pub fn span_warn(&self, sp: Span, m: &str) {
1153 self.sess.span_diagnostic.span_warn(sp, m)
1155 pub fn span_err(&self, sp: Span, m: &str) {
1156 self.sess.span_diagnostic.span_err(sp, m)
1158 pub fn span_err_help(&self, sp: Span, m: &str, h: &str) {
1159 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1163 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1164 self.sess.span_diagnostic.span_bug(sp, m)
1166 pub fn abort_if_errors(&self) {
1167 self.sess.span_diagnostic.abort_if_errors();
1170 fn cancel(&self, err: &mut DiagnosticBuilder) {
1171 self.sess.span_diagnostic.cancel(err)
1174 pub fn diagnostic(&self) -> &'a errors::Handler {
1175 &self.sess.span_diagnostic
1178 /// Is the current token one of the keywords that signals a bare function
1180 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1181 self.check_keyword(keywords::Fn) ||
1182 self.check_keyword(keywords::Unsafe) ||
1183 self.check_keyword(keywords::Extern)
1186 fn get_label(&mut self) -> ast::Ident {
1188 token::Lifetime(ref ident) => *ident,
1189 _ => self.bug("not a lifetime"),
1193 /// parse a TyKind::BareFn type:
1194 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<LifetimeDef>)
1195 -> PResult<'a, TyKind> {
1198 [unsafe] [extern "ABI"] fn (S) -> T
1208 let unsafety = self.parse_unsafety()?;
1209 let abi = if self.eat_keyword(keywords::Extern) {
1210 self.parse_opt_abi()?.unwrap_or(Abi::C)
1215 self.expect_keyword(keywords::Fn)?;
1216 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1217 let ret_ty = self.parse_ret_ty()?;
1218 let decl = P(FnDecl {
1223 Ok(TyKind::BareFn(P(BareFnTy {
1226 lifetimes: lifetime_defs,
1231 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1232 if self.eat_keyword(keywords::Unsafe) {
1233 return Ok(Unsafety::Unsafe);
1235 return Ok(Unsafety::Normal);
1239 /// Parse the items in a trait declaration
1240 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1241 maybe_whole!(self, NtTraitItem, |x| x);
1242 let attrs = self.parse_outer_attributes()?;
1243 let (mut item, tokens) = self.collect_tokens(|this| {
1244 this.parse_trait_item_(at_end, attrs)
1246 // See `parse_item` for why this clause is here.
1247 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1248 item.tokens = Some(tokens);
1253 fn parse_trait_item_(&mut self,
1255 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1258 let (name, node) = if self.eat_keyword(keywords::Type) {
1259 let TyParam {ident, bounds, default, ..} = self.parse_ty_param(vec![])?;
1260 self.expect(&token::Semi)?;
1261 (ident, TraitItemKind::Type(bounds, default))
1262 } else if self.is_const_item() {
1263 self.expect_keyword(keywords::Const)?;
1264 let ident = self.parse_ident()?;
1265 self.expect(&token::Colon)?;
1266 let ty = self.parse_ty()?;
1267 let default = if self.check(&token::Eq) {
1269 let expr = self.parse_expr()?;
1270 self.expect(&token::Semi)?;
1273 self.expect(&token::Semi)?;
1276 (ident, TraitItemKind::Const(ty, default))
1277 } else if self.token.is_path_start() {
1278 // trait item macro.
1279 // code copied from parse_macro_use_or_failure... abstraction!
1280 let prev_span = self.prev_span;
1282 let pth = self.parse_path(PathStyle::Mod)?;
1284 if pth.segments.len() == 1 {
1285 if !self.eat(&token::Not) {
1286 return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1289 self.expect(&token::Not)?;
1292 // eat a matched-delimiter token tree:
1293 let (delim, tts) = self.expect_delimited_token_tree()?;
1294 if delim != token::Brace {
1295 self.expect(&token::Semi)?
1298 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1299 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac))
1301 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
1303 let ident = self.parse_ident()?;
1304 let mut generics = self.parse_generics()?;
1306 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1307 // This is somewhat dubious; We don't want to allow
1308 // argument names to be left off if there is a
1310 p.parse_arg_general(false)
1313 generics.where_clause = self.parse_where_clause()?;
1314 let sig = ast::MethodSig {
1316 constness: constness,
1322 let body = match self.token {
1326 debug!("parse_trait_methods(): parsing required method");
1329 token::OpenDelim(token::Brace) => {
1330 debug!("parse_trait_methods(): parsing provided method");
1332 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1333 attrs.extend(inner_attrs.iter().cloned());
1337 let token_str = self.this_token_to_string();
1338 return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1341 (ident, ast::TraitItemKind::Method(sig, body))
1345 id: ast::DUMMY_NODE_ID,
1349 span: lo.to(self.prev_span),
1354 /// Parse optional return type [ -> TY ] in function decl
1355 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1356 if self.eat(&token::RArrow) {
1357 Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
1359 Ok(FunctionRetTy::Default(Span { hi: self.span.lo, ..self.span }))
1364 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1365 self.parse_ty_common(true)
1368 /// Parse a type in restricted contexts where `+` is not permitted.
1369 /// Example 1: `&'a TYPE`
1370 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1371 /// Example 2: `value1 as TYPE + value2`
1372 /// `+` is prohibited to avoid interactions with expression grammar.
1373 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1374 self.parse_ty_common(false)
1377 fn parse_ty_common(&mut self, allow_plus: bool) -> PResult<'a, P<Ty>> {
1378 maybe_whole!(self, NtTy, |x| x);
1381 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1382 // `(TYPE)` is a parenthesized type.
1383 // `(TYPE,)` is a tuple with a single field of type TYPE.
1384 let mut ts = vec![];
1385 let mut last_comma = false;
1386 while self.token != token::CloseDelim(token::Paren) {
1387 ts.push(self.parse_ty()?);
1388 if self.eat(&token::Comma) {
1395 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1396 self.expect(&token::CloseDelim(token::Paren))?;
1398 if ts.len() == 1 && !last_comma {
1399 let ty = ts.into_iter().nth(0).unwrap().unwrap();
1400 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1402 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1403 TyKind::Path(None, ref path) if maybe_bounds => {
1404 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1406 TyKind::TraitObject(ref bounds)
1407 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1408 let path = match bounds[0] {
1409 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1410 _ => self.bug("unexpected lifetime bound"),
1412 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1415 _ => TyKind::Paren(P(ty))
1420 } else if self.eat(&token::Not) {
1423 } else if self.eat(&token::BinOp(token::Star)) {
1425 TyKind::Ptr(self.parse_ptr()?)
1426 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1428 let t = self.parse_ty()?;
1429 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1430 let t = match self.maybe_parse_fixed_length_of_vec()? {
1431 None => TyKind::Slice(t),
1432 Some(suffix) => TyKind::Array(t, suffix),
1434 self.expect(&token::CloseDelim(token::Bracket))?;
1436 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1439 self.parse_borrowed_pointee()?
1440 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1442 // In order to not be ambiguous, the type must be surrounded by parens.
1443 self.expect(&token::OpenDelim(token::Paren))?;
1444 let e = self.parse_expr()?;
1445 self.expect(&token::CloseDelim(token::Paren))?;
1447 } else if self.eat(&token::Underscore) {
1448 // A type to be inferred `_`
1450 } else if self.eat_lt() {
1452 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1453 TyKind::Path(Some(qself), path)
1454 } else if self.token.is_path_start() {
1456 let path = self.parse_path(PathStyle::Type)?;
1457 if self.eat(&token::Not) {
1458 // Macro invocation in type position
1459 let (_, tts) = self.expect_delimited_token_tree()?;
1460 TyKind::Mac(respan(lo.to(self.span), Mac_ { path: path, tts: tts }))
1462 // Just a type path or bound list (trait object type) starting with a trait.
1464 // `Trait1 + Trait2 + 'a`
1465 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1466 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1468 TyKind::Path(None, path)
1471 } else if self.token_is_bare_fn_keyword() {
1472 // Function pointer type
1473 self.parse_ty_bare_fn(Vec::new())?
1474 } else if self.check_keyword(keywords::For) {
1475 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1476 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1477 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1479 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1480 if self.token_is_bare_fn_keyword() {
1481 self.parse_ty_bare_fn(lifetime_defs)?
1483 let path = self.parse_path(PathStyle::Type)?;
1484 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1485 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1487 } else if self.eat_keyword(keywords::Impl) {
1488 // FIXME: figure out priority of `+` in `impl Trait1 + Trait2` (#34511).
1489 TyKind::ImplTrait(self.parse_ty_param_bounds()?)
1490 } else if self.check(&token::Question) ||
1491 self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)){
1492 // Bound list (trait object type)
1493 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?)
1495 let msg = format!("expected type, found {}", self.this_token_descr());
1496 return Err(self.fatal(&msg));
1499 let span = lo.to(self.prev_span);
1500 let ty = Ty { node: node, span: span, id: ast::DUMMY_NODE_ID };
1502 // Try to recover from use of `+` with incorrect priority.
1503 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1508 fn parse_remaining_bounds(&mut self, lifetime_defs: Vec<LifetimeDef>, path: ast::Path,
1509 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1510 let poly_trait_ref = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
1511 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1514 bounds.append(&mut self.parse_ty_param_bounds()?);
1516 Ok(TyKind::TraitObject(bounds))
1519 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1520 // Do not add `+` to expected tokens.
1521 if !allow_plus || self.token != token::BinOp(token::Plus) {
1526 let bounds = self.parse_ty_param_bounds()?;
1527 let sum_span = ty.span.to(self.prev_span);
1529 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1530 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1533 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1534 let sum_with_parens = pprust::to_string(|s| {
1535 use print::pprust::PrintState;
1538 s.print_opt_lifetime(lifetime)?;
1539 s.print_mutability(mut_ty.mutbl)?;
1541 s.print_type(&mut_ty.ty)?;
1542 s.print_bounds(" +", &bounds)?;
1545 err.span_suggestion(sum_span, "try adding parentheses", sum_with_parens);
1547 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1548 err.span_label(sum_span, "perhaps you forgot parentheses?");
1551 err.span_label(sum_span, "expected a path");
1558 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1559 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1560 let mutbl = self.parse_mutability();
1561 let ty = self.parse_ty_no_plus()?;
1562 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1565 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1566 let mutbl = if self.eat_keyword(keywords::Mut) {
1568 } else if self.eat_keyword(keywords::Const) {
1569 Mutability::Immutable
1571 let span = self.prev_span;
1573 "expected mut or const in raw pointer type (use \
1574 `*mut T` or `*const T` as appropriate)");
1575 Mutability::Immutable
1577 let t = self.parse_ty_no_plus()?;
1578 Ok(MutTy { ty: t, mutbl: mutbl })
1581 pub fn is_named_argument(&mut self) -> bool {
1582 let offset = match self.token {
1583 token::BinOp(token::And) |
1585 _ if self.token.is_keyword(keywords::Mut) => 1,
1589 debug!("parser is_named_argument offset:{}", offset);
1592 is_ident_or_underscore(&self.token)
1593 && self.look_ahead(1, |t| *t == token::Colon)
1595 self.look_ahead(offset, |t| is_ident_or_underscore(t))
1596 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1600 /// This version of parse arg doesn't necessarily require
1601 /// identifier names.
1602 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1603 maybe_whole!(self, NtArg, |x| x);
1605 let pat = if require_name || self.is_named_argument() {
1606 debug!("parse_arg_general parse_pat (require_name:{})",
1608 let pat = self.parse_pat()?;
1610 self.expect(&token::Colon)?;
1613 debug!("parse_arg_general ident_to_pat");
1614 let sp = self.prev_span;
1615 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1617 id: ast::DUMMY_NODE_ID,
1618 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1624 let t = self.parse_ty()?;
1629 id: ast::DUMMY_NODE_ID,
1633 /// Parse a single function argument
1634 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1635 self.parse_arg_general(true)
1638 /// Parse an argument in a lambda header e.g. |arg, arg|
1639 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1640 let pat = self.parse_pat()?;
1641 let t = if self.eat(&token::Colon) {
1645 id: ast::DUMMY_NODE_ID,
1646 node: TyKind::Infer,
1653 id: ast::DUMMY_NODE_ID
1657 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1658 if self.eat(&token::Semi) {
1659 Ok(Some(self.parse_expr()?))
1665 /// Matches token_lit = LIT_INTEGER | ...
1666 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1667 let out = match self.token {
1668 token::Interpolated(ref nt) => match nt.0 {
1669 token::NtExpr(ref v) => match v.node {
1670 ExprKind::Lit(ref lit) => { lit.node.clone() }
1671 _ => { return self.unexpected_last(&self.token); }
1673 _ => { return self.unexpected_last(&self.token); }
1675 token::Literal(lit, suf) => {
1676 let diag = Some((self.span, &self.sess.span_diagnostic));
1677 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1681 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1686 _ => { return self.unexpected_last(&self.token); }
1693 /// Matches lit = true | false | token_lit
1694 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1696 let lit = if self.eat_keyword(keywords::True) {
1698 } else if self.eat_keyword(keywords::False) {
1699 LitKind::Bool(false)
1701 let lit = self.parse_lit_token()?;
1704 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1707 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1708 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1709 maybe_whole_expr!(self);
1711 let minus_lo = self.span;
1712 let minus_present = self.eat(&token::BinOp(token::Minus));
1714 let literal = P(self.parse_lit()?);
1715 let hi = self.prev_span;
1716 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1719 let minus_hi = self.prev_span;
1720 let unary = self.mk_unary(UnOp::Neg, expr);
1721 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1727 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1729 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1733 _ => self.parse_ident(),
1737 /// Parses qualified path.
1738 /// Assumes that the leading `<` has been parsed already.
1740 /// `qualified_path = <type [as trait_ref]>::path`
1744 /// `<T as U>::F::a<S>` (without disambiguator)
1745 /// `<T as U>::F::a::<S>` (with disambiguator)
1746 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1747 let lo = self.prev_span;
1748 let ty = self.parse_ty()?;
1749 let mut path = if self.eat_keyword(keywords::As) {
1750 self.parse_path(PathStyle::Type)?
1752 ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP }
1754 self.expect(&token::Gt)?;
1755 self.expect(&token::ModSep)?;
1757 let qself = QSelf { ty, position: path.segments.len() };
1758 self.parse_path_segments(&mut path.segments, style)?;
1760 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1763 /// Parses simple paths.
1765 /// `path = [::] segment+`
1766 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1769 /// `a::b::C<D>` (without disambiguator)
1770 /// `a::b::C::<D>` (with disambiguator)
1771 /// `Fn(Args)` (without disambiguator)
1772 /// `Fn::(Args)` (with disambiguator)
1773 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path>
1775 maybe_whole!(self, NtPath, |x| x);
1777 let lo = self.meta_var_span.unwrap_or(self.span);
1778 let mut segments = Vec::new();
1779 if self.eat(&token::ModSep) {
1780 segments.push(PathSegment::crate_root(lo));
1782 self.parse_path_segments(&mut segments, style)?;
1784 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1787 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1788 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1789 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1790 let meta_ident = match self.token {
1791 token::Interpolated(ref nt) => match nt.0 {
1792 token::NtMeta(ref meta) => match meta.node {
1793 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
1800 if let Some(ident) = meta_ident {
1802 return Ok(ast::Path::from_ident(self.prev_span, ident));
1804 self.parse_path(style)
1807 fn parse_path_segments(&mut self, segments: &mut Vec<PathSegment>, style: PathStyle)
1808 -> PResult<'a, ()> {
1810 segments.push(self.parse_path_segment(style)?);
1812 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1818 fn parse_path_segment(&mut self, style: PathStyle) -> PResult<'a, PathSegment> {
1819 let ident_span = self.span;
1820 let ident = self.parse_path_segment_ident()?;
1822 let is_args_start = |token: &token::Token| match *token {
1823 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
1826 let check_args_start = |this: &mut Self| {
1827 this.expected_tokens.extend_from_slice(
1828 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1830 is_args_start(&this.token)
1833 Ok(if style == PathStyle::Type && check_args_start(self) ||
1834 style != PathStyle::Mod && self.check(&token::ModSep)
1835 && self.look_ahead(1, |t| is_args_start(t)) {
1836 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1838 if self.eat(&token::ModSep) {
1839 // These errors are not strictly necessary and may be removed in the future.
1840 if style == PathStyle::Type {
1841 let mut err = self.diagnostic().struct_span_err(self.prev_span,
1842 "unnecessary path disambiguator");
1843 err.span_label(self.prev_span, "try removing `::`");
1845 } else if self.token == token::OpenDelim(token::Paren) {
1846 self.diagnostic().span_err(self.prev_span,
1847 "`::` is not supported before parenthesized generic arguments")
1851 let parameters = if self.eat_lt() {
1853 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1855 let span = lo.to(self.prev_span);
1856 AngleBracketedParameterData { lifetimes, types, bindings, span }.into()
1860 let inputs = self.parse_seq_to_end(&token::CloseDelim(token::Paren),
1861 SeqSep::trailing_allowed(token::Comma),
1863 let output = if self.eat(&token::RArrow) {
1864 Some(self.parse_ty_no_plus()?)
1868 let span = lo.to(self.prev_span);
1869 ParenthesizedParameterData { inputs, output, span }.into()
1872 PathSegment { identifier: ident, span: ident_span, parameters }
1874 // Generic arguments are not found.
1875 PathSegment::from_ident(ident, ident_span)
1879 fn check_lifetime(&mut self) -> bool {
1880 self.expected_tokens.push(TokenType::Lifetime);
1881 self.token.is_lifetime()
1884 /// Parse single lifetime 'a or panic.
1885 fn expect_lifetime(&mut self) -> Lifetime {
1887 token::Lifetime(ident) => {
1888 let ident_span = self.span;
1890 Lifetime { ident: ident, span: ident_span, id: ast::DUMMY_NODE_ID }
1892 _ => self.span_bug(self.span, "not a lifetime")
1896 /// Parse mutability (`mut` or nothing).
1897 fn parse_mutability(&mut self) -> Mutability {
1898 if self.eat_keyword(keywords::Mut) {
1901 Mutability::Immutable
1905 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1906 if let token::Literal(token::Integer(name), None) = self.token {
1908 Ok(Ident::with_empty_ctxt(name))
1914 /// Parse ident (COLON expr)?
1915 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1916 let attrs = self.parse_outer_attributes()?;
1920 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1921 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1922 let fieldname = self.parse_field_name()?;
1924 hi = self.prev_span;
1925 (fieldname, self.parse_expr()?, false)
1927 let fieldname = self.parse_ident()?;
1928 hi = self.prev_span;
1930 // Mimic `x: x` for the `x` field shorthand.
1931 let path = ast::Path::from_ident(lo.to(hi), fieldname);
1932 (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
1935 ident: respan(lo.to(hi), fieldname),
1936 span: lo.to(expr.span),
1938 is_shorthand: is_shorthand,
1939 attrs: attrs.into(),
1943 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1945 id: ast::DUMMY_NODE_ID,
1948 attrs: attrs.into(),
1952 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
1953 ExprKind::Unary(unop, expr)
1956 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1957 ExprKind::Binary(binop, lhs, rhs)
1960 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
1961 ExprKind::Call(f, args)
1964 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
1965 ExprKind::Index(expr, idx)
1968 pub fn mk_range(&mut self,
1969 start: Option<P<Expr>>,
1970 end: Option<P<Expr>>,
1971 limits: RangeLimits)
1972 -> PResult<'a, ast::ExprKind> {
1973 if end.is_none() && limits == RangeLimits::Closed {
1974 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
1976 Ok(ExprKind::Range(start, end, limits))
1980 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
1981 ExprKind::TupField(expr, idx)
1984 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
1985 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1986 ExprKind::AssignOp(binop, lhs, rhs)
1989 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
1991 id: ast::DUMMY_NODE_ID,
1992 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
1998 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
1999 let span = &self.span;
2000 let lv_lit = P(codemap::Spanned {
2001 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2006 id: ast::DUMMY_NODE_ID,
2007 node: ExprKind::Lit(lv_lit),
2013 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2015 token::OpenDelim(delim) => match self.parse_token_tree() {
2016 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2017 _ => unreachable!(),
2019 _ => Err(self.fatal("expected open delimiter")),
2023 /// At the bottom (top?) of the precedence hierarchy,
2024 /// parse things like parenthesized exprs,
2025 /// macros, return, etc.
2027 /// NB: This does not parse outer attributes,
2028 /// and is private because it only works
2029 /// correctly if called from parse_dot_or_call_expr().
2030 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2031 maybe_whole_expr!(self);
2033 // Outer attributes are already parsed and will be
2034 // added to the return value after the fact.
2036 // Therefore, prevent sub-parser from parsing
2037 // attributes by giving them a empty "already parsed" list.
2038 let mut attrs = ThinVec::new();
2041 let mut hi = self.span;
2045 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2047 token::OpenDelim(token::Paren) => {
2050 attrs.extend(self.parse_inner_attributes()?);
2052 // (e) is parenthesized e
2053 // (e,) is a tuple with only one field, e
2054 let mut es = vec![];
2055 let mut trailing_comma = false;
2056 while self.token != token::CloseDelim(token::Paren) {
2057 es.push(self.parse_expr()?);
2058 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2059 if self.check(&token::Comma) {
2060 trailing_comma = true;
2064 trailing_comma = false;
2070 hi = self.prev_span;
2071 let span = lo.to(hi);
2072 return if es.len() == 1 && !trailing_comma {
2073 Ok(self.mk_expr(span, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2075 Ok(self.mk_expr(span, ExprKind::Tup(es), attrs))
2078 token::OpenDelim(token::Brace) => {
2079 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2081 token::BinOp(token::Or) | token::OrOr => {
2083 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2085 token::OpenDelim(token::Bracket) => {
2088 attrs.extend(self.parse_inner_attributes()?);
2090 if self.check(&token::CloseDelim(token::Bracket)) {
2093 ex = ExprKind::Array(Vec::new());
2096 let first_expr = self.parse_expr()?;
2097 if self.check(&token::Semi) {
2098 // Repeating array syntax: [ 0; 512 ]
2100 let count = self.parse_expr()?;
2101 self.expect(&token::CloseDelim(token::Bracket))?;
2102 ex = ExprKind::Repeat(first_expr, count);
2103 } else if self.check(&token::Comma) {
2104 // Vector with two or more elements.
2106 let remaining_exprs = self.parse_seq_to_end(
2107 &token::CloseDelim(token::Bracket),
2108 SeqSep::trailing_allowed(token::Comma),
2109 |p| Ok(p.parse_expr()?)
2111 let mut exprs = vec![first_expr];
2112 exprs.extend(remaining_exprs);
2113 ex = ExprKind::Array(exprs);
2115 // Vector with one element.
2116 self.expect(&token::CloseDelim(token::Bracket))?;
2117 ex = ExprKind::Array(vec![first_expr]);
2120 hi = self.prev_span;
2124 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2126 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2128 if self.eat_keyword(keywords::Move) {
2129 let lo = self.prev_span;
2130 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2132 if self.eat_keyword(keywords::If) {
2133 return self.parse_if_expr(attrs);
2135 if self.eat_keyword(keywords::For) {
2136 let lo = self.prev_span;
2137 return self.parse_for_expr(None, lo, attrs);
2139 if self.eat_keyword(keywords::While) {
2140 let lo = self.prev_span;
2141 return self.parse_while_expr(None, lo, attrs);
2143 if self.token.is_lifetime() {
2144 let label = Spanned { node: self.get_label(),
2148 self.expect(&token::Colon)?;
2149 if self.eat_keyword(keywords::While) {
2150 return self.parse_while_expr(Some(label), lo, attrs)
2152 if self.eat_keyword(keywords::For) {
2153 return self.parse_for_expr(Some(label), lo, attrs)
2155 if self.eat_keyword(keywords::Loop) {
2156 return self.parse_loop_expr(Some(label), lo, attrs)
2158 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2160 if self.eat_keyword(keywords::Loop) {
2161 let lo = self.prev_span;
2162 return self.parse_loop_expr(None, lo, attrs);
2164 if self.eat_keyword(keywords::Continue) {
2165 let ex = if self.token.is_lifetime() {
2166 let ex = ExprKind::Continue(Some(Spanned{
2167 node: self.get_label(),
2173 ExprKind::Continue(None)
2175 let hi = self.prev_span;
2176 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2178 if self.eat_keyword(keywords::Match) {
2179 return self.parse_match_expr(attrs);
2181 if self.eat_keyword(keywords::Unsafe) {
2182 return self.parse_block_expr(
2184 BlockCheckMode::Unsafe(ast::UserProvided),
2187 if self.is_catch_expr() {
2189 assert!(self.eat_keyword(keywords::Do));
2190 assert!(self.eat_keyword(keywords::Catch));
2191 return self.parse_catch_expr(lo, attrs);
2193 if self.eat_keyword(keywords::Return) {
2194 if self.token.can_begin_expr() {
2195 let e = self.parse_expr()?;
2197 ex = ExprKind::Ret(Some(e));
2199 ex = ExprKind::Ret(None);
2201 } else if self.eat_keyword(keywords::Break) {
2202 let lt = if self.token.is_lifetime() {
2203 let spanned_lt = Spanned {
2204 node: self.get_label(),
2212 let e = if self.token.can_begin_expr()
2213 && !(self.token == token::OpenDelim(token::Brace)
2214 && self.restrictions.contains(
2215 RESTRICTION_NO_STRUCT_LITERAL)) {
2216 Some(self.parse_expr()?)
2220 ex = ExprKind::Break(lt, e);
2221 hi = self.prev_span;
2222 } else if self.token.is_keyword(keywords::Let) {
2223 // Catch this syntax error here, instead of in `parse_ident`, so
2224 // that we can explicitly mention that let is not to be used as an expression
2225 let mut db = self.fatal("expected expression, found statement (`let`)");
2226 db.note("variable declaration using `let` is a statement");
2228 } else if self.token.is_path_start() {
2229 let pth = self.parse_path(PathStyle::Expr)?;
2231 // `!`, as an operator, is prefix, so we know this isn't that
2232 if self.eat(&token::Not) {
2233 // MACRO INVOCATION expression
2234 let (_, tts) = self.expect_delimited_token_tree()?;
2235 let hi = self.prev_span;
2236 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2238 if self.check(&token::OpenDelim(token::Brace)) {
2239 // This is a struct literal, unless we're prohibited
2240 // from parsing struct literals here.
2241 let prohibited = self.restrictions.contains(
2242 RESTRICTION_NO_STRUCT_LITERAL
2245 return self.parse_struct_expr(lo, pth, attrs);
2250 ex = ExprKind::Path(None, pth);
2252 match self.parse_lit() {
2255 ex = ExprKind::Lit(P(lit));
2258 self.cancel(&mut err);
2259 let msg = format!("expected expression, found {}",
2260 self.this_token_descr());
2261 return Err(self.fatal(&msg));
2268 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2271 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2272 -> PResult<'a, P<Expr>> {
2274 let mut fields = Vec::new();
2275 let mut base = None;
2277 attrs.extend(self.parse_inner_attributes()?);
2279 while self.token != token::CloseDelim(token::Brace) {
2280 if self.eat(&token::DotDot) {
2281 match self.parse_expr() {
2287 self.recover_stmt();
2293 match self.parse_field() {
2294 Ok(f) => fields.push(f),
2297 self.recover_stmt();
2302 match self.expect_one_of(&[token::Comma],
2303 &[token::CloseDelim(token::Brace)]) {
2307 self.recover_stmt();
2313 let span = lo.to(self.span);
2314 self.expect(&token::CloseDelim(token::Brace))?;
2315 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2318 fn parse_or_use_outer_attributes(&mut self,
2319 already_parsed_attrs: Option<ThinVec<Attribute>>)
2320 -> PResult<'a, ThinVec<Attribute>> {
2321 if let Some(attrs) = already_parsed_attrs {
2324 self.parse_outer_attributes().map(|a| a.into())
2328 /// Parse a block or unsafe block
2329 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2330 outer_attrs: ThinVec<Attribute>)
2331 -> PResult<'a, P<Expr>> {
2332 self.expect(&token::OpenDelim(token::Brace))?;
2334 let mut attrs = outer_attrs;
2335 attrs.extend(self.parse_inner_attributes()?);
2337 let blk = self.parse_block_tail(lo, blk_mode)?;
2338 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2341 /// parse a.b or a(13) or a[4] or just a
2342 pub fn parse_dot_or_call_expr(&mut self,
2343 already_parsed_attrs: Option<ThinVec<Attribute>>)
2344 -> PResult<'a, P<Expr>> {
2345 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2347 let b = self.parse_bottom_expr();
2348 let (span, b) = self.interpolated_or_expr_span(b)?;
2349 self.parse_dot_or_call_expr_with(b, span, attrs)
2352 pub fn parse_dot_or_call_expr_with(&mut self,
2355 mut attrs: ThinVec<Attribute>)
2356 -> PResult<'a, P<Expr>> {
2357 // Stitch the list of outer attributes onto the return value.
2358 // A little bit ugly, but the best way given the current code
2360 self.parse_dot_or_call_expr_with_(e0, lo)
2362 expr.map(|mut expr| {
2363 attrs.extend::<Vec<_>>(expr.attrs.into());
2366 ExprKind::If(..) | ExprKind::IfLet(..) => {
2367 if !expr.attrs.is_empty() {
2368 // Just point to the first attribute in there...
2369 let span = expr.attrs[0].span;
2372 "attributes are not yet allowed on `if` \
2383 // Assuming we have just parsed `.`, continue parsing into an expression.
2384 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2385 let segment = self.parse_path_segment(PathStyle::Expr)?;
2386 Ok(match self.token {
2387 token::OpenDelim(token::Paren) => {
2388 // Method call `expr.f()`
2389 let mut args = self.parse_unspanned_seq(
2390 &token::OpenDelim(token::Paren),
2391 &token::CloseDelim(token::Paren),
2392 SeqSep::trailing_allowed(token::Comma),
2393 |p| Ok(p.parse_expr()?)
2395 args.insert(0, self_arg);
2397 let span = lo.to(self.prev_span);
2398 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2401 // Field access `expr.f`
2402 if let Some(parameters) = segment.parameters {
2403 self.span_err(parameters.span(),
2404 "field expressions may not have generic arguments");
2407 let span = lo.to(self.prev_span);
2408 let ident = respan(segment.span, segment.identifier);
2409 self.mk_expr(span, ExprKind::Field(self_arg, ident), ThinVec::new())
2414 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2419 while self.eat(&token::Question) {
2420 let hi = self.prev_span;
2421 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2425 if self.eat(&token::Dot) {
2427 token::Ident(..) => {
2428 e = self.parse_dot_suffix(e, lo)?;
2430 token::Literal(token::Integer(n), suf) => {
2433 // A tuple index may not have a suffix
2434 self.expect_no_suffix(sp, "tuple index", suf);
2436 let dot_span = self.prev_span;
2440 let index = n.as_str().parse::<usize>().ok();
2443 let id = respan(dot_span.to(hi), n);
2444 let field = self.mk_tup_field(e, id);
2445 e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2448 let prev_span = self.prev_span;
2449 self.span_err(prev_span, "invalid tuple or tuple struct index");
2453 token::Literal(token::Float(n), _suf) => {
2455 let fstr = n.as_str();
2456 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2457 &format!("unexpected token: `{}`", n));
2458 err.span_label(self.prev_span, "unexpected token");
2459 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2460 let float = match fstr.parse::<f64>().ok() {
2464 let sugg = pprust::to_string(|s| {
2465 use print::pprust::PrintState;
2469 s.print_usize(float.trunc() as usize)?;
2472 s.s.word(fstr.splitn(2, ".").last().unwrap())
2474 err.span_suggestion(
2475 lo.to(self.prev_span),
2476 "try parenthesizing the first index",
2483 // FIXME Could factor this out into non_fatal_unexpected or something.
2484 let actual = self.this_token_to_string();
2485 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2490 if self.expr_is_complete(&e) { break; }
2493 token::OpenDelim(token::Paren) => {
2494 let es = self.parse_unspanned_seq(
2495 &token::OpenDelim(token::Paren),
2496 &token::CloseDelim(token::Paren),
2497 SeqSep::trailing_allowed(token::Comma),
2498 |p| Ok(p.parse_expr()?)
2500 hi = self.prev_span;
2502 let nd = self.mk_call(e, es);
2503 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2507 // Could be either an index expression or a slicing expression.
2508 token::OpenDelim(token::Bracket) => {
2510 let ix = self.parse_expr()?;
2512 self.expect(&token::CloseDelim(token::Bracket))?;
2513 let index = self.mk_index(e, ix);
2514 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2522 pub fn process_potential_macro_variable(&mut self) {
2523 let ident = match self.token {
2524 token::Dollar if self.span.ctxt != syntax_pos::hygiene::SyntaxContext::empty() &&
2525 self.look_ahead(1, |t| t.is_ident()) => {
2527 let name = match self.token { token::Ident(ident) => ident, _ => unreachable!() };
2528 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2531 token::Interpolated(ref nt) => {
2532 self.meta_var_span = Some(self.span);
2534 token::NtIdent(ident) => ident,
2540 self.token = token::Ident(ident.node);
2541 self.span = ident.span;
2544 /// parse a single token tree from the input.
2545 pub fn parse_token_tree(&mut self) -> TokenTree {
2547 token::OpenDelim(..) => {
2548 let frame = mem::replace(&mut self.token_cursor.frame,
2549 self.token_cursor.stack.pop().unwrap());
2550 self.span = frame.span;
2552 TokenTree::Delimited(frame.span, Delimited {
2554 tts: frame.tree_cursor.original_stream().into(),
2557 token::CloseDelim(_) | token::Eof => unreachable!(),
2559 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2561 TokenTree::Token(span, token)
2566 // parse a stream of tokens into a list of TokenTree's,
2568 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2569 let mut tts = Vec::new();
2570 while self.token != token::Eof {
2571 tts.push(self.parse_token_tree());
2576 pub fn parse_tokens(&mut self) -> TokenStream {
2577 let mut result = Vec::new();
2580 token::Eof | token::CloseDelim(..) => break,
2581 _ => result.push(self.parse_token_tree().into()),
2584 TokenStream::concat(result)
2587 /// Parse a prefix-unary-operator expr
2588 pub fn parse_prefix_expr(&mut self,
2589 already_parsed_attrs: Option<ThinVec<Attribute>>)
2590 -> PResult<'a, P<Expr>> {
2591 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2593 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2594 let (hi, ex) = match self.token {
2597 let e = self.parse_prefix_expr(None);
2598 let (span, e) = self.interpolated_or_expr_span(e)?;
2599 (span, self.mk_unary(UnOp::Not, e))
2601 // Suggest `!` for bitwise negation when encountering a `~`
2604 let e = self.parse_prefix_expr(None);
2605 let (span, e) = self.interpolated_or_expr_span(e)?;
2606 let span_of_tilde = lo;
2607 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2608 "`~` can not be used as a unary operator");
2609 err.span_label(span_of_tilde, "did you mean `!`?");
2610 err.help("use `!` instead of `~` if you meant to perform bitwise negation");
2612 (span, self.mk_unary(UnOp::Not, e))
2614 token::BinOp(token::Minus) => {
2616 let e = self.parse_prefix_expr(None);
2617 let (span, e) = self.interpolated_or_expr_span(e)?;
2618 (span, self.mk_unary(UnOp::Neg, e))
2620 token::BinOp(token::Star) => {
2622 let e = self.parse_prefix_expr(None);
2623 let (span, e) = self.interpolated_or_expr_span(e)?;
2624 (span, self.mk_unary(UnOp::Deref, e))
2626 token::BinOp(token::And) | token::AndAnd => {
2628 let m = self.parse_mutability();
2629 let e = self.parse_prefix_expr(None);
2630 let (span, e) = self.interpolated_or_expr_span(e)?;
2631 (span, ExprKind::AddrOf(m, e))
2633 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2635 let place = self.parse_expr_res(
2636 RESTRICTION_NO_STRUCT_LITERAL,
2639 let blk = self.parse_block()?;
2640 let span = blk.span;
2641 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2642 (span, ExprKind::InPlace(place, blk_expr))
2644 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2646 let e = self.parse_prefix_expr(None);
2647 let (span, e) = self.interpolated_or_expr_span(e)?;
2648 (span, ExprKind::Box(e))
2650 _ => return self.parse_dot_or_call_expr(Some(attrs))
2652 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2655 /// Parse an associative expression
2657 /// This parses an expression accounting for associativity and precedence of the operators in
2659 pub fn parse_assoc_expr(&mut self,
2660 already_parsed_attrs: Option<ThinVec<Attribute>>)
2661 -> PResult<'a, P<Expr>> {
2662 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2665 /// Parse an associative expression with operators of at least `min_prec` precedence
2666 pub fn parse_assoc_expr_with(&mut self,
2669 -> PResult<'a, P<Expr>> {
2670 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2673 let attrs = match lhs {
2674 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2677 if self.token == token::DotDot || self.token == token::DotDotDot {
2678 return self.parse_prefix_range_expr(attrs);
2680 self.parse_prefix_expr(attrs)?
2684 if self.expr_is_complete(&lhs) {
2685 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2688 self.expected_tokens.push(TokenType::Operator);
2689 while let Some(op) = AssocOp::from_token(&self.token) {
2691 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2692 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2693 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2694 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2695 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2696 (PrevTokenKind::Interpolated, _) => self.prev_span,
2697 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2698 if path.segments.len() == 1 => self.prev_span,
2702 let cur_op_span = self.span;
2703 let restrictions = if op.is_assign_like() {
2704 self.restrictions & RESTRICTION_NO_STRUCT_LITERAL
2708 if op.precedence() < min_prec {
2712 if op.is_comparison() {
2713 self.check_no_chained_comparison(&lhs, &op);
2716 if op == AssocOp::As {
2717 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2719 } else if op == AssocOp::Colon {
2720 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2723 err.span_label(self.span,
2724 "expecting a type here because of type ascription");
2725 let cm = self.sess.codemap();
2726 let cur_pos = cm.lookup_char_pos(self.span.lo);
2727 let op_pos = cm.lookup_char_pos(cur_op_span.hi);
2728 if cur_pos.line != op_pos.line {
2729 err.span_suggestion_short(cur_op_span,
2730 "did you mean to use `;` here?",
2737 } else if op == AssocOp::DotDot || op == AssocOp::DotDotDot {
2738 // If we didn’t have to handle `x..`/`x...`, it would be pretty easy to
2739 // generalise it to the Fixity::None code.
2741 // We have 2 alternatives here: `x..y`/`x...y` and `x..`/`x...` The other
2742 // two variants are handled with `parse_prefix_range_expr` call above.
2743 let rhs = if self.is_at_start_of_range_notation_rhs() {
2744 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2745 LhsExpr::NotYetParsed)?)
2749 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2754 let limits = if op == AssocOp::DotDot {
2755 RangeLimits::HalfOpen
2760 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2761 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2765 let rhs = match op.fixity() {
2766 Fixity::Right => self.with_res(
2767 restrictions - RESTRICTION_STMT_EXPR,
2769 this.parse_assoc_expr_with(op.precedence(),
2770 LhsExpr::NotYetParsed)
2772 Fixity::Left => self.with_res(
2773 restrictions - RESTRICTION_STMT_EXPR,
2775 this.parse_assoc_expr_with(op.precedence() + 1,
2776 LhsExpr::NotYetParsed)
2778 // We currently have no non-associative operators that are not handled above by
2779 // the special cases. The code is here only for future convenience.
2780 Fixity::None => self.with_res(
2781 restrictions - RESTRICTION_STMT_EXPR,
2783 this.parse_assoc_expr_with(op.precedence() + 1,
2784 LhsExpr::NotYetParsed)
2788 let span = lhs_span.to(rhs.span);
2790 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2791 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2792 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2793 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2794 AssocOp::Greater | AssocOp::GreaterEqual => {
2795 let ast_op = op.to_ast_binop().unwrap();
2796 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2797 self.mk_expr(span, binary, ThinVec::new())
2800 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2802 self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
2803 AssocOp::AssignOp(k) => {
2805 token::Plus => BinOpKind::Add,
2806 token::Minus => BinOpKind::Sub,
2807 token::Star => BinOpKind::Mul,
2808 token::Slash => BinOpKind::Div,
2809 token::Percent => BinOpKind::Rem,
2810 token::Caret => BinOpKind::BitXor,
2811 token::And => BinOpKind::BitAnd,
2812 token::Or => BinOpKind::BitOr,
2813 token::Shl => BinOpKind::Shl,
2814 token::Shr => BinOpKind::Shr,
2816 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2817 self.mk_expr(span, aopexpr, ThinVec::new())
2819 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotDot => {
2820 self.bug("As, Colon, DotDot or DotDotDot branch reached")
2824 if op.fixity() == Fixity::None { break }
2829 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
2830 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
2831 -> PResult<'a, P<Expr>> {
2832 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
2833 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
2836 // Save the state of the parser before parsing type normally, in case there is a
2837 // LessThan comparison after this cast.
2838 let parser_snapshot_before_type = self.clone();
2839 match self.parse_ty_no_plus() {
2841 Ok(mk_expr(self, rhs))
2843 Err(mut type_err) => {
2844 // Rewind to before attempting to parse the type with generics, to recover
2845 // from situations like `x as usize < y` in which we first tried to parse
2846 // `usize < y` as a type with generic arguments.
2847 let parser_snapshot_after_type = self.clone();
2848 mem::replace(self, parser_snapshot_before_type);
2850 match self.parse_path(PathStyle::Expr) {
2852 // Successfully parsed the type path leaving a `<` yet to parse.
2855 // Report non-fatal diagnostics, keep `x as usize` as an expression
2856 // in AST and continue parsing.
2857 let msg = format!("`<` is interpreted as a start of generic \
2858 arguments for `{}`, not a comparison", path);
2859 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
2860 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
2861 "interpreted as generic arguments");
2862 err.span_label(self.span, "not interpreted as comparison");
2864 let expr = mk_expr(self, P(Ty {
2866 node: TyKind::Path(None, path),
2867 id: ast::DUMMY_NODE_ID
2870 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
2871 .unwrap_or(pprust::expr_to_string(&expr));
2872 err.span_suggestion(expr.span,
2873 "try comparing the casted value",
2874 format!("({})", expr_str));
2879 Err(mut path_err) => {
2880 // Couldn't parse as a path, return original error and parser state.
2882 mem::replace(self, parser_snapshot_after_type);
2890 /// Produce an error if comparison operators are chained (RFC #558).
2891 /// We only need to check lhs, not rhs, because all comparison ops
2892 /// have same precedence and are left-associative
2893 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2894 debug_assert!(outer_op.is_comparison(),
2895 "check_no_chained_comparison: {:?} is not comparison",
2898 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2899 // respan to include both operators
2900 let op_span = op.span.to(self.span);
2901 let mut err = self.diagnostic().struct_span_err(op_span,
2902 "chained comparison operators require parentheses");
2903 if op.node == BinOpKind::Lt &&
2904 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
2905 *outer_op == AssocOp::Greater // even in a case like the following:
2906 { // Foo<Bar<Baz<Qux, ()>>>
2908 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2916 /// Parse prefix-forms of range notation: `..expr`, `..`, `...expr`
2917 fn parse_prefix_range_expr(&mut self,
2918 already_parsed_attrs: Option<ThinVec<Attribute>>)
2919 -> PResult<'a, P<Expr>> {
2920 debug_assert!(self.token == token::DotDot || self.token == token::DotDotDot,
2921 "parse_prefix_range_expr: token {:?} is not DotDot or DotDotDot",
2923 let tok = self.token.clone();
2924 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2926 let mut hi = self.span;
2928 let opt_end = if self.is_at_start_of_range_notation_rhs() {
2929 // RHS must be parsed with more associativity than the dots.
2930 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
2931 Some(self.parse_assoc_expr_with(next_prec,
2932 LhsExpr::NotYetParsed)
2940 let limits = if tok == token::DotDot {
2941 RangeLimits::HalfOpen
2946 let r = try!(self.mk_range(None,
2949 Ok(self.mk_expr(lo.to(hi), r, attrs))
2952 fn is_at_start_of_range_notation_rhs(&self) -> bool {
2953 if self.token.can_begin_expr() {
2954 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2955 if self.token == token::OpenDelim(token::Brace) {
2956 return !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL);
2964 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2965 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
2966 if self.check_keyword(keywords::Let) {
2967 return self.parse_if_let_expr(attrs);
2969 let lo = self.prev_span;
2970 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
2971 let thn = self.parse_block()?;
2972 let mut els: Option<P<Expr>> = None;
2973 let mut hi = thn.span;
2974 if self.eat_keyword(keywords::Else) {
2975 let elexpr = self.parse_else_expr()?;
2979 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
2982 /// Parse an 'if let' expression ('if' token already eaten)
2983 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
2984 -> PResult<'a, P<Expr>> {
2985 let lo = self.prev_span;
2986 self.expect_keyword(keywords::Let)?;
2987 let pat = self.parse_pat()?;
2988 self.expect(&token::Eq)?;
2989 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
2990 let thn = self.parse_block()?;
2991 let (hi, els) = if self.eat_keyword(keywords::Else) {
2992 let expr = self.parse_else_expr()?;
2993 (expr.span, Some(expr))
2997 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
3000 // `move |args| expr`
3001 pub fn parse_lambda_expr(&mut self,
3003 capture_clause: CaptureBy,
3004 attrs: ThinVec<Attribute>)
3005 -> PResult<'a, P<Expr>>
3007 let decl = self.parse_fn_block_decl()?;
3008 let decl_hi = self.prev_span;
3009 let body = match decl.output {
3010 FunctionRetTy::Default(_) => self.parse_expr()?,
3012 // If an explicit return type is given, require a
3013 // block to appear (RFC 968).
3014 let body_lo = self.span;
3015 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3021 ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3025 // `else` token already eaten
3026 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3027 if self.eat_keyword(keywords::If) {
3028 return self.parse_if_expr(ThinVec::new());
3030 let blk = self.parse_block()?;
3031 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3035 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3036 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3038 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3039 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3041 let pat = self.parse_pat()?;
3042 self.expect_keyword(keywords::In)?;
3043 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3044 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3045 attrs.extend(iattrs);
3047 let hi = self.prev_span;
3048 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3051 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3052 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3054 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3055 if self.token.is_keyword(keywords::Let) {
3056 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3058 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3059 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3060 attrs.extend(iattrs);
3061 let span = span_lo.to(body.span);
3062 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3065 /// Parse a 'while let' expression ('while' token already eaten)
3066 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3068 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3069 self.expect_keyword(keywords::Let)?;
3070 let pat = self.parse_pat()?;
3071 self.expect(&token::Eq)?;
3072 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3073 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3074 attrs.extend(iattrs);
3075 let span = span_lo.to(body.span);
3076 return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3079 // parse `loop {...}`, `loop` token already eaten
3080 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3082 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3083 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3084 attrs.extend(iattrs);
3085 let span = span_lo.to(body.span);
3086 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3089 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3090 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3091 -> PResult<'a, P<Expr>>
3093 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3094 attrs.extend(iattrs);
3095 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3098 // `match` token already eaten
3099 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3100 let match_span = self.prev_span;
3101 let lo = self.prev_span;
3102 let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL,
3104 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3105 if self.token == token::Token::Semi {
3106 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3110 attrs.extend(self.parse_inner_attributes()?);
3112 let mut arms: Vec<Arm> = Vec::new();
3113 while self.token != token::CloseDelim(token::Brace) {
3114 match self.parse_arm() {
3115 Ok(arm) => arms.push(arm),
3117 // Recover by skipping to the end of the block.
3119 self.recover_stmt();
3120 let span = lo.to(self.span);
3121 if self.token == token::CloseDelim(token::Brace) {
3124 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3130 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3133 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3134 maybe_whole!(self, NtArm, |x| x);
3136 let attrs = self.parse_outer_attributes()?;
3137 let pats = self.parse_pats()?;
3138 let guard = if self.eat_keyword(keywords::If) {
3139 Some(self.parse_expr()?)
3143 self.expect(&token::FatArrow)?;
3144 let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR, None)?;
3146 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3147 && self.token != token::CloseDelim(token::Brace);
3150 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3152 self.eat(&token::Comma);
3163 /// Parse an expression
3164 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3165 self.parse_expr_res(Restrictions::empty(), None)
3168 /// Evaluate the closure with restrictions in place.
3170 /// After the closure is evaluated, restrictions are reset.
3171 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3172 where F: FnOnce(&mut Self) -> T
3174 let old = self.restrictions;
3175 self.restrictions = r;
3177 self.restrictions = old;
3182 /// Parse an expression, subject to the given restrictions
3183 pub fn parse_expr_res(&mut self, r: Restrictions,
3184 already_parsed_attrs: Option<ThinVec<Attribute>>)
3185 -> PResult<'a, P<Expr>> {
3186 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3189 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3190 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3191 if self.check(&token::Eq) {
3193 Ok(Some(self.parse_expr()?))
3199 /// Parse patterns, separated by '|' s
3200 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3201 let mut pats = Vec::new();
3203 pats.push(self.parse_pat()?);
3204 if self.check(&token::BinOp(token::Or)) { self.bump();}
3205 else { return Ok(pats); }
3209 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3210 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3211 let mut fields = vec![];
3212 let mut ddpos = None;
3214 while !self.check(&token::CloseDelim(token::Paren)) {
3215 if ddpos.is_none() && self.eat(&token::DotDot) {
3216 ddpos = Some(fields.len());
3217 if self.eat(&token::Comma) {
3218 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3219 fields.push(self.parse_pat()?);
3221 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3222 // Emit a friendly error, ignore `..` and continue parsing
3223 self.span_err(self.prev_span, "`..` can only be used once per \
3224 tuple or tuple struct pattern");
3226 fields.push(self.parse_pat()?);
3229 if !self.check(&token::CloseDelim(token::Paren)) ||
3230 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3231 self.expect(&token::Comma)?;
3238 fn parse_pat_vec_elements(
3240 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3241 let mut before = Vec::new();
3242 let mut slice = None;
3243 let mut after = Vec::new();
3244 let mut first = true;
3245 let mut before_slice = true;
3247 while self.token != token::CloseDelim(token::Bracket) {
3251 self.expect(&token::Comma)?;
3253 if self.token == token::CloseDelim(token::Bracket)
3254 && (before_slice || !after.is_empty()) {
3260 if self.eat(&token::DotDot) {
3262 if self.check(&token::Comma) ||
3263 self.check(&token::CloseDelim(token::Bracket)) {
3264 slice = Some(P(ast::Pat {
3265 id: ast::DUMMY_NODE_ID,
3266 node: PatKind::Wild,
3269 before_slice = false;
3275 let subpat = self.parse_pat()?;
3276 if before_slice && self.eat(&token::DotDot) {
3277 slice = Some(subpat);
3278 before_slice = false;
3279 } else if before_slice {
3280 before.push(subpat);
3286 Ok((before, slice, after))
3289 /// Parse the fields of a struct-like pattern
3290 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3291 let mut fields = Vec::new();
3292 let mut etc = false;
3293 let mut first = true;
3294 while self.token != token::CloseDelim(token::Brace) {
3298 self.expect(&token::Comma)?;
3299 // accept trailing commas
3300 if self.check(&token::CloseDelim(token::Brace)) { break }
3303 let attrs = self.parse_outer_attributes()?;
3307 if self.check(&token::DotDot) {
3309 if self.token != token::CloseDelim(token::Brace) {
3310 let token_str = self.this_token_to_string();
3311 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3318 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3319 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3320 // Parsing a pattern of the form "fieldname: pat"
3321 let fieldname = self.parse_field_name()?;
3323 let pat = self.parse_pat()?;
3325 (pat, fieldname, false)
3327 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3328 let is_box = self.eat_keyword(keywords::Box);
3329 let boxed_span = self.span;
3330 let is_ref = self.eat_keyword(keywords::Ref);
3331 let is_mut = self.eat_keyword(keywords::Mut);
3332 let fieldname = self.parse_ident()?;
3333 hi = self.prev_span;
3335 let bind_type = match (is_ref, is_mut) {
3336 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3337 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3338 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3339 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3341 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3342 let fieldpat = P(ast::Pat{
3343 id: ast::DUMMY_NODE_ID,
3344 node: PatKind::Ident(bind_type, fieldpath, None),
3345 span: boxed_span.to(hi),
3348 let subpat = if is_box {
3350 id: ast::DUMMY_NODE_ID,
3351 node: PatKind::Box(fieldpat),
3357 (subpat, fieldname, true)
3360 fields.push(codemap::Spanned { span: lo.to(hi),
3361 node: ast::FieldPat {
3364 is_shorthand: is_shorthand,
3365 attrs: attrs.into(),
3369 return Ok((fields, etc));
3372 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3373 if self.token.is_path_start() {
3375 let (qself, path) = if self.eat_lt() {
3376 // Parse a qualified path
3377 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3380 // Parse an unqualified path
3381 (None, self.parse_path(PathStyle::Expr)?)
3383 let hi = self.prev_span;
3384 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3386 self.parse_pat_literal_maybe_minus()
3390 // helper function to decide whether to parse as ident binding or to try to do
3391 // something more complex like range patterns
3392 fn parse_as_ident(&mut self) -> bool {
3393 self.look_ahead(1, |t| match *t {
3394 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3395 token::DotDotDot | token::ModSep | token::Not => Some(false),
3396 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3397 // range pattern branch
3398 token::DotDot => None,
3400 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3401 token::Comma | token::CloseDelim(token::Bracket) => true,
3406 /// Parse a pattern.
3407 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3408 maybe_whole!(self, NtPat, |x| x);
3413 token::Underscore => {
3416 pat = PatKind::Wild;
3418 token::BinOp(token::And) | token::AndAnd => {
3419 // Parse &pat / &mut pat
3421 let mutbl = self.parse_mutability();
3422 if let token::Lifetime(ident) = self.token {
3423 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3425 let subpat = self.parse_pat()?;
3426 pat = PatKind::Ref(subpat, mutbl);
3428 token::OpenDelim(token::Paren) => {
3429 // Parse (pat,pat,pat,...) as tuple pattern
3431 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3432 self.expect(&token::CloseDelim(token::Paren))?;
3433 pat = PatKind::Tuple(fields, ddpos);
3435 token::OpenDelim(token::Bracket) => {
3436 // Parse [pat,pat,...] as slice pattern
3438 let (before, slice, after) = self.parse_pat_vec_elements()?;
3439 self.expect(&token::CloseDelim(token::Bracket))?;
3440 pat = PatKind::Slice(before, slice, after);
3442 // At this point, token != _, &, &&, (, [
3443 _ => if self.eat_keyword(keywords::Mut) {
3444 // Parse mut ident @ pat / mut ref ident @ pat
3445 let mutref_span = self.prev_span.to(self.span);
3446 let binding_mode = if self.eat_keyword(keywords::Ref) {
3448 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3449 .span_suggestion(mutref_span, "try switching the order", "ref mut".into())
3451 BindingMode::ByRef(Mutability::Mutable)
3453 BindingMode::ByValue(Mutability::Mutable)
3455 pat = self.parse_pat_ident(binding_mode)?;
3456 } else if self.eat_keyword(keywords::Ref) {
3457 // Parse ref ident @ pat / ref mut ident @ pat
3458 let mutbl = self.parse_mutability();
3459 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3460 } else if self.eat_keyword(keywords::Box) {
3462 let subpat = self.parse_pat()?;
3463 pat = PatKind::Box(subpat);
3464 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3465 self.parse_as_ident() {
3466 // Parse ident @ pat
3467 // This can give false positives and parse nullary enums,
3468 // they are dealt with later in resolve
3469 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3470 pat = self.parse_pat_ident(binding_mode)?;
3471 } else if self.token.is_path_start() {
3472 // Parse pattern starting with a path
3473 let (qself, path) = if self.eat_lt() {
3474 // Parse a qualified path
3475 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3478 // Parse an unqualified path
3479 (None, self.parse_path(PathStyle::Expr)?)
3482 token::Not if qself.is_none() => {
3483 // Parse macro invocation
3485 let (_, tts) = self.expect_delimited_token_tree()?;
3486 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3487 pat = PatKind::Mac(mac);
3489 token::DotDotDot | token::DotDot => {
3490 let end_kind = match self.token {
3491 token::DotDot => RangeEnd::Excluded,
3492 token::DotDotDot => RangeEnd::Included,
3493 _ => panic!("can only parse `..` or `...` for ranges (checked above)"),
3496 let span = lo.to(self.prev_span);
3497 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3499 let end = self.parse_pat_range_end()?;
3500 pat = PatKind::Range(begin, end, end_kind);
3502 token::OpenDelim(token::Brace) => {
3503 if qself.is_some() {
3504 return Err(self.fatal("unexpected `{` after qualified path"));
3506 // Parse struct pattern
3508 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3510 self.recover_stmt();
3514 pat = PatKind::Struct(path, fields, etc);
3516 token::OpenDelim(token::Paren) => {
3517 if qself.is_some() {
3518 return Err(self.fatal("unexpected `(` after qualified path"));
3520 // Parse tuple struct or enum pattern
3522 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3523 self.expect(&token::CloseDelim(token::Paren))?;
3524 pat = PatKind::TupleStruct(path, fields, ddpos)
3526 _ => pat = PatKind::Path(qself, path),
3529 // Try to parse everything else as literal with optional minus
3530 match self.parse_pat_literal_maybe_minus() {
3532 if self.eat(&token::DotDotDot) {
3533 let end = self.parse_pat_range_end()?;
3534 pat = PatKind::Range(begin, end, RangeEnd::Included);
3535 } else if self.eat(&token::DotDot) {
3536 let end = self.parse_pat_range_end()?;
3537 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3539 pat = PatKind::Lit(begin);
3543 self.cancel(&mut err);
3544 let msg = format!("expected pattern, found {}", self.this_token_descr());
3545 return Err(self.fatal(&msg));
3552 id: ast::DUMMY_NODE_ID,
3554 span: lo.to(self.prev_span),
3558 /// Parse ident or ident @ pat
3559 /// used by the copy foo and ref foo patterns to give a good
3560 /// error message when parsing mistakes like ref foo(a,b)
3561 fn parse_pat_ident(&mut self,
3562 binding_mode: ast::BindingMode)
3563 -> PResult<'a, PatKind> {
3564 let ident_span = self.span;
3565 let ident = self.parse_ident()?;
3566 let name = codemap::Spanned{span: ident_span, node: ident};
3567 let sub = if self.eat(&token::At) {
3568 Some(self.parse_pat()?)
3573 // just to be friendly, if they write something like
3575 // we end up here with ( as the current token. This shortly
3576 // leads to a parse error. Note that if there is no explicit
3577 // binding mode then we do not end up here, because the lookahead
3578 // will direct us over to parse_enum_variant()
3579 if self.token == token::OpenDelim(token::Paren) {
3580 return Err(self.span_fatal(
3582 "expected identifier, found enum pattern"))
3585 Ok(PatKind::Ident(binding_mode, name, sub))
3588 /// Parse a local variable declaration
3589 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3591 let pat = self.parse_pat()?;
3593 let ty = if self.eat(&token::Colon) {
3594 Some(self.parse_ty()?)
3598 let init = self.parse_initializer()?;
3603 id: ast::DUMMY_NODE_ID,
3604 span: lo.to(self.prev_span),
3609 /// Parse a structure field
3610 fn parse_name_and_ty(&mut self,
3613 attrs: Vec<Attribute>)
3614 -> PResult<'a, StructField> {
3615 let name = self.parse_ident()?;
3616 self.expect(&token::Colon)?;
3617 let ty = self.parse_ty()?;
3619 span: lo.to(self.prev_span),
3622 id: ast::DUMMY_NODE_ID,
3628 /// Emit an expected item after attributes error.
3629 fn expected_item_err(&self, attrs: &[Attribute]) {
3630 let message = match attrs.last() {
3631 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3632 _ => "expected item after attributes",
3635 self.span_err(self.prev_span, message);
3638 /// Parse a statement. This stops just before trailing semicolons on everything but items.
3639 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3640 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3641 Ok(self.parse_stmt_(true))
3644 // Eat tokens until we can be relatively sure we reached the end of the
3645 // statement. This is something of a best-effort heuristic.
3647 // We terminate when we find an unmatched `}` (without consuming it).
3648 fn recover_stmt(&mut self) {
3649 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
3652 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3653 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3654 // approximate - it can mean we break too early due to macros, but that
3655 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3657 // If `break_on_block` is `Break`, then we will stop consuming tokens
3658 // after finding (and consuming) a brace-delimited block.
3659 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
3660 let mut brace_depth = 0;
3661 let mut bracket_depth = 0;
3662 let mut in_block = false;
3663 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
3664 break_on_semi, break_on_block);
3666 debug!("recover_stmt_ loop {:?}", self.token);
3668 token::OpenDelim(token::DelimToken::Brace) => {
3671 if break_on_block == BlockMode::Break &&
3673 bracket_depth == 0 {
3677 token::OpenDelim(token::DelimToken::Bracket) => {
3681 token::CloseDelim(token::DelimToken::Brace) => {
3682 if brace_depth == 0 {
3683 debug!("recover_stmt_ return - close delim {:?}", self.token);
3688 if in_block && bracket_depth == 0 && brace_depth == 0 {
3689 debug!("recover_stmt_ return - block end {:?}", self.token);
3693 token::CloseDelim(token::DelimToken::Bracket) => {
3695 if bracket_depth < 0 {
3701 debug!("recover_stmt_ return - Eof");
3706 if break_on_semi == SemiColonMode::Break &&
3708 bracket_depth == 0 {
3709 debug!("recover_stmt_ return - Semi");
3720 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
3721 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
3723 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
3728 fn is_catch_expr(&mut self) -> bool {
3729 self.token.is_keyword(keywords::Do) &&
3730 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
3731 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
3733 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3734 !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL)
3737 fn is_union_item(&self) -> bool {
3738 self.token.is_keyword(keywords::Union) &&
3739 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
3742 fn is_defaultness(&self) -> bool {
3743 // `pub` is included for better error messages
3744 self.token.is_keyword(keywords::Default) &&
3745 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
3746 t.is_keyword(keywords::Const) ||
3747 t.is_keyword(keywords::Fn) ||
3748 t.is_keyword(keywords::Unsafe) ||
3749 t.is_keyword(keywords::Extern) ||
3750 t.is_keyword(keywords::Type) ||
3751 t.is_keyword(keywords::Pub))
3754 fn eat_defaultness(&mut self) -> bool {
3755 let is_defaultness = self.is_defaultness();
3759 self.expected_tokens.push(TokenType::Keyword(keywords::Default));
3764 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility)
3765 -> PResult<'a, Option<P<Item>>> {
3767 let (ident, def) = match self.token {
3768 token::Ident(ident) if ident.name == keywords::Macro.name() => {
3770 let ident = self.parse_ident()?;
3771 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
3772 match self.parse_token_tree() {
3773 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
3774 _ => unreachable!(),
3776 } else if self.check(&token::OpenDelim(token::Paren)) {
3777 let args = self.parse_token_tree();
3778 let body = if self.check(&token::OpenDelim(token::Brace)) {
3779 self.parse_token_tree()
3784 TokenStream::concat(vec![
3786 TokenTree::Token(lo.to(self.prev_span), token::FatArrow).into(),
3794 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
3796 token::Ident(ident) if ident.name == "macro_rules" &&
3797 self.look_ahead(1, |t| *t == token::Not) => {
3798 let prev_span = self.prev_span;
3799 self.complain_if_pub_macro(vis, prev_span);
3803 let ident = self.parse_ident()?;
3804 let (delim, tokens) = self.expect_delimited_token_tree()?;
3805 if delim != token::Brace {
3806 if !self.eat(&token::Semi) {
3807 let msg = "macros that expand to items must either \
3808 be surrounded with braces or followed by a semicolon";
3809 self.span_err(self.prev_span, msg);
3813 (ident, ast::MacroDef { tokens: tokens, legacy: true })
3815 _ => return Ok(None),
3818 let span = lo.to(self.prev_span);
3819 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
3822 fn parse_stmt_without_recovery(&mut self,
3823 macro_legacy_warnings: bool)
3824 -> PResult<'a, Option<Stmt>> {
3825 maybe_whole!(self, NtStmt, |x| Some(x));
3827 let attrs = self.parse_outer_attributes()?;
3830 Ok(Some(if self.eat_keyword(keywords::Let) {
3832 id: ast::DUMMY_NODE_ID,
3833 node: StmtKind::Local(self.parse_local(attrs.into())?),
3834 span: lo.to(self.prev_span),
3836 } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited)? {
3838 id: ast::DUMMY_NODE_ID,
3839 node: StmtKind::Item(macro_def),
3840 span: lo.to(self.prev_span),
3842 // Starts like a simple path, but not a union item.
3843 } else if self.token.is_path_start() &&
3844 !self.token.is_qpath_start() &&
3845 !self.is_union_item() {
3846 let pth = self.parse_path(PathStyle::Expr)?;
3848 if !self.eat(&token::Not) {
3849 let expr = if self.check(&token::OpenDelim(token::Brace)) {
3850 self.parse_struct_expr(lo, pth, ThinVec::new())?
3852 let hi = self.prev_span;
3853 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
3856 let expr = self.with_res(RESTRICTION_STMT_EXPR, |this| {
3857 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
3858 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
3861 return Ok(Some(Stmt {
3862 id: ast::DUMMY_NODE_ID,
3863 node: StmtKind::Expr(expr),
3864 span: lo.to(self.prev_span),
3868 // it's a macro invocation
3869 let id = match self.token {
3870 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
3871 _ => self.parse_ident()?,
3874 // check that we're pointing at delimiters (need to check
3875 // again after the `if`, because of `parse_ident`
3876 // consuming more tokens).
3877 let delim = match self.token {
3878 token::OpenDelim(delim) => delim,
3880 // we only expect an ident if we didn't parse one
3882 let ident_str = if id.name == keywords::Invalid.name() {
3887 let tok_str = self.this_token_to_string();
3888 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3894 let (_, tts) = self.expect_delimited_token_tree()?;
3895 let hi = self.prev_span;
3897 let style = if delim == token::Brace {
3898 MacStmtStyle::Braces
3900 MacStmtStyle::NoBraces
3903 if id.name == keywords::Invalid.name() {
3904 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
3905 let node = if delim == token::Brace ||
3906 self.token == token::Semi || self.token == token::Eof {
3907 StmtKind::Mac(P((mac, style, attrs.into())))
3909 // We used to incorrectly stop parsing macro-expanded statements here.
3910 // If the next token will be an error anyway but could have parsed with the
3911 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
3912 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
3913 // These can continue an expression, so we can't stop parsing and warn.
3914 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
3915 token::BinOp(token::Minus) | token::BinOp(token::Star) |
3916 token::BinOp(token::And) | token::BinOp(token::Or) |
3917 token::AndAnd | token::OrOr |
3918 token::DotDot | token::DotDotDot => false,
3921 self.warn_missing_semicolon();
3922 StmtKind::Mac(P((mac, style, attrs.into())))
3924 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
3925 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
3926 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
3930 id: ast::DUMMY_NODE_ID,
3935 // if it has a special ident, it's definitely an item
3937 // Require a semicolon or braces.
3938 if style != MacStmtStyle::Braces {
3939 if !self.eat(&token::Semi) {
3940 self.span_err(self.prev_span,
3941 "macros that expand to items must \
3942 either be surrounded with braces or \
3943 followed by a semicolon");
3946 let span = lo.to(hi);
3948 id: ast::DUMMY_NODE_ID,
3950 node: StmtKind::Item({
3952 span, id /*id is good here*/,
3953 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
3954 Visibility::Inherited,
3960 // FIXME: Bad copy of attrs
3961 let old_directory_ownership =
3962 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
3963 let item = self.parse_item_(attrs.clone(), false, true)?;
3964 self.directory.ownership = old_directory_ownership;
3968 id: ast::DUMMY_NODE_ID,
3969 span: lo.to(i.span),
3970 node: StmtKind::Item(i),
3973 let unused_attrs = |attrs: &[_], s: &mut Self| {
3974 if !attrs.is_empty() {
3975 if s.prev_token_kind == PrevTokenKind::DocComment {
3976 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
3978 s.span_err(s.span, "expected statement after outer attribute");
3983 // Do not attempt to parse an expression if we're done here.
3984 if self.token == token::Semi {
3985 unused_attrs(&attrs, self);
3990 if self.token == token::CloseDelim(token::Brace) {
3991 unused_attrs(&attrs, self);
3995 // Remainder are line-expr stmts.
3996 let e = self.parse_expr_res(
3997 RESTRICTION_STMT_EXPR, Some(attrs.into()))?;
3999 id: ast::DUMMY_NODE_ID,
4000 span: lo.to(e.span),
4001 node: StmtKind::Expr(e),
4008 /// Is this expression a successfully-parsed statement?
4009 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4010 self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
4011 !classify::expr_requires_semi_to_be_stmt(e)
4014 /// Parse a block. No inner attrs are allowed.
4015 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4016 maybe_whole!(self, NtBlock, |x| x);
4020 if !self.eat(&token::OpenDelim(token::Brace)) {
4022 let tok = self.this_token_to_string();
4023 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4025 // Check to see if the user has written something like
4030 // Which is valid in other languages, but not Rust.
4031 match self.parse_stmt_without_recovery(false) {
4033 let mut stmt_span = stmt.span;
4034 // expand the span to include the semicolon, if it exists
4035 if self.eat(&token::Semi) {
4036 stmt_span.hi = self.prev_span.hi;
4038 let sugg = pprust::to_string(|s| {
4039 use print::pprust::{PrintState, INDENT_UNIT};
4040 s.ibox(INDENT_UNIT)?;
4042 s.print_stmt(&stmt)?;
4043 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4045 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4048 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4049 self.cancel(&mut e);
4056 self.parse_block_tail(lo, BlockCheckMode::Default)
4059 /// Parse a block. Inner attrs are allowed.
4060 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4061 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4064 self.expect(&token::OpenDelim(token::Brace))?;
4065 Ok((self.parse_inner_attributes()?,
4066 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4069 /// Parse the rest of a block expression or function body
4070 /// Precondition: already parsed the '{'.
4071 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4072 let mut stmts = vec![];
4074 while !self.eat(&token::CloseDelim(token::Brace)) {
4075 if let Some(stmt) = self.parse_full_stmt(false)? {
4077 } else if self.token == token::Eof {
4080 // Found only `;` or `}`.
4087 id: ast::DUMMY_NODE_ID,
4089 span: lo.to(self.prev_span),
4093 /// Parse a statement, including the trailing semicolon.
4094 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4095 let mut stmt = match self.parse_stmt_(macro_legacy_warnings) {
4097 None => return Ok(None),
4101 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4102 // expression without semicolon
4103 if classify::expr_requires_semi_to_be_stmt(expr) {
4104 // Just check for errors and recover; do not eat semicolon yet.
4106 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4109 self.recover_stmt();
4113 StmtKind::Local(..) => {
4114 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4115 if macro_legacy_warnings && self.token != token::Semi {
4116 self.warn_missing_semicolon();
4118 self.expect_one_of(&[token::Semi], &[])?;
4124 if self.eat(&token::Semi) {
4125 stmt = stmt.add_trailing_semicolon();
4128 stmt.span.hi = self.prev_span.hi;
4132 fn warn_missing_semicolon(&self) {
4133 self.diagnostic().struct_span_warn(self.span, {
4134 &format!("expected `;`, found `{}`", self.this_token_to_string())
4136 "This was erroneously allowed and will become a hard error in a future release"
4140 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4141 // BOUND = TY_BOUND | LT_BOUND
4142 // LT_BOUND = LIFETIME (e.g. `'a`)
4143 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4144 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4145 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4146 let mut bounds = Vec::new();
4148 let is_bound_start = self.check_path() || self.check_lifetime() ||
4149 self.check(&token::Question) ||
4150 self.check_keyword(keywords::For) ||
4151 self.check(&token::OpenDelim(token::Paren));
4153 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4154 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4155 if self.token.is_lifetime() {
4156 if let Some(question_span) = question {
4157 self.span_err(question_span,
4158 "`?` may only modify trait bounds, not lifetime bounds");
4160 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4163 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4164 let path = self.parse_path(PathStyle::Type)?;
4165 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4166 let modifier = if question.is_some() {
4167 TraitBoundModifier::Maybe
4169 TraitBoundModifier::None
4171 bounds.push(TraitTyParamBound(poly_trait, modifier));
4174 self.expect(&token::CloseDelim(token::Paren))?;
4175 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4176 self.span_err(self.prev_span,
4177 "parenthesized lifetime bounds are not supported");
4184 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4192 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4193 self.parse_ty_param_bounds_common(true)
4196 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4197 // BOUND = LT_BOUND (e.g. `'a`)
4198 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4199 let mut lifetimes = Vec::new();
4200 while self.check_lifetime() {
4201 lifetimes.push(self.expect_lifetime());
4203 if !self.eat(&token::BinOp(token::Plus)) {
4210 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4211 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4212 let span = self.span;
4213 let ident = self.parse_ident()?;
4215 // Parse optional colon and param bounds.
4216 let bounds = if self.eat(&token::Colon) {
4217 self.parse_ty_param_bounds()?
4222 let default = if self.eat(&token::Eq) {
4223 Some(self.parse_ty()?)
4229 attrs: preceding_attrs.into(),
4231 id: ast::DUMMY_NODE_ID,
4238 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4239 /// trailing comma and erroneous trailing attributes.
4240 pub fn parse_generic_params(&mut self) -> PResult<'a, (Vec<LifetimeDef>, Vec<TyParam>)> {
4241 let mut lifetime_defs = Vec::new();
4242 let mut ty_params = Vec::new();
4243 let mut seen_ty_param = false;
4245 let attrs = self.parse_outer_attributes()?;
4246 if self.check_lifetime() {
4247 let lifetime = self.expect_lifetime();
4248 // Parse lifetime parameter.
4249 let bounds = if self.eat(&token::Colon) {
4250 self.parse_lt_param_bounds()
4254 lifetime_defs.push(LifetimeDef {
4255 attrs: attrs.into(),
4260 self.span_err(self.prev_span,
4261 "lifetime parameters must be declared prior to type parameters");
4263 } else if self.check_ident() {
4264 // Parse type parameter.
4265 ty_params.push(self.parse_ty_param(attrs)?);
4266 seen_ty_param = true;
4268 // Check for trailing attributes and stop parsing.
4269 if !attrs.is_empty() {
4270 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4271 self.span_err(attrs[0].span,
4272 &format!("trailing attribute after {} parameters", param_kind));
4277 if !self.eat(&token::Comma) {
4281 Ok((lifetime_defs, ty_params))
4284 /// Parse a set of optional generic type parameter declarations. Where
4285 /// clauses are not parsed here, and must be added later via
4286 /// `parse_where_clause()`.
4288 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4289 /// | ( < lifetimes , typaramseq ( , )? > )
4290 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4291 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4292 maybe_whole!(self, NtGenerics, |x| x);
4294 let span_lo = self.span;
4296 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4299 lifetimes: lifetime_defs,
4300 ty_params: ty_params,
4301 where_clause: WhereClause {
4302 id: ast::DUMMY_NODE_ID,
4303 predicates: Vec::new(),
4304 span: syntax_pos::DUMMY_SP,
4306 span: span_lo.to(self.prev_span),
4309 Ok(ast::Generics::default())
4313 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4314 /// possibly including trailing comma.
4315 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4316 let mut lifetimes = Vec::new();
4317 let mut types = Vec::new();
4318 let mut bindings = Vec::new();
4319 let mut seen_type = false;
4320 let mut seen_binding = false;
4322 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4323 // Parse lifetime argument.
4324 lifetimes.push(self.expect_lifetime());
4325 if seen_type || seen_binding {
4326 self.span_err(self.prev_span,
4327 "lifetime parameters must be declared prior to type parameters");
4329 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4330 // Parse associated type binding.
4332 let ident = self.parse_ident()?;
4334 let ty = self.parse_ty()?;
4335 bindings.push(TypeBinding {
4336 id: ast::DUMMY_NODE_ID,
4339 span: lo.to(self.prev_span),
4341 seen_binding = true;
4342 } else if self.check_type() {
4343 // Parse type argument.
4344 types.push(self.parse_ty()?);
4346 self.span_err(types[types.len() - 1].span,
4347 "type parameters must be declared prior to associated type bindings");
4354 if !self.eat(&token::Comma) {
4358 Ok((lifetimes, types, bindings))
4361 /// Parses an optional `where` clause and places it in `generics`.
4363 /// ```ignore (only-for-syntax-highlight)
4364 /// where T : Trait<U, V> + 'b, 'a : 'b
4366 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4367 maybe_whole!(self, NtWhereClause, |x| x);
4369 let mut where_clause = WhereClause {
4370 id: ast::DUMMY_NODE_ID,
4371 predicates: Vec::new(),
4372 span: syntax_pos::DUMMY_SP,
4375 if !self.eat_keyword(keywords::Where) {
4376 return Ok(where_clause);
4378 let lo = self.prev_span;
4380 // This is a temporary future proofing.
4382 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4383 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4384 // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4385 if token::Lt == self.token {
4386 let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4387 if ident_or_lifetime {
4388 let gt_comma_or_colon = self.look_ahead(2, |t| {
4389 *t == token::Gt || *t == token::Comma || *t == token::Colon
4391 if gt_comma_or_colon {
4392 self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4399 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4400 let lifetime = self.expect_lifetime();
4401 // Bounds starting with a colon are mandatory, but possibly empty.
4402 self.expect(&token::Colon)?;
4403 let bounds = self.parse_lt_param_bounds();
4404 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4405 ast::WhereRegionPredicate {
4406 span: lo.to(self.prev_span),
4411 } else if self.check_type() {
4412 // Parse optional `for<'a, 'b>`.
4413 // This `for` is parsed greedily and applies to the whole predicate,
4414 // the bounded type can have its own `for` applying only to it.
4415 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4416 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4417 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4418 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4420 // Parse type with mandatory colon and (possibly empty) bounds,
4421 // or with mandatory equality sign and the second type.
4422 let ty = self.parse_ty()?;
4423 if self.eat(&token::Colon) {
4424 let bounds = self.parse_ty_param_bounds()?;
4425 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4426 ast::WhereBoundPredicate {
4427 span: lo.to(self.prev_span),
4428 bound_lifetimes: lifetime_defs,
4433 // FIXME: Decide what should be used here, `=` or `==`.
4434 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4435 let rhs_ty = self.parse_ty()?;
4436 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4437 ast::WhereEqPredicate {
4438 span: lo.to(self.prev_span),
4441 id: ast::DUMMY_NODE_ID,
4445 return self.unexpected();
4451 if !self.eat(&token::Comma) {
4456 where_clause.span = lo.to(self.prev_span);
4460 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4461 -> PResult<'a, (Vec<Arg> , bool)> {
4463 let mut variadic = false;
4464 let args: Vec<Option<Arg>> =
4465 self.parse_unspanned_seq(
4466 &token::OpenDelim(token::Paren),
4467 &token::CloseDelim(token::Paren),
4468 SeqSep::trailing_allowed(token::Comma),
4470 if p.token == token::DotDotDot {
4473 if p.token != token::CloseDelim(token::Paren) {
4476 "`...` must be last in argument list for variadic function");
4481 "only foreign functions are allowed to be variadic");
4486 match p.parse_arg_general(named_args) {
4487 Ok(arg) => Ok(Some(arg)),
4490 let lo = p.prev_span;
4491 // Skip every token until next possible arg or end.
4492 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4493 // Create a placeholder argument for proper arg count (#34264).
4494 let span = lo.to(p.prev_span);
4495 Ok(Some(dummy_arg(span)))
4502 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4504 if variadic && args.is_empty() {
4506 "variadic function must be declared with at least one named argument");
4509 Ok((args, variadic))
4512 /// Parse the argument list and result type of a function declaration
4513 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4515 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4516 let ret_ty = self.parse_ret_ty()?;
4525 /// Returns the parsed optional self argument and whether a self shortcut was used.
4526 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4527 let expect_ident = |this: &mut Self| match this.token {
4528 // Preserve hygienic context.
4529 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4532 let isolated_self = |this: &mut Self, n| {
4533 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4534 this.look_ahead(n + 1, |t| t != &token::ModSep)
4537 // Parse optional self parameter of a method.
4538 // Only a limited set of initial token sequences is considered self parameters, anything
4539 // else is parsed as a normal function parameter list, so some lookahead is required.
4540 let eself_lo = self.span;
4541 let (eself, eself_ident) = match self.token {
4542 token::BinOp(token::And) => {
4548 if isolated_self(self, 1) {
4550 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4551 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4552 isolated_self(self, 2) {
4555 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4556 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4557 isolated_self(self, 2) {
4559 let lt = self.expect_lifetime();
4560 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4561 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4562 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4563 isolated_self(self, 3) {
4565 let lt = self.expect_lifetime();
4567 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4572 token::BinOp(token::Star) => {
4577 // Emit special error for `self` cases.
4578 if isolated_self(self, 1) {
4580 self.span_err(self.span, "cannot pass `self` by raw pointer");
4581 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4582 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4583 isolated_self(self, 2) {
4586 self.span_err(self.span, "cannot pass `self` by raw pointer");
4587 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4592 token::Ident(..) => {
4593 if isolated_self(self, 0) {
4596 let eself_ident = expect_ident(self);
4597 if self.eat(&token::Colon) {
4598 let ty = self.parse_ty()?;
4599 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4601 (SelfKind::Value(Mutability::Immutable), eself_ident)
4603 } else if self.token.is_keyword(keywords::Mut) &&
4604 isolated_self(self, 1) {
4608 let eself_ident = expect_ident(self);
4609 if self.eat(&token::Colon) {
4610 let ty = self.parse_ty()?;
4611 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4613 (SelfKind::Value(Mutability::Mutable), eself_ident)
4619 _ => return Ok(None),
4622 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
4623 Ok(Some(Arg::from_self(eself, eself_ident)))
4626 /// Parse the parameter list and result type of a function that may have a `self` parameter.
4627 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
4628 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4630 self.expect(&token::OpenDelim(token::Paren))?;
4632 // Parse optional self argument
4633 let self_arg = self.parse_self_arg()?;
4635 // Parse the rest of the function parameter list.
4636 let sep = SeqSep::trailing_allowed(token::Comma);
4637 let fn_inputs = if let Some(self_arg) = self_arg {
4638 if self.check(&token::CloseDelim(token::Paren)) {
4640 } else if self.eat(&token::Comma) {
4641 let mut fn_inputs = vec![self_arg];
4642 fn_inputs.append(&mut self.parse_seq_to_before_end(
4643 &token::CloseDelim(token::Paren), sep, parse_arg_fn)
4647 return self.unexpected();
4650 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4653 // Parse closing paren and return type.
4654 self.expect(&token::CloseDelim(token::Paren))?;
4657 output: self.parse_ret_ty()?,
4662 // parse the |arg, arg| header on a lambda
4663 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4664 let inputs_captures = {
4665 if self.eat(&token::OrOr) {
4668 self.expect(&token::BinOp(token::Or))?;
4669 let args = self.parse_seq_to_before_end(
4670 &token::BinOp(token::Or),
4671 SeqSep::trailing_allowed(token::Comma),
4672 |p| p.parse_fn_block_arg()
4678 let output = self.parse_ret_ty()?;
4681 inputs: inputs_captures,
4687 /// Parse the name and optional generic types of a function header.
4688 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4689 let id = self.parse_ident()?;
4690 let generics = self.parse_generics()?;
4694 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
4695 attrs: Vec<Attribute>) -> P<Item> {
4699 id: ast::DUMMY_NODE_ID,
4707 /// Parse an item-position function declaration.
4708 fn parse_item_fn(&mut self,
4710 constness: Spanned<Constness>,
4712 -> PResult<'a, ItemInfo> {
4713 let (ident, mut generics) = self.parse_fn_header()?;
4714 let decl = self.parse_fn_decl(false)?;
4715 generics.where_clause = self.parse_where_clause()?;
4716 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4717 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4720 /// true if we are looking at `const ID`, false for things like `const fn` etc
4721 pub fn is_const_item(&mut self) -> bool {
4722 self.token.is_keyword(keywords::Const) &&
4723 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4724 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4727 /// parses all the "front matter" for a `fn` declaration, up to
4728 /// and including the `fn` keyword:
4732 /// - `const unsafe fn`
4735 pub fn parse_fn_front_matter(&mut self)
4736 -> PResult<'a, (Spanned<ast::Constness>,
4739 let is_const_fn = self.eat_keyword(keywords::Const);
4740 let const_span = self.prev_span;
4741 let unsafety = self.parse_unsafety()?;
4742 let (constness, unsafety, abi) = if is_const_fn {
4743 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
4745 let abi = if self.eat_keyword(keywords::Extern) {
4746 self.parse_opt_abi()?.unwrap_or(Abi::C)
4750 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
4752 self.expect_keyword(keywords::Fn)?;
4753 Ok((constness, unsafety, abi))
4756 /// Parse an impl item.
4757 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
4758 maybe_whole!(self, NtImplItem, |x| x);
4759 let attrs = self.parse_outer_attributes()?;
4760 let (mut item, tokens) = self.collect_tokens(|this| {
4761 this.parse_impl_item_(at_end, attrs)
4764 // See `parse_item` for why this clause is here.
4765 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
4766 item.tokens = Some(tokens);
4771 fn parse_impl_item_(&mut self,
4773 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
4775 let vis = self.parse_visibility(false)?;
4776 let defaultness = self.parse_defaultness()?;
4777 let (name, node) = if self.eat_keyword(keywords::Type) {
4778 let name = self.parse_ident()?;
4779 self.expect(&token::Eq)?;
4780 let typ = self.parse_ty()?;
4781 self.expect(&token::Semi)?;
4782 (name, ast::ImplItemKind::Type(typ))
4783 } else if self.is_const_item() {
4784 self.expect_keyword(keywords::Const)?;
4785 let name = self.parse_ident()?;
4786 self.expect(&token::Colon)?;
4787 let typ = self.parse_ty()?;
4788 self.expect(&token::Eq)?;
4789 let expr = self.parse_expr()?;
4790 self.expect(&token::Semi)?;
4791 (name, ast::ImplItemKind::Const(typ, expr))
4793 let (name, inner_attrs, node) = self.parse_impl_method(&vis, at_end)?;
4794 attrs.extend(inner_attrs);
4799 id: ast::DUMMY_NODE_ID,
4800 span: lo.to(self.prev_span),
4803 defaultness: defaultness,
4810 fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
4811 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
4816 fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
4818 Visibility::Inherited => Ok(()),
4820 let is_macro_rules: bool = match self.token {
4821 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
4825 let mut err = self.diagnostic()
4826 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
4827 err.help("did you mean #[macro_export]?");
4830 let mut err = self.diagnostic()
4831 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
4832 err.help("try adjusting the macro to put `pub` inside the invocation");
4839 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
4840 -> DiagnosticBuilder<'a>
4842 // Given this code `path(`, it seems like this is not
4843 // setting the visibility of a macro invocation, but rather
4844 // a mistyped method declaration.
4845 // Create a diagnostic pointing out that `fn` is missing.
4847 // x | pub path(&self) {
4848 // | ^ missing `fn`, `type`, or `const`
4850 // ^^ `sp` below will point to this
4851 let sp = prev_span.between(self.prev_span);
4852 let mut err = self.diagnostic().struct_span_err(
4854 &format!("missing `fn`, `type`, or `const` for {}-item declaration",
4856 err.span_label(sp, "missing `fn`, `type`, or `const`");
4860 /// Parse a method or a macro invocation in a trait impl.
4861 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
4862 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4863 // code copied from parse_macro_use_or_failure... abstraction!
4864 if self.token.is_path_start() {
4867 let prev_span = self.prev_span;
4870 let pth = self.parse_path(PathStyle::Mod)?;
4871 if pth.segments.len() == 1 {
4872 if !self.eat(&token::Not) {
4873 return Err(self.missing_assoc_item_kind_err("impl", prev_span));
4876 self.expect(&token::Not)?;
4879 self.complain_if_pub_macro(vis, prev_span);
4881 // eat a matched-delimiter token tree:
4883 let (delim, tts) = self.expect_delimited_token_tree()?;
4884 if delim != token::Brace {
4885 self.expect(&token::Semi)?
4888 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
4889 Ok((keywords::Invalid.ident(), vec![], ast::ImplItemKind::Macro(mac)))
4891 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
4892 let ident = self.parse_ident()?;
4893 let mut generics = self.parse_generics()?;
4894 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
4895 generics.where_clause = self.parse_where_clause()?;
4897 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4898 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4902 constness: constness,
4908 /// Parse trait Foo { ... }
4909 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4910 let ident = self.parse_ident()?;
4911 let mut tps = self.parse_generics()?;
4913 // Parse optional colon and supertrait bounds.
4914 let bounds = if self.eat(&token::Colon) {
4915 self.parse_ty_param_bounds()?
4920 tps.where_clause = self.parse_where_clause()?;
4922 self.expect(&token::OpenDelim(token::Brace))?;
4923 let mut trait_items = vec![];
4924 while !self.eat(&token::CloseDelim(token::Brace)) {
4925 let mut at_end = false;
4926 match self.parse_trait_item(&mut at_end) {
4927 Ok(item) => trait_items.push(item),
4931 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
4936 Ok((ident, ItemKind::Trait(unsafety, tps, bounds, trait_items), None))
4939 /// Parses items implementations variants
4940 /// impl<T> Foo { ... }
4941 /// impl<T> ToString for &'static T { ... }
4942 /// impl Send for .. {}
4943 fn parse_item_impl(&mut self,
4944 unsafety: ast::Unsafety,
4945 defaultness: Defaultness) -> PResult<'a, ItemInfo> {
4946 let impl_span = self.span;
4948 // First, parse type parameters if necessary.
4949 let mut generics = self.parse_generics()?;
4951 // Special case: if the next identifier that follows is '(', don't
4952 // allow this to be parsed as a trait.
4953 let could_be_trait = self.token != token::OpenDelim(token::Paren);
4955 let neg_span = self.span;
4956 let polarity = if self.eat(&token::Not) {
4957 ast::ImplPolarity::Negative
4959 ast::ImplPolarity::Positive
4963 let mut ty = self.parse_ty()?;
4965 // Parse traits, if necessary.
4966 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4967 // New-style trait. Reinterpret the type as a trait.
4969 TyKind::Path(None, ref path) => {
4971 path: (*path).clone(),
4976 self.span_err(ty.span, "not a trait");
4981 if polarity == ast::ImplPolarity::Negative {
4982 // This is a negated type implementation
4983 // `impl !MyType {}`, which is not allowed.
4984 self.span_err(neg_span, "inherent implementation can't be negated");
4989 if opt_trait.is_some() && self.eat(&token::DotDot) {
4990 if generics.is_parameterized() {
4991 self.span_err(impl_span, "default trait implementations are not \
4992 allowed to have generics");
4995 if let ast::Defaultness::Default = defaultness {
4996 self.span_err(impl_span, "`default impl` is not allowed for \
4997 default trait implementations");
5000 self.expect(&token::OpenDelim(token::Brace))?;
5001 self.expect(&token::CloseDelim(token::Brace))?;
5002 Ok((keywords::Invalid.ident(),
5003 ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
5005 if opt_trait.is_some() {
5006 ty = self.parse_ty()?;
5008 generics.where_clause = self.parse_where_clause()?;
5010 self.expect(&token::OpenDelim(token::Brace))?;
5011 let attrs = self.parse_inner_attributes()?;
5013 let mut impl_items = vec![];
5014 while !self.eat(&token::CloseDelim(token::Brace)) {
5015 let mut at_end = false;
5016 match self.parse_impl_item(&mut at_end) {
5017 Ok(item) => impl_items.push(item),
5021 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5027 Ok((keywords::Invalid.ident(),
5028 ItemKind::Impl(unsafety, polarity, defaultness, generics, opt_trait, ty, impl_items),
5033 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<LifetimeDef>> {
5034 if self.eat_keyword(keywords::For) {
5036 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
5038 if !ty_params.is_empty() {
5039 self.span_err(ty_params[0].span,
5040 "only lifetime parameters can be used in this context");
5048 /// Parse struct Foo { ... }
5049 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5050 let class_name = self.parse_ident()?;
5052 let mut generics = self.parse_generics()?;
5054 // There is a special case worth noting here, as reported in issue #17904.
5055 // If we are parsing a tuple struct it is the case that the where clause
5056 // should follow the field list. Like so:
5058 // struct Foo<T>(T) where T: Copy;
5060 // If we are parsing a normal record-style struct it is the case
5061 // that the where clause comes before the body, and after the generics.
5062 // So if we look ahead and see a brace or a where-clause we begin
5063 // parsing a record style struct.
5065 // Otherwise if we look ahead and see a paren we parse a tuple-style
5068 let vdata = if self.token.is_keyword(keywords::Where) {
5069 generics.where_clause = self.parse_where_clause()?;
5070 if self.eat(&token::Semi) {
5071 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5072 VariantData::Unit(ast::DUMMY_NODE_ID)
5074 // If we see: `struct Foo<T> where T: Copy { ... }`
5075 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5077 // No `where` so: `struct Foo<T>;`
5078 } else if self.eat(&token::Semi) {
5079 VariantData::Unit(ast::DUMMY_NODE_ID)
5080 // Record-style struct definition
5081 } else if self.token == token::OpenDelim(token::Brace) {
5082 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5083 // Tuple-style struct definition with optional where-clause.
5084 } else if self.token == token::OpenDelim(token::Paren) {
5085 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5086 generics.where_clause = self.parse_where_clause()?;
5087 self.expect(&token::Semi)?;
5090 let token_str = self.this_token_to_string();
5091 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5092 name, found `{}`", token_str)))
5095 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5098 /// Parse union Foo { ... }
5099 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5100 let class_name = self.parse_ident()?;
5102 let mut generics = self.parse_generics()?;
5104 let vdata = if self.token.is_keyword(keywords::Where) {
5105 generics.where_clause = self.parse_where_clause()?;
5106 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5107 } else if self.token == token::OpenDelim(token::Brace) {
5108 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5110 let token_str = self.this_token_to_string();
5111 return Err(self.fatal(&format!("expected `where` or `{{` after union \
5112 name, found `{}`", token_str)))
5115 Ok((class_name, ItemKind::Union(vdata, generics), None))
5118 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5119 let mut fields = Vec::new();
5120 if self.eat(&token::OpenDelim(token::Brace)) {
5121 while self.token != token::CloseDelim(token::Brace) {
5122 fields.push(self.parse_struct_decl_field().map_err(|e| {
5123 self.recover_stmt();
5124 self.eat(&token::CloseDelim(token::Brace));
5131 let token_str = self.this_token_to_string();
5132 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5140 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5141 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5142 // Unit like structs are handled in parse_item_struct function
5143 let fields = self.parse_unspanned_seq(
5144 &token::OpenDelim(token::Paren),
5145 &token::CloseDelim(token::Paren),
5146 SeqSep::trailing_allowed(token::Comma),
5148 let attrs = p.parse_outer_attributes()?;
5150 let vis = p.parse_visibility(true)?;
5151 let ty = p.parse_ty()?;
5153 span: lo.to(p.span),
5156 id: ast::DUMMY_NODE_ID,
5165 /// Parse a structure field declaration
5166 pub fn parse_single_struct_field(&mut self,
5169 attrs: Vec<Attribute> )
5170 -> PResult<'a, StructField> {
5171 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5176 token::CloseDelim(token::Brace) => {}
5177 token::DocComment(_) => return Err(self.span_fatal_err(self.span,
5178 Error::UselessDocComment)),
5179 _ => return Err(self.span_fatal_help(self.span,
5180 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5181 "struct fields should be separated by commas")),
5186 /// Parse an element of a struct definition
5187 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5188 let attrs = self.parse_outer_attributes()?;
5190 let vis = self.parse_visibility(false)?;
5191 self.parse_single_struct_field(lo, vis, attrs)
5194 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5195 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5196 /// a function definition, it's not a tuple struct field) and the contents within the parens
5197 /// isn't valid, emit a proper diagnostic.
5198 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5199 maybe_whole!(self, NtVis, |x| x);
5201 if !self.eat_keyword(keywords::Pub) {
5202 return Ok(Visibility::Inherited)
5205 if self.check(&token::OpenDelim(token::Paren)) {
5206 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5207 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5208 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5209 // by the following tokens.
5210 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5213 self.bump(); // `crate`
5214 let vis = Visibility::Crate(self.prev_span);
5215 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5217 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5220 self.bump(); // `in`
5221 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5222 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5223 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5225 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5226 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5227 t.is_keyword(keywords::SelfValue)) {
5228 // `pub(self)` or `pub(super)`
5230 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5231 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5232 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5234 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5235 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5237 let msg = "incorrect visibility restriction";
5238 let suggestion = r##"some possible visibility restrictions are:
5239 `pub(crate)`: visible only on the current crate
5240 `pub(super)`: visible only in the current module's parent
5241 `pub(in path::to::module)`: visible only on the specified path"##;
5242 let path = self.parse_path(PathStyle::Mod)?;
5243 let path_span = self.prev_span;
5244 let help_msg = format!("make this visible only to module `{}` with `in`", path);
5245 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5246 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5247 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5248 err.emit(); // emit diagnostic, but continue with public visibility
5252 Ok(Visibility::Public)
5255 /// Parse defaultness: DEFAULT or nothing
5256 fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5257 if self.eat_defaultness() {
5258 Ok(Defaultness::Default)
5260 Ok(Defaultness::Final)
5264 /// Given a termination token, parse all of the items in a module
5265 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5266 let mut items = vec![];
5267 while let Some(item) = self.parse_item()? {
5271 if !self.eat(term) {
5272 let token_str = self.this_token_to_string();
5273 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5276 let hi = if self.span == syntax_pos::DUMMY_SP {
5283 inner: inner_lo.to(hi),
5288 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5289 let id = self.parse_ident()?;
5290 self.expect(&token::Colon)?;
5291 let ty = self.parse_ty()?;
5292 self.expect(&token::Eq)?;
5293 let e = self.parse_expr()?;
5294 self.expect(&token::Semi)?;
5295 let item = match m {
5296 Some(m) => ItemKind::Static(ty, m, e),
5297 None => ItemKind::Const(ty, e),
5299 Ok((id, item, None))
5302 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5303 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5304 let (in_cfg, outer_attrs) = {
5305 let mut strip_unconfigured = ::config::StripUnconfigured {
5307 should_test: false, // irrelevant
5308 features: None, // don't perform gated feature checking
5310 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5311 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5314 let id_span = self.span;
5315 let id = self.parse_ident()?;
5316 if self.check(&token::Semi) {
5318 if in_cfg && self.recurse_into_file_modules {
5319 // This mod is in an external file. Let's go get it!
5320 let ModulePathSuccess { path, directory_ownership, warn } =
5321 self.submod_path(id, &outer_attrs, id_span)?;
5322 let (module, mut attrs) =
5323 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5325 let attr = ast::Attribute {
5326 id: attr::mk_attr_id(),
5327 style: ast::AttrStyle::Outer,
5328 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5329 Ident::from_str("warn_directory_ownership")),
5330 tokens: TokenStream::empty(),
5331 is_sugared_doc: false,
5332 span: syntax_pos::DUMMY_SP,
5334 attr::mark_known(&attr);
5337 Ok((id, module, Some(attrs)))
5339 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5340 Ok((id, ItemKind::Mod(placeholder), None))
5343 let old_directory = self.directory.clone();
5344 self.push_directory(id, &outer_attrs);
5346 self.expect(&token::OpenDelim(token::Brace))?;
5347 let mod_inner_lo = self.span;
5348 let attrs = self.parse_inner_attributes()?;
5349 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5351 self.directory = old_directory;
5352 Ok((id, ItemKind::Mod(module), Some(attrs)))
5356 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5357 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5358 self.directory.path.push(&path.as_str());
5359 self.directory.ownership = DirectoryOwnership::Owned;
5361 self.directory.path.push(&id.name.as_str());
5365 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5366 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5369 /// Returns either a path to a module, or .
5370 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5371 let mod_name = id.to_string();
5372 let default_path_str = format!("{}.rs", mod_name);
5373 let secondary_path_str = format!("{}{}mod.rs", mod_name, path::MAIN_SEPARATOR);
5374 let default_path = dir_path.join(&default_path_str);
5375 let secondary_path = dir_path.join(&secondary_path_str);
5376 let default_exists = codemap.file_exists(&default_path);
5377 let secondary_exists = codemap.file_exists(&secondary_path);
5379 let result = match (default_exists, secondary_exists) {
5380 (true, false) => Ok(ModulePathSuccess {
5382 directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5385 (false, true) => Ok(ModulePathSuccess {
5386 path: secondary_path,
5387 directory_ownership: DirectoryOwnership::Owned,
5390 (false, false) => Err(Error::FileNotFoundForModule {
5391 mod_name: mod_name.clone(),
5392 default_path: default_path_str,
5393 secondary_path: secondary_path_str,
5394 dir_path: format!("{}", dir_path.display()),
5396 (true, true) => Err(Error::DuplicatePaths {
5397 mod_name: mod_name.clone(),
5398 default_path: default_path_str,
5399 secondary_path: secondary_path_str,
5405 path_exists: default_exists || secondary_exists,
5410 fn submod_path(&mut self,
5412 outer_attrs: &[ast::Attribute],
5414 -> PResult<'a, ModulePathSuccess> {
5415 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5416 return Ok(ModulePathSuccess {
5417 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5418 Some("mod.rs") => DirectoryOwnership::Owned,
5419 _ => DirectoryOwnership::UnownedViaMod(true),
5426 let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5428 if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5430 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5431 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5432 if paths.path_exists {
5433 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5435 err.span_note(id_sp, &msg);
5438 } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5440 if let Ok(result) = paths.result {
5441 return Ok(ModulePathSuccess { warn: true, ..result });
5444 let mut err = self.diagnostic().struct_span_err(id_sp,
5445 "cannot declare a new module at this location");
5446 if id_sp != syntax_pos::DUMMY_SP {
5447 let src_path = PathBuf::from(self.sess.codemap().span_to_filename(id_sp));
5448 if let Some(stem) = src_path.file_stem() {
5449 let mut dest_path = src_path.clone();
5450 dest_path.set_file_name(stem);
5451 dest_path.push("mod.rs");
5452 err.span_note(id_sp,
5453 &format!("maybe move this module `{}` to its own \
5454 directory via `{}`", src_path.to_string_lossy(),
5455 dest_path.to_string_lossy()));
5458 if paths.path_exists {
5459 err.span_note(id_sp,
5460 &format!("... or maybe `use` the module `{}` instead \
5461 of possibly redeclaring it",
5466 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5470 /// Read a module from a source file.
5471 fn eval_src_mod(&mut self,
5473 directory_ownership: DirectoryOwnership,
5476 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5477 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5478 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5479 let mut err = String::from("circular modules: ");
5480 let len = included_mod_stack.len();
5481 for p in &included_mod_stack[i.. len] {
5482 err.push_str(&p.to_string_lossy());
5483 err.push_str(" -> ");
5485 err.push_str(&path.to_string_lossy());
5486 return Err(self.span_fatal(id_sp, &err[..]));
5488 included_mod_stack.push(path.clone());
5489 drop(included_mod_stack);
5492 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5493 p0.cfg_mods = self.cfg_mods;
5494 let mod_inner_lo = p0.span;
5495 let mod_attrs = p0.parse_inner_attributes()?;
5496 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5497 self.sess.included_mod_stack.borrow_mut().pop();
5498 Ok((ast::ItemKind::Mod(m0), mod_attrs))
5501 /// Parse a function declaration from a foreign module
5502 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5503 -> PResult<'a, ForeignItem> {
5504 self.expect_keyword(keywords::Fn)?;
5506 let (ident, mut generics) = self.parse_fn_header()?;
5507 let decl = self.parse_fn_decl(true)?;
5508 generics.where_clause = self.parse_where_clause()?;
5510 self.expect(&token::Semi)?;
5511 Ok(ast::ForeignItem {
5514 node: ForeignItemKind::Fn(decl, generics),
5515 id: ast::DUMMY_NODE_ID,
5521 /// Parse a static item from a foreign module
5522 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5523 -> PResult<'a, ForeignItem> {
5524 self.expect_keyword(keywords::Static)?;
5525 let mutbl = self.eat_keyword(keywords::Mut);
5527 let ident = self.parse_ident()?;
5528 self.expect(&token::Colon)?;
5529 let ty = self.parse_ty()?;
5531 self.expect(&token::Semi)?;
5535 node: ForeignItemKind::Static(ty, mutbl),
5536 id: ast::DUMMY_NODE_ID,
5542 /// Parse extern crate links
5546 /// extern crate foo;
5547 /// extern crate bar as foo;
5548 fn parse_item_extern_crate(&mut self,
5550 visibility: Visibility,
5551 attrs: Vec<Attribute>)
5552 -> PResult<'a, P<Item>> {
5554 let crate_name = self.parse_ident()?;
5555 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
5556 (Some(crate_name.name), ident)
5560 self.expect(&token::Semi)?;
5562 let prev_span = self.prev_span;
5563 Ok(self.mk_item(lo.to(prev_span),
5565 ItemKind::ExternCrate(maybe_path),
5570 /// Parse `extern` for foreign ABIs
5573 /// `extern` is expected to have been
5574 /// consumed before calling this method
5580 fn parse_item_foreign_mod(&mut self,
5582 opt_abi: Option<abi::Abi>,
5583 visibility: Visibility,
5584 mut attrs: Vec<Attribute>)
5585 -> PResult<'a, P<Item>> {
5586 self.expect(&token::OpenDelim(token::Brace))?;
5588 let abi = opt_abi.unwrap_or(Abi::C);
5590 attrs.extend(self.parse_inner_attributes()?);
5592 let mut foreign_items = vec![];
5593 while let Some(item) = self.parse_foreign_item()? {
5594 foreign_items.push(item);
5596 self.expect(&token::CloseDelim(token::Brace))?;
5598 let prev_span = self.prev_span;
5599 let m = ast::ForeignMod {
5601 items: foreign_items
5603 let invalid = keywords::Invalid.ident();
5604 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
5607 /// Parse type Foo = Bar;
5608 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5609 let ident = self.parse_ident()?;
5610 let mut tps = self.parse_generics()?;
5611 tps.where_clause = self.parse_where_clause()?;
5612 self.expect(&token::Eq)?;
5613 let ty = self.parse_ty()?;
5614 self.expect(&token::Semi)?;
5615 Ok((ident, ItemKind::Ty(ty, tps), None))
5618 /// Parse the part of an "enum" decl following the '{'
5619 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5620 let mut variants = Vec::new();
5621 let mut all_nullary = true;
5622 let mut any_disr = None;
5623 while self.token != token::CloseDelim(token::Brace) {
5624 let variant_attrs = self.parse_outer_attributes()?;
5625 let vlo = self.span;
5628 let mut disr_expr = None;
5629 let ident = self.parse_ident()?;
5630 if self.check(&token::OpenDelim(token::Brace)) {
5631 // Parse a struct variant.
5632 all_nullary = false;
5633 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
5634 ast::DUMMY_NODE_ID);
5635 } else if self.check(&token::OpenDelim(token::Paren)) {
5636 all_nullary = false;
5637 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
5638 ast::DUMMY_NODE_ID);
5639 } else if self.eat(&token::Eq) {
5640 disr_expr = Some(self.parse_expr()?);
5641 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5642 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5644 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5647 let vr = ast::Variant_ {
5649 attrs: variant_attrs,
5651 disr_expr: disr_expr,
5653 variants.push(respan(vlo.to(self.prev_span), vr));
5655 if !self.eat(&token::Comma) { break; }
5657 self.expect(&token::CloseDelim(token::Brace))?;
5659 Some(disr_span) if !all_nullary =>
5660 self.span_err(disr_span,
5661 "discriminator values can only be used with a c-like enum"),
5665 Ok(ast::EnumDef { variants: variants })
5668 /// Parse an "enum" declaration
5669 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5670 let id = self.parse_ident()?;
5671 let mut generics = self.parse_generics()?;
5672 generics.where_clause = self.parse_where_clause()?;
5673 self.expect(&token::OpenDelim(token::Brace))?;
5675 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
5676 self.recover_stmt();
5677 self.eat(&token::CloseDelim(token::Brace));
5680 Ok((id, ItemKind::Enum(enum_definition, generics), None))
5683 /// Parses a string as an ABI spec on an extern type or module. Consumes
5684 /// the `extern` keyword, if one is found.
5685 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5687 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5689 self.expect_no_suffix(sp, "ABI spec", suf);
5691 match abi::lookup(&s.as_str()) {
5692 Some(abi) => Ok(Some(abi)),
5694 let prev_span = self.prev_span;
5697 &format!("invalid ABI: expected one of [{}], \
5699 abi::all_names().join(", "),
5710 /// Parse one of the items allowed by the flags.
5711 /// NB: this function no longer parses the items inside an
5713 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5714 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5715 maybe_whole!(self, NtItem, |item| {
5716 let mut item = item.unwrap();
5717 let mut attrs = attrs;
5718 mem::swap(&mut item.attrs, &mut attrs);
5719 item.attrs.extend(attrs);
5725 let visibility = self.parse_visibility(false)?;
5727 if self.eat_keyword(keywords::Use) {
5729 let item_ = ItemKind::Use(self.parse_view_path()?);
5730 self.expect(&token::Semi)?;
5732 let prev_span = self.prev_span;
5733 let invalid = keywords::Invalid.ident();
5734 let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
5735 return Ok(Some(item));
5738 if self.eat_keyword(keywords::Extern) {
5739 if self.eat_keyword(keywords::Crate) {
5740 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
5743 let opt_abi = self.parse_opt_abi()?;
5745 if self.eat_keyword(keywords::Fn) {
5746 // EXTERN FUNCTION ITEM
5747 let fn_span = self.prev_span;
5748 let abi = opt_abi.unwrap_or(Abi::C);
5749 let (ident, item_, extra_attrs) =
5750 self.parse_item_fn(Unsafety::Normal,
5751 respan(fn_span, Constness::NotConst),
5753 let prev_span = self.prev_span;
5754 let item = self.mk_item(lo.to(prev_span),
5758 maybe_append(attrs, extra_attrs));
5759 return Ok(Some(item));
5760 } else if self.check(&token::OpenDelim(token::Brace)) {
5761 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
5767 if self.eat_keyword(keywords::Static) {
5769 let m = if self.eat_keyword(keywords::Mut) {
5772 Mutability::Immutable
5774 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
5775 let prev_span = self.prev_span;
5776 let item = self.mk_item(lo.to(prev_span),
5780 maybe_append(attrs, extra_attrs));
5781 return Ok(Some(item));
5783 if self.eat_keyword(keywords::Const) {
5784 let const_span = self.prev_span;
5785 if self.check_keyword(keywords::Fn)
5786 || (self.check_keyword(keywords::Unsafe)
5787 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5788 // CONST FUNCTION ITEM
5789 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5795 let (ident, item_, extra_attrs) =
5796 self.parse_item_fn(unsafety,
5797 respan(const_span, Constness::Const),
5799 let prev_span = self.prev_span;
5800 let item = self.mk_item(lo.to(prev_span),
5804 maybe_append(attrs, extra_attrs));
5805 return Ok(Some(item));
5809 if self.eat_keyword(keywords::Mut) {
5810 let prev_span = self.prev_span;
5811 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
5812 .help("did you mean to declare a static?")
5815 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
5816 let prev_span = self.prev_span;
5817 let item = self.mk_item(lo.to(prev_span),
5821 maybe_append(attrs, extra_attrs));
5822 return Ok(Some(item));
5824 if self.check_keyword(keywords::Unsafe) &&
5825 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5827 // UNSAFE TRAIT ITEM
5828 self.expect_keyword(keywords::Unsafe)?;
5829 self.expect_keyword(keywords::Trait)?;
5830 let (ident, item_, extra_attrs) =
5831 self.parse_item_trait(ast::Unsafety::Unsafe)?;
5832 let prev_span = self.prev_span;
5833 let item = self.mk_item(lo.to(prev_span),
5837 maybe_append(attrs, extra_attrs));
5838 return Ok(Some(item));
5840 if (self.check_keyword(keywords::Unsafe) &&
5841 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))) ||
5842 (self.check_keyword(keywords::Default) &&
5843 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) &&
5844 self.look_ahead(2, |t| t.is_keyword(keywords::Impl)))
5847 let defaultness = self.parse_defaultness()?;
5848 self.expect_keyword(keywords::Unsafe)?;
5849 self.expect_keyword(keywords::Impl)?;
5852 extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe, defaultness)?;
5853 let prev_span = self.prev_span;
5854 let item = self.mk_item(lo.to(prev_span),
5858 maybe_append(attrs, extra_attrs));
5859 return Ok(Some(item));
5861 if self.check_keyword(keywords::Fn) {
5864 let fn_span = self.prev_span;
5865 let (ident, item_, extra_attrs) =
5866 self.parse_item_fn(Unsafety::Normal,
5867 respan(fn_span, Constness::NotConst),
5869 let prev_span = self.prev_span;
5870 let item = self.mk_item(lo.to(prev_span),
5874 maybe_append(attrs, extra_attrs));
5875 return Ok(Some(item));
5877 if self.check_keyword(keywords::Unsafe)
5878 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5879 // UNSAFE FUNCTION ITEM
5881 let abi = if self.eat_keyword(keywords::Extern) {
5882 self.parse_opt_abi()?.unwrap_or(Abi::C)
5886 self.expect_keyword(keywords::Fn)?;
5887 let fn_span = self.prev_span;
5888 let (ident, item_, extra_attrs) =
5889 self.parse_item_fn(Unsafety::Unsafe,
5890 respan(fn_span, Constness::NotConst),
5892 let prev_span = self.prev_span;
5893 let item = self.mk_item(lo.to(prev_span),
5897 maybe_append(attrs, extra_attrs));
5898 return Ok(Some(item));
5900 if self.eat_keyword(keywords::Mod) {
5902 let (ident, item_, extra_attrs) =
5903 self.parse_item_mod(&attrs[..])?;
5904 let prev_span = self.prev_span;
5905 let item = self.mk_item(lo.to(prev_span),
5909 maybe_append(attrs, extra_attrs));
5910 return Ok(Some(item));
5912 if self.eat_keyword(keywords::Type) {
5914 let (ident, item_, extra_attrs) = self.parse_item_type()?;
5915 let prev_span = self.prev_span;
5916 let item = self.mk_item(lo.to(prev_span),
5920 maybe_append(attrs, extra_attrs));
5921 return Ok(Some(item));
5923 if self.eat_keyword(keywords::Enum) {
5925 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
5926 let prev_span = self.prev_span;
5927 let item = self.mk_item(lo.to(prev_span),
5931 maybe_append(attrs, extra_attrs));
5932 return Ok(Some(item));
5934 if self.eat_keyword(keywords::Trait) {
5936 let (ident, item_, extra_attrs) =
5937 self.parse_item_trait(ast::Unsafety::Normal)?;
5938 let prev_span = self.prev_span;
5939 let item = self.mk_item(lo.to(prev_span),
5943 maybe_append(attrs, extra_attrs));
5944 return Ok(Some(item));
5946 if (self.check_keyword(keywords::Impl)) ||
5947 (self.check_keyword(keywords::Default) &&
5948 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)))
5951 let defaultness = self.parse_defaultness()?;
5952 self.expect_keyword(keywords::Impl)?;
5955 extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal, defaultness)?;
5956 let prev_span = self.prev_span;
5957 let item = self.mk_item(lo.to(prev_span),
5961 maybe_append(attrs, extra_attrs));
5962 return Ok(Some(item));
5964 if self.eat_keyword(keywords::Struct) {
5966 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
5967 let prev_span = self.prev_span;
5968 let item = self.mk_item(lo.to(prev_span),
5972 maybe_append(attrs, extra_attrs));
5973 return Ok(Some(item));
5975 if self.is_union_item() {
5978 let (ident, item_, extra_attrs) = self.parse_item_union()?;
5979 let prev_span = self.prev_span;
5980 let item = self.mk_item(lo.to(prev_span),
5984 maybe_append(attrs, extra_attrs));
5985 return Ok(Some(item));
5987 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility)? {
5988 return Ok(Some(macro_def));
5991 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5994 /// Parse a foreign item.
5995 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
5996 let attrs = self.parse_outer_attributes()?;
5998 let visibility = self.parse_visibility(false)?;
6000 if self.check_keyword(keywords::Static) {
6001 // FOREIGN STATIC ITEM
6002 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6004 if self.check_keyword(keywords::Fn) {
6005 // FOREIGN FUNCTION ITEM
6006 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6009 if self.check_keyword(keywords::Const) {
6010 return Err(self.span_fatal(self.span, "extern items cannot be `const`"));
6013 // FIXME #5668: this will occur for a macro invocation:
6014 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
6016 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
6022 /// This is the fall-through for parsing items.
6023 fn parse_macro_use_or_failure(
6025 attrs: Vec<Attribute> ,
6026 macros_allowed: bool,
6027 attributes_allowed: bool,
6029 visibility: Visibility
6030 ) -> PResult<'a, Option<P<Item>>> {
6031 if macros_allowed && self.token.is_path_start() {
6032 // MACRO INVOCATION ITEM
6034 let prev_span = self.prev_span;
6035 self.complain_if_pub_macro(&visibility, prev_span);
6037 let mac_lo = self.span;
6040 let pth = self.parse_path(PathStyle::Mod)?;
6041 self.expect(&token::Not)?;
6043 // a 'special' identifier (like what `macro_rules!` uses)
6044 // is optional. We should eventually unify invoc syntax
6046 let id = if self.token.is_ident() {
6049 keywords::Invalid.ident() // no special identifier
6051 // eat a matched-delimiter token tree:
6052 let (delim, tts) = self.expect_delimited_token_tree()?;
6053 if delim != token::Brace {
6054 if !self.eat(&token::Semi) {
6055 self.span_err(self.prev_span,
6056 "macros that expand to items must either \
6057 be surrounded with braces or followed by \
6062 let hi = self.prev_span;
6063 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6064 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6065 return Ok(Some(item));
6068 // FAILURE TO PARSE ITEM
6070 Visibility::Inherited => {}
6072 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
6076 if !attributes_allowed && !attrs.is_empty() {
6077 self.expected_item_err(&attrs);
6082 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
6083 where F: FnOnce(&mut Self) -> PResult<'a, R>
6085 // Record all tokens we parse when parsing this item.
6086 let mut tokens = Vec::new();
6087 match self.token_cursor.frame.last_token {
6088 LastToken::Collecting(_) => {
6089 panic!("cannot collect tokens recursively yet")
6091 LastToken::Was(ref mut last) => tokens.extend(last.take()),
6093 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
6094 let prev = self.token_cursor.stack.len();
6096 let last_token = if self.token_cursor.stack.len() == prev {
6097 &mut self.token_cursor.frame.last_token
6099 &mut self.token_cursor.stack[prev].last_token
6101 let mut tokens = match *last_token {
6102 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
6103 LastToken::Was(_) => panic!("our vector went away?"),
6106 // If we're not at EOF our current token wasn't actually consumed by
6107 // `f`, but it'll still be in our list that we pulled out. In that case
6109 if self.token == token::Eof {
6110 *last_token = LastToken::Was(None);
6112 *last_token = LastToken::Was(tokens.pop());
6115 Ok((ret?, tokens.into_iter().collect()))
6118 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6119 let attrs = self.parse_outer_attributes()?;
6121 let (ret, tokens) = self.collect_tokens(|this| {
6122 this.parse_item_(attrs, true, false)
6125 // Once we've parsed an item and recorded the tokens we got while
6126 // parsing we may want to store `tokens` into the item we're about to
6127 // return. Note, though, that we specifically didn't capture tokens
6128 // related to outer attributes. The `tokens` field here may later be
6129 // used with procedural macros to convert this item back into a token
6130 // stream, but during expansion we may be removing attributes as we go
6133 // If we've got inner attributes then the `tokens` we've got above holds
6134 // these inner attributes. If an inner attribute is expanded we won't
6135 // actually remove it from the token stream, so we'll just keep yielding
6136 // it (bad!). To work around this case for now we just avoid recording
6137 // `tokens` if we detect any inner attributes. This should help keep
6138 // expansion correct, but we should fix this bug one day!
6141 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6142 i.tokens = Some(tokens);
6149 fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> {
6150 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
6151 &token::CloseDelim(token::Brace),
6152 SeqSep::trailing_allowed(token::Comma), |this| {
6154 let ident = if this.eat_keyword(keywords::SelfValue) {
6155 keywords::SelfValue.ident()
6159 let rename = this.parse_rename()?;
6160 let node = ast::PathListItem_ {
6163 id: ast::DUMMY_NODE_ID
6165 Ok(respan(lo.to(this.prev_span), node))
6170 fn is_import_coupler(&mut self) -> bool {
6171 self.check(&token::ModSep) &&
6172 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6173 *t == token::BinOp(token::Star))
6176 /// Matches ViewPath:
6177 /// MOD_SEP? non_global_path
6178 /// MOD_SEP? non_global_path as IDENT
6179 /// MOD_SEP? non_global_path MOD_SEP STAR
6180 /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE
6181 /// MOD_SEP? LBRACE item_seq RBRACE
6182 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
6184 if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) ||
6185 self.is_import_coupler() {
6186 // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`.
6187 self.eat(&token::ModSep);
6188 let prefix = ast::Path {
6189 segments: vec![PathSegment::crate_root(lo)],
6190 span: lo.to(self.span),
6192 let view_path_kind = if self.eat(&token::BinOp(token::Star)) {
6193 ViewPathGlob(prefix)
6195 ViewPathList(prefix, self.parse_path_list_items()?)
6197 Ok(P(respan(lo.to(self.span), view_path_kind)))
6199 let prefix = self.parse_path(PathStyle::Mod)?.default_to_global();
6200 if self.is_import_coupler() {
6201 // `foo::bar::{a, b}` or `foo::bar::*`
6203 if self.check(&token::BinOp(token::Star)) {
6205 Ok(P(respan(lo.to(self.span), ViewPathGlob(prefix))))
6207 let items = self.parse_path_list_items()?;
6208 Ok(P(respan(lo.to(self.span), ViewPathList(prefix, items))))
6211 // `foo::bar` or `foo::bar as baz`
6212 let rename = self.parse_rename()?.
6213 unwrap_or(prefix.segments.last().unwrap().identifier);
6214 Ok(P(respan(lo.to(self.prev_span), ViewPathSimple(rename, prefix))))
6219 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6220 if self.eat_keyword(keywords::As) {
6221 self.parse_ident().map(Some)
6227 /// Parses a source module as a crate. This is the main
6228 /// entry point for the parser.
6229 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6232 attrs: self.parse_inner_attributes()?,
6233 module: self.parse_mod_items(&token::Eof, lo)?,
6234 span: lo.to(self.span),
6238 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6239 let ret = match self.token {
6240 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6241 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6248 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6249 match self.parse_optional_str() {
6250 Some((s, style, suf)) => {
6251 let sp = self.prev_span;
6252 self.expect_no_suffix(sp, "string literal", suf);
6255 _ => Err(self.fatal("expected string literal"))