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, TraitObjectSyntax};
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};
41 use ast::{RangeEnd, RangeSyntax};
43 use codemap::{self, CodeMap, Spanned, respan};
44 use syntax_pos::{self, Span, BytePos};
45 use errors::{self, DiagnosticBuilder};
46 use parse::{self, classify, token};
47 use parse::common::SeqSep;
48 use parse::lexer::TokenAndSpan;
49 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
50 use parse::obsolete::ObsoleteSyntax;
51 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
52 use util::parser::{AssocOp, Fixity};
56 use tokenstream::{self, Delimited, ThinTokenStream, TokenTree, TokenStream};
57 use symbol::{Symbol, keywords};
61 use std::collections::HashSet;
63 use std::path::{self, Path, PathBuf};
67 pub struct Restrictions: u8 {
68 const STMT_EXPR = 1 << 0;
69 const NO_STRUCT_LITERAL = 1 << 1;
73 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute> >);
75 /// How to parse a path.
76 #[derive(Copy, Clone, PartialEq)]
78 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
79 /// with something else. For example, in expressions `segment < ....` can be interpreted
80 /// as a comparison and `segment ( ....` can be interpreted as a function call.
81 /// In all such contexts the non-path interpretation is preferred by default for practical
82 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
83 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
85 /// In other contexts, notably in types, no ambiguity exists and paths can be written
86 /// without the disambiguator, e.g. `x<y>` - unambiguously a path.
87 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
89 /// A path with generic arguments disallowed, e.g. `foo::bar::Baz`, used in imports,
90 /// visibilities or attributes.
91 /// Technically, this variant is unnecessary and e.g. `Expr` can be used instead
92 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
93 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
94 /// tokens when something goes wrong.
98 #[derive(Clone, Copy, Debug, PartialEq)]
99 pub enum SemiColonMode {
104 #[derive(Clone, Copy, Debug, PartialEq)]
110 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
111 /// dropped into the token stream, which happens while parsing the result of
112 /// macro expansion). Placement of these is not as complex as I feared it would
113 /// be. The important thing is to make sure that lookahead doesn't balk at
114 /// `token::Interpolated` tokens.
115 macro_rules! maybe_whole_expr {
117 if let token::Interpolated(nt) = $p.token.clone() {
119 token::NtExpr(ref e) => {
121 return Ok((*e).clone());
123 token::NtPath(ref path) => {
126 let kind = ExprKind::Path(None, (*path).clone());
127 return Ok($p.mk_expr(span, kind, ThinVec::new()));
129 token::NtBlock(ref block) => {
132 let kind = ExprKind::Block((*block).clone());
133 return Ok($p.mk_expr(span, kind, ThinVec::new()));
141 /// As maybe_whole_expr, but for things other than expressions
142 macro_rules! maybe_whole {
143 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
144 if let token::Interpolated(nt) = $p.token.clone() {
145 if let token::$constructor($x) = nt.0.clone() {
153 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
155 if let Some(ref attrs) = rhs {
156 lhs.extend(attrs.iter().cloned())
161 #[derive(Debug, Clone, Copy, PartialEq)]
172 /* ident is handled by common.rs */
175 pub struct Parser<'a> {
176 pub sess: &'a ParseSess,
177 /// the current token:
178 pub token: token::Token,
179 /// the span of the current token:
181 /// the span of the previous token:
182 pub meta_var_span: Option<Span>,
184 /// the previous token kind
185 prev_token_kind: PrevTokenKind,
186 pub restrictions: Restrictions,
187 /// The set of seen errors about obsolete syntax. Used to suppress
188 /// extra detail when the same error is seen twice
189 pub obsolete_set: HashSet<ObsoleteSyntax>,
190 /// Used to determine the path to externally loaded source files
191 pub directory: Directory,
192 /// Whether to parse sub-modules in other files.
193 pub recurse_into_file_modules: bool,
194 /// Name of the root module this parser originated from. If `None`, then the
195 /// name is not known. This does not change while the parser is descending
196 /// into modules, and sub-parsers have new values for this name.
197 pub root_module_name: Option<String>,
198 pub expected_tokens: Vec<TokenType>,
199 token_cursor: TokenCursor,
200 pub desugar_doc_comments: bool,
201 /// Whether we should configure out of line modules as we parse.
208 frame: TokenCursorFrame,
209 stack: Vec<TokenCursorFrame>,
213 struct TokenCursorFrame {
214 delim: token::DelimToken,
217 tree_cursor: tokenstream::Cursor,
219 last_token: LastToken,
222 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
223 /// by the parser, and then that's transitively used to record the tokens that
224 /// each parse AST item is created with.
226 /// Right now this has two states, either collecting tokens or not collecting
227 /// tokens. If we're collecting tokens we just save everything off into a local
228 /// `Vec`. This should eventually though likely save tokens from the original
229 /// token stream and just use slicing of token streams to avoid creation of a
230 /// whole new vector.
232 /// The second state is where we're passively not recording tokens, but the last
233 /// token is still tracked for when we want to start recording tokens. This
234 /// "last token" means that when we start recording tokens we'll want to ensure
235 /// that this, the first token, is included in the output.
237 /// You can find some more example usage of this in the `collect_tokens` method
241 Collecting(Vec<TokenTree>),
242 Was(Option<TokenTree>),
245 impl TokenCursorFrame {
246 fn new(sp: Span, delimited: &Delimited) -> Self {
248 delim: delimited.delim,
250 open_delim: delimited.delim == token::NoDelim,
251 tree_cursor: delimited.stream().into_trees(),
252 close_delim: delimited.delim == token::NoDelim,
253 last_token: LastToken::Was(None),
259 fn next(&mut self) -> TokenAndSpan {
261 let tree = if !self.frame.open_delim {
262 self.frame.open_delim = true;
263 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
264 .open_tt(self.frame.span)
265 } else if let Some(tree) = self.frame.tree_cursor.next() {
267 } else if !self.frame.close_delim {
268 self.frame.close_delim = true;
269 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
270 .close_tt(self.frame.span)
271 } else if let Some(frame) = self.stack.pop() {
275 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
278 match self.frame.last_token {
279 LastToken::Collecting(ref mut v) => v.push(tree.clone()),
280 LastToken::Was(ref mut t) => *t = Some(tree.clone()),
284 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
285 TokenTree::Delimited(sp, ref delimited) => {
286 let frame = TokenCursorFrame::new(sp, delimited);
287 self.stack.push(mem::replace(&mut self.frame, frame));
293 fn next_desugared(&mut self) -> TokenAndSpan {
294 let (sp, name) = match self.next() {
295 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
299 let stripped = strip_doc_comment_decoration(&name.as_str());
301 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
302 // required to wrap the text.
303 let mut num_of_hashes = 0;
305 for ch in stripped.chars() {
308 '#' if count > 0 => count + 1,
311 num_of_hashes = cmp::max(num_of_hashes, count);
314 let body = TokenTree::Delimited(sp, Delimited {
315 delim: token::Bracket,
316 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"))),
317 TokenTree::Token(sp, token::Eq),
318 TokenTree::Token(sp, token::Literal(
319 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
320 .iter().cloned().collect::<TokenStream>().into(),
323 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
324 delim: token::NoDelim,
325 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
326 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
327 .iter().cloned().collect::<TokenStream>().into()
329 [TokenTree::Token(sp, token::Pound), body]
330 .iter().cloned().collect::<TokenStream>().into()
338 #[derive(PartialEq, Eq, Clone)]
341 Keyword(keywords::Keyword),
350 fn to_string(&self) -> String {
352 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
353 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
354 TokenType::Operator => "an operator".to_string(),
355 TokenType::Lifetime => "lifetime".to_string(),
356 TokenType::Ident => "identifier".to_string(),
357 TokenType::Path => "path".to_string(),
358 TokenType::Type => "type".to_string(),
363 fn is_ident_or_underscore(t: &token::Token) -> bool {
364 t.is_ident() || *t == token::Underscore
367 // Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
368 // `IDENT<<u8 as Trait>::AssocTy>`, `IDENT(u8, u8) -> u8`.
369 fn can_continue_type_after_ident(t: &token::Token) -> bool {
370 t == &token::ModSep || t == &token::Lt ||
371 t == &token::BinOp(token::Shl) || t == &token::OpenDelim(token::Paren)
374 /// Information about the path to a module.
375 pub struct ModulePath {
377 pub path_exists: bool,
378 pub result: Result<ModulePathSuccess, Error>,
381 pub struct ModulePathSuccess {
383 pub directory_ownership: DirectoryOwnership,
387 pub struct ModulePathError {
389 pub help_msg: String,
393 FileNotFoundForModule {
395 default_path: String,
396 secondary_path: String,
401 default_path: String,
402 secondary_path: String,
405 InclusiveRangeWithNoEnd,
409 pub fn span_err(self, sp: Span, handler: &errors::Handler) -> DiagnosticBuilder {
411 Error::FileNotFoundForModule { ref mod_name,
415 let mut err = struct_span_err!(handler, sp, E0583,
416 "file not found for module `{}`", mod_name);
417 err.help(&format!("name the file either {} or {} inside the directory {:?}",
423 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
424 let mut err = struct_span_err!(handler, sp, E0584,
425 "file for module `{}` found at both {} and {}",
429 err.help("delete or rename one of them to remove the ambiguity");
432 Error::UselessDocComment => {
433 let mut err = struct_span_err!(handler, sp, E0585,
434 "found a documentation comment that doesn't document anything");
435 err.help("doc comments must come before what they document, maybe a comment was \
436 intended with `//`?");
439 Error::InclusiveRangeWithNoEnd => {
440 let mut err = struct_span_err!(handler, sp, E0586,
441 "inclusive range with no end");
442 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
452 AttributesParsed(ThinVec<Attribute>),
453 AlreadyParsed(P<Expr>),
456 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
457 fn from(o: Option<ThinVec<Attribute>>) -> Self {
458 if let Some(attrs) = o {
459 LhsExpr::AttributesParsed(attrs)
461 LhsExpr::NotYetParsed
466 impl From<P<Expr>> for LhsExpr {
467 fn from(expr: P<Expr>) -> Self {
468 LhsExpr::AlreadyParsed(expr)
472 /// Create a placeholder argument.
473 fn dummy_arg(span: Span) -> Arg {
474 let spanned = Spanned {
476 node: keywords::Invalid.ident()
479 id: ast::DUMMY_NODE_ID,
480 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), spanned, None),
486 id: ast::DUMMY_NODE_ID
488 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
491 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
492 enum TokenExpectType {
497 impl<'a> Parser<'a> {
498 pub fn new(sess: &'a ParseSess,
500 directory: Option<Directory>,
501 recurse_into_file_modules: bool,
502 desugar_doc_comments: bool)
504 let mut parser = Parser {
506 token: token::Underscore,
507 span: syntax_pos::DUMMY_SP,
508 prev_span: syntax_pos::DUMMY_SP,
510 prev_token_kind: PrevTokenKind::Other,
511 restrictions: Restrictions::empty(),
512 obsolete_set: HashSet::new(),
513 recurse_into_file_modules,
514 directory: Directory { path: PathBuf::new(), ownership: DirectoryOwnership::Owned },
515 root_module_name: None,
516 expected_tokens: Vec::new(),
517 token_cursor: TokenCursor {
518 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
519 delim: token::NoDelim,
524 desugar_doc_comments,
528 let tok = parser.next_tok();
529 parser.token = tok.tok;
530 parser.span = tok.sp;
532 if let Some(directory) = directory {
533 parser.directory = directory;
534 } else if parser.span != syntax_pos::DUMMY_SP {
535 parser.directory.path = sess.codemap().span_to_unmapped_path(parser.span);
536 parser.directory.path.pop();
539 parser.process_potential_macro_variable();
543 fn next_tok(&mut self) -> TokenAndSpan {
544 let mut next = if self.desugar_doc_comments {
545 self.token_cursor.next_desugared()
547 self.token_cursor.next()
549 if next.sp == syntax_pos::DUMMY_SP {
550 next.sp = self.prev_span;
555 /// Convert a token to a string using self's reader
556 pub fn token_to_string(token: &token::Token) -> String {
557 pprust::token_to_string(token)
560 /// Convert the current token to a string using self's reader
561 pub fn this_token_to_string(&self) -> String {
562 Parser::token_to_string(&self.token)
565 pub fn this_token_descr(&self) -> String {
566 let prefix = match &self.token {
567 t if t.is_special_ident() => "reserved identifier ",
568 t if t.is_used_keyword() => "keyword ",
569 t if t.is_unused_keyword() => "reserved keyword ",
572 format!("{}`{}`", prefix, self.this_token_to_string())
575 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
576 let token_str = Parser::token_to_string(t);
577 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
580 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
581 match self.expect_one_of(&[], &[]) {
583 Ok(_) => unreachable!(),
587 /// Expect and consume the token t. Signal an error if
588 /// the next token is not t.
589 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
590 if self.expected_tokens.is_empty() {
591 if self.token == *t {
595 let token_str = Parser::token_to_string(t);
596 let this_token_str = self.this_token_to_string();
597 Err(self.fatal(&format!("expected `{}`, found `{}`",
602 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
606 /// Expect next token to be edible or inedible token. If edible,
607 /// then consume it; if inedible, then return without consuming
608 /// anything. Signal a fatal error if next token is unexpected.
609 pub fn expect_one_of(&mut self,
610 edible: &[token::Token],
611 inedible: &[token::Token]) -> PResult<'a, ()>{
612 fn tokens_to_string(tokens: &[TokenType]) -> String {
613 let mut i = tokens.iter();
614 // This might be a sign we need a connect method on Iterator.
616 .map_or("".to_string(), |t| t.to_string());
617 i.enumerate().fold(b, |mut b, (i, a)| {
618 if tokens.len() > 2 && i == tokens.len() - 2 {
620 } else if tokens.len() == 2 && i == tokens.len() - 2 {
625 b.push_str(&a.to_string());
629 if edible.contains(&self.token) {
632 } else if inedible.contains(&self.token) {
633 // leave it in the input
636 let mut expected = edible.iter()
637 .map(|x| TokenType::Token(x.clone()))
638 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
639 .chain(self.expected_tokens.iter().cloned())
640 .collect::<Vec<_>>();
641 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
643 let expect = tokens_to_string(&expected[..]);
644 let actual = self.this_token_to_string();
645 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
646 let short_expect = if expected.len() > 6 {
647 format!("{} possible tokens", expected.len())
651 (format!("expected one of {}, found `{}`", expect, actual),
652 (self.prev_span.next_point(), format!("expected one of {} here", short_expect)))
653 } else if expected.is_empty() {
654 (format!("unexpected token: `{}`", actual),
655 (self.prev_span, "unexpected token after this".to_string()))
657 (format!("expected {}, found `{}`", expect, actual),
658 (self.prev_span.next_point(), format!("expected {} here", expect)))
660 let mut err = self.fatal(&msg_exp);
661 let sp = if self.token == token::Token::Eof {
662 // This is EOF, don't want to point at the following char, but rather the last token
667 if self.span.contains(sp) {
668 err.span_label(self.span, label_exp);
670 err.span_label(sp, label_exp);
671 err.span_label(self.span, "unexpected token");
677 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
678 fn interpolated_or_expr_span(&self,
679 expr: PResult<'a, P<Expr>>)
680 -> PResult<'a, (Span, P<Expr>)> {
682 if self.prev_token_kind == PrevTokenKind::Interpolated {
690 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
693 if self.token.is_reserved_ident() {
694 self.span_err(self.span, &format!("expected identifier, found {}",
695 self.this_token_descr()));
701 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
702 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
704 let mut err = self.fatal(&format!("expected identifier, found `{}`",
705 self.this_token_to_string()));
706 if self.token == token::Underscore {
707 err.note("`_` is a wildcard pattern, not an identifier");
715 /// Check if the next token is `tok`, and return `true` if so.
717 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
719 pub fn check(&mut self, tok: &token::Token) -> bool {
720 let is_present = self.token == *tok;
721 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
725 /// Consume token 'tok' if it exists. Returns true if the given
726 /// token was present, false otherwise.
727 pub fn eat(&mut self, tok: &token::Token) -> bool {
728 let is_present = self.check(tok);
729 if is_present { self.bump() }
733 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
734 self.expected_tokens.push(TokenType::Keyword(kw));
735 self.token.is_keyword(kw)
738 /// If the next token is the given keyword, eat it and return
739 /// true. Otherwise, return false.
740 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
741 if self.check_keyword(kw) {
749 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
750 if self.token.is_keyword(kw) {
758 /// If the given word is not a keyword, signal an error.
759 /// If the next token is not the given word, signal an error.
760 /// Otherwise, eat it.
761 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
762 if !self.eat_keyword(kw) {
769 fn check_ident(&mut self) -> bool {
770 if self.token.is_ident() {
773 self.expected_tokens.push(TokenType::Ident);
778 fn check_path(&mut self) -> bool {
779 if self.token.is_path_start() {
782 self.expected_tokens.push(TokenType::Path);
787 fn check_type(&mut self) -> bool {
788 if self.token.can_begin_type() {
791 self.expected_tokens.push(TokenType::Type);
796 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
797 /// `&` and continue. If an `&` is not seen, signal an error.
798 fn expect_and(&mut self) -> PResult<'a, ()> {
799 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
801 token::BinOp(token::And) => {
806 let span = self.span.with_lo(self.span.lo() + BytePos(1));
807 Ok(self.bump_with(token::BinOp(token::And), span))
809 _ => self.unexpected()
813 /// Expect and consume an `|`. If `||` is seen, replace it with a single
814 /// `|` and continue. If an `|` is not seen, signal an error.
815 fn expect_or(&mut self) -> PResult<'a, ()> {
816 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
818 token::BinOp(token::Or) => {
823 let span = self.span.with_lo(self.span.lo() + BytePos(1));
824 Ok(self.bump_with(token::BinOp(token::Or), span))
826 _ => self.unexpected()
830 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
832 None => {/* everything ok */}
834 let text = suf.as_str();
836 self.span_bug(sp, "found empty literal suffix in Some")
838 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
843 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
844 /// `<` and continue. If a `<` is not seen, return false.
846 /// This is meant to be used when parsing generics on a path to get the
848 fn eat_lt(&mut self) -> bool {
849 self.expected_tokens.push(TokenType::Token(token::Lt));
855 token::BinOp(token::Shl) => {
856 let span = self.span.with_lo(self.span.lo() + BytePos(1));
857 self.bump_with(token::Lt, span);
864 fn expect_lt(&mut self) -> PResult<'a, ()> {
872 /// Expect and consume a GT. if a >> is seen, replace it
873 /// with a single > and continue. If a GT is not seen,
875 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
876 self.expected_tokens.push(TokenType::Token(token::Gt));
882 token::BinOp(token::Shr) => {
883 let span = self.span.with_lo(self.span.lo() + BytePos(1));
884 Ok(self.bump_with(token::Gt, span))
886 token::BinOpEq(token::Shr) => {
887 let span = self.span.with_lo(self.span.lo() + BytePos(1));
888 Ok(self.bump_with(token::Ge, span))
891 let span = self.span.with_lo(self.span.lo() + BytePos(1));
892 Ok(self.bump_with(token::Eq, span))
894 _ => self.unexpected()
898 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
899 sep: Option<token::Token>,
901 -> PResult<'a, (Vec<T>, bool)>
902 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
904 let mut v = Vec::new();
905 // This loop works by alternating back and forth between parsing types
906 // and commas. For example, given a string `A, B,>`, the parser would
907 // first parse `A`, then a comma, then `B`, then a comma. After that it
908 // would encounter a `>` and stop. This lets the parser handle trailing
909 // commas in generic parameters, because it can stop either after
910 // parsing a type or after parsing a comma.
912 if self.check(&token::Gt)
913 || self.token == token::BinOp(token::Shr)
914 || self.token == token::Ge
915 || self.token == token::BinOpEq(token::Shr) {
921 Some(result) => v.push(result),
922 None => return Ok((v, true))
925 if let Some(t) = sep.as_ref() {
931 return Ok((v, false));
934 /// Parse a sequence bracketed by '<' and '>', stopping
936 pub fn parse_seq_to_before_gt<T, F>(&mut self,
937 sep: Option<token::Token>,
939 -> PResult<'a, Vec<T>> where
940 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
942 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
943 |p| Ok(Some(f(p)?)))?;
948 pub fn parse_seq_to_gt<T, F>(&mut self,
949 sep: Option<token::Token>,
951 -> PResult<'a, Vec<T>> where
952 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
954 let v = self.parse_seq_to_before_gt(sep, f)?;
959 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
960 sep: Option<token::Token>,
962 -> PResult<'a, (Vec<T>, bool)> where
963 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
965 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
969 return Ok((v, returned));
972 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
973 /// passes through any errors encountered. Used for error recovery.
974 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
975 let handler = self.diagnostic();
977 self.parse_seq_to_before_tokens(kets,
979 TokenExpectType::Expect,
980 |p| Ok(p.parse_token_tree()),
981 |mut e| handler.cancel(&mut e));
984 /// Parse a sequence, including the closing delimiter. The function
985 /// f must consume tokens until reaching the next separator or
987 pub fn parse_seq_to_end<T, F>(&mut self,
991 -> PResult<'a, Vec<T>> where
992 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
994 let val = self.parse_seq_to_before_end(ket, sep, f);
999 /// Parse a sequence, not including the closing delimiter. The function
1000 /// f must consume tokens until reaching the next separator or
1001 /// closing bracket.
1002 pub fn parse_seq_to_before_end<T, F>(&mut self,
1007 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1009 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f, |mut e| e.emit())
1012 // `fe` is an error handler.
1013 fn parse_seq_to_before_tokens<T, F, Fe>(&mut self,
1014 kets: &[&token::Token],
1016 expect: TokenExpectType,
1020 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1021 Fe: FnMut(DiagnosticBuilder)
1023 let mut first: bool = true;
1025 while !kets.contains(&&self.token) {
1027 token::CloseDelim(..) | token::Eof => break,
1030 if let Some(ref t) = sep.sep {
1034 if let Err(e) = self.expect(t) {
1040 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1042 TokenExpectType::Expect => self.check(k),
1043 TokenExpectType::NoExpect => self.token == **k,
1061 /// Parse a sequence, including the closing delimiter. The function
1062 /// f must consume tokens until reaching the next separator or
1063 /// closing bracket.
1064 pub fn parse_unspanned_seq<T, F>(&mut self,
1069 -> PResult<'a, Vec<T>> where
1070 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1073 let result = self.parse_seq_to_before_end(ket, sep, f);
1074 if self.token == *ket {
1080 // NB: Do not use this function unless you actually plan to place the
1081 // spanned list in the AST.
1082 pub fn parse_seq<T, F>(&mut self,
1087 -> PResult<'a, Spanned<Vec<T>>> where
1088 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1092 let result = self.parse_seq_to_before_end(ket, sep, f);
1095 Ok(respan(lo.to(hi), result))
1098 /// Advance the parser by one token
1099 pub fn bump(&mut self) {
1100 if self.prev_token_kind == PrevTokenKind::Eof {
1101 // Bumping after EOF is a bad sign, usually an infinite loop.
1102 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1105 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1107 // Record last token kind for possible error recovery.
1108 self.prev_token_kind = match self.token {
1109 token::DocComment(..) => PrevTokenKind::DocComment,
1110 token::Comma => PrevTokenKind::Comma,
1111 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1112 token::Interpolated(..) => PrevTokenKind::Interpolated,
1113 token::Eof => PrevTokenKind::Eof,
1114 token::Ident(..) => PrevTokenKind::Ident,
1115 _ => PrevTokenKind::Other,
1118 let next = self.next_tok();
1119 self.span = next.sp;
1120 self.token = next.tok;
1121 self.expected_tokens.clear();
1122 // check after each token
1123 self.process_potential_macro_variable();
1126 /// Advance the parser using provided token as a next one. Use this when
1127 /// consuming a part of a token. For example a single `<` from `<<`.
1128 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1129 self.prev_span = self.span.with_hi(span.lo());
1130 // It would be incorrect to record the kind of the current token, but
1131 // fortunately for tokens currently using `bump_with`, the
1132 // prev_token_kind will be of no use anyway.
1133 self.prev_token_kind = PrevTokenKind::Other;
1136 self.expected_tokens.clear();
1139 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1140 F: FnOnce(&token::Token) -> R,
1143 return f(&self.token)
1146 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1147 Some(tree) => match tree {
1148 TokenTree::Token(_, tok) => tok,
1149 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1151 None => token::CloseDelim(self.token_cursor.frame.delim),
1154 fn look_ahead_span(&self, dist: usize) -> Span {
1159 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1160 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1161 None => self.look_ahead_span(dist - 1),
1164 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1165 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1167 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1168 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1170 pub fn span_fatal_err(&self, sp: Span, err: Error) -> DiagnosticBuilder<'a> {
1171 err.span_err(sp, self.diagnostic())
1173 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1174 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1178 pub fn bug(&self, m: &str) -> ! {
1179 self.sess.span_diagnostic.span_bug(self.span, m)
1181 pub fn warn(&self, m: &str) {
1182 self.sess.span_diagnostic.span_warn(self.span, m)
1184 pub fn span_warn(&self, sp: Span, m: &str) {
1185 self.sess.span_diagnostic.span_warn(sp, m)
1187 pub fn span_err(&self, sp: Span, m: &str) {
1188 self.sess.span_diagnostic.span_err(sp, m)
1190 pub fn span_err_help(&self, sp: Span, m: &str, h: &str) {
1191 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1195 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1196 self.sess.span_diagnostic.span_bug(sp, m)
1198 pub fn abort_if_errors(&self) {
1199 self.sess.span_diagnostic.abort_if_errors();
1202 fn cancel(&self, err: &mut DiagnosticBuilder) {
1203 self.sess.span_diagnostic.cancel(err)
1206 pub fn diagnostic(&self) -> &'a errors::Handler {
1207 &self.sess.span_diagnostic
1210 /// Is the current token one of the keywords that signals a bare function
1212 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1213 self.check_keyword(keywords::Fn) ||
1214 self.check_keyword(keywords::Unsafe) ||
1215 self.check_keyword(keywords::Extern)
1218 fn get_label(&mut self) -> ast::Ident {
1220 token::Lifetime(ref ident) => *ident,
1221 _ => self.bug("not a lifetime"),
1225 /// parse a TyKind::BareFn type:
1226 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<LifetimeDef>)
1227 -> PResult<'a, TyKind> {
1230 [unsafe] [extern "ABI"] fn (S) -> T
1240 let unsafety = self.parse_unsafety()?;
1241 let abi = if self.eat_keyword(keywords::Extern) {
1242 self.parse_opt_abi()?.unwrap_or(Abi::C)
1247 self.expect_keyword(keywords::Fn)?;
1248 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1249 let ret_ty = self.parse_ret_ty()?;
1250 let decl = P(FnDecl {
1255 Ok(TyKind::BareFn(P(BareFnTy {
1258 lifetimes: lifetime_defs,
1263 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1264 if self.eat_keyword(keywords::Unsafe) {
1265 return Ok(Unsafety::Unsafe);
1267 return Ok(Unsafety::Normal);
1271 /// Parse the items in a trait declaration
1272 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1273 maybe_whole!(self, NtTraitItem, |x| x);
1274 let attrs = self.parse_outer_attributes()?;
1275 let (mut item, tokens) = self.collect_tokens(|this| {
1276 this.parse_trait_item_(at_end, attrs)
1278 // See `parse_item` for why this clause is here.
1279 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1280 item.tokens = Some(tokens);
1285 fn parse_trait_item_(&mut self,
1287 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1290 let (name, node) = if self.eat_keyword(keywords::Type) {
1291 let TyParam {ident, bounds, default, ..} = self.parse_ty_param(vec![])?;
1292 self.expect(&token::Semi)?;
1293 (ident, TraitItemKind::Type(bounds, default))
1294 } else if self.is_const_item() {
1295 self.expect_keyword(keywords::Const)?;
1296 let ident = self.parse_ident()?;
1297 self.expect(&token::Colon)?;
1298 let ty = self.parse_ty()?;
1299 let default = if self.check(&token::Eq) {
1301 let expr = self.parse_expr()?;
1302 self.expect(&token::Semi)?;
1305 self.expect(&token::Semi)?;
1308 (ident, TraitItemKind::Const(ty, default))
1309 } else if self.token.is_path_start() {
1310 // trait item macro.
1311 // code copied from parse_macro_use_or_failure... abstraction!
1312 let prev_span = self.prev_span;
1314 let pth = self.parse_path(PathStyle::Mod)?;
1316 if pth.segments.len() == 1 {
1317 if !self.eat(&token::Not) {
1318 return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1321 self.expect(&token::Not)?;
1324 // eat a matched-delimiter token tree:
1325 let (delim, tts) = self.expect_delimited_token_tree()?;
1326 if delim != token::Brace {
1327 self.expect(&token::Semi)?
1330 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1331 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac))
1333 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
1335 let ident = self.parse_ident()?;
1336 let mut generics = self.parse_generics()?;
1338 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1339 // This is somewhat dubious; We don't want to allow
1340 // argument names to be left off if there is a
1342 p.parse_arg_general(false)
1345 generics.where_clause = self.parse_where_clause()?;
1346 let sig = ast::MethodSig {
1354 let body = match self.token {
1358 debug!("parse_trait_methods(): parsing required method");
1361 token::OpenDelim(token::Brace) => {
1362 debug!("parse_trait_methods(): parsing provided method");
1364 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1365 attrs.extend(inner_attrs.iter().cloned());
1369 let token_str = self.this_token_to_string();
1370 return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1373 (ident, ast::TraitItemKind::Method(sig, body))
1377 id: ast::DUMMY_NODE_ID,
1381 span: lo.to(self.prev_span),
1386 /// Parse optional return type [ -> TY ] in function decl
1387 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1388 if self.eat(&token::RArrow) {
1389 Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
1391 Ok(FunctionRetTy::Default(self.span.with_hi(self.span.lo())))
1396 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1397 self.parse_ty_common(true)
1400 /// Parse a type in restricted contexts where `+` is not permitted.
1401 /// Example 1: `&'a TYPE`
1402 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1403 /// Example 2: `value1 as TYPE + value2`
1404 /// `+` is prohibited to avoid interactions with expression grammar.
1405 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1406 self.parse_ty_common(false)
1409 fn parse_ty_common(&mut self, allow_plus: bool) -> PResult<'a, P<Ty>> {
1410 maybe_whole!(self, NtTy, |x| x);
1413 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1414 // `(TYPE)` is a parenthesized type.
1415 // `(TYPE,)` is a tuple with a single field of type TYPE.
1416 let mut ts = vec![];
1417 let mut last_comma = false;
1418 while self.token != token::CloseDelim(token::Paren) {
1419 ts.push(self.parse_ty()?);
1420 if self.eat(&token::Comma) {
1427 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1428 self.expect(&token::CloseDelim(token::Paren))?;
1430 if ts.len() == 1 && !last_comma {
1431 let ty = ts.into_iter().nth(0).unwrap().unwrap();
1432 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1434 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1435 TyKind::Path(None, ref path) if maybe_bounds => {
1436 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1438 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1439 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1440 let path = match bounds[0] {
1441 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1442 _ => self.bug("unexpected lifetime bound"),
1444 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1447 _ => TyKind::Paren(P(ty))
1452 } else if self.eat(&token::Not) {
1455 } else if self.eat(&token::BinOp(token::Star)) {
1457 TyKind::Ptr(self.parse_ptr()?)
1458 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1460 let t = self.parse_ty()?;
1461 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1462 let t = match self.maybe_parse_fixed_length_of_vec()? {
1463 None => TyKind::Slice(t),
1464 Some(suffix) => TyKind::Array(t, suffix),
1466 self.expect(&token::CloseDelim(token::Bracket))?;
1468 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1471 self.parse_borrowed_pointee()?
1472 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1474 // In order to not be ambiguous, the type must be surrounded by parens.
1475 self.expect(&token::OpenDelim(token::Paren))?;
1476 let e = self.parse_expr()?;
1477 self.expect(&token::CloseDelim(token::Paren))?;
1479 } else if self.eat(&token::Underscore) {
1480 // A type to be inferred `_`
1482 } else if self.token_is_bare_fn_keyword() {
1483 // Function pointer type
1484 self.parse_ty_bare_fn(Vec::new())?
1485 } else if self.check_keyword(keywords::For) {
1486 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1487 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1488 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1490 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1491 if self.token_is_bare_fn_keyword() {
1492 self.parse_ty_bare_fn(lifetime_defs)?
1494 let path = self.parse_path(PathStyle::Type)?;
1495 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1496 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1498 } else if self.eat_keyword(keywords::Impl) {
1499 // FIXME: figure out priority of `+` in `impl Trait1 + Trait2` (#34511).
1500 TyKind::ImplTrait(self.parse_ty_param_bounds()?)
1501 } else if self.check_keyword(keywords::Dyn) &&
1502 self.look_ahead(1, |t| t.can_begin_bound() && !can_continue_type_after_ident(t)) {
1503 // FIXME: figure out priority of `+` in `dyn Trait1 + Trait2` (#34511).
1504 self.bump(); // `dyn`
1505 TyKind::TraitObject(self.parse_ty_param_bounds()?, TraitObjectSyntax::Dyn)
1506 } else if self.check(&token::Question) ||
1507 self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)) {
1508 // Bound list (trait object type)
1509 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?,
1510 TraitObjectSyntax::None)
1511 } else if self.eat_lt() {
1513 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1514 TyKind::Path(Some(qself), path)
1515 } else if self.token.is_path_start() {
1517 let path = self.parse_path(PathStyle::Type)?;
1518 if self.eat(&token::Not) {
1519 // Macro invocation in type position
1520 let (_, tts) = self.expect_delimited_token_tree()?;
1521 TyKind::Mac(respan(lo.to(self.span), Mac_ { path: path, tts: tts }))
1523 // Just a type path or bound list (trait object type) starting with a trait.
1525 // `Trait1 + Trait2 + 'a`
1526 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1527 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1529 TyKind::Path(None, path)
1533 let msg = format!("expected type, found {}", self.this_token_descr());
1534 return Err(self.fatal(&msg));
1537 let span = lo.to(self.prev_span);
1538 let ty = Ty { node: node, span: span, id: ast::DUMMY_NODE_ID };
1540 // Try to recover from use of `+` with incorrect priority.
1541 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1546 fn parse_remaining_bounds(&mut self, lifetime_defs: Vec<LifetimeDef>, path: ast::Path,
1547 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1548 let poly_trait_ref = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
1549 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1552 bounds.append(&mut self.parse_ty_param_bounds()?);
1554 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1557 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1558 // Do not add `+` to expected tokens.
1559 if !allow_plus || self.token != token::BinOp(token::Plus) {
1564 let bounds = self.parse_ty_param_bounds()?;
1565 let sum_span = ty.span.to(self.prev_span);
1567 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1568 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1571 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1572 let sum_with_parens = pprust::to_string(|s| {
1573 use print::pprust::PrintState;
1576 s.print_opt_lifetime(lifetime)?;
1577 s.print_mutability(mut_ty.mutbl)?;
1579 s.print_type(&mut_ty.ty)?;
1580 s.print_bounds(" +", &bounds)?;
1583 err.span_suggestion(sum_span, "try adding parentheses", sum_with_parens);
1585 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1586 err.span_label(sum_span, "perhaps you forgot parentheses?");
1589 err.span_label(sum_span, "expected a path");
1596 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1597 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1598 let mutbl = self.parse_mutability();
1599 let ty = self.parse_ty_no_plus()?;
1600 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1603 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1604 let mutbl = if self.eat_keyword(keywords::Mut) {
1606 } else if self.eat_keyword(keywords::Const) {
1607 Mutability::Immutable
1609 let span = self.prev_span;
1611 "expected mut or const in raw pointer type (use \
1612 `*mut T` or `*const T` as appropriate)");
1613 Mutability::Immutable
1615 let t = self.parse_ty_no_plus()?;
1616 Ok(MutTy { ty: t, mutbl: mutbl })
1619 pub fn is_named_argument(&mut self) -> bool {
1620 let offset = match self.token {
1621 token::BinOp(token::And) |
1623 _ if self.token.is_keyword(keywords::Mut) => 1,
1627 debug!("parser is_named_argument offset:{}", offset);
1630 is_ident_or_underscore(&self.token)
1631 && self.look_ahead(1, |t| *t == token::Colon)
1633 self.look_ahead(offset, |t| is_ident_or_underscore(t))
1634 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1638 /// This version of parse arg doesn't necessarily require
1639 /// identifier names.
1640 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1641 maybe_whole!(self, NtArg, |x| x);
1643 let pat = if require_name || self.is_named_argument() {
1644 debug!("parse_arg_general parse_pat (require_name:{})",
1646 let pat = self.parse_pat()?;
1648 self.expect(&token::Colon)?;
1651 debug!("parse_arg_general ident_to_pat");
1652 let sp = self.prev_span;
1653 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1655 id: ast::DUMMY_NODE_ID,
1656 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1662 let t = self.parse_ty()?;
1667 id: ast::DUMMY_NODE_ID,
1671 /// Parse a single function argument
1672 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1673 self.parse_arg_general(true)
1676 /// Parse an argument in a lambda header e.g. |arg, arg|
1677 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1678 let pat = self.parse_pat()?;
1679 let t = if self.eat(&token::Colon) {
1683 id: ast::DUMMY_NODE_ID,
1684 node: TyKind::Infer,
1691 id: ast::DUMMY_NODE_ID
1695 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1696 if self.eat(&token::Semi) {
1697 Ok(Some(self.parse_expr()?))
1703 /// Matches token_lit = LIT_INTEGER | ...
1704 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1705 let out = match self.token {
1706 token::Interpolated(ref nt) => match nt.0 {
1707 token::NtExpr(ref v) => match v.node {
1708 ExprKind::Lit(ref lit) => { lit.node.clone() }
1709 _ => { return self.unexpected_last(&self.token); }
1711 _ => { return self.unexpected_last(&self.token); }
1713 token::Literal(lit, suf) => {
1714 let diag = Some((self.span, &self.sess.span_diagnostic));
1715 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1719 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1724 _ => { return self.unexpected_last(&self.token); }
1731 /// Matches lit = true | false | token_lit
1732 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1734 let lit = if self.eat_keyword(keywords::True) {
1736 } else if self.eat_keyword(keywords::False) {
1737 LitKind::Bool(false)
1739 let lit = self.parse_lit_token()?;
1742 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1745 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1746 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1747 maybe_whole_expr!(self);
1749 let minus_lo = self.span;
1750 let minus_present = self.eat(&token::BinOp(token::Minus));
1752 let literal = P(self.parse_lit()?);
1753 let hi = self.prev_span;
1754 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1757 let minus_hi = self.prev_span;
1758 let unary = self.mk_unary(UnOp::Neg, expr);
1759 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1765 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1767 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1771 _ => self.parse_ident(),
1775 /// Parses qualified path.
1776 /// Assumes that the leading `<` has been parsed already.
1778 /// `qualified_path = <type [as trait_ref]>::path`
1782 /// `<T as U>::F::a<S>` (without disambiguator)
1783 /// `<T as U>::F::a::<S>` (with disambiguator)
1784 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1785 let lo = self.prev_span;
1786 let ty = self.parse_ty()?;
1787 let mut path = if self.eat_keyword(keywords::As) {
1788 self.parse_path(PathStyle::Type)?
1790 ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP }
1792 self.expect(&token::Gt)?;
1793 self.expect(&token::ModSep)?;
1795 let qself = QSelf { ty, position: path.segments.len() };
1796 self.parse_path_segments(&mut path.segments, style, true)?;
1798 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1801 /// Parses simple paths.
1803 /// `path = [::] segment+`
1804 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1807 /// `a::b::C<D>` (without disambiguator)
1808 /// `a::b::C::<D>` (with disambiguator)
1809 /// `Fn(Args)` (without disambiguator)
1810 /// `Fn::(Args)` (with disambiguator)
1811 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1812 self.parse_path_common(style, true)
1815 pub fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1816 -> PResult<'a, ast::Path> {
1817 maybe_whole!(self, NtPath, |path| {
1818 if style == PathStyle::Mod &&
1819 path.segments.iter().any(|segment| segment.parameters.is_some()) {
1820 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1825 let lo = self.meta_var_span.unwrap_or(self.span);
1826 let mut segments = Vec::new();
1827 if self.eat(&token::ModSep) {
1828 segments.push(PathSegment::crate_root(lo));
1830 self.parse_path_segments(&mut segments, style, enable_warning)?;
1832 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1835 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1836 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1837 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1838 let meta_ident = match self.token {
1839 token::Interpolated(ref nt) => match nt.0 {
1840 token::NtMeta(ref meta) => match meta.node {
1841 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
1848 if let Some(ident) = meta_ident {
1850 return Ok(ast::Path::from_ident(self.prev_span, ident));
1852 self.parse_path(style)
1855 fn parse_path_segments(&mut self, segments: &mut Vec<PathSegment>, style: PathStyle,
1856 enable_warning: bool) -> PResult<'a, ()> {
1858 segments.push(self.parse_path_segment(style, enable_warning)?);
1860 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1866 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
1867 -> PResult<'a, PathSegment> {
1868 let ident_span = self.span;
1869 let ident = self.parse_path_segment_ident()?;
1871 let is_args_start = |token: &token::Token| match *token {
1872 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
1875 let check_args_start = |this: &mut Self| {
1876 this.expected_tokens.extend_from_slice(
1877 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1879 is_args_start(&this.token)
1882 Ok(if style == PathStyle::Type && check_args_start(self) ||
1883 style != PathStyle::Mod && self.check(&token::ModSep)
1884 && self.look_ahead(1, |t| is_args_start(t)) {
1885 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1887 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
1888 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
1889 .span_label(self.prev_span, "try removing `::`").emit();
1892 let parameters = if self.eat_lt() {
1894 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1896 let span = lo.to(self.prev_span);
1897 AngleBracketedParameterData { lifetimes, types, bindings, span }.into()
1901 let inputs = self.parse_seq_to_end(&token::CloseDelim(token::Paren),
1902 SeqSep::trailing_allowed(token::Comma),
1904 let output = if self.eat(&token::RArrow) {
1905 Some(self.parse_ty_no_plus()?)
1909 let span = lo.to(self.prev_span);
1910 ParenthesizedParameterData { inputs, output, span }.into()
1913 PathSegment { identifier: ident, span: ident_span, parameters }
1915 // Generic arguments are not found.
1916 PathSegment::from_ident(ident, ident_span)
1920 fn check_lifetime(&mut self) -> bool {
1921 self.expected_tokens.push(TokenType::Lifetime);
1922 self.token.is_lifetime()
1925 /// Parse single lifetime 'a or panic.
1926 fn expect_lifetime(&mut self) -> Lifetime {
1928 token::Lifetime(ident) => {
1929 let ident_span = self.span;
1931 Lifetime { ident: ident, span: ident_span, id: ast::DUMMY_NODE_ID }
1933 _ => self.span_bug(self.span, "not a lifetime")
1937 /// Parse mutability (`mut` or nothing).
1938 fn parse_mutability(&mut self) -> Mutability {
1939 if self.eat_keyword(keywords::Mut) {
1942 Mutability::Immutable
1946 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1947 if let token::Literal(token::Integer(name), None) = self.token {
1949 Ok(Ident::with_empty_ctxt(name))
1955 /// Parse ident (COLON expr)?
1956 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1957 let attrs = self.parse_outer_attributes()?;
1961 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1962 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1963 let fieldname = self.parse_field_name()?;
1965 hi = self.prev_span;
1966 (fieldname, self.parse_expr()?, false)
1968 let fieldname = self.parse_ident()?;
1969 hi = self.prev_span;
1971 // Mimic `x: x` for the `x` field shorthand.
1972 let path = ast::Path::from_ident(lo.to(hi), fieldname);
1973 (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
1976 ident: respan(lo.to(hi), fieldname),
1977 span: lo.to(expr.span),
1980 attrs: attrs.into(),
1984 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1986 id: ast::DUMMY_NODE_ID,
1989 attrs: attrs.into(),
1993 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
1994 ExprKind::Unary(unop, expr)
1997 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
1998 ExprKind::Binary(binop, lhs, rhs)
2001 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2002 ExprKind::Call(f, args)
2005 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2006 ExprKind::Index(expr, idx)
2009 pub fn mk_range(&mut self,
2010 start: Option<P<Expr>>,
2011 end: Option<P<Expr>>,
2012 limits: RangeLimits)
2013 -> PResult<'a, ast::ExprKind> {
2014 if end.is_none() && limits == RangeLimits::Closed {
2015 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2017 Ok(ExprKind::Range(start, end, limits))
2021 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2022 ExprKind::TupField(expr, idx)
2025 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2026 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2027 ExprKind::AssignOp(binop, lhs, rhs)
2030 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2032 id: ast::DUMMY_NODE_ID,
2033 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2039 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2040 let span = &self.span;
2041 let lv_lit = P(codemap::Spanned {
2042 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2047 id: ast::DUMMY_NODE_ID,
2048 node: ExprKind::Lit(lv_lit),
2054 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2056 token::OpenDelim(delim) => match self.parse_token_tree() {
2057 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2058 _ => unreachable!(),
2060 _ => Err(self.fatal("expected open delimiter")),
2064 /// At the bottom (top?) of the precedence hierarchy,
2065 /// parse things like parenthesized exprs,
2066 /// macros, return, etc.
2068 /// NB: This does not parse outer attributes,
2069 /// and is private because it only works
2070 /// correctly if called from parse_dot_or_call_expr().
2071 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2072 maybe_whole_expr!(self);
2074 // Outer attributes are already parsed and will be
2075 // added to the return value after the fact.
2077 // Therefore, prevent sub-parser from parsing
2078 // attributes by giving them a empty "already parsed" list.
2079 let mut attrs = ThinVec::new();
2082 let mut hi = self.span;
2086 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2088 token::OpenDelim(token::Paren) => {
2091 attrs.extend(self.parse_inner_attributes()?);
2093 // (e) is parenthesized e
2094 // (e,) is a tuple with only one field, e
2095 let mut es = vec![];
2096 let mut trailing_comma = false;
2097 while self.token != token::CloseDelim(token::Paren) {
2098 es.push(self.parse_expr()?);
2099 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2100 if self.check(&token::Comma) {
2101 trailing_comma = true;
2105 trailing_comma = false;
2111 hi = self.prev_span;
2112 let span = lo.to(hi);
2113 return if es.len() == 1 && !trailing_comma {
2114 Ok(self.mk_expr(span, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2116 Ok(self.mk_expr(span, ExprKind::Tup(es), attrs))
2119 token::OpenDelim(token::Brace) => {
2120 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2122 token::BinOp(token::Or) | token::OrOr => {
2124 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2126 token::OpenDelim(token::Bracket) => {
2129 attrs.extend(self.parse_inner_attributes()?);
2131 if self.check(&token::CloseDelim(token::Bracket)) {
2134 ex = ExprKind::Array(Vec::new());
2137 let first_expr = self.parse_expr()?;
2138 if self.check(&token::Semi) {
2139 // Repeating array syntax: [ 0; 512 ]
2141 let count = self.parse_expr()?;
2142 self.expect(&token::CloseDelim(token::Bracket))?;
2143 ex = ExprKind::Repeat(first_expr, count);
2144 } else if self.check(&token::Comma) {
2145 // Vector with two or more elements.
2147 let remaining_exprs = self.parse_seq_to_end(
2148 &token::CloseDelim(token::Bracket),
2149 SeqSep::trailing_allowed(token::Comma),
2150 |p| Ok(p.parse_expr()?)
2152 let mut exprs = vec![first_expr];
2153 exprs.extend(remaining_exprs);
2154 ex = ExprKind::Array(exprs);
2156 // Vector with one element.
2157 self.expect(&token::CloseDelim(token::Bracket))?;
2158 ex = ExprKind::Array(vec![first_expr]);
2161 hi = self.prev_span;
2165 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2167 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2169 if self.eat_keyword(keywords::Move) {
2170 let lo = self.prev_span;
2171 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2173 if self.eat_keyword(keywords::If) {
2174 return self.parse_if_expr(attrs);
2176 if self.eat_keyword(keywords::For) {
2177 let lo = self.prev_span;
2178 return self.parse_for_expr(None, lo, attrs);
2180 if self.eat_keyword(keywords::While) {
2181 let lo = self.prev_span;
2182 return self.parse_while_expr(None, lo, attrs);
2184 if self.token.is_lifetime() {
2185 let label = Spanned { node: self.get_label(),
2189 self.expect(&token::Colon)?;
2190 if self.eat_keyword(keywords::While) {
2191 return self.parse_while_expr(Some(label), lo, attrs)
2193 if self.eat_keyword(keywords::For) {
2194 return self.parse_for_expr(Some(label), lo, attrs)
2196 if self.eat_keyword(keywords::Loop) {
2197 return self.parse_loop_expr(Some(label), lo, attrs)
2199 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2201 if self.eat_keyword(keywords::Loop) {
2202 let lo = self.prev_span;
2203 return self.parse_loop_expr(None, lo, attrs);
2205 if self.eat_keyword(keywords::Continue) {
2206 let ex = if self.token.is_lifetime() {
2207 let ex = ExprKind::Continue(Some(Spanned{
2208 node: self.get_label(),
2214 ExprKind::Continue(None)
2216 let hi = self.prev_span;
2217 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2219 if self.eat_keyword(keywords::Match) {
2220 return self.parse_match_expr(attrs);
2222 if self.eat_keyword(keywords::Unsafe) {
2223 return self.parse_block_expr(
2225 BlockCheckMode::Unsafe(ast::UserProvided),
2228 if self.is_catch_expr() {
2230 assert!(self.eat_keyword(keywords::Do));
2231 assert!(self.eat_keyword(keywords::Catch));
2232 return self.parse_catch_expr(lo, attrs);
2234 if self.eat_keyword(keywords::Return) {
2235 if self.token.can_begin_expr() {
2236 let e = self.parse_expr()?;
2238 ex = ExprKind::Ret(Some(e));
2240 ex = ExprKind::Ret(None);
2242 } else if self.eat_keyword(keywords::Break) {
2243 let lt = if self.token.is_lifetime() {
2244 let spanned_lt = Spanned {
2245 node: self.get_label(),
2253 let e = if self.token.can_begin_expr()
2254 && !(self.token == token::OpenDelim(token::Brace)
2255 && self.restrictions.contains(
2256 Restrictions::NO_STRUCT_LITERAL)) {
2257 Some(self.parse_expr()?)
2261 ex = ExprKind::Break(lt, e);
2262 hi = self.prev_span;
2263 } else if self.eat_keyword(keywords::Yield) {
2264 if self.token.can_begin_expr() {
2265 let e = self.parse_expr()?;
2267 ex = ExprKind::Yield(Some(e));
2269 ex = ExprKind::Yield(None);
2271 } else if self.token.is_keyword(keywords::Let) {
2272 // Catch this syntax error here, instead of in `parse_ident`, so
2273 // that we can explicitly mention that let is not to be used as an expression
2274 let mut db = self.fatal("expected expression, found statement (`let`)");
2275 db.note("variable declaration using `let` is a statement");
2277 } else if self.token.is_path_start() {
2278 let pth = self.parse_path(PathStyle::Expr)?;
2280 // `!`, as an operator, is prefix, so we know this isn't that
2281 if self.eat(&token::Not) {
2282 // MACRO INVOCATION expression
2283 let (_, tts) = self.expect_delimited_token_tree()?;
2284 let hi = self.prev_span;
2285 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2287 if self.check(&token::OpenDelim(token::Brace)) {
2288 // This is a struct literal, unless we're prohibited
2289 // from parsing struct literals here.
2290 let prohibited = self.restrictions.contains(
2291 Restrictions::NO_STRUCT_LITERAL
2294 return self.parse_struct_expr(lo, pth, attrs);
2299 ex = ExprKind::Path(None, pth);
2301 match self.parse_lit() {
2304 ex = ExprKind::Lit(P(lit));
2307 self.cancel(&mut err);
2308 let msg = format!("expected expression, found {}",
2309 self.this_token_descr());
2310 return Err(self.fatal(&msg));
2317 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2320 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2321 -> PResult<'a, P<Expr>> {
2323 let mut fields = Vec::new();
2324 let mut base = None;
2326 attrs.extend(self.parse_inner_attributes()?);
2328 while self.token != token::CloseDelim(token::Brace) {
2329 if self.eat(&token::DotDot) {
2330 let exp_span = self.prev_span;
2331 match self.parse_expr() {
2337 self.recover_stmt();
2340 if self.token == token::Comma {
2341 let mut err = self.sess.span_diagnostic.mut_span_err(
2342 exp_span.to(self.prev_span),
2343 "cannot use a comma after the base struct",
2345 err.span_suggestion_short(self.span, "remove this comma", "".to_owned());
2346 err.note("the base struct must always be the last field");
2348 self.recover_stmt();
2353 match self.parse_field() {
2354 Ok(f) => fields.push(f),
2357 self.recover_stmt();
2362 match self.expect_one_of(&[token::Comma],
2363 &[token::CloseDelim(token::Brace)]) {
2367 self.recover_stmt();
2373 let span = lo.to(self.span);
2374 self.expect(&token::CloseDelim(token::Brace))?;
2375 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2378 fn parse_or_use_outer_attributes(&mut self,
2379 already_parsed_attrs: Option<ThinVec<Attribute>>)
2380 -> PResult<'a, ThinVec<Attribute>> {
2381 if let Some(attrs) = already_parsed_attrs {
2384 self.parse_outer_attributes().map(|a| a.into())
2388 /// Parse a block or unsafe block
2389 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2390 outer_attrs: ThinVec<Attribute>)
2391 -> PResult<'a, P<Expr>> {
2392 self.expect(&token::OpenDelim(token::Brace))?;
2394 let mut attrs = outer_attrs;
2395 attrs.extend(self.parse_inner_attributes()?);
2397 let blk = self.parse_block_tail(lo, blk_mode)?;
2398 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2401 /// parse a.b or a(13) or a[4] or just a
2402 pub fn parse_dot_or_call_expr(&mut self,
2403 already_parsed_attrs: Option<ThinVec<Attribute>>)
2404 -> PResult<'a, P<Expr>> {
2405 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2407 let b = self.parse_bottom_expr();
2408 let (span, b) = self.interpolated_or_expr_span(b)?;
2409 self.parse_dot_or_call_expr_with(b, span, attrs)
2412 pub fn parse_dot_or_call_expr_with(&mut self,
2415 mut attrs: ThinVec<Attribute>)
2416 -> PResult<'a, P<Expr>> {
2417 // Stitch the list of outer attributes onto the return value.
2418 // A little bit ugly, but the best way given the current code
2420 self.parse_dot_or_call_expr_with_(e0, lo)
2422 expr.map(|mut expr| {
2423 attrs.extend::<Vec<_>>(expr.attrs.into());
2426 ExprKind::If(..) | ExprKind::IfLet(..) => {
2427 if !expr.attrs.is_empty() {
2428 // Just point to the first attribute in there...
2429 let span = expr.attrs[0].span;
2432 "attributes are not yet allowed on `if` \
2443 // Assuming we have just parsed `.`, continue parsing into an expression.
2444 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2445 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2446 Ok(match self.token {
2447 token::OpenDelim(token::Paren) => {
2448 // Method call `expr.f()`
2449 let mut args = self.parse_unspanned_seq(
2450 &token::OpenDelim(token::Paren),
2451 &token::CloseDelim(token::Paren),
2452 SeqSep::trailing_allowed(token::Comma),
2453 |p| Ok(p.parse_expr()?)
2455 args.insert(0, self_arg);
2457 let span = lo.to(self.prev_span);
2458 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2461 // Field access `expr.f`
2462 if let Some(parameters) = segment.parameters {
2463 self.span_err(parameters.span(),
2464 "field expressions may not have generic arguments");
2467 let span = lo.to(self.prev_span);
2468 let ident = respan(segment.span, segment.identifier);
2469 self.mk_expr(span, ExprKind::Field(self_arg, ident), ThinVec::new())
2474 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2479 while self.eat(&token::Question) {
2480 let hi = self.prev_span;
2481 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2485 if self.eat(&token::Dot) {
2487 token::Ident(..) => {
2488 e = self.parse_dot_suffix(e, lo)?;
2490 token::Literal(token::Integer(n), suf) => {
2493 // A tuple index may not have a suffix
2494 self.expect_no_suffix(sp, "tuple index", suf);
2496 let dot_span = self.prev_span;
2500 let index = n.as_str().parse::<usize>().ok();
2503 let id = respan(dot_span.to(hi), n);
2504 let field = self.mk_tup_field(e, id);
2505 e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2508 let prev_span = self.prev_span;
2509 self.span_err(prev_span, "invalid tuple or tuple struct index");
2513 token::Literal(token::Float(n), _suf) => {
2515 let fstr = n.as_str();
2516 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2517 &format!("unexpected token: `{}`", n));
2518 err.span_label(self.prev_span, "unexpected token");
2519 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2520 let float = match fstr.parse::<f64>().ok() {
2524 let sugg = pprust::to_string(|s| {
2525 use print::pprust::PrintState;
2529 s.print_usize(float.trunc() as usize)?;
2532 s.s.word(fstr.splitn(2, ".").last().unwrap())
2534 err.span_suggestion(
2535 lo.to(self.prev_span),
2536 "try parenthesizing the first index",
2543 // FIXME Could factor this out into non_fatal_unexpected or something.
2544 let actual = self.this_token_to_string();
2545 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2550 if self.expr_is_complete(&e) { break; }
2553 token::OpenDelim(token::Paren) => {
2554 let es = self.parse_unspanned_seq(
2555 &token::OpenDelim(token::Paren),
2556 &token::CloseDelim(token::Paren),
2557 SeqSep::trailing_allowed(token::Comma),
2558 |p| Ok(p.parse_expr()?)
2560 hi = self.prev_span;
2562 let nd = self.mk_call(e, es);
2563 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2567 // Could be either an index expression or a slicing expression.
2568 token::OpenDelim(token::Bracket) => {
2570 let ix = self.parse_expr()?;
2572 self.expect(&token::CloseDelim(token::Bracket))?;
2573 let index = self.mk_index(e, ix);
2574 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2582 pub fn process_potential_macro_variable(&mut self) {
2583 let ident = match self.token {
2584 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2585 self.look_ahead(1, |t| t.is_ident()) => {
2587 let name = match self.token { token::Ident(ident) => ident, _ => unreachable!() };
2588 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2591 token::Interpolated(ref nt) => {
2592 self.meta_var_span = Some(self.span);
2594 token::NtIdent(ident) => ident,
2600 self.token = token::Ident(ident.node);
2601 self.span = ident.span;
2604 /// parse a single token tree from the input.
2605 pub fn parse_token_tree(&mut self) -> TokenTree {
2607 token::OpenDelim(..) => {
2608 let frame = mem::replace(&mut self.token_cursor.frame,
2609 self.token_cursor.stack.pop().unwrap());
2610 self.span = frame.span;
2612 TokenTree::Delimited(frame.span, Delimited {
2614 tts: frame.tree_cursor.original_stream().into(),
2617 token::CloseDelim(_) | token::Eof => unreachable!(),
2619 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2621 TokenTree::Token(span, token)
2626 // parse a stream of tokens into a list of TokenTree's,
2628 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2629 let mut tts = Vec::new();
2630 while self.token != token::Eof {
2631 tts.push(self.parse_token_tree());
2636 pub fn parse_tokens(&mut self) -> TokenStream {
2637 let mut result = Vec::new();
2640 token::Eof | token::CloseDelim(..) => break,
2641 _ => result.push(self.parse_token_tree().into()),
2644 TokenStream::concat(result)
2647 /// Parse a prefix-unary-operator expr
2648 pub fn parse_prefix_expr(&mut self,
2649 already_parsed_attrs: Option<ThinVec<Attribute>>)
2650 -> PResult<'a, P<Expr>> {
2651 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2653 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2654 let (hi, ex) = match self.token {
2657 let e = self.parse_prefix_expr(None);
2658 let (span, e) = self.interpolated_or_expr_span(e)?;
2659 (lo.to(span), self.mk_unary(UnOp::Not, e))
2661 // Suggest `!` for bitwise negation when encountering a `~`
2664 let e = self.parse_prefix_expr(None);
2665 let (span, e) = self.interpolated_or_expr_span(e)?;
2666 let span_of_tilde = lo;
2667 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2668 "`~` can not be used as a unary operator");
2669 err.span_label(span_of_tilde, "did you mean `!`?");
2670 err.help("use `!` instead of `~` if you meant to perform bitwise negation");
2672 (lo.to(span), self.mk_unary(UnOp::Not, e))
2674 token::BinOp(token::Minus) => {
2676 let e = self.parse_prefix_expr(None);
2677 let (span, e) = self.interpolated_or_expr_span(e)?;
2678 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2680 token::BinOp(token::Star) => {
2682 let e = self.parse_prefix_expr(None);
2683 let (span, e) = self.interpolated_or_expr_span(e)?;
2684 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2686 token::BinOp(token::And) | token::AndAnd => {
2688 let m = self.parse_mutability();
2689 let e = self.parse_prefix_expr(None);
2690 let (span, e) = self.interpolated_or_expr_span(e)?;
2691 (lo.to(span), ExprKind::AddrOf(m, e))
2693 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2695 let place = self.parse_expr_res(
2696 Restrictions::NO_STRUCT_LITERAL,
2699 let blk = self.parse_block()?;
2700 let span = blk.span;
2701 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2702 (lo.to(span), ExprKind::InPlace(place, blk_expr))
2704 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2706 let e = self.parse_prefix_expr(None);
2707 let (span, e) = self.interpolated_or_expr_span(e)?;
2708 (lo.to(span), ExprKind::Box(e))
2710 _ => return self.parse_dot_or_call_expr(Some(attrs))
2712 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2715 /// Parse an associative expression
2717 /// This parses an expression accounting for associativity and precedence of the operators in
2719 pub fn parse_assoc_expr(&mut self,
2720 already_parsed_attrs: Option<ThinVec<Attribute>>)
2721 -> PResult<'a, P<Expr>> {
2722 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2725 /// Parse an associative expression with operators of at least `min_prec` precedence
2726 pub fn parse_assoc_expr_with(&mut self,
2729 -> PResult<'a, P<Expr>> {
2730 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2733 let attrs = match lhs {
2734 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2737 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2738 return self.parse_prefix_range_expr(attrs);
2740 self.parse_prefix_expr(attrs)?
2744 if self.expr_is_complete(&lhs) {
2745 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2748 self.expected_tokens.push(TokenType::Operator);
2749 while let Some(op) = AssocOp::from_token(&self.token) {
2751 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2752 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2753 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2754 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2755 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2756 (PrevTokenKind::Interpolated, _) => self.prev_span,
2757 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2758 if path.segments.len() == 1 => self.prev_span,
2762 let cur_op_span = self.span;
2763 let restrictions = if op.is_assign_like() {
2764 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2768 if op.precedence() < min_prec {
2771 // Warn about deprecated ... syntax (until SNAP)
2772 if self.token == token::DotDotDot {
2773 self.warn_dotdoteq(self.span);
2776 if op.is_comparison() {
2777 self.check_no_chained_comparison(&lhs, &op);
2780 if op == AssocOp::As {
2781 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2783 } else if op == AssocOp::Colon {
2784 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2787 err.span_label(self.span,
2788 "expecting a type here because of type ascription");
2789 let cm = self.sess.codemap();
2790 let cur_pos = cm.lookup_char_pos(self.span.lo());
2791 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
2792 if cur_pos.line != op_pos.line {
2793 err.span_suggestion_short(cur_op_span,
2794 "did you mean to use `;` here?",
2801 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2802 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2803 // generalise it to the Fixity::None code.
2805 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2806 // two variants are handled with `parse_prefix_range_expr` call above.
2807 // (and `x...y`/`x...` until SNAP)
2808 let rhs = if self.is_at_start_of_range_notation_rhs() {
2809 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2810 LhsExpr::NotYetParsed)?)
2814 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2819 let limits = if op == AssocOp::DotDot {
2820 RangeLimits::HalfOpen
2825 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2826 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2830 let rhs = match op.fixity() {
2831 Fixity::Right => self.with_res(
2832 restrictions - Restrictions::STMT_EXPR,
2834 this.parse_assoc_expr_with(op.precedence(),
2835 LhsExpr::NotYetParsed)
2837 Fixity::Left => self.with_res(
2838 restrictions - Restrictions::STMT_EXPR,
2840 this.parse_assoc_expr_with(op.precedence() + 1,
2841 LhsExpr::NotYetParsed)
2843 // We currently have no non-associative operators that are not handled above by
2844 // the special cases. The code is here only for future convenience.
2845 Fixity::None => self.with_res(
2846 restrictions - Restrictions::STMT_EXPR,
2848 this.parse_assoc_expr_with(op.precedence() + 1,
2849 LhsExpr::NotYetParsed)
2853 let span = lhs_span.to(rhs.span);
2855 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2856 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2857 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2858 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2859 AssocOp::Greater | AssocOp::GreaterEqual => {
2860 let ast_op = op.to_ast_binop().unwrap();
2861 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2862 self.mk_expr(span, binary, ThinVec::new())
2865 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2867 self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
2868 AssocOp::AssignOp(k) => {
2870 token::Plus => BinOpKind::Add,
2871 token::Minus => BinOpKind::Sub,
2872 token::Star => BinOpKind::Mul,
2873 token::Slash => BinOpKind::Div,
2874 token::Percent => BinOpKind::Rem,
2875 token::Caret => BinOpKind::BitXor,
2876 token::And => BinOpKind::BitAnd,
2877 token::Or => BinOpKind::BitOr,
2878 token::Shl => BinOpKind::Shl,
2879 token::Shr => BinOpKind::Shr,
2881 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2882 self.mk_expr(span, aopexpr, ThinVec::new())
2884 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
2885 self.bug("AssocOp should have been handled by special case")
2889 if op.fixity() == Fixity::None { break }
2894 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
2895 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
2896 -> PResult<'a, P<Expr>> {
2897 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
2898 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
2901 // Save the state of the parser before parsing type normally, in case there is a
2902 // LessThan comparison after this cast.
2903 let parser_snapshot_before_type = self.clone();
2904 match self.parse_ty_no_plus() {
2906 Ok(mk_expr(self, rhs))
2908 Err(mut type_err) => {
2909 // Rewind to before attempting to parse the type with generics, to recover
2910 // from situations like `x as usize < y` in which we first tried to parse
2911 // `usize < y` as a type with generic arguments.
2912 let parser_snapshot_after_type = self.clone();
2913 mem::replace(self, parser_snapshot_before_type);
2915 match self.parse_path(PathStyle::Expr) {
2917 let (op_noun, op_verb) = match self.token {
2918 token::Lt => ("comparison", "comparing"),
2919 token::BinOp(token::Shl) => ("shift", "shifting"),
2921 // We can end up here even without `<` being the next token, for
2922 // example because `parse_ty_no_plus` returns `Err` on keywords,
2923 // but `parse_path` returns `Ok` on them due to error recovery.
2924 // Return original error and parser state.
2925 mem::replace(self, parser_snapshot_after_type);
2926 return Err(type_err);
2930 // Successfully parsed the type path leaving a `<` yet to parse.
2933 // Report non-fatal diagnostics, keep `x as usize` as an expression
2934 // in AST and continue parsing.
2935 let msg = format!("`<` is interpreted as a start of generic \
2936 arguments for `{}`, not a {}", path, op_noun);
2937 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
2938 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
2939 "interpreted as generic arguments");
2940 err.span_label(self.span, format!("not interpreted as {}", op_noun));
2942 let expr = mk_expr(self, P(Ty {
2944 node: TyKind::Path(None, path),
2945 id: ast::DUMMY_NODE_ID
2948 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
2949 .unwrap_or(pprust::expr_to_string(&expr));
2950 err.span_suggestion(expr.span,
2951 &format!("try {} the casted value", op_verb),
2952 format!("({})", expr_str));
2957 Err(mut path_err) => {
2958 // Couldn't parse as a path, return original error and parser state.
2960 mem::replace(self, parser_snapshot_after_type);
2968 /// Produce an error if comparison operators are chained (RFC #558).
2969 /// We only need to check lhs, not rhs, because all comparison ops
2970 /// have same precedence and are left-associative
2971 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2972 debug_assert!(outer_op.is_comparison(),
2973 "check_no_chained_comparison: {:?} is not comparison",
2976 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2977 // respan to include both operators
2978 let op_span = op.span.to(self.span);
2979 let mut err = self.diagnostic().struct_span_err(op_span,
2980 "chained comparison operators require parentheses");
2981 if op.node == BinOpKind::Lt &&
2982 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
2983 *outer_op == AssocOp::Greater // even in a case like the following:
2984 { // Foo<Bar<Baz<Qux, ()>>>
2986 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2987 err.help("or use `(...)` if you meant to specify fn arguments");
2995 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr` (and `...expr` until SNAP)
2996 fn parse_prefix_range_expr(&mut self,
2997 already_parsed_attrs: Option<ThinVec<Attribute>>)
2998 -> PResult<'a, P<Expr>> {
2999 // SNAP remove DotDotDot
3000 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3001 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotDot/DotDotEq",
3003 let tok = self.token.clone();
3004 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3006 let mut hi = self.span;
3007 // Warn about deprecated ... syntax (until SNAP)
3008 if tok == token::DotDotDot {
3009 self.warn_dotdoteq(self.span);
3012 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3013 // RHS must be parsed with more associativity than the dots.
3014 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3015 Some(self.parse_assoc_expr_with(next_prec,
3016 LhsExpr::NotYetParsed)
3024 let limits = if tok == token::DotDot {
3025 RangeLimits::HalfOpen
3030 let r = try!(self.mk_range(None,
3033 Ok(self.mk_expr(lo.to(hi), r, attrs))
3036 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3037 if self.token.can_begin_expr() {
3038 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3039 if self.token == token::OpenDelim(token::Brace) {
3040 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3048 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3049 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3050 if self.check_keyword(keywords::Let) {
3051 return self.parse_if_let_expr(attrs);
3053 let lo = self.prev_span;
3054 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3056 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3057 // verify that the last statement is either an implicit return (no `;`) or an explicit
3058 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3059 // the dead code lint.
3060 if self.eat_keyword(keywords::Else) || !cond.returns() {
3061 let sp = lo.next_point();
3062 let mut err = self.diagnostic()
3063 .struct_span_err(sp, "missing condition for `if` statemement");
3064 err.span_label(sp, "expected if condition here");
3067 let thn = self.parse_block()?;
3068 let mut els: Option<P<Expr>> = None;
3069 let mut hi = thn.span;
3070 if self.eat_keyword(keywords::Else) {
3071 let elexpr = self.parse_else_expr()?;
3075 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3078 /// Parse an 'if let' expression ('if' token already eaten)
3079 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3080 -> PResult<'a, P<Expr>> {
3081 let lo = self.prev_span;
3082 self.expect_keyword(keywords::Let)?;
3083 let pat = self.parse_pat()?;
3084 self.expect(&token::Eq)?;
3085 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3086 let thn = self.parse_block()?;
3087 let (hi, els) = if self.eat_keyword(keywords::Else) {
3088 let expr = self.parse_else_expr()?;
3089 (expr.span, Some(expr))
3093 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
3096 // `move |args| expr`
3097 pub fn parse_lambda_expr(&mut self,
3099 capture_clause: CaptureBy,
3100 attrs: ThinVec<Attribute>)
3101 -> PResult<'a, P<Expr>>
3103 let decl = self.parse_fn_block_decl()?;
3104 let decl_hi = self.prev_span;
3105 let body = match decl.output {
3106 FunctionRetTy::Default(_) => {
3107 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3108 self.parse_expr_res(restrictions, None)?
3111 // If an explicit return type is given, require a
3112 // block to appear (RFC 968).
3113 let body_lo = self.span;
3114 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3120 ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3124 // `else` token already eaten
3125 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3126 if self.eat_keyword(keywords::If) {
3127 return self.parse_if_expr(ThinVec::new());
3129 let blk = self.parse_block()?;
3130 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3134 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3135 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3137 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3138 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3140 let pat = self.parse_pat()?;
3141 self.expect_keyword(keywords::In)?;
3142 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3143 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3144 attrs.extend(iattrs);
3146 let hi = self.prev_span;
3147 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3150 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3151 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3153 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3154 if self.token.is_keyword(keywords::Let) {
3155 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3157 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3158 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3159 attrs.extend(iattrs);
3160 let span = span_lo.to(body.span);
3161 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3164 /// Parse a 'while let' expression ('while' token already eaten)
3165 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3167 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3168 self.expect_keyword(keywords::Let)?;
3169 let pat = self.parse_pat()?;
3170 self.expect(&token::Eq)?;
3171 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3172 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3173 attrs.extend(iattrs);
3174 let span = span_lo.to(body.span);
3175 return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3178 // parse `loop {...}`, `loop` token already eaten
3179 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3181 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3182 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3183 attrs.extend(iattrs);
3184 let span = span_lo.to(body.span);
3185 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3188 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3189 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3190 -> PResult<'a, P<Expr>>
3192 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3193 attrs.extend(iattrs);
3194 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3197 // `match` token already eaten
3198 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3199 let match_span = self.prev_span;
3200 let lo = self.prev_span;
3201 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3203 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3204 if self.token == token::Token::Semi {
3205 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3209 attrs.extend(self.parse_inner_attributes()?);
3211 let mut arms: Vec<Arm> = Vec::new();
3212 while self.token != token::CloseDelim(token::Brace) {
3213 match self.parse_arm() {
3214 Ok(arm) => arms.push(arm),
3216 // Recover by skipping to the end of the block.
3218 self.recover_stmt();
3219 let span = lo.to(self.span);
3220 if self.token == token::CloseDelim(token::Brace) {
3223 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3229 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3232 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3233 maybe_whole!(self, NtArm, |x| x);
3235 let attrs = self.parse_outer_attributes()?;
3236 // Allow a '|' before the pats (RFC 1925)
3237 let beginning_vert = if self.eat(&token::BinOp(token::Or)) {
3238 Some(self.prev_span)
3242 let pats = self.parse_pats()?;
3243 let guard = if self.eat_keyword(keywords::If) {
3244 Some(self.parse_expr()?)
3248 self.expect(&token::FatArrow)?;
3249 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)?;
3251 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3252 && self.token != token::CloseDelim(token::Brace);
3255 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3257 self.eat(&token::Comma);
3269 /// Parse an expression
3270 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3271 self.parse_expr_res(Restrictions::empty(), None)
3274 /// Evaluate the closure with restrictions in place.
3276 /// After the closure is evaluated, restrictions are reset.
3277 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3278 where F: FnOnce(&mut Self) -> T
3280 let old = self.restrictions;
3281 self.restrictions = r;
3283 self.restrictions = old;
3288 /// Parse an expression, subject to the given restrictions
3289 pub fn parse_expr_res(&mut self, r: Restrictions,
3290 already_parsed_attrs: Option<ThinVec<Attribute>>)
3291 -> PResult<'a, P<Expr>> {
3292 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3295 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3296 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3297 if self.check(&token::Eq) {
3299 Ok(Some(self.parse_expr()?))
3305 /// Parse patterns, separated by '|' s
3306 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3307 let mut pats = Vec::new();
3309 pats.push(self.parse_pat()?);
3310 if self.check(&token::BinOp(token::Or)) { self.bump();}
3311 else { return Ok(pats); }
3315 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3316 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3317 let mut fields = vec![];
3318 let mut ddpos = None;
3320 while !self.check(&token::CloseDelim(token::Paren)) {
3321 if ddpos.is_none() && self.eat(&token::DotDot) {
3322 ddpos = Some(fields.len());
3323 if self.eat(&token::Comma) {
3324 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3325 fields.push(self.parse_pat()?);
3327 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3328 // Emit a friendly error, ignore `..` and continue parsing
3329 self.span_err(self.prev_span, "`..` can only be used once per \
3330 tuple or tuple struct pattern");
3332 fields.push(self.parse_pat()?);
3335 if !self.check(&token::CloseDelim(token::Paren)) ||
3336 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3337 self.expect(&token::Comma)?;
3344 fn parse_pat_vec_elements(
3346 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3347 let mut before = Vec::new();
3348 let mut slice = None;
3349 let mut after = Vec::new();
3350 let mut first = true;
3351 let mut before_slice = true;
3353 while self.token != token::CloseDelim(token::Bracket) {
3357 self.expect(&token::Comma)?;
3359 if self.token == token::CloseDelim(token::Bracket)
3360 && (before_slice || !after.is_empty()) {
3366 if self.eat(&token::DotDot) {
3368 if self.check(&token::Comma) ||
3369 self.check(&token::CloseDelim(token::Bracket)) {
3370 slice = Some(P(ast::Pat {
3371 id: ast::DUMMY_NODE_ID,
3372 node: PatKind::Wild,
3375 before_slice = false;
3381 let subpat = self.parse_pat()?;
3382 if before_slice && self.eat(&token::DotDot) {
3383 slice = Some(subpat);
3384 before_slice = false;
3385 } else if before_slice {
3386 before.push(subpat);
3392 Ok((before, slice, after))
3395 /// Parse the fields of a struct-like pattern
3396 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3397 let mut fields = Vec::new();
3398 let mut etc = false;
3399 let mut first = true;
3400 while self.token != token::CloseDelim(token::Brace) {
3404 self.expect(&token::Comma)?;
3405 // accept trailing commas
3406 if self.check(&token::CloseDelim(token::Brace)) { break }
3409 let attrs = self.parse_outer_attributes()?;
3413 if self.check(&token::DotDot) {
3415 if self.token != token::CloseDelim(token::Brace) {
3416 let token_str = self.this_token_to_string();
3417 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3424 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3425 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3426 // Parsing a pattern of the form "fieldname: pat"
3427 let fieldname = self.parse_field_name()?;
3429 let pat = self.parse_pat()?;
3431 (pat, fieldname, false)
3433 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3434 let is_box = self.eat_keyword(keywords::Box);
3435 let boxed_span = self.span;
3436 let is_ref = self.eat_keyword(keywords::Ref);
3437 let is_mut = self.eat_keyword(keywords::Mut);
3438 let fieldname = self.parse_ident()?;
3439 hi = self.prev_span;
3441 let bind_type = match (is_ref, is_mut) {
3442 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3443 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3444 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3445 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3447 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3448 let fieldpat = P(ast::Pat{
3449 id: ast::DUMMY_NODE_ID,
3450 node: PatKind::Ident(bind_type, fieldpath, None),
3451 span: boxed_span.to(hi),
3454 let subpat = if is_box {
3456 id: ast::DUMMY_NODE_ID,
3457 node: PatKind::Box(fieldpat),
3463 (subpat, fieldname, true)
3466 fields.push(codemap::Spanned { span: lo.to(hi),
3467 node: ast::FieldPat {
3471 attrs: attrs.into(),
3475 return Ok((fields, etc));
3478 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3479 if self.token.is_path_start() {
3481 let (qself, path) = if self.eat_lt() {
3482 // Parse a qualified path
3483 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3486 // Parse an unqualified path
3487 (None, self.parse_path(PathStyle::Expr)?)
3489 let hi = self.prev_span;
3490 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3492 self.parse_pat_literal_maybe_minus()
3496 // helper function to decide whether to parse as ident binding or to try to do
3497 // something more complex like range patterns
3498 fn parse_as_ident(&mut self) -> bool {
3499 self.look_ahead(1, |t| match *t {
3500 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3501 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3502 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3503 // range pattern branch
3504 token::DotDot => None,
3506 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3507 token::Comma | token::CloseDelim(token::Bracket) => true,
3512 /// Parse a pattern.
3513 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3514 maybe_whole!(self, NtPat, |x| x);
3519 token::Underscore => {
3522 pat = PatKind::Wild;
3524 token::BinOp(token::And) | token::AndAnd => {
3525 // Parse &pat / &mut pat
3527 let mutbl = self.parse_mutability();
3528 if let token::Lifetime(ident) = self.token {
3529 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3531 let subpat = self.parse_pat()?;
3532 pat = PatKind::Ref(subpat, mutbl);
3534 token::OpenDelim(token::Paren) => {
3535 // Parse (pat,pat,pat,...) as tuple pattern
3537 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3538 self.expect(&token::CloseDelim(token::Paren))?;
3539 pat = PatKind::Tuple(fields, ddpos);
3541 token::OpenDelim(token::Bracket) => {
3542 // Parse [pat,pat,...] as slice pattern
3544 let (before, slice, after) = self.parse_pat_vec_elements()?;
3545 self.expect(&token::CloseDelim(token::Bracket))?;
3546 pat = PatKind::Slice(before, slice, after);
3548 // At this point, token != _, &, &&, (, [
3549 _ => if self.eat_keyword(keywords::Mut) {
3550 // Parse mut ident @ pat / mut ref ident @ pat
3551 let mutref_span = self.prev_span.to(self.span);
3552 let binding_mode = if self.eat_keyword(keywords::Ref) {
3554 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3555 .span_suggestion(mutref_span, "try switching the order", "ref mut".into())
3557 BindingMode::ByRef(Mutability::Mutable)
3559 BindingMode::ByValue(Mutability::Mutable)
3561 pat = self.parse_pat_ident(binding_mode)?;
3562 } else if self.eat_keyword(keywords::Ref) {
3563 // Parse ref ident @ pat / ref mut ident @ pat
3564 let mutbl = self.parse_mutability();
3565 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3566 } else if self.eat_keyword(keywords::Box) {
3568 let subpat = self.parse_pat()?;
3569 pat = PatKind::Box(subpat);
3570 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3571 self.parse_as_ident() {
3572 // Parse ident @ pat
3573 // This can give false positives and parse nullary enums,
3574 // they are dealt with later in resolve
3575 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3576 pat = self.parse_pat_ident(binding_mode)?;
3577 } else if self.token.is_path_start() {
3578 // Parse pattern starting with a path
3579 let (qself, path) = if self.eat_lt() {
3580 // Parse a qualified path
3581 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3584 // Parse an unqualified path
3585 (None, self.parse_path(PathStyle::Expr)?)
3588 token::Not if qself.is_none() => {
3589 // Parse macro invocation
3591 let (_, tts) = self.expect_delimited_token_tree()?;
3592 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3593 pat = PatKind::Mac(mac);
3595 token::DotDotDot | token::DotDotEq | token::DotDot => {
3596 let end_kind = match self.token {
3597 token::DotDot => RangeEnd::Excluded,
3598 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
3599 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
3600 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
3604 let span = lo.to(self.prev_span);
3605 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3607 let end = self.parse_pat_range_end()?;
3608 pat = PatKind::Range(begin, end, end_kind);
3610 token::OpenDelim(token::Brace) => {
3611 if qself.is_some() {
3612 return Err(self.fatal("unexpected `{` after qualified path"));
3614 // Parse struct pattern
3616 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3618 self.recover_stmt();
3622 pat = PatKind::Struct(path, fields, etc);
3624 token::OpenDelim(token::Paren) => {
3625 if qself.is_some() {
3626 return Err(self.fatal("unexpected `(` after qualified path"));
3628 // Parse tuple struct or enum pattern
3630 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3631 self.expect(&token::CloseDelim(token::Paren))?;
3632 pat = PatKind::TupleStruct(path, fields, ddpos)
3634 _ => pat = PatKind::Path(qself, path),
3637 // Try to parse everything else as literal with optional minus
3638 match self.parse_pat_literal_maybe_minus() {
3640 if self.eat(&token::DotDotDot) {
3641 let end = self.parse_pat_range_end()?;
3642 pat = PatKind::Range(begin, end,
3643 RangeEnd::Included(RangeSyntax::DotDotDot));
3644 } else if self.eat(&token::DotDotEq) {
3645 let end = self.parse_pat_range_end()?;
3646 pat = PatKind::Range(begin, end,
3647 RangeEnd::Included(RangeSyntax::DotDotEq));
3648 } else if self.eat(&token::DotDot) {
3649 let end = self.parse_pat_range_end()?;
3650 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3652 pat = PatKind::Lit(begin);
3656 self.cancel(&mut err);
3657 let msg = format!("expected pattern, found {}", self.this_token_descr());
3658 return Err(self.fatal(&msg));
3665 id: ast::DUMMY_NODE_ID,
3667 span: lo.to(self.prev_span),
3671 /// Parse ident or ident @ pat
3672 /// used by the copy foo and ref foo patterns to give a good
3673 /// error message when parsing mistakes like ref foo(a,b)
3674 fn parse_pat_ident(&mut self,
3675 binding_mode: ast::BindingMode)
3676 -> PResult<'a, PatKind> {
3677 let ident_span = self.span;
3678 let ident = self.parse_ident()?;
3679 let name = codemap::Spanned{span: ident_span, node: ident};
3680 let sub = if self.eat(&token::At) {
3681 Some(self.parse_pat()?)
3686 // just to be friendly, if they write something like
3688 // we end up here with ( as the current token. This shortly
3689 // leads to a parse error. Note that if there is no explicit
3690 // binding mode then we do not end up here, because the lookahead
3691 // will direct us over to parse_enum_variant()
3692 if self.token == token::OpenDelim(token::Paren) {
3693 return Err(self.span_fatal(
3695 "expected identifier, found enum pattern"))
3698 Ok(PatKind::Ident(binding_mode, name, sub))
3701 /// Parse a local variable declaration
3702 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3703 let lo = self.prev_span;
3704 let pat = self.parse_pat()?;
3706 let ty = if self.eat(&token::Colon) {
3707 Some(self.parse_ty()?)
3711 let init = self.parse_initializer()?;
3712 let hi = if self.token == token::Semi {
3721 id: ast::DUMMY_NODE_ID,
3727 /// Parse a structure field
3728 fn parse_name_and_ty(&mut self,
3731 attrs: Vec<Attribute>)
3732 -> PResult<'a, StructField> {
3733 let name = self.parse_ident()?;
3734 self.expect(&token::Colon)?;
3735 let ty = self.parse_ty()?;
3737 span: lo.to(self.prev_span),
3740 id: ast::DUMMY_NODE_ID,
3746 /// Emit an expected item after attributes error.
3747 fn expected_item_err(&self, attrs: &[Attribute]) {
3748 let message = match attrs.last() {
3749 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3750 _ => "expected item after attributes",
3753 self.span_err(self.prev_span, message);
3756 /// Parse a statement. This stops just before trailing semicolons on everything but items.
3757 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3758 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3759 Ok(self.parse_stmt_(true))
3762 // Eat tokens until we can be relatively sure we reached the end of the
3763 // statement. This is something of a best-effort heuristic.
3765 // We terminate when we find an unmatched `}` (without consuming it).
3766 fn recover_stmt(&mut self) {
3767 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
3770 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3771 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3772 // approximate - it can mean we break too early due to macros, but that
3773 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3775 // If `break_on_block` is `Break`, then we will stop consuming tokens
3776 // after finding (and consuming) a brace-delimited block.
3777 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
3778 let mut brace_depth = 0;
3779 let mut bracket_depth = 0;
3780 let mut in_block = false;
3781 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
3782 break_on_semi, break_on_block);
3784 debug!("recover_stmt_ loop {:?}", self.token);
3786 token::OpenDelim(token::DelimToken::Brace) => {
3789 if break_on_block == BlockMode::Break &&
3791 bracket_depth == 0 {
3795 token::OpenDelim(token::DelimToken::Bracket) => {
3799 token::CloseDelim(token::DelimToken::Brace) => {
3800 if brace_depth == 0 {
3801 debug!("recover_stmt_ return - close delim {:?}", self.token);
3806 if in_block && bracket_depth == 0 && brace_depth == 0 {
3807 debug!("recover_stmt_ return - block end {:?}", self.token);
3811 token::CloseDelim(token::DelimToken::Bracket) => {
3813 if bracket_depth < 0 {
3819 debug!("recover_stmt_ return - Eof");
3824 if break_on_semi == SemiColonMode::Break &&
3826 bracket_depth == 0 {
3827 debug!("recover_stmt_ return - Semi");
3838 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
3839 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
3841 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
3846 fn is_catch_expr(&mut self) -> bool {
3847 self.token.is_keyword(keywords::Do) &&
3848 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
3849 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
3851 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3852 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
3855 fn is_union_item(&self) -> bool {
3856 self.token.is_keyword(keywords::Union) &&
3857 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
3860 fn is_defaultness(&self) -> bool {
3861 // `pub` is included for better error messages
3862 self.token.is_keyword(keywords::Default) &&
3863 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
3864 t.is_keyword(keywords::Const) ||
3865 t.is_keyword(keywords::Fn) ||
3866 t.is_keyword(keywords::Unsafe) ||
3867 t.is_keyword(keywords::Extern) ||
3868 t.is_keyword(keywords::Type) ||
3869 t.is_keyword(keywords::Pub))
3872 fn eat_defaultness(&mut self) -> bool {
3873 let is_defaultness = self.is_defaultness();
3877 self.expected_tokens.push(TokenType::Keyword(keywords::Default));
3882 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
3883 -> PResult<'a, Option<P<Item>>> {
3884 let token_lo = self.span;
3885 let (ident, def) = match self.token {
3886 token::Ident(ident) if ident.name == keywords::Macro.name() => {
3888 let ident = self.parse_ident()?;
3889 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
3890 match self.parse_token_tree() {
3891 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
3892 _ => unreachable!(),
3894 } else if self.check(&token::OpenDelim(token::Paren)) {
3895 let args = self.parse_token_tree();
3896 let body = if self.check(&token::OpenDelim(token::Brace)) {
3897 self.parse_token_tree()
3902 TokenStream::concat(vec![
3904 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
3912 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
3914 token::Ident(ident) if ident.name == "macro_rules" &&
3915 self.look_ahead(1, |t| *t == token::Not) => {
3916 let prev_span = self.prev_span;
3917 self.complain_if_pub_macro(vis, prev_span);
3921 let ident = self.parse_ident()?;
3922 let (delim, tokens) = self.expect_delimited_token_tree()?;
3923 if delim != token::Brace {
3924 if !self.eat(&token::Semi) {
3925 let msg = "macros that expand to items must either \
3926 be surrounded with braces or followed by a semicolon";
3927 self.span_err(self.prev_span, msg);
3931 (ident, ast::MacroDef { tokens: tokens, legacy: true })
3933 _ => return Ok(None),
3936 let span = lo.to(self.prev_span);
3937 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
3940 fn parse_stmt_without_recovery(&mut self,
3941 macro_legacy_warnings: bool)
3942 -> PResult<'a, Option<Stmt>> {
3943 maybe_whole!(self, NtStmt, |x| Some(x));
3945 let attrs = self.parse_outer_attributes()?;
3948 Ok(Some(if self.eat_keyword(keywords::Let) {
3950 id: ast::DUMMY_NODE_ID,
3951 node: StmtKind::Local(self.parse_local(attrs.into())?),
3952 span: lo.to(self.prev_span),
3954 } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited, lo)? {
3956 id: ast::DUMMY_NODE_ID,
3957 node: StmtKind::Item(macro_def),
3958 span: lo.to(self.prev_span),
3960 // Starts like a simple path, but not a union item.
3961 } else if self.token.is_path_start() &&
3962 !self.token.is_qpath_start() &&
3963 !self.is_union_item() {
3964 let pth = self.parse_path(PathStyle::Expr)?;
3966 if !self.eat(&token::Not) {
3967 let expr = if self.check(&token::OpenDelim(token::Brace)) {
3968 self.parse_struct_expr(lo, pth, ThinVec::new())?
3970 let hi = self.prev_span;
3971 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
3974 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
3975 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
3976 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
3979 return Ok(Some(Stmt {
3980 id: ast::DUMMY_NODE_ID,
3981 node: StmtKind::Expr(expr),
3982 span: lo.to(self.prev_span),
3986 // it's a macro invocation
3987 let id = match self.token {
3988 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
3989 _ => self.parse_ident()?,
3992 // check that we're pointing at delimiters (need to check
3993 // again after the `if`, because of `parse_ident`
3994 // consuming more tokens).
3995 let delim = match self.token {
3996 token::OpenDelim(delim) => delim,
3998 // we only expect an ident if we didn't parse one
4000 let ident_str = if id.name == keywords::Invalid.name() {
4005 let tok_str = self.this_token_to_string();
4006 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4012 let (_, tts) = self.expect_delimited_token_tree()?;
4013 let hi = self.prev_span;
4015 let style = if delim == token::Brace {
4016 MacStmtStyle::Braces
4018 MacStmtStyle::NoBraces
4021 if id.name == keywords::Invalid.name() {
4022 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
4023 let node = if delim == token::Brace ||
4024 self.token == token::Semi || self.token == token::Eof {
4025 StmtKind::Mac(P((mac, style, attrs.into())))
4027 // We used to incorrectly stop parsing macro-expanded statements here.
4028 // If the next token will be an error anyway but could have parsed with the
4029 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4030 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4031 // These can continue an expression, so we can't stop parsing and warn.
4032 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4033 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4034 token::BinOp(token::And) | token::BinOp(token::Or) |
4035 token::AndAnd | token::OrOr |
4036 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4039 self.warn_missing_semicolon();
4040 StmtKind::Mac(P((mac, style, attrs.into())))
4042 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4043 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4044 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4048 id: ast::DUMMY_NODE_ID,
4053 // if it has a special ident, it's definitely an item
4055 // Require a semicolon or braces.
4056 if style != MacStmtStyle::Braces {
4057 if !self.eat(&token::Semi) {
4058 self.span_err(self.prev_span,
4059 "macros that expand to items must \
4060 either be surrounded with braces or \
4061 followed by a semicolon");
4064 let span = lo.to(hi);
4066 id: ast::DUMMY_NODE_ID,
4068 node: StmtKind::Item({
4070 span, id /*id is good here*/,
4071 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
4072 Visibility::Inherited,
4078 // FIXME: Bad copy of attrs
4079 let old_directory_ownership =
4080 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4081 let item = self.parse_item_(attrs.clone(), false, true)?;
4082 self.directory.ownership = old_directory_ownership;
4086 id: ast::DUMMY_NODE_ID,
4087 span: lo.to(i.span),
4088 node: StmtKind::Item(i),
4091 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4092 if !attrs.is_empty() {
4093 if s.prev_token_kind == PrevTokenKind::DocComment {
4094 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4095 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4096 s.span_err(s.span, "expected statement after outer attribute");
4101 // Do not attempt to parse an expression if we're done here.
4102 if self.token == token::Semi {
4103 unused_attrs(&attrs, self);
4108 if self.token == token::CloseDelim(token::Brace) {
4109 unused_attrs(&attrs, self);
4113 // Remainder are line-expr stmts.
4114 let e = self.parse_expr_res(
4115 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4117 id: ast::DUMMY_NODE_ID,
4118 span: lo.to(e.span),
4119 node: StmtKind::Expr(e),
4126 /// Is this expression a successfully-parsed statement?
4127 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4128 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4129 !classify::expr_requires_semi_to_be_stmt(e)
4132 /// Parse a block. No inner attrs are allowed.
4133 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4134 maybe_whole!(self, NtBlock, |x| x);
4138 if !self.eat(&token::OpenDelim(token::Brace)) {
4140 let tok = self.this_token_to_string();
4141 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4143 // Check to see if the user has written something like
4148 // Which is valid in other languages, but not Rust.
4149 match self.parse_stmt_without_recovery(false) {
4151 let mut stmt_span = stmt.span;
4152 // expand the span to include the semicolon, if it exists
4153 if self.eat(&token::Semi) {
4154 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4156 let sugg = pprust::to_string(|s| {
4157 use print::pprust::{PrintState, INDENT_UNIT};
4158 s.ibox(INDENT_UNIT)?;
4160 s.print_stmt(&stmt)?;
4161 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4163 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4166 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4167 self.cancel(&mut e);
4174 self.parse_block_tail(lo, BlockCheckMode::Default)
4177 /// Parse a block. Inner attrs are allowed.
4178 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4179 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4182 self.expect(&token::OpenDelim(token::Brace))?;
4183 Ok((self.parse_inner_attributes()?,
4184 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4187 /// Parse the rest of a block expression or function body
4188 /// Precondition: already parsed the '{'.
4189 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4190 let mut stmts = vec![];
4192 while !self.eat(&token::CloseDelim(token::Brace)) {
4193 if let Some(stmt) = self.parse_full_stmt(false)? {
4195 } else if self.token == token::Eof {
4198 // Found only `;` or `}`.
4205 id: ast::DUMMY_NODE_ID,
4207 span: lo.to(self.prev_span),
4211 /// Parse a statement, including the trailing semicolon.
4212 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4213 let mut stmt = match self.parse_stmt_(macro_legacy_warnings) {
4215 None => return Ok(None),
4219 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4220 // expression without semicolon
4221 if classify::expr_requires_semi_to_be_stmt(expr) {
4222 // Just check for errors and recover; do not eat semicolon yet.
4224 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4227 self.recover_stmt();
4231 StmtKind::Local(..) => {
4232 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4233 if macro_legacy_warnings && self.token != token::Semi {
4234 self.warn_missing_semicolon();
4236 self.expect_one_of(&[token::Semi], &[])?;
4242 if self.eat(&token::Semi) {
4243 stmt = stmt.add_trailing_semicolon();
4246 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4250 fn warn_missing_semicolon(&self) {
4251 self.diagnostic().struct_span_warn(self.span, {
4252 &format!("expected `;`, found `{}`", self.this_token_to_string())
4254 "This was erroneously allowed and will become a hard error in a future release"
4258 fn warn_dotdoteq(&self, span: Span) {
4259 self.diagnostic().struct_span_warn(span, {
4260 "`...` is being replaced by `..=`"
4264 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4265 // BOUND = TY_BOUND | LT_BOUND
4266 // LT_BOUND = LIFETIME (e.g. `'a`)
4267 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4268 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4269 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4270 let mut bounds = Vec::new();
4272 // This needs to be syncronized with `Token::can_begin_bound`.
4273 let is_bound_start = self.check_path() || self.check_lifetime() ||
4274 self.check(&token::Question) ||
4275 self.check_keyword(keywords::For) ||
4276 self.check(&token::OpenDelim(token::Paren));
4278 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4279 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4280 if self.token.is_lifetime() {
4281 if let Some(question_span) = question {
4282 self.span_err(question_span,
4283 "`?` may only modify trait bounds, not lifetime bounds");
4285 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4288 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4289 let path = self.parse_path(PathStyle::Type)?;
4290 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4291 let modifier = if question.is_some() {
4292 TraitBoundModifier::Maybe
4294 TraitBoundModifier::None
4296 bounds.push(TraitTyParamBound(poly_trait, modifier));
4299 self.expect(&token::CloseDelim(token::Paren))?;
4300 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4301 self.span_err(self.prev_span,
4302 "parenthesized lifetime bounds are not supported");
4309 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4317 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4318 self.parse_ty_param_bounds_common(true)
4321 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4322 // BOUND = LT_BOUND (e.g. `'a`)
4323 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4324 let mut lifetimes = Vec::new();
4325 while self.check_lifetime() {
4326 lifetimes.push(self.expect_lifetime());
4328 if !self.eat(&token::BinOp(token::Plus)) {
4335 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4336 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4337 let span = self.span;
4338 let ident = self.parse_ident()?;
4340 // Parse optional colon and param bounds.
4341 let bounds = if self.eat(&token::Colon) {
4342 self.parse_ty_param_bounds()?
4347 let default = if self.eat(&token::Eq) {
4348 Some(self.parse_ty()?)
4354 attrs: preceding_attrs.into(),
4356 id: ast::DUMMY_NODE_ID,
4363 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4364 /// trailing comma and erroneous trailing attributes.
4365 pub fn parse_generic_params(&mut self) -> PResult<'a, (Vec<LifetimeDef>, Vec<TyParam>)> {
4366 let mut lifetime_defs = Vec::new();
4367 let mut ty_params = Vec::new();
4368 let mut seen_ty_param = false;
4370 let attrs = self.parse_outer_attributes()?;
4371 if self.check_lifetime() {
4372 let lifetime = self.expect_lifetime();
4373 // Parse lifetime parameter.
4374 let bounds = if self.eat(&token::Colon) {
4375 self.parse_lt_param_bounds()
4379 lifetime_defs.push(LifetimeDef {
4380 attrs: attrs.into(),
4385 self.span_err(self.prev_span,
4386 "lifetime parameters must be declared prior to type parameters");
4388 } else if self.check_ident() {
4389 // Parse type parameter.
4390 ty_params.push(self.parse_ty_param(attrs)?);
4391 seen_ty_param = true;
4393 // Check for trailing attributes and stop parsing.
4394 if !attrs.is_empty() {
4395 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4396 self.span_err(attrs[0].span,
4397 &format!("trailing attribute after {} parameters", param_kind));
4402 if !self.eat(&token::Comma) {
4406 Ok((lifetime_defs, ty_params))
4409 /// Parse a set of optional generic type parameter declarations. Where
4410 /// clauses are not parsed here, and must be added later via
4411 /// `parse_where_clause()`.
4413 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4414 /// | ( < lifetimes , typaramseq ( , )? > )
4415 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4416 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4417 maybe_whole!(self, NtGenerics, |x| x);
4419 let span_lo = self.span;
4421 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4424 lifetimes: lifetime_defs,
4426 where_clause: WhereClause {
4427 id: ast::DUMMY_NODE_ID,
4428 predicates: Vec::new(),
4429 span: syntax_pos::DUMMY_SP,
4431 span: span_lo.to(self.prev_span),
4434 Ok(ast::Generics::default())
4438 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4439 /// possibly including trailing comma.
4440 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4441 let mut lifetimes = Vec::new();
4442 let mut types = Vec::new();
4443 let mut bindings = Vec::new();
4444 let mut seen_type = false;
4445 let mut seen_binding = false;
4447 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4448 // Parse lifetime argument.
4449 lifetimes.push(self.expect_lifetime());
4450 if seen_type || seen_binding {
4451 self.span_err(self.prev_span,
4452 "lifetime parameters must be declared prior to type parameters");
4454 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4455 // Parse associated type binding.
4457 let ident = self.parse_ident()?;
4459 let ty = self.parse_ty()?;
4460 bindings.push(TypeBinding {
4461 id: ast::DUMMY_NODE_ID,
4464 span: lo.to(self.prev_span),
4466 seen_binding = true;
4467 } else if self.check_type() {
4468 // Parse type argument.
4469 types.push(self.parse_ty()?);
4471 self.span_err(types[types.len() - 1].span,
4472 "type parameters must be declared prior to associated type bindings");
4479 if !self.eat(&token::Comma) {
4483 Ok((lifetimes, types, bindings))
4486 /// Parses an optional `where` clause and places it in `generics`.
4488 /// ```ignore (only-for-syntax-highlight)
4489 /// where T : Trait<U, V> + 'b, 'a : 'b
4491 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4492 maybe_whole!(self, NtWhereClause, |x| x);
4494 let mut where_clause = WhereClause {
4495 id: ast::DUMMY_NODE_ID,
4496 predicates: Vec::new(),
4497 span: syntax_pos::DUMMY_SP,
4500 if !self.eat_keyword(keywords::Where) {
4501 return Ok(where_clause);
4503 let lo = self.prev_span;
4505 // This is a temporary future proofing.
4507 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4508 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4509 // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4510 if token::Lt == self.token {
4511 let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4512 if ident_or_lifetime {
4513 let gt_comma_or_colon = self.look_ahead(2, |t| {
4514 *t == token::Gt || *t == token::Comma || *t == token::Colon
4516 if gt_comma_or_colon {
4517 self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4524 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4525 let lifetime = self.expect_lifetime();
4526 // Bounds starting with a colon are mandatory, but possibly empty.
4527 self.expect(&token::Colon)?;
4528 let bounds = self.parse_lt_param_bounds();
4529 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4530 ast::WhereRegionPredicate {
4531 span: lo.to(self.prev_span),
4536 } else if self.check_type() {
4537 // Parse optional `for<'a, 'b>`.
4538 // This `for` is parsed greedily and applies to the whole predicate,
4539 // the bounded type can have its own `for` applying only to it.
4540 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4541 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4542 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4543 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4545 // Parse type with mandatory colon and (possibly empty) bounds,
4546 // or with mandatory equality sign and the second type.
4547 let ty = self.parse_ty()?;
4548 if self.eat(&token::Colon) {
4549 let bounds = self.parse_ty_param_bounds()?;
4550 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4551 ast::WhereBoundPredicate {
4552 span: lo.to(self.prev_span),
4553 bound_lifetimes: lifetime_defs,
4558 // FIXME: Decide what should be used here, `=` or `==`.
4559 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4560 let rhs_ty = self.parse_ty()?;
4561 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4562 ast::WhereEqPredicate {
4563 span: lo.to(self.prev_span),
4566 id: ast::DUMMY_NODE_ID,
4570 return self.unexpected();
4576 if !self.eat(&token::Comma) {
4581 where_clause.span = lo.to(self.prev_span);
4585 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4586 -> PResult<'a, (Vec<Arg> , bool)> {
4588 let mut variadic = false;
4589 let args: Vec<Option<Arg>> =
4590 self.parse_unspanned_seq(
4591 &token::OpenDelim(token::Paren),
4592 &token::CloseDelim(token::Paren),
4593 SeqSep::trailing_allowed(token::Comma),
4595 if p.token == token::DotDotDot {
4598 if p.token != token::CloseDelim(token::Paren) {
4601 "`...` must be last in argument list for variadic function");
4606 "only foreign functions are allowed to be variadic");
4611 match p.parse_arg_general(named_args) {
4612 Ok(arg) => Ok(Some(arg)),
4615 let lo = p.prev_span;
4616 // Skip every token until next possible arg or end.
4617 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4618 // Create a placeholder argument for proper arg count (#34264).
4619 let span = lo.to(p.prev_span);
4620 Ok(Some(dummy_arg(span)))
4627 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4629 if variadic && args.is_empty() {
4631 "variadic function must be declared with at least one named argument");
4634 Ok((args, variadic))
4637 /// Parse the argument list and result type of a function declaration
4638 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4640 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4641 let ret_ty = self.parse_ret_ty()?;
4650 /// Returns the parsed optional self argument and whether a self shortcut was used.
4651 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4652 let expect_ident = |this: &mut Self| match this.token {
4653 // Preserve hygienic context.
4654 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4657 let isolated_self = |this: &mut Self, n| {
4658 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4659 this.look_ahead(n + 1, |t| t != &token::ModSep)
4662 // Parse optional self parameter of a method.
4663 // Only a limited set of initial token sequences is considered self parameters, anything
4664 // else is parsed as a normal function parameter list, so some lookahead is required.
4665 let eself_lo = self.span;
4666 let (eself, eself_ident) = match self.token {
4667 token::BinOp(token::And) => {
4673 if isolated_self(self, 1) {
4675 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4676 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4677 isolated_self(self, 2) {
4680 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4681 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4682 isolated_self(self, 2) {
4684 let lt = self.expect_lifetime();
4685 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4686 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4687 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4688 isolated_self(self, 3) {
4690 let lt = self.expect_lifetime();
4692 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4697 token::BinOp(token::Star) => {
4702 // Emit special error for `self` cases.
4703 if isolated_self(self, 1) {
4705 self.span_err(self.span, "cannot pass `self` by raw pointer");
4706 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4707 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4708 isolated_self(self, 2) {
4711 self.span_err(self.span, "cannot pass `self` by raw pointer");
4712 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4717 token::Ident(..) => {
4718 if isolated_self(self, 0) {
4721 let eself_ident = expect_ident(self);
4722 if self.eat(&token::Colon) {
4723 let ty = self.parse_ty()?;
4724 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4726 (SelfKind::Value(Mutability::Immutable), eself_ident)
4728 } else if self.token.is_keyword(keywords::Mut) &&
4729 isolated_self(self, 1) {
4733 let eself_ident = expect_ident(self);
4734 if self.eat(&token::Colon) {
4735 let ty = self.parse_ty()?;
4736 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4738 (SelfKind::Value(Mutability::Mutable), eself_ident)
4744 _ => return Ok(None),
4747 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
4748 Ok(Some(Arg::from_self(eself, eself_ident)))
4751 /// Parse the parameter list and result type of a function that may have a `self` parameter.
4752 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
4753 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4755 self.expect(&token::OpenDelim(token::Paren))?;
4757 // Parse optional self argument
4758 let self_arg = self.parse_self_arg()?;
4760 // Parse the rest of the function parameter list.
4761 let sep = SeqSep::trailing_allowed(token::Comma);
4762 let fn_inputs = if let Some(self_arg) = self_arg {
4763 if self.check(&token::CloseDelim(token::Paren)) {
4765 } else if self.eat(&token::Comma) {
4766 let mut fn_inputs = vec![self_arg];
4767 fn_inputs.append(&mut self.parse_seq_to_before_end(
4768 &token::CloseDelim(token::Paren), sep, parse_arg_fn)
4772 return self.unexpected();
4775 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4778 // Parse closing paren and return type.
4779 self.expect(&token::CloseDelim(token::Paren))?;
4782 output: self.parse_ret_ty()?,
4787 // parse the |arg, arg| header on a lambda
4788 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4789 let inputs_captures = {
4790 if self.eat(&token::OrOr) {
4793 self.expect(&token::BinOp(token::Or))?;
4794 let args = self.parse_seq_to_before_tokens(
4795 &[&token::BinOp(token::Or), &token::OrOr],
4796 SeqSep::trailing_allowed(token::Comma),
4797 TokenExpectType::NoExpect,
4798 |p| p.parse_fn_block_arg(),
4805 let output = self.parse_ret_ty()?;
4808 inputs: inputs_captures,
4814 /// Parse the name and optional generic types of a function header.
4815 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4816 let id = self.parse_ident()?;
4817 let generics = self.parse_generics()?;
4821 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
4822 attrs: Vec<Attribute>) -> P<Item> {
4826 id: ast::DUMMY_NODE_ID,
4834 /// Parse an item-position function declaration.
4835 fn parse_item_fn(&mut self,
4837 constness: Spanned<Constness>,
4839 -> PResult<'a, ItemInfo> {
4840 let (ident, mut generics) = self.parse_fn_header()?;
4841 let decl = self.parse_fn_decl(false)?;
4842 generics.where_clause = self.parse_where_clause()?;
4843 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4844 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4847 /// true if we are looking at `const ID`, false for things like `const fn` etc
4848 pub fn is_const_item(&mut self) -> bool {
4849 self.token.is_keyword(keywords::Const) &&
4850 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4851 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4854 /// parses all the "front matter" for a `fn` declaration, up to
4855 /// and including the `fn` keyword:
4859 /// - `const unsafe fn`
4862 pub fn parse_fn_front_matter(&mut self)
4863 -> PResult<'a, (Spanned<ast::Constness>,
4866 let is_const_fn = self.eat_keyword(keywords::Const);
4867 let const_span = self.prev_span;
4868 let unsafety = self.parse_unsafety()?;
4869 let (constness, unsafety, abi) = if is_const_fn {
4870 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
4872 let abi = if self.eat_keyword(keywords::Extern) {
4873 self.parse_opt_abi()?.unwrap_or(Abi::C)
4877 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
4879 self.expect_keyword(keywords::Fn)?;
4880 Ok((constness, unsafety, abi))
4883 /// Parse an impl item.
4884 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
4885 maybe_whole!(self, NtImplItem, |x| x);
4886 let attrs = self.parse_outer_attributes()?;
4887 let (mut item, tokens) = self.collect_tokens(|this| {
4888 this.parse_impl_item_(at_end, attrs)
4891 // See `parse_item` for why this clause is here.
4892 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
4893 item.tokens = Some(tokens);
4898 fn parse_impl_item_(&mut self,
4900 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
4902 let vis = self.parse_visibility(false)?;
4903 let defaultness = self.parse_defaultness()?;
4904 let (name, node) = if self.eat_keyword(keywords::Type) {
4905 let name = self.parse_ident()?;
4906 self.expect(&token::Eq)?;
4907 let typ = self.parse_ty()?;
4908 self.expect(&token::Semi)?;
4909 (name, ast::ImplItemKind::Type(typ))
4910 } else if self.is_const_item() {
4911 self.expect_keyword(keywords::Const)?;
4912 let name = self.parse_ident()?;
4913 self.expect(&token::Colon)?;
4914 let typ = self.parse_ty()?;
4915 self.expect(&token::Eq)?;
4916 let expr = self.parse_expr()?;
4917 self.expect(&token::Semi)?;
4918 (name, ast::ImplItemKind::Const(typ, expr))
4920 let (name, inner_attrs, node) = self.parse_impl_method(&vis, at_end)?;
4921 attrs.extend(inner_attrs);
4926 id: ast::DUMMY_NODE_ID,
4927 span: lo.to(self.prev_span),
4937 fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
4938 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
4943 fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
4945 Visibility::Inherited => Ok(()),
4947 let is_macro_rules: bool = match self.token {
4948 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
4952 let mut err = self.diagnostic()
4953 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
4954 err.help("did you mean #[macro_export]?");
4957 let mut err = self.diagnostic()
4958 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
4959 err.help("try adjusting the macro to put `pub` inside the invocation");
4966 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
4967 -> DiagnosticBuilder<'a>
4969 // Given this code `path(`, it seems like this is not
4970 // setting the visibility of a macro invocation, but rather
4971 // a mistyped method declaration.
4972 // Create a diagnostic pointing out that `fn` is missing.
4974 // x | pub path(&self) {
4975 // | ^ missing `fn`, `type`, or `const`
4977 // ^^ `sp` below will point to this
4978 let sp = prev_span.between(self.prev_span);
4979 let mut err = self.diagnostic().struct_span_err(
4981 &format!("missing `fn`, `type`, or `const` for {}-item declaration",
4983 err.span_label(sp, "missing `fn`, `type`, or `const`");
4987 /// Parse a method or a macro invocation in a trait impl.
4988 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
4989 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4990 // code copied from parse_macro_use_or_failure... abstraction!
4991 if self.token.is_path_start() {
4994 let prev_span = self.prev_span;
4997 let pth = self.parse_path(PathStyle::Mod)?;
4998 if pth.segments.len() == 1 {
4999 if !self.eat(&token::Not) {
5000 return Err(self.missing_assoc_item_kind_err("impl", prev_span));
5003 self.expect(&token::Not)?;
5006 self.complain_if_pub_macro(vis, prev_span);
5008 // eat a matched-delimiter token tree:
5010 let (delim, tts) = self.expect_delimited_token_tree()?;
5011 if delim != token::Brace {
5012 self.expect(&token::Semi)?
5015 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
5016 Ok((keywords::Invalid.ident(), vec![], ast::ImplItemKind::Macro(mac)))
5018 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
5019 let ident = self.parse_ident()?;
5020 let mut generics = self.parse_generics()?;
5021 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5022 generics.where_clause = self.parse_where_clause()?;
5024 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5025 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
5035 /// Parse trait Foo { ... }
5036 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5037 let ident = self.parse_ident()?;
5038 let mut tps = self.parse_generics()?;
5040 // Parse optional colon and supertrait bounds.
5041 let bounds = if self.eat(&token::Colon) {
5042 self.parse_ty_param_bounds()?
5047 tps.where_clause = self.parse_where_clause()?;
5049 self.expect(&token::OpenDelim(token::Brace))?;
5050 let mut trait_items = vec![];
5051 while !self.eat(&token::CloseDelim(token::Brace)) {
5052 let mut at_end = false;
5053 match self.parse_trait_item(&mut at_end) {
5054 Ok(item) => trait_items.push(item),
5058 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5063 Ok((ident, ItemKind::Trait(unsafety, tps, bounds, trait_items), None))
5066 /// Parses items implementations variants
5067 /// impl<T> Foo { ... }
5068 /// impl<T> ToString for &'static T { ... }
5069 /// impl Send for .. {}
5070 fn parse_item_impl(&mut self,
5071 unsafety: ast::Unsafety,
5072 defaultness: Defaultness) -> PResult<'a, ItemInfo> {
5073 let impl_span = self.span;
5075 // First, parse type parameters if necessary.
5076 let mut generics = self.parse_generics()?;
5078 // Special case: if the next identifier that follows is '(', don't
5079 // allow this to be parsed as a trait.
5080 let could_be_trait = self.token != token::OpenDelim(token::Paren);
5082 let neg_span = self.span;
5083 let polarity = if self.eat(&token::Not) {
5084 ast::ImplPolarity::Negative
5086 ast::ImplPolarity::Positive
5090 let mut ty = self.parse_ty()?;
5092 // Parse traits, if necessary.
5093 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
5094 // New-style trait. Reinterpret the type as a trait.
5096 TyKind::Path(None, ref path) => {
5098 path: (*path).clone(),
5103 self.span_err(ty.span, "not a trait");
5108 if polarity == ast::ImplPolarity::Negative {
5109 // This is a negated type implementation
5110 // `impl !MyType {}`, which is not allowed.
5111 self.span_err(neg_span, "inherent implementation can't be negated");
5116 if opt_trait.is_some() && self.eat(&token::DotDot) {
5117 if generics.is_parameterized() {
5118 self.span_err(impl_span, "default trait implementations are not \
5119 allowed to have generics");
5122 if let ast::Defaultness::Default = defaultness {
5123 self.span_err(impl_span, "`default impl` is not allowed for \
5124 default trait implementations");
5127 self.expect(&token::OpenDelim(token::Brace))?;
5128 self.expect(&token::CloseDelim(token::Brace))?;
5129 Ok((keywords::Invalid.ident(),
5130 ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
5132 if opt_trait.is_some() {
5133 ty = self.parse_ty()?;
5135 generics.where_clause = self.parse_where_clause()?;
5137 self.expect(&token::OpenDelim(token::Brace))?;
5138 let attrs = self.parse_inner_attributes()?;
5140 let mut impl_items = vec![];
5141 while !self.eat(&token::CloseDelim(token::Brace)) {
5142 let mut at_end = false;
5143 match self.parse_impl_item(&mut at_end) {
5144 Ok(item) => impl_items.push(item),
5148 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5154 Ok((keywords::Invalid.ident(),
5155 ItemKind::Impl(unsafety, polarity, defaultness, generics, opt_trait, ty, impl_items),
5160 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<LifetimeDef>> {
5161 if self.eat_keyword(keywords::For) {
5163 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
5165 if !ty_params.is_empty() {
5166 self.span_err(ty_params[0].span,
5167 "only lifetime parameters can be used in this context");
5175 /// Parse struct Foo { ... }
5176 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5177 let class_name = self.parse_ident()?;
5179 let mut generics = self.parse_generics()?;
5181 // There is a special case worth noting here, as reported in issue #17904.
5182 // If we are parsing a tuple struct it is the case that the where clause
5183 // should follow the field list. Like so:
5185 // struct Foo<T>(T) where T: Copy;
5187 // If we are parsing a normal record-style struct it is the case
5188 // that the where clause comes before the body, and after the generics.
5189 // So if we look ahead and see a brace or a where-clause we begin
5190 // parsing a record style struct.
5192 // Otherwise if we look ahead and see a paren we parse a tuple-style
5195 let vdata = if self.token.is_keyword(keywords::Where) {
5196 generics.where_clause = self.parse_where_clause()?;
5197 if self.eat(&token::Semi) {
5198 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5199 VariantData::Unit(ast::DUMMY_NODE_ID)
5201 // If we see: `struct Foo<T> where T: Copy { ... }`
5202 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5204 // No `where` so: `struct Foo<T>;`
5205 } else if self.eat(&token::Semi) {
5206 VariantData::Unit(ast::DUMMY_NODE_ID)
5207 // Record-style struct definition
5208 } else if self.token == token::OpenDelim(token::Brace) {
5209 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5210 // Tuple-style struct definition with optional where-clause.
5211 } else if self.token == token::OpenDelim(token::Paren) {
5212 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5213 generics.where_clause = self.parse_where_clause()?;
5214 self.expect(&token::Semi)?;
5217 let token_str = self.this_token_to_string();
5218 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5219 name, found `{}`", token_str)))
5222 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5225 /// Parse union Foo { ... }
5226 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5227 let class_name = self.parse_ident()?;
5229 let mut generics = self.parse_generics()?;
5231 let vdata = if self.token.is_keyword(keywords::Where) {
5232 generics.where_clause = self.parse_where_clause()?;
5233 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5234 } else if self.token == token::OpenDelim(token::Brace) {
5235 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5237 let token_str = self.this_token_to_string();
5238 return Err(self.fatal(&format!("expected `where` or `{{` after union \
5239 name, found `{}`", token_str)))
5242 Ok((class_name, ItemKind::Union(vdata, generics), None))
5245 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5246 let mut fields = Vec::new();
5247 if self.eat(&token::OpenDelim(token::Brace)) {
5248 while self.token != token::CloseDelim(token::Brace) {
5249 fields.push(self.parse_struct_decl_field().map_err(|e| {
5250 self.recover_stmt();
5251 self.eat(&token::CloseDelim(token::Brace));
5258 let token_str = self.this_token_to_string();
5259 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5267 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5268 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5269 // Unit like structs are handled in parse_item_struct function
5270 let fields = self.parse_unspanned_seq(
5271 &token::OpenDelim(token::Paren),
5272 &token::CloseDelim(token::Paren),
5273 SeqSep::trailing_allowed(token::Comma),
5275 let attrs = p.parse_outer_attributes()?;
5277 let vis = p.parse_visibility(true)?;
5278 let ty = p.parse_ty()?;
5280 span: lo.to(p.span),
5283 id: ast::DUMMY_NODE_ID,
5292 /// Parse a structure field declaration
5293 pub fn parse_single_struct_field(&mut self,
5296 attrs: Vec<Attribute> )
5297 -> PResult<'a, StructField> {
5298 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5303 token::CloseDelim(token::Brace) => {}
5304 token::DocComment(_) => return Err(self.span_fatal_err(self.span,
5305 Error::UselessDocComment)),
5306 _ => return Err(self.span_fatal_help(self.span,
5307 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5308 "struct fields should be separated by commas")),
5313 /// Parse an element of a struct definition
5314 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5315 let attrs = self.parse_outer_attributes()?;
5317 let vis = self.parse_visibility(false)?;
5318 self.parse_single_struct_field(lo, vis, attrs)
5321 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5322 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5323 /// a function definition, it's not a tuple struct field) and the contents within the parens
5324 /// isn't valid, emit a proper diagnostic.
5325 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5326 maybe_whole!(self, NtVis, |x| x);
5328 if !self.eat_keyword(keywords::Pub) {
5329 return Ok(Visibility::Inherited)
5332 if self.check(&token::OpenDelim(token::Paren)) {
5333 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5334 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5335 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5336 // by the following tokens.
5337 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5340 self.bump(); // `crate`
5341 let vis = Visibility::Crate(self.prev_span);
5342 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5344 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5347 self.bump(); // `in`
5348 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5349 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5350 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5352 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5353 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5354 t.is_keyword(keywords::SelfValue)) {
5355 // `pub(self)` or `pub(super)`
5357 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5358 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5359 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5361 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5362 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5364 let msg = "incorrect visibility restriction";
5365 let suggestion = r##"some possible visibility restrictions are:
5366 `pub(crate)`: visible only on the current crate
5367 `pub(super)`: visible only in the current module's parent
5368 `pub(in path::to::module)`: visible only on the specified path"##;
5369 let path = self.parse_path(PathStyle::Mod)?;
5370 let path_span = self.prev_span;
5371 let help_msg = format!("make this visible only to module `{}` with `in`", path);
5372 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5373 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5374 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5375 err.emit(); // emit diagnostic, but continue with public visibility
5379 Ok(Visibility::Public)
5382 /// Parse defaultness: DEFAULT or nothing
5383 fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5384 if self.eat_defaultness() {
5385 Ok(Defaultness::Default)
5387 Ok(Defaultness::Final)
5391 /// Given a termination token, parse all of the items in a module
5392 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5393 let mut items = vec![];
5394 while let Some(item) = self.parse_item()? {
5398 if !self.eat(term) {
5399 let token_str = self.this_token_to_string();
5400 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5403 let hi = if self.span == syntax_pos::DUMMY_SP {
5410 inner: inner_lo.to(hi),
5415 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5416 let id = self.parse_ident()?;
5417 self.expect(&token::Colon)?;
5418 let ty = self.parse_ty()?;
5419 self.expect(&token::Eq)?;
5420 let e = self.parse_expr()?;
5421 self.expect(&token::Semi)?;
5422 let item = match m {
5423 Some(m) => ItemKind::Static(ty, m, e),
5424 None => ItemKind::Const(ty, e),
5426 Ok((id, item, None))
5429 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5430 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5431 let (in_cfg, outer_attrs) = {
5432 let mut strip_unconfigured = ::config::StripUnconfigured {
5434 should_test: false, // irrelevant
5435 features: None, // don't perform gated feature checking
5437 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5438 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5441 let id_span = self.span;
5442 let id = self.parse_ident()?;
5443 if self.check(&token::Semi) {
5445 if in_cfg && self.recurse_into_file_modules {
5446 // This mod is in an external file. Let's go get it!
5447 let ModulePathSuccess { path, directory_ownership, warn } =
5448 self.submod_path(id, &outer_attrs, id_span)?;
5449 let (module, mut attrs) =
5450 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5452 let attr = ast::Attribute {
5453 id: attr::mk_attr_id(),
5454 style: ast::AttrStyle::Outer,
5455 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5456 Ident::from_str("warn_directory_ownership")),
5457 tokens: TokenStream::empty(),
5458 is_sugared_doc: false,
5459 span: syntax_pos::DUMMY_SP,
5461 attr::mark_known(&attr);
5464 Ok((id, module, Some(attrs)))
5466 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5467 Ok((id, ItemKind::Mod(placeholder), None))
5470 let old_directory = self.directory.clone();
5471 self.push_directory(id, &outer_attrs);
5473 self.expect(&token::OpenDelim(token::Brace))?;
5474 let mod_inner_lo = self.span;
5475 let attrs = self.parse_inner_attributes()?;
5476 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5478 self.directory = old_directory;
5479 Ok((id, ItemKind::Mod(module), Some(attrs)))
5483 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5484 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5485 self.directory.path.push(&path.as_str());
5486 self.directory.ownership = DirectoryOwnership::Owned;
5488 self.directory.path.push(&id.name.as_str());
5492 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5493 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5496 /// Returns either a path to a module, or .
5497 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5498 let mod_name = id.to_string();
5499 let default_path_str = format!("{}.rs", mod_name);
5500 let secondary_path_str = format!("{}{}mod.rs", mod_name, path::MAIN_SEPARATOR);
5501 let default_path = dir_path.join(&default_path_str);
5502 let secondary_path = dir_path.join(&secondary_path_str);
5503 let default_exists = codemap.file_exists(&default_path);
5504 let secondary_exists = codemap.file_exists(&secondary_path);
5506 let result = match (default_exists, secondary_exists) {
5507 (true, false) => Ok(ModulePathSuccess {
5509 directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5512 (false, true) => Ok(ModulePathSuccess {
5513 path: secondary_path,
5514 directory_ownership: DirectoryOwnership::Owned,
5517 (false, false) => Err(Error::FileNotFoundForModule {
5518 mod_name: mod_name.clone(),
5519 default_path: default_path_str,
5520 secondary_path: secondary_path_str,
5521 dir_path: format!("{}", dir_path.display()),
5523 (true, true) => Err(Error::DuplicatePaths {
5524 mod_name: mod_name.clone(),
5525 default_path: default_path_str,
5526 secondary_path: secondary_path_str,
5532 path_exists: default_exists || secondary_exists,
5537 fn submod_path(&mut self,
5539 outer_attrs: &[ast::Attribute],
5541 -> PResult<'a, ModulePathSuccess> {
5542 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5543 return Ok(ModulePathSuccess {
5544 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5545 Some("mod.rs") => DirectoryOwnership::Owned,
5546 _ => DirectoryOwnership::UnownedViaMod(true),
5553 let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5555 if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5557 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5558 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5559 if paths.path_exists {
5560 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5562 err.span_note(id_sp, &msg);
5565 } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5567 if let Ok(result) = paths.result {
5568 return Ok(ModulePathSuccess { warn: true, ..result });
5571 let mut err = self.diagnostic().struct_span_err(id_sp,
5572 "cannot declare a new module at this location");
5573 if id_sp != syntax_pos::DUMMY_SP {
5574 let src_path = PathBuf::from(self.sess.codemap().span_to_filename(id_sp));
5575 if let Some(stem) = src_path.file_stem() {
5576 let mut dest_path = src_path.clone();
5577 dest_path.set_file_name(stem);
5578 dest_path.push("mod.rs");
5579 err.span_note(id_sp,
5580 &format!("maybe move this module `{}` to its own \
5581 directory via `{}`", src_path.to_string_lossy(),
5582 dest_path.to_string_lossy()));
5585 if paths.path_exists {
5586 err.span_note(id_sp,
5587 &format!("... or maybe `use` the module `{}` instead \
5588 of possibly redeclaring it",
5593 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5597 /// Read a module from a source file.
5598 fn eval_src_mod(&mut self,
5600 directory_ownership: DirectoryOwnership,
5603 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5604 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5605 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5606 let mut err = String::from("circular modules: ");
5607 let len = included_mod_stack.len();
5608 for p in &included_mod_stack[i.. len] {
5609 err.push_str(&p.to_string_lossy());
5610 err.push_str(" -> ");
5612 err.push_str(&path.to_string_lossy());
5613 return Err(self.span_fatal(id_sp, &err[..]));
5615 included_mod_stack.push(path.clone());
5616 drop(included_mod_stack);
5619 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5620 p0.cfg_mods = self.cfg_mods;
5621 let mod_inner_lo = p0.span;
5622 let mod_attrs = p0.parse_inner_attributes()?;
5623 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5624 self.sess.included_mod_stack.borrow_mut().pop();
5625 Ok((ast::ItemKind::Mod(m0), mod_attrs))
5628 /// Parse a function declaration from a foreign module
5629 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5630 -> PResult<'a, ForeignItem> {
5631 self.expect_keyword(keywords::Fn)?;
5633 let (ident, mut generics) = self.parse_fn_header()?;
5634 let decl = self.parse_fn_decl(true)?;
5635 generics.where_clause = self.parse_where_clause()?;
5637 self.expect(&token::Semi)?;
5638 Ok(ast::ForeignItem {
5641 node: ForeignItemKind::Fn(decl, generics),
5642 id: ast::DUMMY_NODE_ID,
5648 /// Parse a static item from a foreign module.
5649 /// Assumes that the `static` keyword is already parsed.
5650 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5651 -> PResult<'a, ForeignItem> {
5652 let mutbl = self.eat_keyword(keywords::Mut);
5653 let ident = self.parse_ident()?;
5654 self.expect(&token::Colon)?;
5655 let ty = self.parse_ty()?;
5657 self.expect(&token::Semi)?;
5661 node: ForeignItemKind::Static(ty, mutbl),
5662 id: ast::DUMMY_NODE_ID,
5668 /// Parse extern crate links
5672 /// extern crate foo;
5673 /// extern crate bar as foo;
5674 fn parse_item_extern_crate(&mut self,
5676 visibility: Visibility,
5677 attrs: Vec<Attribute>)
5678 -> PResult<'a, P<Item>> {
5680 let crate_name = self.parse_ident()?;
5681 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
5682 (Some(crate_name.name), ident)
5686 self.expect(&token::Semi)?;
5688 let prev_span = self.prev_span;
5689 Ok(self.mk_item(lo.to(prev_span),
5691 ItemKind::ExternCrate(maybe_path),
5696 /// Parse `extern` for foreign ABIs
5699 /// `extern` is expected to have been
5700 /// consumed before calling this method
5706 fn parse_item_foreign_mod(&mut self,
5708 opt_abi: Option<abi::Abi>,
5709 visibility: Visibility,
5710 mut attrs: Vec<Attribute>)
5711 -> PResult<'a, P<Item>> {
5712 self.expect(&token::OpenDelim(token::Brace))?;
5714 let abi = opt_abi.unwrap_or(Abi::C);
5716 attrs.extend(self.parse_inner_attributes()?);
5718 let mut foreign_items = vec![];
5719 while let Some(item) = self.parse_foreign_item()? {
5720 foreign_items.push(item);
5722 self.expect(&token::CloseDelim(token::Brace))?;
5724 let prev_span = self.prev_span;
5725 let m = ast::ForeignMod {
5727 items: foreign_items
5729 let invalid = keywords::Invalid.ident();
5730 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
5733 /// Parse type Foo = Bar;
5734 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5735 let ident = self.parse_ident()?;
5736 let mut tps = self.parse_generics()?;
5737 tps.where_clause = self.parse_where_clause()?;
5738 self.expect(&token::Eq)?;
5739 let ty = self.parse_ty()?;
5740 self.expect(&token::Semi)?;
5741 Ok((ident, ItemKind::Ty(ty, tps), None))
5744 /// Parse the part of an "enum" decl following the '{'
5745 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5746 let mut variants = Vec::new();
5747 let mut all_nullary = true;
5748 let mut any_disr = None;
5749 while self.token != token::CloseDelim(token::Brace) {
5750 let variant_attrs = self.parse_outer_attributes()?;
5751 let vlo = self.span;
5754 let mut disr_expr = None;
5755 let ident = self.parse_ident()?;
5756 if self.check(&token::OpenDelim(token::Brace)) {
5757 // Parse a struct variant.
5758 all_nullary = false;
5759 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
5760 ast::DUMMY_NODE_ID);
5761 } else if self.check(&token::OpenDelim(token::Paren)) {
5762 all_nullary = false;
5763 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
5764 ast::DUMMY_NODE_ID);
5765 } else if self.eat(&token::Eq) {
5766 disr_expr = Some(self.parse_expr()?);
5767 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5768 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5770 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5773 let vr = ast::Variant_ {
5775 attrs: variant_attrs,
5779 variants.push(respan(vlo.to(self.prev_span), vr));
5781 if !self.eat(&token::Comma) { break; }
5783 self.expect(&token::CloseDelim(token::Brace))?;
5785 Some(disr_span) if !all_nullary =>
5786 self.span_err(disr_span,
5787 "discriminator values can only be used with a c-like enum"),
5791 Ok(ast::EnumDef { variants: variants })
5794 /// Parse an "enum" declaration
5795 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5796 let id = self.parse_ident()?;
5797 let mut generics = self.parse_generics()?;
5798 generics.where_clause = self.parse_where_clause()?;
5799 self.expect(&token::OpenDelim(token::Brace))?;
5801 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
5802 self.recover_stmt();
5803 self.eat(&token::CloseDelim(token::Brace));
5806 Ok((id, ItemKind::Enum(enum_definition, generics), None))
5809 /// Parses a string as an ABI spec on an extern type or module. Consumes
5810 /// the `extern` keyword, if one is found.
5811 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5813 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5815 self.expect_no_suffix(sp, "ABI spec", suf);
5817 match abi::lookup(&s.as_str()) {
5818 Some(abi) => Ok(Some(abi)),
5820 let prev_span = self.prev_span;
5823 &format!("invalid ABI: expected one of [{}], \
5825 abi::all_names().join(", "),
5836 /// Parse one of the items allowed by the flags.
5837 /// NB: this function no longer parses the items inside an
5839 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5840 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5841 maybe_whole!(self, NtItem, |item| {
5842 let mut item = item.unwrap();
5843 let mut attrs = attrs;
5844 mem::swap(&mut item.attrs, &mut attrs);
5845 item.attrs.extend(attrs);
5851 let visibility = self.parse_visibility(false)?;
5853 if self.eat_keyword(keywords::Use) {
5855 let item_ = ItemKind::Use(self.parse_view_path()?);
5856 self.expect(&token::Semi)?;
5858 let prev_span = self.prev_span;
5859 let invalid = keywords::Invalid.ident();
5860 let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
5861 return Ok(Some(item));
5864 if self.eat_keyword(keywords::Extern) {
5865 if self.eat_keyword(keywords::Crate) {
5866 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
5869 let opt_abi = self.parse_opt_abi()?;
5871 if self.eat_keyword(keywords::Fn) {
5872 // EXTERN FUNCTION ITEM
5873 let fn_span = self.prev_span;
5874 let abi = opt_abi.unwrap_or(Abi::C);
5875 let (ident, item_, extra_attrs) =
5876 self.parse_item_fn(Unsafety::Normal,
5877 respan(fn_span, Constness::NotConst),
5879 let prev_span = self.prev_span;
5880 let item = self.mk_item(lo.to(prev_span),
5884 maybe_append(attrs, extra_attrs));
5885 return Ok(Some(item));
5886 } else if self.check(&token::OpenDelim(token::Brace)) {
5887 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
5893 if self.eat_keyword(keywords::Static) {
5895 let m = if self.eat_keyword(keywords::Mut) {
5898 Mutability::Immutable
5900 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
5901 let prev_span = self.prev_span;
5902 let item = self.mk_item(lo.to(prev_span),
5906 maybe_append(attrs, extra_attrs));
5907 return Ok(Some(item));
5909 if self.eat_keyword(keywords::Const) {
5910 let const_span = self.prev_span;
5911 if self.check_keyword(keywords::Fn)
5912 || (self.check_keyword(keywords::Unsafe)
5913 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5914 // CONST FUNCTION ITEM
5915 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5921 let (ident, item_, extra_attrs) =
5922 self.parse_item_fn(unsafety,
5923 respan(const_span, Constness::Const),
5925 let prev_span = self.prev_span;
5926 let item = self.mk_item(lo.to(prev_span),
5930 maybe_append(attrs, extra_attrs));
5931 return Ok(Some(item));
5935 if self.eat_keyword(keywords::Mut) {
5936 let prev_span = self.prev_span;
5937 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
5938 .help("did you mean to declare a static?")
5941 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
5942 let prev_span = self.prev_span;
5943 let item = self.mk_item(lo.to(prev_span),
5947 maybe_append(attrs, extra_attrs));
5948 return Ok(Some(item));
5950 if self.check_keyword(keywords::Unsafe) &&
5951 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5953 // UNSAFE TRAIT ITEM
5954 self.expect_keyword(keywords::Unsafe)?;
5955 self.expect_keyword(keywords::Trait)?;
5956 let (ident, item_, extra_attrs) =
5957 self.parse_item_trait(ast::Unsafety::Unsafe)?;
5958 let prev_span = self.prev_span;
5959 let item = self.mk_item(lo.to(prev_span),
5963 maybe_append(attrs, extra_attrs));
5964 return Ok(Some(item));
5966 if (self.check_keyword(keywords::Unsafe) &&
5967 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))) ||
5968 (self.check_keyword(keywords::Default) &&
5969 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) &&
5970 self.look_ahead(2, |t| t.is_keyword(keywords::Impl)))
5973 let defaultness = self.parse_defaultness()?;
5974 self.expect_keyword(keywords::Unsafe)?;
5975 self.expect_keyword(keywords::Impl)?;
5978 extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe, defaultness)?;
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 self.check_keyword(keywords::Fn) {
5990 let fn_span = self.prev_span;
5991 let (ident, item_, extra_attrs) =
5992 self.parse_item_fn(Unsafety::Normal,
5993 respan(fn_span, Constness::NotConst),
5995 let prev_span = self.prev_span;
5996 let item = self.mk_item(lo.to(prev_span),
6000 maybe_append(attrs, extra_attrs));
6001 return Ok(Some(item));
6003 if self.check_keyword(keywords::Unsafe)
6004 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
6005 // UNSAFE FUNCTION ITEM
6007 let abi = if self.eat_keyword(keywords::Extern) {
6008 self.parse_opt_abi()?.unwrap_or(Abi::C)
6012 self.expect_keyword(keywords::Fn)?;
6013 let fn_span = self.prev_span;
6014 let (ident, item_, extra_attrs) =
6015 self.parse_item_fn(Unsafety::Unsafe,
6016 respan(fn_span, Constness::NotConst),
6018 let prev_span = self.prev_span;
6019 let item = self.mk_item(lo.to(prev_span),
6023 maybe_append(attrs, extra_attrs));
6024 return Ok(Some(item));
6026 if self.eat_keyword(keywords::Mod) {
6028 let (ident, item_, extra_attrs) =
6029 self.parse_item_mod(&attrs[..])?;
6030 let prev_span = self.prev_span;
6031 let item = self.mk_item(lo.to(prev_span),
6035 maybe_append(attrs, extra_attrs));
6036 return Ok(Some(item));
6038 if self.eat_keyword(keywords::Type) {
6040 let (ident, item_, extra_attrs) = self.parse_item_type()?;
6041 let prev_span = self.prev_span;
6042 let item = self.mk_item(lo.to(prev_span),
6046 maybe_append(attrs, extra_attrs));
6047 return Ok(Some(item));
6049 if self.eat_keyword(keywords::Enum) {
6051 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
6052 let prev_span = self.prev_span;
6053 let item = self.mk_item(lo.to(prev_span),
6057 maybe_append(attrs, extra_attrs));
6058 return Ok(Some(item));
6060 if self.eat_keyword(keywords::Trait) {
6062 let (ident, item_, extra_attrs) =
6063 self.parse_item_trait(ast::Unsafety::Normal)?;
6064 let prev_span = self.prev_span;
6065 let item = self.mk_item(lo.to(prev_span),
6069 maybe_append(attrs, extra_attrs));
6070 return Ok(Some(item));
6072 if (self.check_keyword(keywords::Impl)) ||
6073 (self.check_keyword(keywords::Default) &&
6074 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)))
6077 let defaultness = self.parse_defaultness()?;
6078 self.expect_keyword(keywords::Impl)?;
6081 extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal, defaultness)?;
6082 let prev_span = self.prev_span;
6083 let item = self.mk_item(lo.to(prev_span),
6087 maybe_append(attrs, extra_attrs));
6088 return Ok(Some(item));
6090 if self.eat_keyword(keywords::Struct) {
6092 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6093 let prev_span = self.prev_span;
6094 let item = self.mk_item(lo.to(prev_span),
6098 maybe_append(attrs, extra_attrs));
6099 return Ok(Some(item));
6101 if self.is_union_item() {
6104 let (ident, item_, extra_attrs) = self.parse_item_union()?;
6105 let prev_span = self.prev_span;
6106 let item = self.mk_item(lo.to(prev_span),
6110 maybe_append(attrs, extra_attrs));
6111 return Ok(Some(item));
6113 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
6114 return Ok(Some(macro_def));
6117 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
6120 /// Parse a foreign item.
6121 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
6122 let attrs = self.parse_outer_attributes()?;
6124 let visibility = self.parse_visibility(false)?;
6126 // FOREIGN STATIC ITEM
6127 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
6128 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
6129 if self.token.is_keyword(keywords::Const) {
6131 .struct_span_err(self.span, "extern items cannot be `const`")
6132 .span_suggestion(self.span, "instead try using", "static".to_owned())
6135 self.bump(); // `static` or `const`
6136 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6138 // FOREIGN FUNCTION ITEM
6139 if self.check_keyword(keywords::Fn) {
6140 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6143 // FIXME #5668: this will occur for a macro invocation:
6144 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
6146 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
6152 /// This is the fall-through for parsing items.
6153 fn parse_macro_use_or_failure(
6155 attrs: Vec<Attribute> ,
6156 macros_allowed: bool,
6157 attributes_allowed: bool,
6159 visibility: Visibility
6160 ) -> PResult<'a, Option<P<Item>>> {
6161 if macros_allowed && self.token.is_path_start() {
6162 // MACRO INVOCATION ITEM
6164 let prev_span = self.prev_span;
6165 self.complain_if_pub_macro(&visibility, prev_span);
6167 let mac_lo = self.span;
6170 let pth = self.parse_path(PathStyle::Mod)?;
6171 self.expect(&token::Not)?;
6173 // a 'special' identifier (like what `macro_rules!` uses)
6174 // is optional. We should eventually unify invoc syntax
6176 let id = if self.token.is_ident() {
6179 keywords::Invalid.ident() // no special identifier
6181 // eat a matched-delimiter token tree:
6182 let (delim, tts) = self.expect_delimited_token_tree()?;
6183 if delim != token::Brace {
6184 if !self.eat(&token::Semi) {
6185 self.span_err(self.prev_span,
6186 "macros that expand to items must either \
6187 be surrounded with braces or followed by \
6192 let hi = self.prev_span;
6193 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6194 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6195 return Ok(Some(item));
6198 // FAILURE TO PARSE ITEM
6200 Visibility::Inherited => {}
6202 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
6206 if !attributes_allowed && !attrs.is_empty() {
6207 self.expected_item_err(&attrs);
6212 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
6213 where F: FnOnce(&mut Self) -> PResult<'a, R>
6215 // Record all tokens we parse when parsing this item.
6216 let mut tokens = Vec::new();
6217 match self.token_cursor.frame.last_token {
6218 LastToken::Collecting(_) => {
6219 panic!("cannot collect tokens recursively yet")
6221 LastToken::Was(ref mut last) => tokens.extend(last.take()),
6223 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
6224 let prev = self.token_cursor.stack.len();
6226 let last_token = if self.token_cursor.stack.len() == prev {
6227 &mut self.token_cursor.frame.last_token
6229 &mut self.token_cursor.stack[prev].last_token
6231 let mut tokens = match *last_token {
6232 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
6233 LastToken::Was(_) => panic!("our vector went away?"),
6236 // If we're not at EOF our current token wasn't actually consumed by
6237 // `f`, but it'll still be in our list that we pulled out. In that case
6239 if self.token == token::Eof {
6240 *last_token = LastToken::Was(None);
6242 *last_token = LastToken::Was(tokens.pop());
6245 Ok((ret?, tokens.into_iter().collect()))
6248 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6249 let attrs = self.parse_outer_attributes()?;
6251 let (ret, tokens) = self.collect_tokens(|this| {
6252 this.parse_item_(attrs, true, false)
6255 // Once we've parsed an item and recorded the tokens we got while
6256 // parsing we may want to store `tokens` into the item we're about to
6257 // return. Note, though, that we specifically didn't capture tokens
6258 // related to outer attributes. The `tokens` field here may later be
6259 // used with procedural macros to convert this item back into a token
6260 // stream, but during expansion we may be removing attributes as we go
6263 // If we've got inner attributes then the `tokens` we've got above holds
6264 // these inner attributes. If an inner attribute is expanded we won't
6265 // actually remove it from the token stream, so we'll just keep yielding
6266 // it (bad!). To work around this case for now we just avoid recording
6267 // `tokens` if we detect any inner attributes. This should help keep
6268 // expansion correct, but we should fix this bug one day!
6271 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6272 i.tokens = Some(tokens);
6279 fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> {
6280 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
6281 &token::CloseDelim(token::Brace),
6282 SeqSep::trailing_allowed(token::Comma), |this| {
6284 let ident = if this.eat_keyword(keywords::SelfValue) {
6285 keywords::SelfValue.ident()
6289 let rename = this.parse_rename()?;
6290 let node = ast::PathListItem_ {
6293 id: ast::DUMMY_NODE_ID
6295 Ok(respan(lo.to(this.prev_span), node))
6300 fn is_import_coupler(&mut self) -> bool {
6301 self.check(&token::ModSep) &&
6302 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6303 *t == token::BinOp(token::Star))
6306 /// Matches ViewPath:
6307 /// MOD_SEP? non_global_path
6308 /// MOD_SEP? non_global_path as IDENT
6309 /// MOD_SEP? non_global_path MOD_SEP STAR
6310 /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE
6311 /// MOD_SEP? LBRACE item_seq RBRACE
6312 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
6314 if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) ||
6315 self.is_import_coupler() {
6316 // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`.
6317 self.eat(&token::ModSep);
6318 let prefix = ast::Path {
6319 segments: vec![PathSegment::crate_root(lo)],
6320 span: lo.to(self.span),
6322 let view_path_kind = if self.eat(&token::BinOp(token::Star)) {
6323 ViewPathGlob(prefix)
6325 ViewPathList(prefix, self.parse_path_list_items()?)
6327 Ok(P(respan(lo.to(self.span), view_path_kind)))
6329 let prefix = self.parse_path(PathStyle::Mod)?.default_to_global();
6330 if self.is_import_coupler() {
6331 // `foo::bar::{a, b}` or `foo::bar::*`
6333 if self.check(&token::BinOp(token::Star)) {
6335 Ok(P(respan(lo.to(self.span), ViewPathGlob(prefix))))
6337 let items = self.parse_path_list_items()?;
6338 Ok(P(respan(lo.to(self.span), ViewPathList(prefix, items))))
6341 // `foo::bar` or `foo::bar as baz`
6342 let rename = self.parse_rename()?.
6343 unwrap_or(prefix.segments.last().unwrap().identifier);
6344 Ok(P(respan(lo.to(self.prev_span), ViewPathSimple(rename, prefix))))
6349 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6350 if self.eat_keyword(keywords::As) {
6351 self.parse_ident().map(Some)
6357 /// Parses a source module as a crate. This is the main
6358 /// entry point for the parser.
6359 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6362 attrs: self.parse_inner_attributes()?,
6363 module: self.parse_mod_items(&token::Eof, lo)?,
6364 span: lo.to(self.span),
6368 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6369 let ret = match self.token {
6370 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6371 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6378 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6379 match self.parse_optional_str() {
6380 Some((s, style, suf)) => {
6381 let sp = self.prev_span;
6382 self.expect_no_suffix(sp, "string literal", suf);
6385 _ => Err(self.fatal("expected string literal"))