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, CrateSugar};
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) {
1036 // Attempt to keep parsing if it was a similar separator
1037 if let Some(ref tokens) = t.similar_tokens() {
1038 if tokens.contains(&self.token) {
1042 // Attempt to keep parsing if it was an omitted separator
1056 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1058 TokenExpectType::Expect => self.check(k),
1059 TokenExpectType::NoExpect => self.token == **k,
1077 /// Parse a sequence, including the closing delimiter. The function
1078 /// f must consume tokens until reaching the next separator or
1079 /// closing bracket.
1080 pub fn parse_unspanned_seq<T, F>(&mut self,
1085 -> PResult<'a, Vec<T>> where
1086 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1089 let result = self.parse_seq_to_before_end(ket, sep, f);
1090 if self.token == *ket {
1096 // NB: Do not use this function unless you actually plan to place the
1097 // spanned list in the AST.
1098 pub fn parse_seq<T, F>(&mut self,
1103 -> PResult<'a, Spanned<Vec<T>>> where
1104 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1108 let result = self.parse_seq_to_before_end(ket, sep, f);
1111 Ok(respan(lo.to(hi), result))
1114 /// Advance the parser by one token
1115 pub fn bump(&mut self) {
1116 if self.prev_token_kind == PrevTokenKind::Eof {
1117 // Bumping after EOF is a bad sign, usually an infinite loop.
1118 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1121 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1123 // Record last token kind for possible error recovery.
1124 self.prev_token_kind = match self.token {
1125 token::DocComment(..) => PrevTokenKind::DocComment,
1126 token::Comma => PrevTokenKind::Comma,
1127 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1128 token::Interpolated(..) => PrevTokenKind::Interpolated,
1129 token::Eof => PrevTokenKind::Eof,
1130 token::Ident(..) => PrevTokenKind::Ident,
1131 _ => PrevTokenKind::Other,
1134 let next = self.next_tok();
1135 self.span = next.sp;
1136 self.token = next.tok;
1137 self.expected_tokens.clear();
1138 // check after each token
1139 self.process_potential_macro_variable();
1142 /// Advance the parser using provided token as a next one. Use this when
1143 /// consuming a part of a token. For example a single `<` from `<<`.
1144 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1145 self.prev_span = self.span.with_hi(span.lo());
1146 // It would be incorrect to record the kind of the current token, but
1147 // fortunately for tokens currently using `bump_with`, the
1148 // prev_token_kind will be of no use anyway.
1149 self.prev_token_kind = PrevTokenKind::Other;
1152 self.expected_tokens.clear();
1155 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1156 F: FnOnce(&token::Token) -> R,
1159 return f(&self.token)
1162 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1163 Some(tree) => match tree {
1164 TokenTree::Token(_, tok) => tok,
1165 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1167 None => token::CloseDelim(self.token_cursor.frame.delim),
1170 fn look_ahead_span(&self, dist: usize) -> Span {
1175 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1176 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1177 None => self.look_ahead_span(dist - 1),
1180 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1181 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1183 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1184 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1186 pub fn span_fatal_err(&self, sp: Span, err: Error) -> DiagnosticBuilder<'a> {
1187 err.span_err(sp, self.diagnostic())
1189 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1190 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1194 pub fn bug(&self, m: &str) -> ! {
1195 self.sess.span_diagnostic.span_bug(self.span, m)
1197 pub fn warn(&self, m: &str) {
1198 self.sess.span_diagnostic.span_warn(self.span, m)
1200 pub fn span_warn(&self, sp: Span, m: &str) {
1201 self.sess.span_diagnostic.span_warn(sp, m)
1203 pub fn span_err(&self, sp: Span, m: &str) {
1204 self.sess.span_diagnostic.span_err(sp, m)
1206 pub fn span_err_help(&self, sp: Span, m: &str, h: &str) {
1207 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1211 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1212 self.sess.span_diagnostic.span_bug(sp, m)
1214 pub fn abort_if_errors(&self) {
1215 self.sess.span_diagnostic.abort_if_errors();
1218 fn cancel(&self, err: &mut DiagnosticBuilder) {
1219 self.sess.span_diagnostic.cancel(err)
1222 pub fn diagnostic(&self) -> &'a errors::Handler {
1223 &self.sess.span_diagnostic
1226 /// Is the current token one of the keywords that signals a bare function
1228 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1229 self.check_keyword(keywords::Fn) ||
1230 self.check_keyword(keywords::Unsafe) ||
1231 self.check_keyword(keywords::Extern)
1234 fn get_label(&mut self) -> ast::Ident {
1236 token::Lifetime(ref ident) => *ident,
1237 _ => self.bug("not a lifetime"),
1241 /// parse a TyKind::BareFn type:
1242 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<LifetimeDef>)
1243 -> PResult<'a, TyKind> {
1246 [unsafe] [extern "ABI"] fn (S) -> T
1256 let unsafety = self.parse_unsafety()?;
1257 let abi = if self.eat_keyword(keywords::Extern) {
1258 self.parse_opt_abi()?.unwrap_or(Abi::C)
1263 self.expect_keyword(keywords::Fn)?;
1264 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1265 let ret_ty = self.parse_ret_ty()?;
1266 let decl = P(FnDecl {
1271 Ok(TyKind::BareFn(P(BareFnTy {
1274 lifetimes: lifetime_defs,
1279 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1280 if self.eat_keyword(keywords::Unsafe) {
1281 return Ok(Unsafety::Unsafe);
1283 return Ok(Unsafety::Normal);
1287 /// Parse the items in a trait declaration
1288 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1289 maybe_whole!(self, NtTraitItem, |x| x);
1290 let attrs = self.parse_outer_attributes()?;
1291 let (mut item, tokens) = self.collect_tokens(|this| {
1292 this.parse_trait_item_(at_end, attrs)
1294 // See `parse_item` for why this clause is here.
1295 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1296 item.tokens = Some(tokens);
1301 fn parse_trait_item_(&mut self,
1303 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1306 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1307 let TyParam {ident, bounds, default, ..} = self.parse_ty_param(vec![])?;
1308 self.expect(&token::Semi)?;
1309 (ident, TraitItemKind::Type(bounds, default), ast::Generics::default())
1310 } else if self.is_const_item() {
1311 self.expect_keyword(keywords::Const)?;
1312 let ident = self.parse_ident()?;
1313 self.expect(&token::Colon)?;
1314 let ty = self.parse_ty()?;
1315 let default = if self.check(&token::Eq) {
1317 let expr = self.parse_expr()?;
1318 self.expect(&token::Semi)?;
1321 self.expect(&token::Semi)?;
1324 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1325 } else if self.token.is_path_start() {
1326 // trait item macro.
1327 // code copied from parse_macro_use_or_failure... abstraction!
1328 let prev_span = self.prev_span;
1330 let pth = self.parse_path(PathStyle::Mod)?;
1332 if pth.segments.len() == 1 {
1333 if !self.eat(&token::Not) {
1334 return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1337 self.expect(&token::Not)?;
1340 // eat a matched-delimiter token tree:
1341 let (delim, tts) = self.expect_delimited_token_tree()?;
1342 if delim != token::Brace {
1343 self.expect(&token::Semi)?
1346 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1347 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1349 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
1351 let ident = self.parse_ident()?;
1352 let mut generics = self.parse_generics()?;
1354 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1355 // This is somewhat dubious; We don't want to allow
1356 // argument names to be left off if there is a
1358 p.parse_arg_general(false)
1360 generics.where_clause = self.parse_where_clause()?;
1362 let sig = ast::MethodSig {
1369 let body = match self.token {
1373 debug!("parse_trait_methods(): parsing required method");
1376 token::OpenDelim(token::Brace) => {
1377 debug!("parse_trait_methods(): parsing provided method");
1379 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1380 attrs.extend(inner_attrs.iter().cloned());
1384 let token_str = self.this_token_to_string();
1385 return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1388 (ident, ast::TraitItemKind::Method(sig, body), generics)
1392 id: ast::DUMMY_NODE_ID,
1397 span: lo.to(self.prev_span),
1402 /// Parse optional return type [ -> TY ] in function decl
1403 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1404 if self.eat(&token::RArrow) {
1405 Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
1407 Ok(FunctionRetTy::Default(self.span.with_hi(self.span.lo())))
1412 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1413 self.parse_ty_common(true)
1416 /// Parse a type in restricted contexts where `+` is not permitted.
1417 /// Example 1: `&'a TYPE`
1418 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1419 /// Example 2: `value1 as TYPE + value2`
1420 /// `+` is prohibited to avoid interactions with expression grammar.
1421 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1422 self.parse_ty_common(false)
1425 fn parse_ty_common(&mut self, allow_plus: bool) -> PResult<'a, P<Ty>> {
1426 maybe_whole!(self, NtTy, |x| x);
1429 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1430 // `(TYPE)` is a parenthesized type.
1431 // `(TYPE,)` is a tuple with a single field of type TYPE.
1432 let mut ts = vec![];
1433 let mut last_comma = false;
1434 while self.token != token::CloseDelim(token::Paren) {
1435 ts.push(self.parse_ty()?);
1436 if self.eat(&token::Comma) {
1443 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1444 self.expect(&token::CloseDelim(token::Paren))?;
1446 if ts.len() == 1 && !last_comma {
1447 let ty = ts.into_iter().nth(0).unwrap().unwrap();
1448 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1450 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1451 TyKind::Path(None, ref path) if maybe_bounds => {
1452 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1454 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1455 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1456 let path = match bounds[0] {
1457 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1458 _ => self.bug("unexpected lifetime bound"),
1460 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1463 _ => TyKind::Paren(P(ty))
1468 } else if self.eat(&token::Not) {
1471 } else if self.eat(&token::BinOp(token::Star)) {
1473 TyKind::Ptr(self.parse_ptr()?)
1474 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1476 let t = self.parse_ty()?;
1477 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1478 let t = match self.maybe_parse_fixed_length_of_vec()? {
1479 None => TyKind::Slice(t),
1480 Some(suffix) => TyKind::Array(t, suffix),
1482 self.expect(&token::CloseDelim(token::Bracket))?;
1484 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1487 self.parse_borrowed_pointee()?
1488 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1490 // In order to not be ambiguous, the type must be surrounded by parens.
1491 self.expect(&token::OpenDelim(token::Paren))?;
1492 let e = self.parse_expr()?;
1493 self.expect(&token::CloseDelim(token::Paren))?;
1495 } else if self.eat(&token::Underscore) {
1496 // A type to be inferred `_`
1498 } else if self.token_is_bare_fn_keyword() {
1499 // Function pointer type
1500 self.parse_ty_bare_fn(Vec::new())?
1501 } else if self.check_keyword(keywords::For) {
1502 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1503 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1504 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1506 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1507 if self.token_is_bare_fn_keyword() {
1508 self.parse_ty_bare_fn(lifetime_defs)?
1510 let path = self.parse_path(PathStyle::Type)?;
1511 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1512 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1514 } else if self.eat_keyword(keywords::Impl) {
1515 // FIXME: figure out priority of `+` in `impl Trait1 + Trait2` (#34511).
1516 TyKind::ImplTrait(self.parse_ty_param_bounds()?)
1517 } else if self.check_keyword(keywords::Dyn) &&
1518 self.look_ahead(1, |t| t.can_begin_bound() && !can_continue_type_after_ident(t)) {
1519 // FIXME: figure out priority of `+` in `dyn Trait1 + Trait2` (#34511).
1520 self.bump(); // `dyn`
1521 TyKind::TraitObject(self.parse_ty_param_bounds()?, TraitObjectSyntax::Dyn)
1522 } else if self.check(&token::Question) ||
1523 self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)) {
1524 // Bound list (trait object type)
1525 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?,
1526 TraitObjectSyntax::None)
1527 } else if self.eat_lt() {
1529 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1530 TyKind::Path(Some(qself), path)
1531 } else if self.token.is_path_start() {
1533 let path = self.parse_path(PathStyle::Type)?;
1534 if self.eat(&token::Not) {
1535 // Macro invocation in type position
1536 let (_, tts) = self.expect_delimited_token_tree()?;
1537 TyKind::Mac(respan(lo.to(self.span), Mac_ { path: path, tts: tts }))
1539 // Just a type path or bound list (trait object type) starting with a trait.
1541 // `Trait1 + Trait2 + 'a`
1542 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1543 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1545 TyKind::Path(None, path)
1549 let msg = format!("expected type, found {}", self.this_token_descr());
1550 return Err(self.fatal(&msg));
1553 let span = lo.to(self.prev_span);
1554 let ty = Ty { node: node, span: span, id: ast::DUMMY_NODE_ID };
1556 // Try to recover from use of `+` with incorrect priority.
1557 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1562 fn parse_remaining_bounds(&mut self, lifetime_defs: Vec<LifetimeDef>, path: ast::Path,
1563 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1564 let poly_trait_ref = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
1565 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1568 bounds.append(&mut self.parse_ty_param_bounds()?);
1570 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1573 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1574 // Do not add `+` to expected tokens.
1575 if !allow_plus || self.token != token::BinOp(token::Plus) {
1580 let bounds = self.parse_ty_param_bounds()?;
1581 let sum_span = ty.span.to(self.prev_span);
1583 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1584 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1587 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1588 let sum_with_parens = pprust::to_string(|s| {
1589 use print::pprust::PrintState;
1592 s.print_opt_lifetime(lifetime)?;
1593 s.print_mutability(mut_ty.mutbl)?;
1595 s.print_type(&mut_ty.ty)?;
1596 s.print_bounds(" +", &bounds)?;
1599 err.span_suggestion(sum_span, "try adding parentheses", sum_with_parens);
1601 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1602 err.span_label(sum_span, "perhaps you forgot parentheses?");
1605 err.span_label(sum_span, "expected a path");
1612 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1613 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1614 let mutbl = self.parse_mutability();
1615 let ty = self.parse_ty_no_plus()?;
1616 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1619 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1620 let mutbl = if self.eat_keyword(keywords::Mut) {
1622 } else if self.eat_keyword(keywords::Const) {
1623 Mutability::Immutable
1625 let span = self.prev_span;
1627 "expected mut or const in raw pointer type (use \
1628 `*mut T` or `*const T` as appropriate)");
1629 Mutability::Immutable
1631 let t = self.parse_ty_no_plus()?;
1632 Ok(MutTy { ty: t, mutbl: mutbl })
1635 pub fn is_named_argument(&mut self) -> bool {
1636 let offset = match self.token {
1637 token::BinOp(token::And) |
1639 _ if self.token.is_keyword(keywords::Mut) => 1,
1643 debug!("parser is_named_argument offset:{}", offset);
1646 is_ident_or_underscore(&self.token)
1647 && self.look_ahead(1, |t| *t == token::Colon)
1649 self.look_ahead(offset, |t| is_ident_or_underscore(t))
1650 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1654 /// This version of parse arg doesn't necessarily require
1655 /// identifier names.
1656 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1657 maybe_whole!(self, NtArg, |x| x);
1659 let pat = if require_name || self.is_named_argument() {
1660 debug!("parse_arg_general parse_pat (require_name:{})",
1662 let pat = self.parse_pat()?;
1664 self.expect(&token::Colon)?;
1667 debug!("parse_arg_general ident_to_pat");
1668 let sp = self.prev_span;
1669 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1671 id: ast::DUMMY_NODE_ID,
1672 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1678 let t = self.parse_ty()?;
1683 id: ast::DUMMY_NODE_ID,
1687 /// Parse a single function argument
1688 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1689 self.parse_arg_general(true)
1692 /// Parse an argument in a lambda header e.g. |arg, arg|
1693 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1694 let pat = self.parse_pat()?;
1695 let t = if self.eat(&token::Colon) {
1699 id: ast::DUMMY_NODE_ID,
1700 node: TyKind::Infer,
1707 id: ast::DUMMY_NODE_ID
1711 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1712 if self.eat(&token::Semi) {
1713 Ok(Some(self.parse_expr()?))
1719 /// Matches token_lit = LIT_INTEGER | ...
1720 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1721 let out = match self.token {
1722 token::Interpolated(ref nt) => match nt.0 {
1723 token::NtExpr(ref v) => match v.node {
1724 ExprKind::Lit(ref lit) => { lit.node.clone() }
1725 _ => { return self.unexpected_last(&self.token); }
1727 _ => { return self.unexpected_last(&self.token); }
1729 token::Literal(lit, suf) => {
1730 let diag = Some((self.span, &self.sess.span_diagnostic));
1731 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1735 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1740 _ => { return self.unexpected_last(&self.token); }
1747 /// Matches lit = true | false | token_lit
1748 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1750 let lit = if self.eat_keyword(keywords::True) {
1752 } else if self.eat_keyword(keywords::False) {
1753 LitKind::Bool(false)
1755 let lit = self.parse_lit_token()?;
1758 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1761 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1762 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1763 maybe_whole_expr!(self);
1765 let minus_lo = self.span;
1766 let minus_present = self.eat(&token::BinOp(token::Minus));
1768 let literal = P(self.parse_lit()?);
1769 let hi = self.prev_span;
1770 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1773 let minus_hi = self.prev_span;
1774 let unary = self.mk_unary(UnOp::Neg, expr);
1775 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1781 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1783 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1787 _ => self.parse_ident(),
1791 /// Parses qualified path.
1792 /// Assumes that the leading `<` has been parsed already.
1794 /// `qualified_path = <type [as trait_ref]>::path`
1798 /// `<T as U>::F::a<S>` (without disambiguator)
1799 /// `<T as U>::F::a::<S>` (with disambiguator)
1800 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1801 let lo = self.prev_span;
1802 let ty = self.parse_ty()?;
1803 let mut path = if self.eat_keyword(keywords::As) {
1804 self.parse_path(PathStyle::Type)?
1806 ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP }
1808 self.expect(&token::Gt)?;
1809 self.expect(&token::ModSep)?;
1811 let qself = QSelf { ty, position: path.segments.len() };
1812 self.parse_path_segments(&mut path.segments, style, true)?;
1814 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1817 /// Parses simple paths.
1819 /// `path = [::] segment+`
1820 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1823 /// `a::b::C<D>` (without disambiguator)
1824 /// `a::b::C::<D>` (with disambiguator)
1825 /// `Fn(Args)` (without disambiguator)
1826 /// `Fn::(Args)` (with disambiguator)
1827 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1828 self.parse_path_common(style, true)
1831 pub fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1832 -> PResult<'a, ast::Path> {
1833 maybe_whole!(self, NtPath, |path| {
1834 if style == PathStyle::Mod &&
1835 path.segments.iter().any(|segment| segment.parameters.is_some()) {
1836 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1841 let lo = self.meta_var_span.unwrap_or(self.span);
1842 let mut segments = Vec::new();
1843 if self.eat(&token::ModSep) {
1844 segments.push(PathSegment::crate_root(lo));
1846 self.parse_path_segments(&mut segments, style, enable_warning)?;
1848 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1851 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1852 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1853 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1854 let meta_ident = match self.token {
1855 token::Interpolated(ref nt) => match nt.0 {
1856 token::NtMeta(ref meta) => match meta.node {
1857 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
1864 if let Some(ident) = meta_ident {
1866 return Ok(ast::Path::from_ident(self.prev_span, ident));
1868 self.parse_path(style)
1871 fn parse_path_segments(&mut self, segments: &mut Vec<PathSegment>, style: PathStyle,
1872 enable_warning: bool) -> PResult<'a, ()> {
1874 segments.push(self.parse_path_segment(style, enable_warning)?);
1876 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1882 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
1883 -> PResult<'a, PathSegment> {
1884 let ident_span = self.span;
1885 let ident = self.parse_path_segment_ident()?;
1887 let is_args_start = |token: &token::Token| match *token {
1888 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
1891 let check_args_start = |this: &mut Self| {
1892 this.expected_tokens.extend_from_slice(
1893 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1895 is_args_start(&this.token)
1898 Ok(if style == PathStyle::Type && check_args_start(self) ||
1899 style != PathStyle::Mod && self.check(&token::ModSep)
1900 && self.look_ahead(1, |t| is_args_start(t)) {
1901 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1903 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
1904 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
1905 .span_label(self.prev_span, "try removing `::`").emit();
1908 let parameters = if self.eat_lt() {
1910 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1912 let span = lo.to(self.prev_span);
1913 AngleBracketedParameterData { lifetimes, types, bindings, span }.into()
1917 let inputs = self.parse_seq_to_end(&token::CloseDelim(token::Paren),
1918 SeqSep::trailing_allowed(token::Comma),
1920 let output = if self.eat(&token::RArrow) {
1921 Some(self.parse_ty_no_plus()?)
1925 let span = lo.to(self.prev_span);
1926 ParenthesizedParameterData { inputs, output, span }.into()
1929 PathSegment { identifier: ident, span: ident_span, parameters }
1931 // Generic arguments are not found.
1932 PathSegment::from_ident(ident, ident_span)
1936 fn check_lifetime(&mut self) -> bool {
1937 self.expected_tokens.push(TokenType::Lifetime);
1938 self.token.is_lifetime()
1941 /// Parse single lifetime 'a or panic.
1942 fn expect_lifetime(&mut self) -> Lifetime {
1944 token::Lifetime(ident) => {
1945 let ident_span = self.span;
1947 Lifetime { ident: ident, span: ident_span, id: ast::DUMMY_NODE_ID }
1949 _ => self.span_bug(self.span, "not a lifetime")
1953 /// Parse mutability (`mut` or nothing).
1954 fn parse_mutability(&mut self) -> Mutability {
1955 if self.eat_keyword(keywords::Mut) {
1958 Mutability::Immutable
1962 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1963 if let token::Literal(token::Integer(name), None) = self.token {
1965 Ok(Ident::with_empty_ctxt(name))
1971 /// Parse ident (COLON expr)?
1972 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1973 let attrs = self.parse_outer_attributes()?;
1977 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1978 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1979 let fieldname = self.parse_field_name()?;
1981 hi = self.prev_span;
1982 (fieldname, self.parse_expr()?, false)
1984 let fieldname = self.parse_ident()?;
1985 hi = self.prev_span;
1987 // Mimic `x: x` for the `x` field shorthand.
1988 let path = ast::Path::from_ident(lo.to(hi), fieldname);
1989 (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
1992 ident: respan(lo.to(hi), fieldname),
1993 span: lo.to(expr.span),
1996 attrs: attrs.into(),
2000 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2002 id: ast::DUMMY_NODE_ID,
2005 attrs: attrs.into(),
2009 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2010 ExprKind::Unary(unop, expr)
2013 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2014 ExprKind::Binary(binop, lhs, rhs)
2017 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2018 ExprKind::Call(f, args)
2021 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2022 ExprKind::Index(expr, idx)
2025 pub fn mk_range(&mut self,
2026 start: Option<P<Expr>>,
2027 end: Option<P<Expr>>,
2028 limits: RangeLimits)
2029 -> PResult<'a, ast::ExprKind> {
2030 if end.is_none() && limits == RangeLimits::Closed {
2031 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2033 Ok(ExprKind::Range(start, end, limits))
2037 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2038 ExprKind::TupField(expr, idx)
2041 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2042 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2043 ExprKind::AssignOp(binop, lhs, rhs)
2046 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2048 id: ast::DUMMY_NODE_ID,
2049 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2055 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2056 let span = &self.span;
2057 let lv_lit = P(codemap::Spanned {
2058 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2063 id: ast::DUMMY_NODE_ID,
2064 node: ExprKind::Lit(lv_lit),
2070 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2072 token::OpenDelim(delim) => match self.parse_token_tree() {
2073 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2074 _ => unreachable!(),
2076 _ => Err(self.fatal("expected open delimiter")),
2080 /// At the bottom (top?) of the precedence hierarchy,
2081 /// parse things like parenthesized exprs,
2082 /// macros, return, etc.
2084 /// NB: This does not parse outer attributes,
2085 /// and is private because it only works
2086 /// correctly if called from parse_dot_or_call_expr().
2087 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2088 maybe_whole_expr!(self);
2090 // Outer attributes are already parsed and will be
2091 // added to the return value after the fact.
2093 // Therefore, prevent sub-parser from parsing
2094 // attributes by giving them a empty "already parsed" list.
2095 let mut attrs = ThinVec::new();
2098 let mut hi = self.span;
2102 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2104 token::OpenDelim(token::Paren) => {
2107 attrs.extend(self.parse_inner_attributes()?);
2109 // (e) is parenthesized e
2110 // (e,) is a tuple with only one field, e
2111 let mut es = vec![];
2112 let mut trailing_comma = false;
2113 while self.token != token::CloseDelim(token::Paren) {
2114 es.push(self.parse_expr()?);
2115 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2116 if self.check(&token::Comma) {
2117 trailing_comma = true;
2121 trailing_comma = false;
2127 hi = self.prev_span;
2128 let span = lo.to(hi);
2129 return if es.len() == 1 && !trailing_comma {
2130 Ok(self.mk_expr(span, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2132 Ok(self.mk_expr(span, ExprKind::Tup(es), attrs))
2135 token::OpenDelim(token::Brace) => {
2136 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2138 token::BinOp(token::Or) | token::OrOr => {
2140 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2142 token::OpenDelim(token::Bracket) => {
2145 attrs.extend(self.parse_inner_attributes()?);
2147 if self.check(&token::CloseDelim(token::Bracket)) {
2150 ex = ExprKind::Array(Vec::new());
2153 let first_expr = self.parse_expr()?;
2154 if self.check(&token::Semi) {
2155 // Repeating array syntax: [ 0; 512 ]
2157 let count = self.parse_expr()?;
2158 self.expect(&token::CloseDelim(token::Bracket))?;
2159 ex = ExprKind::Repeat(first_expr, count);
2160 } else if self.check(&token::Comma) {
2161 // Vector with two or more elements.
2163 let remaining_exprs = self.parse_seq_to_end(
2164 &token::CloseDelim(token::Bracket),
2165 SeqSep::trailing_allowed(token::Comma),
2166 |p| Ok(p.parse_expr()?)
2168 let mut exprs = vec![first_expr];
2169 exprs.extend(remaining_exprs);
2170 ex = ExprKind::Array(exprs);
2172 // Vector with one element.
2173 self.expect(&token::CloseDelim(token::Bracket))?;
2174 ex = ExprKind::Array(vec![first_expr]);
2177 hi = self.prev_span;
2181 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2183 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2185 if self.eat_keyword(keywords::Move) {
2186 let lo = self.prev_span;
2187 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2189 if self.eat_keyword(keywords::If) {
2190 return self.parse_if_expr(attrs);
2192 if self.eat_keyword(keywords::For) {
2193 let lo = self.prev_span;
2194 return self.parse_for_expr(None, lo, attrs);
2196 if self.eat_keyword(keywords::While) {
2197 let lo = self.prev_span;
2198 return self.parse_while_expr(None, lo, attrs);
2200 if self.token.is_lifetime() {
2201 let label = Spanned { node: self.get_label(),
2205 self.expect(&token::Colon)?;
2206 if self.eat_keyword(keywords::While) {
2207 return self.parse_while_expr(Some(label), lo, attrs)
2209 if self.eat_keyword(keywords::For) {
2210 return self.parse_for_expr(Some(label), lo, attrs)
2212 if self.eat_keyword(keywords::Loop) {
2213 return self.parse_loop_expr(Some(label), lo, attrs)
2215 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2217 if self.eat_keyword(keywords::Loop) {
2218 let lo = self.prev_span;
2219 return self.parse_loop_expr(None, lo, attrs);
2221 if self.eat_keyword(keywords::Continue) {
2222 let ex = if self.token.is_lifetime() {
2223 let ex = ExprKind::Continue(Some(Spanned{
2224 node: self.get_label(),
2230 ExprKind::Continue(None)
2232 let hi = self.prev_span;
2233 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2235 if self.eat_keyword(keywords::Match) {
2236 return self.parse_match_expr(attrs);
2238 if self.eat_keyword(keywords::Unsafe) {
2239 return self.parse_block_expr(
2241 BlockCheckMode::Unsafe(ast::UserProvided),
2244 if self.is_catch_expr() {
2246 assert!(self.eat_keyword(keywords::Do));
2247 assert!(self.eat_keyword(keywords::Catch));
2248 return self.parse_catch_expr(lo, attrs);
2250 if self.eat_keyword(keywords::Return) {
2251 if self.token.can_begin_expr() {
2252 let e = self.parse_expr()?;
2254 ex = ExprKind::Ret(Some(e));
2256 ex = ExprKind::Ret(None);
2258 } else if self.eat_keyword(keywords::Break) {
2259 let lt = if self.token.is_lifetime() {
2260 let spanned_lt = Spanned {
2261 node: self.get_label(),
2269 let e = if self.token.can_begin_expr()
2270 && !(self.token == token::OpenDelim(token::Brace)
2271 && self.restrictions.contains(
2272 Restrictions::NO_STRUCT_LITERAL)) {
2273 Some(self.parse_expr()?)
2277 ex = ExprKind::Break(lt, e);
2278 hi = self.prev_span;
2279 } else if self.eat_keyword(keywords::Yield) {
2280 if self.token.can_begin_expr() {
2281 let e = self.parse_expr()?;
2283 ex = ExprKind::Yield(Some(e));
2285 ex = ExprKind::Yield(None);
2287 } else if self.token.is_keyword(keywords::Let) {
2288 // Catch this syntax error here, instead of in `parse_ident`, so
2289 // that we can explicitly mention that let is not to be used as an expression
2290 let mut db = self.fatal("expected expression, found statement (`let`)");
2291 db.note("variable declaration using `let` is a statement");
2293 } else if self.token.is_path_start() {
2294 let pth = self.parse_path(PathStyle::Expr)?;
2296 // `!`, as an operator, is prefix, so we know this isn't that
2297 if self.eat(&token::Not) {
2298 // MACRO INVOCATION expression
2299 let (_, tts) = self.expect_delimited_token_tree()?;
2300 let hi = self.prev_span;
2301 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2303 if self.check(&token::OpenDelim(token::Brace)) {
2304 // This is a struct literal, unless we're prohibited
2305 // from parsing struct literals here.
2306 let prohibited = self.restrictions.contains(
2307 Restrictions::NO_STRUCT_LITERAL
2310 return self.parse_struct_expr(lo, pth, attrs);
2315 ex = ExprKind::Path(None, pth);
2317 match self.parse_lit() {
2320 ex = ExprKind::Lit(P(lit));
2323 self.cancel(&mut err);
2324 let msg = format!("expected expression, found {}",
2325 self.this_token_descr());
2326 return Err(self.fatal(&msg));
2333 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2336 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2337 -> PResult<'a, P<Expr>> {
2339 let mut fields = Vec::new();
2340 let mut base = None;
2342 attrs.extend(self.parse_inner_attributes()?);
2344 while self.token != token::CloseDelim(token::Brace) {
2345 if self.eat(&token::DotDot) {
2346 let exp_span = self.prev_span;
2347 match self.parse_expr() {
2353 self.recover_stmt();
2356 if self.token == token::Comma {
2357 let mut err = self.sess.span_diagnostic.mut_span_err(
2358 exp_span.to(self.prev_span),
2359 "cannot use a comma after the base struct",
2361 err.span_suggestion_short(self.span, "remove this comma", "".to_owned());
2362 err.note("the base struct must always be the last field");
2364 self.recover_stmt();
2369 match self.parse_field() {
2370 Ok(f) => fields.push(f),
2373 self.recover_stmt();
2378 match self.expect_one_of(&[token::Comma],
2379 &[token::CloseDelim(token::Brace)]) {
2383 self.recover_stmt();
2389 let span = lo.to(self.span);
2390 self.expect(&token::CloseDelim(token::Brace))?;
2391 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2394 fn parse_or_use_outer_attributes(&mut self,
2395 already_parsed_attrs: Option<ThinVec<Attribute>>)
2396 -> PResult<'a, ThinVec<Attribute>> {
2397 if let Some(attrs) = already_parsed_attrs {
2400 self.parse_outer_attributes().map(|a| a.into())
2404 /// Parse a block or unsafe block
2405 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2406 outer_attrs: ThinVec<Attribute>)
2407 -> PResult<'a, P<Expr>> {
2408 self.expect(&token::OpenDelim(token::Brace))?;
2410 let mut attrs = outer_attrs;
2411 attrs.extend(self.parse_inner_attributes()?);
2413 let blk = self.parse_block_tail(lo, blk_mode)?;
2414 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2417 /// parse a.b or a(13) or a[4] or just a
2418 pub fn parse_dot_or_call_expr(&mut self,
2419 already_parsed_attrs: Option<ThinVec<Attribute>>)
2420 -> PResult<'a, P<Expr>> {
2421 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2423 let b = self.parse_bottom_expr();
2424 let (span, b) = self.interpolated_or_expr_span(b)?;
2425 self.parse_dot_or_call_expr_with(b, span, attrs)
2428 pub fn parse_dot_or_call_expr_with(&mut self,
2431 mut attrs: ThinVec<Attribute>)
2432 -> PResult<'a, P<Expr>> {
2433 // Stitch the list of outer attributes onto the return value.
2434 // A little bit ugly, but the best way given the current code
2436 self.parse_dot_or_call_expr_with_(e0, lo)
2438 expr.map(|mut expr| {
2439 attrs.extend::<Vec<_>>(expr.attrs.into());
2442 ExprKind::If(..) | ExprKind::IfLet(..) => {
2443 if !expr.attrs.is_empty() {
2444 // Just point to the first attribute in there...
2445 let span = expr.attrs[0].span;
2448 "attributes are not yet allowed on `if` \
2459 // Assuming we have just parsed `.`, continue parsing into an expression.
2460 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2461 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2462 Ok(match self.token {
2463 token::OpenDelim(token::Paren) => {
2464 // Method call `expr.f()`
2465 let mut args = self.parse_unspanned_seq(
2466 &token::OpenDelim(token::Paren),
2467 &token::CloseDelim(token::Paren),
2468 SeqSep::trailing_allowed(token::Comma),
2469 |p| Ok(p.parse_expr()?)
2471 args.insert(0, self_arg);
2473 let span = lo.to(self.prev_span);
2474 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2477 // Field access `expr.f`
2478 if let Some(parameters) = segment.parameters {
2479 self.span_err(parameters.span(),
2480 "field expressions may not have generic arguments");
2483 let span = lo.to(self.prev_span);
2484 let ident = respan(segment.span, segment.identifier);
2485 self.mk_expr(span, ExprKind::Field(self_arg, ident), ThinVec::new())
2490 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2495 while self.eat(&token::Question) {
2496 let hi = self.prev_span;
2497 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2501 if self.eat(&token::Dot) {
2503 token::Ident(..) => {
2504 e = self.parse_dot_suffix(e, lo)?;
2506 token::Literal(token::Integer(n), suf) => {
2509 // A tuple index may not have a suffix
2510 self.expect_no_suffix(sp, "tuple index", suf);
2512 let dot_span = self.prev_span;
2516 let index = n.as_str().parse::<usize>().ok();
2519 let id = respan(dot_span.to(hi), n);
2520 let field = self.mk_tup_field(e, id);
2521 e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2524 let prev_span = self.prev_span;
2525 self.span_err(prev_span, "invalid tuple or tuple struct index");
2529 token::Literal(token::Float(n), _suf) => {
2531 let fstr = n.as_str();
2532 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2533 &format!("unexpected token: `{}`", n));
2534 err.span_label(self.prev_span, "unexpected token");
2535 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2536 let float = match fstr.parse::<f64>().ok() {
2540 let sugg = pprust::to_string(|s| {
2541 use print::pprust::PrintState;
2545 s.print_usize(float.trunc() as usize)?;
2548 s.s.word(fstr.splitn(2, ".").last().unwrap())
2550 err.span_suggestion(
2551 lo.to(self.prev_span),
2552 "try parenthesizing the first index",
2559 // FIXME Could factor this out into non_fatal_unexpected or something.
2560 let actual = self.this_token_to_string();
2561 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2566 if self.expr_is_complete(&e) { break; }
2569 token::OpenDelim(token::Paren) => {
2570 let es = self.parse_unspanned_seq(
2571 &token::OpenDelim(token::Paren),
2572 &token::CloseDelim(token::Paren),
2573 SeqSep::trailing_allowed(token::Comma),
2574 |p| Ok(p.parse_expr()?)
2576 hi = self.prev_span;
2578 let nd = self.mk_call(e, es);
2579 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2583 // Could be either an index expression or a slicing expression.
2584 token::OpenDelim(token::Bracket) => {
2586 let ix = self.parse_expr()?;
2588 self.expect(&token::CloseDelim(token::Bracket))?;
2589 let index = self.mk_index(e, ix);
2590 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2598 pub fn process_potential_macro_variable(&mut self) {
2599 let ident = match self.token {
2600 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2601 self.look_ahead(1, |t| t.is_ident()) => {
2603 let name = match self.token { token::Ident(ident) => ident, _ => unreachable!() };
2604 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2607 token::Interpolated(ref nt) => {
2608 self.meta_var_span = Some(self.span);
2610 token::NtIdent(ident) => ident,
2616 self.token = token::Ident(ident.node);
2617 self.span = ident.span;
2620 /// parse a single token tree from the input.
2621 pub fn parse_token_tree(&mut self) -> TokenTree {
2623 token::OpenDelim(..) => {
2624 let frame = mem::replace(&mut self.token_cursor.frame,
2625 self.token_cursor.stack.pop().unwrap());
2626 self.span = frame.span;
2628 TokenTree::Delimited(frame.span, Delimited {
2630 tts: frame.tree_cursor.original_stream().into(),
2633 token::CloseDelim(_) | token::Eof => unreachable!(),
2635 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2637 TokenTree::Token(span, token)
2642 // parse a stream of tokens into a list of TokenTree's,
2644 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2645 let mut tts = Vec::new();
2646 while self.token != token::Eof {
2647 tts.push(self.parse_token_tree());
2652 pub fn parse_tokens(&mut self) -> TokenStream {
2653 let mut result = Vec::new();
2656 token::Eof | token::CloseDelim(..) => break,
2657 _ => result.push(self.parse_token_tree().into()),
2660 TokenStream::concat(result)
2663 /// Parse a prefix-unary-operator expr
2664 pub fn parse_prefix_expr(&mut self,
2665 already_parsed_attrs: Option<ThinVec<Attribute>>)
2666 -> PResult<'a, P<Expr>> {
2667 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2669 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2670 let (hi, ex) = match self.token {
2673 let e = self.parse_prefix_expr(None);
2674 let (span, e) = self.interpolated_or_expr_span(e)?;
2675 (lo.to(span), self.mk_unary(UnOp::Not, e))
2677 // Suggest `!` for bitwise negation when encountering a `~`
2680 let e = self.parse_prefix_expr(None);
2681 let (span, e) = self.interpolated_or_expr_span(e)?;
2682 let span_of_tilde = lo;
2683 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2684 "`~` can not be used as a unary operator");
2685 err.span_label(span_of_tilde, "did you mean `!`?");
2686 err.help("use `!` instead of `~` if you meant to perform bitwise negation");
2688 (lo.to(span), self.mk_unary(UnOp::Not, e))
2690 token::BinOp(token::Minus) => {
2692 let e = self.parse_prefix_expr(None);
2693 let (span, e) = self.interpolated_or_expr_span(e)?;
2694 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2696 token::BinOp(token::Star) => {
2698 let e = self.parse_prefix_expr(None);
2699 let (span, e) = self.interpolated_or_expr_span(e)?;
2700 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2702 token::BinOp(token::And) | token::AndAnd => {
2704 let m = self.parse_mutability();
2705 let e = self.parse_prefix_expr(None);
2706 let (span, e) = self.interpolated_or_expr_span(e)?;
2707 (lo.to(span), ExprKind::AddrOf(m, e))
2709 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2711 let place = self.parse_expr_res(
2712 Restrictions::NO_STRUCT_LITERAL,
2715 let blk = self.parse_block()?;
2716 let span = blk.span;
2717 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2718 (lo.to(span), ExprKind::InPlace(place, blk_expr))
2720 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2722 let e = self.parse_prefix_expr(None);
2723 let (span, e) = self.interpolated_or_expr_span(e)?;
2724 (lo.to(span), ExprKind::Box(e))
2726 _ => return self.parse_dot_or_call_expr(Some(attrs))
2728 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2731 /// Parse an associative expression
2733 /// This parses an expression accounting for associativity and precedence of the operators in
2735 pub fn parse_assoc_expr(&mut self,
2736 already_parsed_attrs: Option<ThinVec<Attribute>>)
2737 -> PResult<'a, P<Expr>> {
2738 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2741 /// Parse an associative expression with operators of at least `min_prec` precedence
2742 pub fn parse_assoc_expr_with(&mut self,
2745 -> PResult<'a, P<Expr>> {
2746 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2749 let attrs = match lhs {
2750 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2753 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2754 return self.parse_prefix_range_expr(attrs);
2756 self.parse_prefix_expr(attrs)?
2760 if self.expr_is_complete(&lhs) {
2761 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2764 self.expected_tokens.push(TokenType::Operator);
2765 while let Some(op) = AssocOp::from_token(&self.token) {
2767 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2768 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2769 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2770 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2771 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2772 (PrevTokenKind::Interpolated, _) => self.prev_span,
2773 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2774 if path.segments.len() == 1 => self.prev_span,
2778 let cur_op_span = self.span;
2779 let restrictions = if op.is_assign_like() {
2780 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2784 if op.precedence() < min_prec {
2787 // Check for deprecated `...` syntax
2788 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2789 self.err_dotdotdot_syntax(self.span);
2793 if op.is_comparison() {
2794 self.check_no_chained_comparison(&lhs, &op);
2797 if op == AssocOp::As {
2798 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2800 } else if op == AssocOp::Colon {
2801 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2804 err.span_label(self.span,
2805 "expecting a type here because of type ascription");
2806 let cm = self.sess.codemap();
2807 let cur_pos = cm.lookup_char_pos(self.span.lo());
2808 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
2809 if cur_pos.line != op_pos.line {
2810 err.span_suggestion_short(cur_op_span,
2811 "did you mean to use `;` here?",
2818 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2819 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2820 // generalise it to the Fixity::None code.
2822 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2823 // two variants are handled with `parse_prefix_range_expr` call above.
2824 let rhs = if self.is_at_start_of_range_notation_rhs() {
2825 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2826 LhsExpr::NotYetParsed)?)
2830 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2835 let limits = if op == AssocOp::DotDot {
2836 RangeLimits::HalfOpen
2841 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2842 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2846 let rhs = match op.fixity() {
2847 Fixity::Right => self.with_res(
2848 restrictions - Restrictions::STMT_EXPR,
2850 this.parse_assoc_expr_with(op.precedence(),
2851 LhsExpr::NotYetParsed)
2853 Fixity::Left => self.with_res(
2854 restrictions - Restrictions::STMT_EXPR,
2856 this.parse_assoc_expr_with(op.precedence() + 1,
2857 LhsExpr::NotYetParsed)
2859 // We currently have no non-associative operators that are not handled above by
2860 // the special cases. The code is here only for future convenience.
2861 Fixity::None => self.with_res(
2862 restrictions - Restrictions::STMT_EXPR,
2864 this.parse_assoc_expr_with(op.precedence() + 1,
2865 LhsExpr::NotYetParsed)
2869 let span = lhs_span.to(rhs.span);
2871 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2872 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2873 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2874 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2875 AssocOp::Greater | AssocOp::GreaterEqual => {
2876 let ast_op = op.to_ast_binop().unwrap();
2877 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2878 self.mk_expr(span, binary, ThinVec::new())
2881 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2883 self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
2884 AssocOp::AssignOp(k) => {
2886 token::Plus => BinOpKind::Add,
2887 token::Minus => BinOpKind::Sub,
2888 token::Star => BinOpKind::Mul,
2889 token::Slash => BinOpKind::Div,
2890 token::Percent => BinOpKind::Rem,
2891 token::Caret => BinOpKind::BitXor,
2892 token::And => BinOpKind::BitAnd,
2893 token::Or => BinOpKind::BitOr,
2894 token::Shl => BinOpKind::Shl,
2895 token::Shr => BinOpKind::Shr,
2897 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2898 self.mk_expr(span, aopexpr, ThinVec::new())
2900 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
2901 self.bug("AssocOp should have been handled by special case")
2905 if op.fixity() == Fixity::None { break }
2910 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
2911 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
2912 -> PResult<'a, P<Expr>> {
2913 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
2914 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
2917 // Save the state of the parser before parsing type normally, in case there is a
2918 // LessThan comparison after this cast.
2919 let parser_snapshot_before_type = self.clone();
2920 match self.parse_ty_no_plus() {
2922 Ok(mk_expr(self, rhs))
2924 Err(mut type_err) => {
2925 // Rewind to before attempting to parse the type with generics, to recover
2926 // from situations like `x as usize < y` in which we first tried to parse
2927 // `usize < y` as a type with generic arguments.
2928 let parser_snapshot_after_type = self.clone();
2929 mem::replace(self, parser_snapshot_before_type);
2931 match self.parse_path(PathStyle::Expr) {
2933 let (op_noun, op_verb) = match self.token {
2934 token::Lt => ("comparison", "comparing"),
2935 token::BinOp(token::Shl) => ("shift", "shifting"),
2937 // We can end up here even without `<` being the next token, for
2938 // example because `parse_ty_no_plus` returns `Err` on keywords,
2939 // but `parse_path` returns `Ok` on them due to error recovery.
2940 // Return original error and parser state.
2941 mem::replace(self, parser_snapshot_after_type);
2942 return Err(type_err);
2946 // Successfully parsed the type path leaving a `<` yet to parse.
2949 // Report non-fatal diagnostics, keep `x as usize` as an expression
2950 // in AST and continue parsing.
2951 let msg = format!("`<` is interpreted as a start of generic \
2952 arguments for `{}`, not a {}", path, op_noun);
2953 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
2954 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
2955 "interpreted as generic arguments");
2956 err.span_label(self.span, format!("not interpreted as {}", op_noun));
2958 let expr = mk_expr(self, P(Ty {
2960 node: TyKind::Path(None, path),
2961 id: ast::DUMMY_NODE_ID
2964 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
2965 .unwrap_or(pprust::expr_to_string(&expr));
2966 err.span_suggestion(expr.span,
2967 &format!("try {} the casted value", op_verb),
2968 format!("({})", expr_str));
2973 Err(mut path_err) => {
2974 // Couldn't parse as a path, return original error and parser state.
2976 mem::replace(self, parser_snapshot_after_type);
2984 /// Produce an error if comparison operators are chained (RFC #558).
2985 /// We only need to check lhs, not rhs, because all comparison ops
2986 /// have same precedence and are left-associative
2987 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2988 debug_assert!(outer_op.is_comparison(),
2989 "check_no_chained_comparison: {:?} is not comparison",
2992 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2993 // respan to include both operators
2994 let op_span = op.span.to(self.span);
2995 let mut err = self.diagnostic().struct_span_err(op_span,
2996 "chained comparison operators require parentheses");
2997 if op.node == BinOpKind::Lt &&
2998 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
2999 *outer_op == AssocOp::Greater // even in a case like the following:
3000 { // Foo<Bar<Baz<Qux, ()>>>
3002 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3003 err.help("or use `(...)` if you meant to specify fn arguments");
3011 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3012 fn parse_prefix_range_expr(&mut self,
3013 already_parsed_attrs: Option<ThinVec<Attribute>>)
3014 -> PResult<'a, P<Expr>> {
3015 // Check for deprecated `...` syntax
3016 if self.token == token::DotDotDot {
3017 self.err_dotdotdot_syntax(self.span);
3020 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3021 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3023 let tok = self.token.clone();
3024 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3026 let mut hi = self.span;
3028 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3029 // RHS must be parsed with more associativity than the dots.
3030 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3031 Some(self.parse_assoc_expr_with(next_prec,
3032 LhsExpr::NotYetParsed)
3040 let limits = if tok == token::DotDot {
3041 RangeLimits::HalfOpen
3046 let r = try!(self.mk_range(None,
3049 Ok(self.mk_expr(lo.to(hi), r, attrs))
3052 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3053 if self.token.can_begin_expr() {
3054 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3055 if self.token == token::OpenDelim(token::Brace) {
3056 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3064 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3065 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3066 if self.check_keyword(keywords::Let) {
3067 return self.parse_if_let_expr(attrs);
3069 let lo = self.prev_span;
3070 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3072 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3073 // verify that the last statement is either an implicit return (no `;`) or an explicit
3074 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3075 // the dead code lint.
3076 if self.eat_keyword(keywords::Else) || !cond.returns() {
3077 let sp = lo.next_point();
3078 let mut err = self.diagnostic()
3079 .struct_span_err(sp, "missing condition for `if` statemement");
3080 err.span_label(sp, "expected if condition here");
3083 let thn = self.parse_block()?;
3084 let mut els: Option<P<Expr>> = None;
3085 let mut hi = thn.span;
3086 if self.eat_keyword(keywords::Else) {
3087 let elexpr = self.parse_else_expr()?;
3091 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3094 /// Parse an 'if let' expression ('if' token already eaten)
3095 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3096 -> PResult<'a, P<Expr>> {
3097 let lo = self.prev_span;
3098 self.expect_keyword(keywords::Let)?;
3099 let pat = self.parse_pat()?;
3100 self.expect(&token::Eq)?;
3101 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3102 let thn = self.parse_block()?;
3103 let (hi, els) = if self.eat_keyword(keywords::Else) {
3104 let expr = self.parse_else_expr()?;
3105 (expr.span, Some(expr))
3109 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
3112 // `move |args| expr`
3113 pub fn parse_lambda_expr(&mut self,
3115 capture_clause: CaptureBy,
3116 attrs: ThinVec<Attribute>)
3117 -> PResult<'a, P<Expr>>
3119 let decl = self.parse_fn_block_decl()?;
3120 let decl_hi = self.prev_span;
3121 let body = match decl.output {
3122 FunctionRetTy::Default(_) => {
3123 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3124 self.parse_expr_res(restrictions, None)?
3127 // If an explicit return type is given, require a
3128 // block to appear (RFC 968).
3129 let body_lo = self.span;
3130 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3136 ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3140 // `else` token already eaten
3141 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3142 if self.eat_keyword(keywords::If) {
3143 return self.parse_if_expr(ThinVec::new());
3145 let blk = self.parse_block()?;
3146 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3150 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3151 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3153 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3154 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3156 let pat = self.parse_pat()?;
3157 self.expect_keyword(keywords::In)?;
3158 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3159 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3160 attrs.extend(iattrs);
3162 let hi = self.prev_span;
3163 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3166 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3167 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3169 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3170 if self.token.is_keyword(keywords::Let) {
3171 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3173 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3174 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3175 attrs.extend(iattrs);
3176 let span = span_lo.to(body.span);
3177 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3180 /// Parse a 'while let' expression ('while' token already eaten)
3181 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3183 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3184 self.expect_keyword(keywords::Let)?;
3185 let pat = self.parse_pat()?;
3186 self.expect(&token::Eq)?;
3187 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3188 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3189 attrs.extend(iattrs);
3190 let span = span_lo.to(body.span);
3191 return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3194 // parse `loop {...}`, `loop` token already eaten
3195 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3197 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3198 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3199 attrs.extend(iattrs);
3200 let span = span_lo.to(body.span);
3201 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3204 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3205 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3206 -> PResult<'a, P<Expr>>
3208 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3209 attrs.extend(iattrs);
3210 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3213 // `match` token already eaten
3214 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3215 let match_span = self.prev_span;
3216 let lo = self.prev_span;
3217 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3219 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3220 if self.token == token::Token::Semi {
3221 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3225 attrs.extend(self.parse_inner_attributes()?);
3227 let mut arms: Vec<Arm> = Vec::new();
3228 while self.token != token::CloseDelim(token::Brace) {
3229 match self.parse_arm() {
3230 Ok(arm) => arms.push(arm),
3232 // Recover by skipping to the end of the block.
3234 self.recover_stmt();
3235 let span = lo.to(self.span);
3236 if self.token == token::CloseDelim(token::Brace) {
3239 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3245 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3248 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3249 maybe_whole!(self, NtArm, |x| x);
3251 let attrs = self.parse_outer_attributes()?;
3252 // Allow a '|' before the pats (RFC 1925)
3253 let beginning_vert = if self.eat(&token::BinOp(token::Or)) {
3254 Some(self.prev_span)
3258 let pats = self.parse_pats()?;
3259 let guard = if self.eat_keyword(keywords::If) {
3260 Some(self.parse_expr()?)
3264 self.expect(&token::FatArrow)?;
3265 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)?;
3267 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3268 && self.token != token::CloseDelim(token::Brace);
3271 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3273 self.eat(&token::Comma);
3285 /// Parse an expression
3286 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3287 self.parse_expr_res(Restrictions::empty(), None)
3290 /// Evaluate the closure with restrictions in place.
3292 /// After the closure is evaluated, restrictions are reset.
3293 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3294 where F: FnOnce(&mut Self) -> T
3296 let old = self.restrictions;
3297 self.restrictions = r;
3299 self.restrictions = old;
3304 /// Parse an expression, subject to the given restrictions
3305 pub fn parse_expr_res(&mut self, r: Restrictions,
3306 already_parsed_attrs: Option<ThinVec<Attribute>>)
3307 -> PResult<'a, P<Expr>> {
3308 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3311 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3312 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3313 if self.check(&token::Eq) {
3315 Ok(Some(self.parse_expr()?))
3321 /// Parse patterns, separated by '|' s
3322 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3323 let mut pats = Vec::new();
3325 pats.push(self.parse_pat()?);
3326 if self.check(&token::BinOp(token::Or)) { self.bump();}
3327 else { return Ok(pats); }
3331 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3332 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3333 let mut fields = vec![];
3334 let mut ddpos = None;
3336 while !self.check(&token::CloseDelim(token::Paren)) {
3337 if ddpos.is_none() && self.eat(&token::DotDot) {
3338 ddpos = Some(fields.len());
3339 if self.eat(&token::Comma) {
3340 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3341 fields.push(self.parse_pat()?);
3343 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3344 // Emit a friendly error, ignore `..` and continue parsing
3345 self.span_err(self.prev_span, "`..` can only be used once per \
3346 tuple or tuple struct pattern");
3348 fields.push(self.parse_pat()?);
3351 if !self.check(&token::CloseDelim(token::Paren)) ||
3352 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3353 self.expect(&token::Comma)?;
3360 fn parse_pat_vec_elements(
3362 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3363 let mut before = Vec::new();
3364 let mut slice = None;
3365 let mut after = Vec::new();
3366 let mut first = true;
3367 let mut before_slice = true;
3369 while self.token != token::CloseDelim(token::Bracket) {
3373 self.expect(&token::Comma)?;
3375 if self.token == token::CloseDelim(token::Bracket)
3376 && (before_slice || !after.is_empty()) {
3382 if self.eat(&token::DotDot) {
3384 if self.check(&token::Comma) ||
3385 self.check(&token::CloseDelim(token::Bracket)) {
3386 slice = Some(P(ast::Pat {
3387 id: ast::DUMMY_NODE_ID,
3388 node: PatKind::Wild,
3391 before_slice = false;
3397 let subpat = self.parse_pat()?;
3398 if before_slice && self.eat(&token::DotDot) {
3399 slice = Some(subpat);
3400 before_slice = false;
3401 } else if before_slice {
3402 before.push(subpat);
3408 Ok((before, slice, after))
3411 /// Parse the fields of a struct-like pattern
3412 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3413 let mut fields = Vec::new();
3414 let mut etc = false;
3415 let mut first = true;
3416 while self.token != token::CloseDelim(token::Brace) {
3420 self.expect(&token::Comma)?;
3421 // accept trailing commas
3422 if self.check(&token::CloseDelim(token::Brace)) { break }
3425 let attrs = self.parse_outer_attributes()?;
3429 if self.check(&token::DotDot) {
3431 if self.token != token::CloseDelim(token::Brace) {
3432 let token_str = self.this_token_to_string();
3433 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3440 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3441 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3442 // Parsing a pattern of the form "fieldname: pat"
3443 let fieldname = self.parse_field_name()?;
3445 let pat = self.parse_pat()?;
3447 (pat, fieldname, false)
3449 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3450 let is_box = self.eat_keyword(keywords::Box);
3451 let boxed_span = self.span;
3452 let is_ref = self.eat_keyword(keywords::Ref);
3453 let is_mut = self.eat_keyword(keywords::Mut);
3454 let fieldname = self.parse_ident()?;
3455 hi = self.prev_span;
3457 let bind_type = match (is_ref, is_mut) {
3458 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3459 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3460 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3461 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3463 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3464 let fieldpat = P(ast::Pat{
3465 id: ast::DUMMY_NODE_ID,
3466 node: PatKind::Ident(bind_type, fieldpath, None),
3467 span: boxed_span.to(hi),
3470 let subpat = if is_box {
3472 id: ast::DUMMY_NODE_ID,
3473 node: PatKind::Box(fieldpat),
3479 (subpat, fieldname, true)
3482 fields.push(codemap::Spanned { span: lo.to(hi),
3483 node: ast::FieldPat {
3487 attrs: attrs.into(),
3491 return Ok((fields, etc));
3494 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3495 if self.token.is_path_start() {
3497 let (qself, path) = if self.eat_lt() {
3498 // Parse a qualified path
3499 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3502 // Parse an unqualified path
3503 (None, self.parse_path(PathStyle::Expr)?)
3505 let hi = self.prev_span;
3506 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3508 self.parse_pat_literal_maybe_minus()
3512 // helper function to decide whether to parse as ident binding or to try to do
3513 // something more complex like range patterns
3514 fn parse_as_ident(&mut self) -> bool {
3515 self.look_ahead(1, |t| match *t {
3516 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3517 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3518 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3519 // range pattern branch
3520 token::DotDot => None,
3522 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3523 token::Comma | token::CloseDelim(token::Bracket) => true,
3528 /// Parse a pattern.
3529 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3530 maybe_whole!(self, NtPat, |x| x);
3535 token::Underscore => {
3538 pat = PatKind::Wild;
3540 token::BinOp(token::And) | token::AndAnd => {
3541 // Parse &pat / &mut pat
3543 let mutbl = self.parse_mutability();
3544 if let token::Lifetime(ident) = self.token {
3545 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3547 let subpat = self.parse_pat()?;
3548 pat = PatKind::Ref(subpat, mutbl);
3550 token::OpenDelim(token::Paren) => {
3551 // Parse (pat,pat,pat,...) as tuple pattern
3553 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3554 self.expect(&token::CloseDelim(token::Paren))?;
3555 pat = PatKind::Tuple(fields, ddpos);
3557 token::OpenDelim(token::Bracket) => {
3558 // Parse [pat,pat,...] as slice pattern
3560 let (before, slice, after) = self.parse_pat_vec_elements()?;
3561 self.expect(&token::CloseDelim(token::Bracket))?;
3562 pat = PatKind::Slice(before, slice, after);
3564 // At this point, token != _, &, &&, (, [
3565 _ => if self.eat_keyword(keywords::Mut) {
3566 // Parse mut ident @ pat / mut ref ident @ pat
3567 let mutref_span = self.prev_span.to(self.span);
3568 let binding_mode = if self.eat_keyword(keywords::Ref) {
3570 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3571 .span_suggestion(mutref_span, "try switching the order", "ref mut".into())
3573 BindingMode::ByRef(Mutability::Mutable)
3575 BindingMode::ByValue(Mutability::Mutable)
3577 pat = self.parse_pat_ident(binding_mode)?;
3578 } else if self.eat_keyword(keywords::Ref) {
3579 // Parse ref ident @ pat / ref mut ident @ pat
3580 let mutbl = self.parse_mutability();
3581 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3582 } else if self.eat_keyword(keywords::Box) {
3584 let subpat = self.parse_pat()?;
3585 pat = PatKind::Box(subpat);
3586 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3587 self.parse_as_ident() {
3588 // Parse ident @ pat
3589 // This can give false positives and parse nullary enums,
3590 // they are dealt with later in resolve
3591 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3592 pat = self.parse_pat_ident(binding_mode)?;
3593 } else if self.token.is_path_start() {
3594 // Parse pattern starting with a path
3595 let (qself, path) = if self.eat_lt() {
3596 // Parse a qualified path
3597 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3600 // Parse an unqualified path
3601 (None, self.parse_path(PathStyle::Expr)?)
3604 token::Not if qself.is_none() => {
3605 // Parse macro invocation
3607 let (_, tts) = self.expect_delimited_token_tree()?;
3608 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3609 pat = PatKind::Mac(mac);
3611 token::DotDotDot | token::DotDotEq | token::DotDot => {
3612 let end_kind = match self.token {
3613 token::DotDot => RangeEnd::Excluded,
3614 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
3615 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
3616 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
3620 let span = lo.to(self.prev_span);
3621 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3623 let end = self.parse_pat_range_end()?;
3624 pat = PatKind::Range(begin, end, end_kind);
3626 token::OpenDelim(token::Brace) => {
3627 if qself.is_some() {
3628 return Err(self.fatal("unexpected `{` after qualified path"));
3630 // Parse struct pattern
3632 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3634 self.recover_stmt();
3638 pat = PatKind::Struct(path, fields, etc);
3640 token::OpenDelim(token::Paren) => {
3641 if qself.is_some() {
3642 return Err(self.fatal("unexpected `(` after qualified path"));
3644 // Parse tuple struct or enum pattern
3646 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3647 self.expect(&token::CloseDelim(token::Paren))?;
3648 pat = PatKind::TupleStruct(path, fields, ddpos)
3650 _ => pat = PatKind::Path(qself, path),
3653 // Try to parse everything else as literal with optional minus
3654 match self.parse_pat_literal_maybe_minus() {
3656 if self.eat(&token::DotDotDot) {
3657 let end = self.parse_pat_range_end()?;
3658 pat = PatKind::Range(begin, end,
3659 RangeEnd::Included(RangeSyntax::DotDotDot));
3660 } else if self.eat(&token::DotDotEq) {
3661 let end = self.parse_pat_range_end()?;
3662 pat = PatKind::Range(begin, end,
3663 RangeEnd::Included(RangeSyntax::DotDotEq));
3664 } else if self.eat(&token::DotDot) {
3665 let end = self.parse_pat_range_end()?;
3666 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3668 pat = PatKind::Lit(begin);
3672 self.cancel(&mut err);
3673 let msg = format!("expected pattern, found {}", self.this_token_descr());
3674 return Err(self.fatal(&msg));
3681 id: ast::DUMMY_NODE_ID,
3683 span: lo.to(self.prev_span),
3687 /// Parse ident or ident @ pat
3688 /// used by the copy foo and ref foo patterns to give a good
3689 /// error message when parsing mistakes like ref foo(a,b)
3690 fn parse_pat_ident(&mut self,
3691 binding_mode: ast::BindingMode)
3692 -> PResult<'a, PatKind> {
3693 let ident_span = self.span;
3694 let ident = self.parse_ident()?;
3695 let name = codemap::Spanned{span: ident_span, node: ident};
3696 let sub = if self.eat(&token::At) {
3697 Some(self.parse_pat()?)
3702 // just to be friendly, if they write something like
3704 // we end up here with ( as the current token. This shortly
3705 // leads to a parse error. Note that if there is no explicit
3706 // binding mode then we do not end up here, because the lookahead
3707 // will direct us over to parse_enum_variant()
3708 if self.token == token::OpenDelim(token::Paren) {
3709 return Err(self.span_fatal(
3711 "expected identifier, found enum pattern"))
3714 Ok(PatKind::Ident(binding_mode, name, sub))
3717 /// Parse a local variable declaration
3718 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3719 let lo = self.prev_span;
3720 let pat = self.parse_pat()?;
3722 let ty = if self.eat(&token::Colon) {
3723 Some(self.parse_ty()?)
3727 let init = self.parse_initializer()?;
3728 let hi = if self.token == token::Semi {
3737 id: ast::DUMMY_NODE_ID,
3743 /// Parse a structure field
3744 fn parse_name_and_ty(&mut self,
3747 attrs: Vec<Attribute>)
3748 -> PResult<'a, StructField> {
3749 let name = self.parse_ident()?;
3750 self.expect(&token::Colon)?;
3751 let ty = self.parse_ty()?;
3753 span: lo.to(self.prev_span),
3756 id: ast::DUMMY_NODE_ID,
3762 /// Emit an expected item after attributes error.
3763 fn expected_item_err(&self, attrs: &[Attribute]) {
3764 let message = match attrs.last() {
3765 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3766 _ => "expected item after attributes",
3769 self.span_err(self.prev_span, message);
3772 /// Parse a statement. This stops just before trailing semicolons on everything but items.
3773 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3774 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3775 Ok(self.parse_stmt_(true))
3778 // Eat tokens until we can be relatively sure we reached the end of the
3779 // statement. This is something of a best-effort heuristic.
3781 // We terminate when we find an unmatched `}` (without consuming it).
3782 fn recover_stmt(&mut self) {
3783 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
3786 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3787 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3788 // approximate - it can mean we break too early due to macros, but that
3789 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3791 // If `break_on_block` is `Break`, then we will stop consuming tokens
3792 // after finding (and consuming) a brace-delimited block.
3793 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
3794 let mut brace_depth = 0;
3795 let mut bracket_depth = 0;
3796 let mut in_block = false;
3797 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
3798 break_on_semi, break_on_block);
3800 debug!("recover_stmt_ loop {:?}", self.token);
3802 token::OpenDelim(token::DelimToken::Brace) => {
3805 if break_on_block == BlockMode::Break &&
3807 bracket_depth == 0 {
3811 token::OpenDelim(token::DelimToken::Bracket) => {
3815 token::CloseDelim(token::DelimToken::Brace) => {
3816 if brace_depth == 0 {
3817 debug!("recover_stmt_ return - close delim {:?}", self.token);
3822 if in_block && bracket_depth == 0 && brace_depth == 0 {
3823 debug!("recover_stmt_ return - block end {:?}", self.token);
3827 token::CloseDelim(token::DelimToken::Bracket) => {
3829 if bracket_depth < 0 {
3835 debug!("recover_stmt_ return - Eof");
3840 if break_on_semi == SemiColonMode::Break &&
3842 bracket_depth == 0 {
3843 debug!("recover_stmt_ return - Semi");
3854 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
3855 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
3857 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
3862 fn is_catch_expr(&mut self) -> bool {
3863 self.token.is_keyword(keywords::Do) &&
3864 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
3865 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
3867 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3868 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
3871 fn is_union_item(&self) -> bool {
3872 self.token.is_keyword(keywords::Union) &&
3873 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
3876 fn is_defaultness(&self) -> bool {
3877 // `pub` is included for better error messages
3878 self.token.is_keyword(keywords::Default) &&
3879 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
3880 t.is_keyword(keywords::Const) ||
3881 t.is_keyword(keywords::Fn) ||
3882 t.is_keyword(keywords::Unsafe) ||
3883 t.is_keyword(keywords::Extern) ||
3884 t.is_keyword(keywords::Type) ||
3885 t.is_keyword(keywords::Pub))
3888 fn eat_defaultness(&mut self) -> bool {
3889 let is_defaultness = self.is_defaultness();
3893 self.expected_tokens.push(TokenType::Keyword(keywords::Default));
3898 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
3899 -> PResult<'a, Option<P<Item>>> {
3900 let token_lo = self.span;
3901 let (ident, def) = match self.token {
3902 token::Ident(ident) if ident.name == keywords::Macro.name() => {
3904 let ident = self.parse_ident()?;
3905 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
3906 match self.parse_token_tree() {
3907 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
3908 _ => unreachable!(),
3910 } else if self.check(&token::OpenDelim(token::Paren)) {
3911 let args = self.parse_token_tree();
3912 let body = if self.check(&token::OpenDelim(token::Brace)) {
3913 self.parse_token_tree()
3918 TokenStream::concat(vec![
3920 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
3928 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
3930 token::Ident(ident) if ident.name == "macro_rules" &&
3931 self.look_ahead(1, |t| *t == token::Not) => {
3932 let prev_span = self.prev_span;
3933 self.complain_if_pub_macro(vis, prev_span);
3937 let ident = self.parse_ident()?;
3938 let (delim, tokens) = self.expect_delimited_token_tree()?;
3939 if delim != token::Brace {
3940 if !self.eat(&token::Semi) {
3941 let msg = "macros that expand to items must either \
3942 be surrounded with braces or followed by a semicolon";
3943 self.span_err(self.prev_span, msg);
3947 (ident, ast::MacroDef { tokens: tokens, legacy: true })
3949 _ => return Ok(None),
3952 let span = lo.to(self.prev_span);
3953 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
3956 fn parse_stmt_without_recovery(&mut self,
3957 macro_legacy_warnings: bool)
3958 -> PResult<'a, Option<Stmt>> {
3959 maybe_whole!(self, NtStmt, |x| Some(x));
3961 let attrs = self.parse_outer_attributes()?;
3964 Ok(Some(if self.eat_keyword(keywords::Let) {
3966 id: ast::DUMMY_NODE_ID,
3967 node: StmtKind::Local(self.parse_local(attrs.into())?),
3968 span: lo.to(self.prev_span),
3970 } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited, lo)? {
3972 id: ast::DUMMY_NODE_ID,
3973 node: StmtKind::Item(macro_def),
3974 span: lo.to(self.prev_span),
3976 // Starts like a simple path, but not a union item.
3977 } else if self.token.is_path_start() &&
3978 !self.token.is_qpath_start() &&
3979 !self.is_union_item() {
3980 let pth = self.parse_path(PathStyle::Expr)?;
3982 if !self.eat(&token::Not) {
3983 let expr = if self.check(&token::OpenDelim(token::Brace)) {
3984 self.parse_struct_expr(lo, pth, ThinVec::new())?
3986 let hi = self.prev_span;
3987 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
3990 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
3991 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
3992 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
3995 return Ok(Some(Stmt {
3996 id: ast::DUMMY_NODE_ID,
3997 node: StmtKind::Expr(expr),
3998 span: lo.to(self.prev_span),
4002 // it's a macro invocation
4003 let id = match self.token {
4004 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4005 _ => self.parse_ident()?,
4008 // check that we're pointing at delimiters (need to check
4009 // again after the `if`, because of `parse_ident`
4010 // consuming more tokens).
4011 let delim = match self.token {
4012 token::OpenDelim(delim) => delim,
4014 // we only expect an ident if we didn't parse one
4016 let ident_str = if id.name == keywords::Invalid.name() {
4021 let tok_str = self.this_token_to_string();
4022 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4028 let (_, tts) = self.expect_delimited_token_tree()?;
4029 let hi = self.prev_span;
4031 let style = if delim == token::Brace {
4032 MacStmtStyle::Braces
4034 MacStmtStyle::NoBraces
4037 if id.name == keywords::Invalid.name() {
4038 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
4039 let node = if delim == token::Brace ||
4040 self.token == token::Semi || self.token == token::Eof {
4041 StmtKind::Mac(P((mac, style, attrs.into())))
4043 // We used to incorrectly stop parsing macro-expanded statements here.
4044 // If the next token will be an error anyway but could have parsed with the
4045 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4046 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4047 // These can continue an expression, so we can't stop parsing and warn.
4048 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4049 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4050 token::BinOp(token::And) | token::BinOp(token::Or) |
4051 token::AndAnd | token::OrOr |
4052 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4055 self.warn_missing_semicolon();
4056 StmtKind::Mac(P((mac, style, attrs.into())))
4058 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4059 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4060 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4064 id: ast::DUMMY_NODE_ID,
4069 // if it has a special ident, it's definitely an item
4071 // Require a semicolon or braces.
4072 if style != MacStmtStyle::Braces {
4073 if !self.eat(&token::Semi) {
4074 self.span_err(self.prev_span,
4075 "macros that expand to items must \
4076 either be surrounded with braces or \
4077 followed by a semicolon");
4080 let span = lo.to(hi);
4082 id: ast::DUMMY_NODE_ID,
4084 node: StmtKind::Item({
4086 span, id /*id is good here*/,
4087 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
4088 Visibility::Inherited,
4094 // FIXME: Bad copy of attrs
4095 let old_directory_ownership =
4096 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4097 let item = self.parse_item_(attrs.clone(), false, true)?;
4098 self.directory.ownership = old_directory_ownership;
4102 id: ast::DUMMY_NODE_ID,
4103 span: lo.to(i.span),
4104 node: StmtKind::Item(i),
4107 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4108 if !attrs.is_empty() {
4109 if s.prev_token_kind == PrevTokenKind::DocComment {
4110 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4111 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4112 s.span_err(s.span, "expected statement after outer attribute");
4117 // Do not attempt to parse an expression if we're done here.
4118 if self.token == token::Semi {
4119 unused_attrs(&attrs, self);
4124 if self.token == token::CloseDelim(token::Brace) {
4125 unused_attrs(&attrs, self);
4129 // Remainder are line-expr stmts.
4130 let e = self.parse_expr_res(
4131 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4133 id: ast::DUMMY_NODE_ID,
4134 span: lo.to(e.span),
4135 node: StmtKind::Expr(e),
4142 /// Is this expression a successfully-parsed statement?
4143 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4144 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4145 !classify::expr_requires_semi_to_be_stmt(e)
4148 /// Parse a block. No inner attrs are allowed.
4149 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4150 maybe_whole!(self, NtBlock, |x| x);
4154 if !self.eat(&token::OpenDelim(token::Brace)) {
4156 let tok = self.this_token_to_string();
4157 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4159 // Check to see if the user has written something like
4164 // Which is valid in other languages, but not Rust.
4165 match self.parse_stmt_without_recovery(false) {
4167 let mut stmt_span = stmt.span;
4168 // expand the span to include the semicolon, if it exists
4169 if self.eat(&token::Semi) {
4170 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4172 let sugg = pprust::to_string(|s| {
4173 use print::pprust::{PrintState, INDENT_UNIT};
4174 s.ibox(INDENT_UNIT)?;
4176 s.print_stmt(&stmt)?;
4177 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4179 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4182 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4183 self.cancel(&mut e);
4190 self.parse_block_tail(lo, BlockCheckMode::Default)
4193 /// Parse a block. Inner attrs are allowed.
4194 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4195 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4198 self.expect(&token::OpenDelim(token::Brace))?;
4199 Ok((self.parse_inner_attributes()?,
4200 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4203 /// Parse the rest of a block expression or function body
4204 /// Precondition: already parsed the '{'.
4205 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4206 let mut stmts = vec![];
4208 while !self.eat(&token::CloseDelim(token::Brace)) {
4209 if let Some(stmt) = self.parse_full_stmt(false)? {
4211 } else if self.token == token::Eof {
4214 // Found only `;` or `}`.
4221 id: ast::DUMMY_NODE_ID,
4223 span: lo.to(self.prev_span),
4227 /// Parse a statement, including the trailing semicolon.
4228 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4229 let mut stmt = match self.parse_stmt_(macro_legacy_warnings) {
4231 None => return Ok(None),
4235 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4236 // expression without semicolon
4237 if classify::expr_requires_semi_to_be_stmt(expr) {
4238 // Just check for errors and recover; do not eat semicolon yet.
4240 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4243 self.recover_stmt();
4247 StmtKind::Local(..) => {
4248 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4249 if macro_legacy_warnings && self.token != token::Semi {
4250 self.warn_missing_semicolon();
4252 self.expect_one_of(&[token::Semi], &[])?;
4258 if self.eat(&token::Semi) {
4259 stmt = stmt.add_trailing_semicolon();
4262 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4266 fn warn_missing_semicolon(&self) {
4267 self.diagnostic().struct_span_warn(self.span, {
4268 &format!("expected `;`, found `{}`", self.this_token_to_string())
4270 "This was erroneously allowed and will become a hard error in a future release"
4274 fn err_dotdotdot_syntax(&self, span: Span) {
4275 self.diagnostic().struct_span_err(span, {
4276 "`...` syntax cannot be used in expressions"
4278 "Use `..` if you need an exclusive range (a < b)"
4280 "or `..=` if you need an inclusive range (a <= b)"
4284 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4285 // BOUND = TY_BOUND | LT_BOUND
4286 // LT_BOUND = LIFETIME (e.g. `'a`)
4287 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4288 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4289 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4290 let mut bounds = Vec::new();
4292 // This needs to be syncronized with `Token::can_begin_bound`.
4293 let is_bound_start = self.check_path() || self.check_lifetime() ||
4294 self.check(&token::Question) ||
4295 self.check_keyword(keywords::For) ||
4296 self.check(&token::OpenDelim(token::Paren));
4298 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4299 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4300 if self.token.is_lifetime() {
4301 if let Some(question_span) = question {
4302 self.span_err(question_span,
4303 "`?` may only modify trait bounds, not lifetime bounds");
4305 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4308 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4309 let path = self.parse_path(PathStyle::Type)?;
4310 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4311 let modifier = if question.is_some() {
4312 TraitBoundModifier::Maybe
4314 TraitBoundModifier::None
4316 bounds.push(TraitTyParamBound(poly_trait, modifier));
4319 self.expect(&token::CloseDelim(token::Paren))?;
4320 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4321 self.span_err(self.prev_span,
4322 "parenthesized lifetime bounds are not supported");
4329 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4337 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4338 self.parse_ty_param_bounds_common(true)
4341 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4342 // BOUND = LT_BOUND (e.g. `'a`)
4343 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4344 let mut lifetimes = Vec::new();
4345 while self.check_lifetime() {
4346 lifetimes.push(self.expect_lifetime());
4348 if !self.eat(&token::BinOp(token::Plus)) {
4355 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4356 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4357 let span = self.span;
4358 let ident = self.parse_ident()?;
4360 // Parse optional colon and param bounds.
4361 let bounds = if self.eat(&token::Colon) {
4362 self.parse_ty_param_bounds()?
4367 let default = if self.eat(&token::Eq) {
4368 Some(self.parse_ty()?)
4374 attrs: preceding_attrs.into(),
4376 id: ast::DUMMY_NODE_ID,
4383 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4384 /// trailing comma and erroneous trailing attributes.
4385 pub fn parse_generic_params(&mut self) -> PResult<'a, (Vec<LifetimeDef>, Vec<TyParam>)> {
4386 let mut lifetime_defs = Vec::new();
4387 let mut ty_params = Vec::new();
4388 let mut seen_ty_param = false;
4390 let attrs = self.parse_outer_attributes()?;
4391 if self.check_lifetime() {
4392 let lifetime = self.expect_lifetime();
4393 // Parse lifetime parameter.
4394 let bounds = if self.eat(&token::Colon) {
4395 self.parse_lt_param_bounds()
4399 lifetime_defs.push(LifetimeDef {
4400 attrs: attrs.into(),
4405 self.span_err(self.prev_span,
4406 "lifetime parameters must be declared prior to type parameters");
4408 } else if self.check_ident() {
4409 // Parse type parameter.
4410 ty_params.push(self.parse_ty_param(attrs)?);
4411 seen_ty_param = true;
4413 // Check for trailing attributes and stop parsing.
4414 if !attrs.is_empty() {
4415 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4416 self.span_err(attrs[0].span,
4417 &format!("trailing attribute after {} parameters", param_kind));
4422 if !self.eat(&token::Comma) {
4426 Ok((lifetime_defs, ty_params))
4429 /// Parse a set of optional generic type parameter declarations. Where
4430 /// clauses are not parsed here, and must be added later via
4431 /// `parse_where_clause()`.
4433 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4434 /// | ( < lifetimes , typaramseq ( , )? > )
4435 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4436 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4437 maybe_whole!(self, NtGenerics, |x| x);
4439 let span_lo = self.span;
4441 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4444 lifetimes: lifetime_defs,
4446 where_clause: WhereClause {
4447 id: ast::DUMMY_NODE_ID,
4448 predicates: Vec::new(),
4449 span: syntax_pos::DUMMY_SP,
4451 span: span_lo.to(self.prev_span),
4454 Ok(ast::Generics::default())
4458 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4459 /// possibly including trailing comma.
4460 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4461 let mut lifetimes = Vec::new();
4462 let mut types = Vec::new();
4463 let mut bindings = Vec::new();
4464 let mut seen_type = false;
4465 let mut seen_binding = false;
4467 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4468 // Parse lifetime argument.
4469 lifetimes.push(self.expect_lifetime());
4470 if seen_type || seen_binding {
4471 self.span_err(self.prev_span,
4472 "lifetime parameters must be declared prior to type parameters");
4474 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4475 // Parse associated type binding.
4477 let ident = self.parse_ident()?;
4479 let ty = self.parse_ty()?;
4480 bindings.push(TypeBinding {
4481 id: ast::DUMMY_NODE_ID,
4484 span: lo.to(self.prev_span),
4486 seen_binding = true;
4487 } else if self.check_type() {
4488 // Parse type argument.
4489 types.push(self.parse_ty()?);
4491 self.span_err(types[types.len() - 1].span,
4492 "type parameters must be declared prior to associated type bindings");
4499 if !self.eat(&token::Comma) {
4503 Ok((lifetimes, types, bindings))
4506 /// Parses an optional `where` clause and places it in `generics`.
4508 /// ```ignore (only-for-syntax-highlight)
4509 /// where T : Trait<U, V> + 'b, 'a : 'b
4511 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4512 maybe_whole!(self, NtWhereClause, |x| x);
4514 let mut where_clause = WhereClause {
4515 id: ast::DUMMY_NODE_ID,
4516 predicates: Vec::new(),
4517 span: syntax_pos::DUMMY_SP,
4520 if !self.eat_keyword(keywords::Where) {
4521 return Ok(where_clause);
4523 let lo = self.prev_span;
4525 // This is a temporary future proofing.
4527 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4528 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4529 // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4530 if token::Lt == self.token {
4531 let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4532 if ident_or_lifetime {
4533 let gt_comma_or_colon = self.look_ahead(2, |t| {
4534 *t == token::Gt || *t == token::Comma || *t == token::Colon
4536 if gt_comma_or_colon {
4537 self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4544 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4545 let lifetime = self.expect_lifetime();
4546 // Bounds starting with a colon are mandatory, but possibly empty.
4547 self.expect(&token::Colon)?;
4548 let bounds = self.parse_lt_param_bounds();
4549 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4550 ast::WhereRegionPredicate {
4551 span: lo.to(self.prev_span),
4556 } else if self.check_type() {
4557 // Parse optional `for<'a, 'b>`.
4558 // This `for` is parsed greedily and applies to the whole predicate,
4559 // the bounded type can have its own `for` applying only to it.
4560 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4561 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4562 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4563 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4565 // Parse type with mandatory colon and (possibly empty) bounds,
4566 // or with mandatory equality sign and the second type.
4567 let ty = self.parse_ty()?;
4568 if self.eat(&token::Colon) {
4569 let bounds = self.parse_ty_param_bounds()?;
4570 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4571 ast::WhereBoundPredicate {
4572 span: lo.to(self.prev_span),
4573 bound_lifetimes: lifetime_defs,
4578 // FIXME: Decide what should be used here, `=` or `==`.
4579 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4580 let rhs_ty = self.parse_ty()?;
4581 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4582 ast::WhereEqPredicate {
4583 span: lo.to(self.prev_span),
4586 id: ast::DUMMY_NODE_ID,
4590 return self.unexpected();
4596 if !self.eat(&token::Comma) {
4601 where_clause.span = lo.to(self.prev_span);
4605 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4606 -> PResult<'a, (Vec<Arg> , bool)> {
4608 let mut variadic = false;
4609 let args: Vec<Option<Arg>> =
4610 self.parse_unspanned_seq(
4611 &token::OpenDelim(token::Paren),
4612 &token::CloseDelim(token::Paren),
4613 SeqSep::trailing_allowed(token::Comma),
4615 if p.token == token::DotDotDot {
4618 if p.token != token::CloseDelim(token::Paren) {
4621 "`...` must be last in argument list for variadic function");
4626 "only foreign functions are allowed to be variadic");
4631 match p.parse_arg_general(named_args) {
4632 Ok(arg) => Ok(Some(arg)),
4635 let lo = p.prev_span;
4636 // Skip every token until next possible arg or end.
4637 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4638 // Create a placeholder argument for proper arg count (#34264).
4639 let span = lo.to(p.prev_span);
4640 Ok(Some(dummy_arg(span)))
4647 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4649 if variadic && args.is_empty() {
4651 "variadic function must be declared with at least one named argument");
4654 Ok((args, variadic))
4657 /// Parse the argument list and result type of a function declaration
4658 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4660 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4661 let ret_ty = self.parse_ret_ty()?;
4670 /// Returns the parsed optional self argument and whether a self shortcut was used.
4671 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4672 let expect_ident = |this: &mut Self| match this.token {
4673 // Preserve hygienic context.
4674 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4677 let isolated_self = |this: &mut Self, n| {
4678 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4679 this.look_ahead(n + 1, |t| t != &token::ModSep)
4682 // Parse optional self parameter of a method.
4683 // Only a limited set of initial token sequences is considered self parameters, anything
4684 // else is parsed as a normal function parameter list, so some lookahead is required.
4685 let eself_lo = self.span;
4686 let (eself, eself_ident) = match self.token {
4687 token::BinOp(token::And) => {
4693 if isolated_self(self, 1) {
4695 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4696 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4697 isolated_self(self, 2) {
4700 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4701 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4702 isolated_self(self, 2) {
4704 let lt = self.expect_lifetime();
4705 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4706 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4707 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4708 isolated_self(self, 3) {
4710 let lt = self.expect_lifetime();
4712 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4717 token::BinOp(token::Star) => {
4722 // Emit special error for `self` cases.
4723 if isolated_self(self, 1) {
4725 self.span_err(self.span, "cannot pass `self` by raw pointer");
4726 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4727 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4728 isolated_self(self, 2) {
4731 self.span_err(self.span, "cannot pass `self` by raw pointer");
4732 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4737 token::Ident(..) => {
4738 if isolated_self(self, 0) {
4741 let eself_ident = expect_ident(self);
4742 if self.eat(&token::Colon) {
4743 let ty = self.parse_ty()?;
4744 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4746 (SelfKind::Value(Mutability::Immutable), eself_ident)
4748 } else if self.token.is_keyword(keywords::Mut) &&
4749 isolated_self(self, 1) {
4753 let eself_ident = expect_ident(self);
4754 if self.eat(&token::Colon) {
4755 let ty = self.parse_ty()?;
4756 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4758 (SelfKind::Value(Mutability::Mutable), eself_ident)
4764 _ => return Ok(None),
4767 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
4768 Ok(Some(Arg::from_self(eself, eself_ident)))
4771 /// Parse the parameter list and result type of a function that may have a `self` parameter.
4772 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
4773 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4775 self.expect(&token::OpenDelim(token::Paren))?;
4777 // Parse optional self argument
4778 let self_arg = self.parse_self_arg()?;
4780 // Parse the rest of the function parameter list.
4781 let sep = SeqSep::trailing_allowed(token::Comma);
4782 let fn_inputs = if let Some(self_arg) = self_arg {
4783 if self.check(&token::CloseDelim(token::Paren)) {
4785 } else if self.eat(&token::Comma) {
4786 let mut fn_inputs = vec![self_arg];
4787 fn_inputs.append(&mut self.parse_seq_to_before_end(
4788 &token::CloseDelim(token::Paren), sep, parse_arg_fn)
4792 return self.unexpected();
4795 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4798 // Parse closing paren and return type.
4799 self.expect(&token::CloseDelim(token::Paren))?;
4802 output: self.parse_ret_ty()?,
4807 // parse the |arg, arg| header on a lambda
4808 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4809 let inputs_captures = {
4810 if self.eat(&token::OrOr) {
4813 self.expect(&token::BinOp(token::Or))?;
4814 let args = self.parse_seq_to_before_tokens(
4815 &[&token::BinOp(token::Or), &token::OrOr],
4816 SeqSep::trailing_allowed(token::Comma),
4817 TokenExpectType::NoExpect,
4818 |p| p.parse_fn_block_arg(),
4825 let output = self.parse_ret_ty()?;
4828 inputs: inputs_captures,
4834 /// Parse the name and optional generic types of a function header.
4835 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4836 let id = self.parse_ident()?;
4837 let generics = self.parse_generics()?;
4841 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
4842 attrs: Vec<Attribute>) -> P<Item> {
4846 id: ast::DUMMY_NODE_ID,
4854 /// Parse an item-position function declaration.
4855 fn parse_item_fn(&mut self,
4857 constness: Spanned<Constness>,
4859 -> PResult<'a, ItemInfo> {
4860 let (ident, mut generics) = self.parse_fn_header()?;
4861 let decl = self.parse_fn_decl(false)?;
4862 generics.where_clause = self.parse_where_clause()?;
4863 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4864 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4867 /// true if we are looking at `const ID`, false for things like `const fn` etc
4868 pub fn is_const_item(&mut self) -> bool {
4869 self.token.is_keyword(keywords::Const) &&
4870 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4871 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4874 /// parses all the "front matter" for a `fn` declaration, up to
4875 /// and including the `fn` keyword:
4879 /// - `const unsafe fn`
4882 pub fn parse_fn_front_matter(&mut self)
4883 -> PResult<'a, (Spanned<ast::Constness>,
4886 let is_const_fn = self.eat_keyword(keywords::Const);
4887 let const_span = self.prev_span;
4888 let unsafety = self.parse_unsafety()?;
4889 let (constness, unsafety, abi) = if is_const_fn {
4890 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
4892 let abi = if self.eat_keyword(keywords::Extern) {
4893 self.parse_opt_abi()?.unwrap_or(Abi::C)
4897 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
4899 self.expect_keyword(keywords::Fn)?;
4900 Ok((constness, unsafety, abi))
4903 /// Parse an impl item.
4904 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
4905 maybe_whole!(self, NtImplItem, |x| x);
4906 let attrs = self.parse_outer_attributes()?;
4907 let (mut item, tokens) = self.collect_tokens(|this| {
4908 this.parse_impl_item_(at_end, attrs)
4911 // See `parse_item` for why this clause is here.
4912 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
4913 item.tokens = Some(tokens);
4918 fn parse_impl_item_(&mut self,
4920 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
4922 let vis = self.parse_visibility(false)?;
4923 let defaultness = self.parse_defaultness()?;
4924 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
4925 let name = self.parse_ident()?;
4926 self.expect(&token::Eq)?;
4927 let typ = self.parse_ty()?;
4928 self.expect(&token::Semi)?;
4929 (name, ast::ImplItemKind::Type(typ), ast::Generics::default())
4930 } else if self.is_const_item() {
4931 self.expect_keyword(keywords::Const)?;
4932 let name = self.parse_ident()?;
4933 self.expect(&token::Colon)?;
4934 let typ = self.parse_ty()?;
4935 self.expect(&token::Eq)?;
4936 let expr = self.parse_expr()?;
4937 self.expect(&token::Semi)?;
4938 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
4940 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
4941 attrs.extend(inner_attrs);
4942 (name, node, generics)
4946 id: ast::DUMMY_NODE_ID,
4947 span: lo.to(self.prev_span),
4958 fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
4959 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
4964 fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
4966 Visibility::Inherited => Ok(()),
4968 let is_macro_rules: bool = match self.token {
4969 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
4973 let mut err = self.diagnostic()
4974 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
4975 err.help("did you mean #[macro_export]?");
4978 let mut err = self.diagnostic()
4979 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
4980 err.help("try adjusting the macro to put `pub` inside the invocation");
4987 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
4988 -> DiagnosticBuilder<'a>
4990 // Given this code `path(`, it seems like this is not
4991 // setting the visibility of a macro invocation, but rather
4992 // a mistyped method declaration.
4993 // Create a diagnostic pointing out that `fn` is missing.
4995 // x | pub path(&self) {
4996 // | ^ missing `fn`, `type`, or `const`
4998 // ^^ `sp` below will point to this
4999 let sp = prev_span.between(self.prev_span);
5000 let mut err = self.diagnostic().struct_span_err(
5002 &format!("missing `fn`, `type`, or `const` for {}-item declaration",
5004 err.span_label(sp, "missing `fn`, `type`, or `const`");
5008 /// Parse a method or a macro invocation in a trait impl.
5009 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5010 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::Generics,
5011 ast::ImplItemKind)> {
5012 // code copied from parse_macro_use_or_failure... abstraction!
5013 if self.token.is_path_start() {
5016 let prev_span = self.prev_span;
5019 let pth = self.parse_path(PathStyle::Mod)?;
5020 if pth.segments.len() == 1 {
5021 if !self.eat(&token::Not) {
5022 return Err(self.missing_assoc_item_kind_err("impl", prev_span));
5025 self.expect(&token::Not)?;
5028 self.complain_if_pub_macro(vis, prev_span);
5030 // eat a matched-delimiter token tree:
5032 let (delim, tts) = self.expect_delimited_token_tree()?;
5033 if delim != token::Brace {
5034 self.expect(&token::Semi)?
5037 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
5038 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5039 ast::ImplItemKind::Macro(mac)))
5041 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
5042 let ident = self.parse_ident()?;
5043 let mut generics = self.parse_generics()?;
5044 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5045 generics.where_clause = self.parse_where_clause()?;
5047 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5048 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(ast::MethodSig {
5057 /// Parse trait Foo { ... }
5058 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5059 let ident = self.parse_ident()?;
5060 let mut tps = self.parse_generics()?;
5062 // Parse optional colon and supertrait bounds.
5063 let bounds = if self.eat(&token::Colon) {
5064 self.parse_ty_param_bounds()?
5069 tps.where_clause = self.parse_where_clause()?;
5071 self.expect(&token::OpenDelim(token::Brace))?;
5072 let mut trait_items = vec![];
5073 while !self.eat(&token::CloseDelim(token::Brace)) {
5074 let mut at_end = false;
5075 match self.parse_trait_item(&mut at_end) {
5076 Ok(item) => trait_items.push(item),
5080 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5085 Ok((ident, ItemKind::Trait(unsafety, tps, bounds, trait_items), None))
5088 /// Parses items implementations variants
5089 /// impl<T> Foo { ... }
5090 /// impl<T> ToString for &'static T { ... }
5091 /// impl Send for .. {}
5092 fn parse_item_impl(&mut self,
5093 unsafety: ast::Unsafety,
5094 defaultness: Defaultness) -> PResult<'a, ItemInfo> {
5095 let impl_span = self.span;
5097 // First, parse type parameters if necessary.
5098 let mut generics = self.parse_generics()?;
5100 // Special case: if the next identifier that follows is '(', don't
5101 // allow this to be parsed as a trait.
5102 let could_be_trait = self.token != token::OpenDelim(token::Paren);
5104 let neg_span = self.span;
5105 let polarity = if self.eat(&token::Not) {
5106 ast::ImplPolarity::Negative
5108 ast::ImplPolarity::Positive
5112 let mut ty = self.parse_ty()?;
5114 // Parse traits, if necessary.
5115 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
5116 // New-style trait. Reinterpret the type as a trait.
5118 TyKind::Path(None, ref path) => {
5120 path: (*path).clone(),
5125 self.span_err(ty.span, "not a trait");
5130 if polarity == ast::ImplPolarity::Negative {
5131 // This is a negated type implementation
5132 // `impl !MyType {}`, which is not allowed.
5133 self.span_err(neg_span, "inherent implementation can't be negated");
5138 if opt_trait.is_some() && self.eat(&token::DotDot) {
5139 if generics.is_parameterized() {
5140 self.span_err(impl_span, "default trait implementations are not \
5141 allowed to have generics");
5144 if let ast::Defaultness::Default = defaultness {
5145 self.span_err(impl_span, "`default impl` is not allowed for \
5146 default trait implementations");
5149 self.expect(&token::OpenDelim(token::Brace))?;
5150 self.expect(&token::CloseDelim(token::Brace))?;
5151 Ok((keywords::Invalid.ident(),
5152 ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
5154 if opt_trait.is_some() {
5155 ty = self.parse_ty()?;
5157 generics.where_clause = self.parse_where_clause()?;
5159 self.expect(&token::OpenDelim(token::Brace))?;
5160 let attrs = self.parse_inner_attributes()?;
5162 let mut impl_items = vec![];
5163 while !self.eat(&token::CloseDelim(token::Brace)) {
5164 let mut at_end = false;
5165 match self.parse_impl_item(&mut at_end) {
5166 Ok(item) => impl_items.push(item),
5170 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5176 Ok((keywords::Invalid.ident(),
5177 ItemKind::Impl(unsafety, polarity, defaultness, generics, opt_trait, ty, impl_items),
5182 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<LifetimeDef>> {
5183 if self.eat_keyword(keywords::For) {
5185 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
5187 if !ty_params.is_empty() {
5188 self.span_err(ty_params[0].span,
5189 "only lifetime parameters can be used in this context");
5197 /// Parse struct Foo { ... }
5198 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5199 let class_name = self.parse_ident()?;
5201 let mut generics = self.parse_generics()?;
5203 // There is a special case worth noting here, as reported in issue #17904.
5204 // If we are parsing a tuple struct it is the case that the where clause
5205 // should follow the field list. Like so:
5207 // struct Foo<T>(T) where T: Copy;
5209 // If we are parsing a normal record-style struct it is the case
5210 // that the where clause comes before the body, and after the generics.
5211 // So if we look ahead and see a brace or a where-clause we begin
5212 // parsing a record style struct.
5214 // Otherwise if we look ahead and see a paren we parse a tuple-style
5217 let vdata = if self.token.is_keyword(keywords::Where) {
5218 generics.where_clause = self.parse_where_clause()?;
5219 if self.eat(&token::Semi) {
5220 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5221 VariantData::Unit(ast::DUMMY_NODE_ID)
5223 // If we see: `struct Foo<T> where T: Copy { ... }`
5224 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5226 // No `where` so: `struct Foo<T>;`
5227 } else if self.eat(&token::Semi) {
5228 VariantData::Unit(ast::DUMMY_NODE_ID)
5229 // Record-style struct definition
5230 } else if self.token == token::OpenDelim(token::Brace) {
5231 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5232 // Tuple-style struct definition with optional where-clause.
5233 } else if self.token == token::OpenDelim(token::Paren) {
5234 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5235 generics.where_clause = self.parse_where_clause()?;
5236 self.expect(&token::Semi)?;
5239 let token_str = self.this_token_to_string();
5240 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5241 name, found `{}`", token_str)))
5244 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5247 /// Parse union Foo { ... }
5248 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5249 let class_name = self.parse_ident()?;
5251 let mut generics = self.parse_generics()?;
5253 let vdata = if self.token.is_keyword(keywords::Where) {
5254 generics.where_clause = self.parse_where_clause()?;
5255 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5256 } else if self.token == token::OpenDelim(token::Brace) {
5257 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5259 let token_str = self.this_token_to_string();
5260 return Err(self.fatal(&format!("expected `where` or `{{` after union \
5261 name, found `{}`", token_str)))
5264 Ok((class_name, ItemKind::Union(vdata, generics), None))
5267 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5268 let mut fields = Vec::new();
5269 if self.eat(&token::OpenDelim(token::Brace)) {
5270 while self.token != token::CloseDelim(token::Brace) {
5271 fields.push(self.parse_struct_decl_field().map_err(|e| {
5272 self.recover_stmt();
5273 self.eat(&token::CloseDelim(token::Brace));
5280 let token_str = self.this_token_to_string();
5281 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5289 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5290 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5291 // Unit like structs are handled in parse_item_struct function
5292 let fields = self.parse_unspanned_seq(
5293 &token::OpenDelim(token::Paren),
5294 &token::CloseDelim(token::Paren),
5295 SeqSep::trailing_allowed(token::Comma),
5297 let attrs = p.parse_outer_attributes()?;
5299 let vis = p.parse_visibility(true)?;
5300 let ty = p.parse_ty()?;
5302 span: lo.to(p.span),
5305 id: ast::DUMMY_NODE_ID,
5314 /// Parse a structure field declaration
5315 pub fn parse_single_struct_field(&mut self,
5318 attrs: Vec<Attribute> )
5319 -> PResult<'a, StructField> {
5320 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5325 token::CloseDelim(token::Brace) => {}
5326 token::DocComment(_) => return Err(self.span_fatal_err(self.span,
5327 Error::UselessDocComment)),
5328 _ => return Err(self.span_fatal_help(self.span,
5329 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5330 "struct fields should be separated by commas")),
5335 /// Parse an element of a struct definition
5336 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5337 let attrs = self.parse_outer_attributes()?;
5339 let vis = self.parse_visibility(false)?;
5340 self.parse_single_struct_field(lo, vis, attrs)
5343 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5344 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5345 /// a function definition, it's not a tuple struct field) and the contents within the parens
5346 /// isn't valid, emit a proper diagnostic.
5347 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5348 maybe_whole!(self, NtVis, |x| x);
5350 if self.eat_keyword(keywords::Crate) {
5351 return Ok(Visibility::Crate(self.prev_span, CrateSugar::JustCrate));
5354 if !self.eat_keyword(keywords::Pub) {
5355 return Ok(Visibility::Inherited)
5358 if self.check(&token::OpenDelim(token::Paren)) {
5359 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5360 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5361 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5362 // by the following tokens.
5363 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5366 self.bump(); // `crate`
5367 let vis = Visibility::Crate(self.prev_span, CrateSugar::PubCrate);
5368 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5370 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5373 self.bump(); // `in`
5374 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5375 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5376 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5378 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5379 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5380 t.is_keyword(keywords::SelfValue)) {
5381 // `pub(self)` or `pub(super)`
5383 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5384 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5385 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5387 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5388 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5390 let msg = "incorrect visibility restriction";
5391 let suggestion = r##"some possible visibility restrictions are:
5392 `pub(crate)`: visible only on the current crate
5393 `pub(super)`: visible only in the current module's parent
5394 `pub(in path::to::module)`: visible only on the specified path"##;
5395 let path = self.parse_path(PathStyle::Mod)?;
5396 let path_span = self.prev_span;
5397 let help_msg = format!("make this visible only to module `{}` with `in`", path);
5398 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5399 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5400 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5401 err.emit(); // emit diagnostic, but continue with public visibility
5405 Ok(Visibility::Public)
5408 /// Parse defaultness: DEFAULT or nothing
5409 fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5410 if self.eat_defaultness() {
5411 Ok(Defaultness::Default)
5413 Ok(Defaultness::Final)
5417 /// Given a termination token, parse all of the items in a module
5418 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5419 let mut items = vec![];
5420 while let Some(item) = self.parse_item()? {
5424 if !self.eat(term) {
5425 let token_str = self.this_token_to_string();
5426 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5429 let hi = if self.span == syntax_pos::DUMMY_SP {
5436 inner: inner_lo.to(hi),
5441 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5442 let id = self.parse_ident()?;
5443 self.expect(&token::Colon)?;
5444 let ty = self.parse_ty()?;
5445 self.expect(&token::Eq)?;
5446 let e = self.parse_expr()?;
5447 self.expect(&token::Semi)?;
5448 let item = match m {
5449 Some(m) => ItemKind::Static(ty, m, e),
5450 None => ItemKind::Const(ty, e),
5452 Ok((id, item, None))
5455 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5456 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5457 let (in_cfg, outer_attrs) = {
5458 let mut strip_unconfigured = ::config::StripUnconfigured {
5460 should_test: false, // irrelevant
5461 features: None, // don't perform gated feature checking
5463 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5464 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5467 let id_span = self.span;
5468 let id = self.parse_ident()?;
5469 if self.check(&token::Semi) {
5471 if in_cfg && self.recurse_into_file_modules {
5472 // This mod is in an external file. Let's go get it!
5473 let ModulePathSuccess { path, directory_ownership, warn } =
5474 self.submod_path(id, &outer_attrs, id_span)?;
5475 let (module, mut attrs) =
5476 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5478 let attr = ast::Attribute {
5479 id: attr::mk_attr_id(),
5480 style: ast::AttrStyle::Outer,
5481 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5482 Ident::from_str("warn_directory_ownership")),
5483 tokens: TokenStream::empty(),
5484 is_sugared_doc: false,
5485 span: syntax_pos::DUMMY_SP,
5487 attr::mark_known(&attr);
5490 Ok((id, module, Some(attrs)))
5492 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5493 Ok((id, ItemKind::Mod(placeholder), None))
5496 let old_directory = self.directory.clone();
5497 self.push_directory(id, &outer_attrs);
5499 self.expect(&token::OpenDelim(token::Brace))?;
5500 let mod_inner_lo = self.span;
5501 let attrs = self.parse_inner_attributes()?;
5502 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5504 self.directory = old_directory;
5505 Ok((id, ItemKind::Mod(module), Some(attrs)))
5509 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5510 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5511 self.directory.path.push(&path.as_str());
5512 self.directory.ownership = DirectoryOwnership::Owned;
5514 self.directory.path.push(&id.name.as_str());
5518 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5519 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5522 /// Returns either a path to a module, or .
5523 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5524 let mod_name = id.to_string();
5525 let default_path_str = format!("{}.rs", mod_name);
5526 let secondary_path_str = format!("{}{}mod.rs", mod_name, path::MAIN_SEPARATOR);
5527 let default_path = dir_path.join(&default_path_str);
5528 let secondary_path = dir_path.join(&secondary_path_str);
5529 let default_exists = codemap.file_exists(&default_path);
5530 let secondary_exists = codemap.file_exists(&secondary_path);
5532 let result = match (default_exists, secondary_exists) {
5533 (true, false) => Ok(ModulePathSuccess {
5535 directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5538 (false, true) => Ok(ModulePathSuccess {
5539 path: secondary_path,
5540 directory_ownership: DirectoryOwnership::Owned,
5543 (false, false) => Err(Error::FileNotFoundForModule {
5544 mod_name: mod_name.clone(),
5545 default_path: default_path_str,
5546 secondary_path: secondary_path_str,
5547 dir_path: format!("{}", dir_path.display()),
5549 (true, true) => Err(Error::DuplicatePaths {
5550 mod_name: mod_name.clone(),
5551 default_path: default_path_str,
5552 secondary_path: secondary_path_str,
5558 path_exists: default_exists || secondary_exists,
5563 fn submod_path(&mut self,
5565 outer_attrs: &[ast::Attribute],
5567 -> PResult<'a, ModulePathSuccess> {
5568 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5569 return Ok(ModulePathSuccess {
5570 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5571 Some("mod.rs") => DirectoryOwnership::Owned,
5572 _ => DirectoryOwnership::UnownedViaMod(true),
5579 let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5581 if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5583 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5584 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5585 if paths.path_exists {
5586 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5588 err.span_note(id_sp, &msg);
5591 } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5593 if let Ok(result) = paths.result {
5594 return Ok(ModulePathSuccess { warn: true, ..result });
5597 let mut err = self.diagnostic().struct_span_err(id_sp,
5598 "cannot declare a new module at this location");
5599 if id_sp != syntax_pos::DUMMY_SP {
5600 let src_path = PathBuf::from(self.sess.codemap().span_to_filename(id_sp));
5601 if let Some(stem) = src_path.file_stem() {
5602 let mut dest_path = src_path.clone();
5603 dest_path.set_file_name(stem);
5604 dest_path.push("mod.rs");
5605 err.span_note(id_sp,
5606 &format!("maybe move this module `{}` to its own \
5607 directory via `{}`", src_path.to_string_lossy(),
5608 dest_path.to_string_lossy()));
5611 if paths.path_exists {
5612 err.span_note(id_sp,
5613 &format!("... or maybe `use` the module `{}` instead \
5614 of possibly redeclaring it",
5619 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5623 /// Read a module from a source file.
5624 fn eval_src_mod(&mut self,
5626 directory_ownership: DirectoryOwnership,
5629 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5630 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5631 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5632 let mut err = String::from("circular modules: ");
5633 let len = included_mod_stack.len();
5634 for p in &included_mod_stack[i.. len] {
5635 err.push_str(&p.to_string_lossy());
5636 err.push_str(" -> ");
5638 err.push_str(&path.to_string_lossy());
5639 return Err(self.span_fatal(id_sp, &err[..]));
5641 included_mod_stack.push(path.clone());
5642 drop(included_mod_stack);
5645 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5646 p0.cfg_mods = self.cfg_mods;
5647 let mod_inner_lo = p0.span;
5648 let mod_attrs = p0.parse_inner_attributes()?;
5649 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5650 self.sess.included_mod_stack.borrow_mut().pop();
5651 Ok((ast::ItemKind::Mod(m0), mod_attrs))
5654 /// Parse a function declaration from a foreign module
5655 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5656 -> PResult<'a, ForeignItem> {
5657 self.expect_keyword(keywords::Fn)?;
5659 let (ident, mut generics) = self.parse_fn_header()?;
5660 let decl = self.parse_fn_decl(true)?;
5661 generics.where_clause = self.parse_where_clause()?;
5663 self.expect(&token::Semi)?;
5664 Ok(ast::ForeignItem {
5667 node: ForeignItemKind::Fn(decl, generics),
5668 id: ast::DUMMY_NODE_ID,
5674 /// Parse a static item from a foreign module.
5675 /// Assumes that the `static` keyword is already parsed.
5676 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5677 -> PResult<'a, ForeignItem> {
5678 let mutbl = self.eat_keyword(keywords::Mut);
5679 let ident = self.parse_ident()?;
5680 self.expect(&token::Colon)?;
5681 let ty = self.parse_ty()?;
5683 self.expect(&token::Semi)?;
5687 node: ForeignItemKind::Static(ty, mutbl),
5688 id: ast::DUMMY_NODE_ID,
5694 /// Parse a type from a foreign module
5695 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5696 -> PResult<'a, ForeignItem> {
5697 self.expect_keyword(keywords::Type)?;
5699 let ident = self.parse_ident()?;
5701 self.expect(&token::Semi)?;
5702 Ok(ast::ForeignItem {
5705 node: ForeignItemKind::Ty,
5706 id: ast::DUMMY_NODE_ID,
5712 /// Parse extern crate links
5716 /// extern crate foo;
5717 /// extern crate bar as foo;
5718 fn parse_item_extern_crate(&mut self,
5720 visibility: Visibility,
5721 attrs: Vec<Attribute>)
5722 -> PResult<'a, P<Item>> {
5724 let crate_name = self.parse_ident()?;
5725 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
5726 (Some(crate_name.name), ident)
5730 self.expect(&token::Semi)?;
5732 let prev_span = self.prev_span;
5733 Ok(self.mk_item(lo.to(prev_span),
5735 ItemKind::ExternCrate(maybe_path),
5740 /// Parse `extern` for foreign ABIs
5743 /// `extern` is expected to have been
5744 /// consumed before calling this method
5750 fn parse_item_foreign_mod(&mut self,
5752 opt_abi: Option<abi::Abi>,
5753 visibility: Visibility,
5754 mut attrs: Vec<Attribute>)
5755 -> PResult<'a, P<Item>> {
5756 self.expect(&token::OpenDelim(token::Brace))?;
5758 let abi = opt_abi.unwrap_or(Abi::C);
5760 attrs.extend(self.parse_inner_attributes()?);
5762 let mut foreign_items = vec![];
5763 while let Some(item) = self.parse_foreign_item()? {
5764 foreign_items.push(item);
5766 self.expect(&token::CloseDelim(token::Brace))?;
5768 let prev_span = self.prev_span;
5769 let m = ast::ForeignMod {
5771 items: foreign_items
5773 let invalid = keywords::Invalid.ident();
5774 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
5777 /// Parse type Foo = Bar;
5778 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5779 let ident = self.parse_ident()?;
5780 let mut tps = self.parse_generics()?;
5781 tps.where_clause = self.parse_where_clause()?;
5782 self.expect(&token::Eq)?;
5783 let ty = self.parse_ty()?;
5784 self.expect(&token::Semi)?;
5785 Ok((ident, ItemKind::Ty(ty, tps), None))
5788 /// Parse the part of an "enum" decl following the '{'
5789 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5790 let mut variants = Vec::new();
5791 let mut all_nullary = true;
5792 let mut any_disr = None;
5793 while self.token != token::CloseDelim(token::Brace) {
5794 let variant_attrs = self.parse_outer_attributes()?;
5795 let vlo = self.span;
5798 let mut disr_expr = None;
5799 let ident = self.parse_ident()?;
5800 if self.check(&token::OpenDelim(token::Brace)) {
5801 // Parse a struct variant.
5802 all_nullary = false;
5803 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
5804 ast::DUMMY_NODE_ID);
5805 } else if self.check(&token::OpenDelim(token::Paren)) {
5806 all_nullary = false;
5807 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
5808 ast::DUMMY_NODE_ID);
5809 } else if self.eat(&token::Eq) {
5810 disr_expr = Some(self.parse_expr()?);
5811 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5812 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5814 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5817 let vr = ast::Variant_ {
5819 attrs: variant_attrs,
5823 variants.push(respan(vlo.to(self.prev_span), vr));
5825 if !self.eat(&token::Comma) { break; }
5827 self.expect(&token::CloseDelim(token::Brace))?;
5829 Some(disr_span) if !all_nullary =>
5830 self.span_err(disr_span,
5831 "discriminator values can only be used with a c-like enum"),
5835 Ok(ast::EnumDef { variants: variants })
5838 /// Parse an "enum" declaration
5839 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5840 let id = self.parse_ident()?;
5841 let mut generics = self.parse_generics()?;
5842 generics.where_clause = self.parse_where_clause()?;
5843 self.expect(&token::OpenDelim(token::Brace))?;
5845 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
5846 self.recover_stmt();
5847 self.eat(&token::CloseDelim(token::Brace));
5850 Ok((id, ItemKind::Enum(enum_definition, generics), None))
5853 /// Parses a string as an ABI spec on an extern type or module. Consumes
5854 /// the `extern` keyword, if one is found.
5855 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5857 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5859 self.expect_no_suffix(sp, "ABI spec", suf);
5861 match abi::lookup(&s.as_str()) {
5862 Some(abi) => Ok(Some(abi)),
5864 let prev_span = self.prev_span;
5867 &format!("invalid ABI: expected one of [{}], \
5869 abi::all_names().join(", "),
5880 /// Parse one of the items allowed by the flags.
5881 /// NB: this function no longer parses the items inside an
5883 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5884 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5885 maybe_whole!(self, NtItem, |item| {
5886 let mut item = item.unwrap();
5887 let mut attrs = attrs;
5888 mem::swap(&mut item.attrs, &mut attrs);
5889 item.attrs.extend(attrs);
5895 let visibility = self.parse_visibility(false)?;
5897 if self.eat_keyword(keywords::Use) {
5899 let item_ = ItemKind::Use(self.parse_view_path()?);
5900 self.expect(&token::Semi)?;
5902 let prev_span = self.prev_span;
5903 let invalid = keywords::Invalid.ident();
5904 let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
5905 return Ok(Some(item));
5908 if self.eat_keyword(keywords::Extern) {
5909 if self.eat_keyword(keywords::Crate) {
5910 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
5913 let opt_abi = self.parse_opt_abi()?;
5915 if self.eat_keyword(keywords::Fn) {
5916 // EXTERN FUNCTION ITEM
5917 let fn_span = self.prev_span;
5918 let abi = opt_abi.unwrap_or(Abi::C);
5919 let (ident, item_, extra_attrs) =
5920 self.parse_item_fn(Unsafety::Normal,
5921 respan(fn_span, Constness::NotConst),
5923 let prev_span = self.prev_span;
5924 let item = self.mk_item(lo.to(prev_span),
5928 maybe_append(attrs, extra_attrs));
5929 return Ok(Some(item));
5930 } else if self.check(&token::OpenDelim(token::Brace)) {
5931 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
5937 if self.eat_keyword(keywords::Static) {
5939 let m = if self.eat_keyword(keywords::Mut) {
5942 Mutability::Immutable
5944 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
5945 let prev_span = self.prev_span;
5946 let item = self.mk_item(lo.to(prev_span),
5950 maybe_append(attrs, extra_attrs));
5951 return Ok(Some(item));
5953 if self.eat_keyword(keywords::Const) {
5954 let const_span = self.prev_span;
5955 if self.check_keyword(keywords::Fn)
5956 || (self.check_keyword(keywords::Unsafe)
5957 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5958 // CONST FUNCTION ITEM
5959 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5965 let (ident, item_, extra_attrs) =
5966 self.parse_item_fn(unsafety,
5967 respan(const_span, Constness::Const),
5969 let prev_span = self.prev_span;
5970 let item = self.mk_item(lo.to(prev_span),
5974 maybe_append(attrs, extra_attrs));
5975 return Ok(Some(item));
5979 if self.eat_keyword(keywords::Mut) {
5980 let prev_span = self.prev_span;
5981 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
5982 .help("did you mean to declare a static?")
5985 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
5986 let prev_span = self.prev_span;
5987 let item = self.mk_item(lo.to(prev_span),
5991 maybe_append(attrs, extra_attrs));
5992 return Ok(Some(item));
5994 if self.check_keyword(keywords::Unsafe) &&
5995 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5997 // UNSAFE TRAIT ITEM
5998 self.expect_keyword(keywords::Unsafe)?;
5999 self.expect_keyword(keywords::Trait)?;
6000 let (ident, item_, extra_attrs) =
6001 self.parse_item_trait(ast::Unsafety::Unsafe)?;
6002 let prev_span = self.prev_span;
6003 let item = self.mk_item(lo.to(prev_span),
6007 maybe_append(attrs, extra_attrs));
6008 return Ok(Some(item));
6010 if (self.check_keyword(keywords::Unsafe) &&
6011 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))) ||
6012 (self.check_keyword(keywords::Default) &&
6013 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) &&
6014 self.look_ahead(2, |t| t.is_keyword(keywords::Impl)))
6017 let defaultness = self.parse_defaultness()?;
6018 self.expect_keyword(keywords::Unsafe)?;
6019 self.expect_keyword(keywords::Impl)?;
6022 extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe, defaultness)?;
6023 let prev_span = self.prev_span;
6024 let item = self.mk_item(lo.to(prev_span),
6028 maybe_append(attrs, extra_attrs));
6029 return Ok(Some(item));
6031 if self.check_keyword(keywords::Fn) {
6034 let fn_span = self.prev_span;
6035 let (ident, item_, extra_attrs) =
6036 self.parse_item_fn(Unsafety::Normal,
6037 respan(fn_span, Constness::NotConst),
6039 let prev_span = self.prev_span;
6040 let item = self.mk_item(lo.to(prev_span),
6044 maybe_append(attrs, extra_attrs));
6045 return Ok(Some(item));
6047 if self.check_keyword(keywords::Unsafe)
6048 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
6049 // UNSAFE FUNCTION ITEM
6051 let abi = if self.eat_keyword(keywords::Extern) {
6052 self.parse_opt_abi()?.unwrap_or(Abi::C)
6056 self.expect_keyword(keywords::Fn)?;
6057 let fn_span = self.prev_span;
6058 let (ident, item_, extra_attrs) =
6059 self.parse_item_fn(Unsafety::Unsafe,
6060 respan(fn_span, Constness::NotConst),
6062 let prev_span = self.prev_span;
6063 let item = self.mk_item(lo.to(prev_span),
6067 maybe_append(attrs, extra_attrs));
6068 return Ok(Some(item));
6070 if self.eat_keyword(keywords::Mod) {
6072 let (ident, item_, extra_attrs) =
6073 self.parse_item_mod(&attrs[..])?;
6074 let prev_span = self.prev_span;
6075 let item = self.mk_item(lo.to(prev_span),
6079 maybe_append(attrs, extra_attrs));
6080 return Ok(Some(item));
6082 if self.eat_keyword(keywords::Type) {
6084 let (ident, item_, extra_attrs) = self.parse_item_type()?;
6085 let prev_span = self.prev_span;
6086 let item = self.mk_item(lo.to(prev_span),
6090 maybe_append(attrs, extra_attrs));
6091 return Ok(Some(item));
6093 if self.eat_keyword(keywords::Enum) {
6095 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
6096 let prev_span = self.prev_span;
6097 let item = self.mk_item(lo.to(prev_span),
6101 maybe_append(attrs, extra_attrs));
6102 return Ok(Some(item));
6104 if self.eat_keyword(keywords::Trait) {
6106 let (ident, item_, extra_attrs) =
6107 self.parse_item_trait(ast::Unsafety::Normal)?;
6108 let prev_span = self.prev_span;
6109 let item = self.mk_item(lo.to(prev_span),
6113 maybe_append(attrs, extra_attrs));
6114 return Ok(Some(item));
6116 if (self.check_keyword(keywords::Impl)) ||
6117 (self.check_keyword(keywords::Default) &&
6118 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)))
6121 let defaultness = self.parse_defaultness()?;
6122 self.expect_keyword(keywords::Impl)?;
6125 extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal, defaultness)?;
6126 let prev_span = self.prev_span;
6127 let item = self.mk_item(lo.to(prev_span),
6131 maybe_append(attrs, extra_attrs));
6132 return Ok(Some(item));
6134 if self.eat_keyword(keywords::Struct) {
6136 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6137 let prev_span = self.prev_span;
6138 let item = self.mk_item(lo.to(prev_span),
6142 maybe_append(attrs, extra_attrs));
6143 return Ok(Some(item));
6145 if self.is_union_item() {
6148 let (ident, item_, extra_attrs) = self.parse_item_union()?;
6149 let prev_span = self.prev_span;
6150 let item = self.mk_item(lo.to(prev_span),
6154 maybe_append(attrs, extra_attrs));
6155 return Ok(Some(item));
6157 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
6158 return Ok(Some(macro_def));
6161 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
6164 /// Parse a foreign item.
6165 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
6166 let attrs = self.parse_outer_attributes()?;
6168 let visibility = self.parse_visibility(false)?;
6170 // FOREIGN STATIC ITEM
6171 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
6172 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
6173 if self.token.is_keyword(keywords::Const) {
6175 .struct_span_err(self.span, "extern items cannot be `const`")
6176 .span_suggestion(self.span, "instead try using", "static".to_owned())
6179 self.bump(); // `static` or `const`
6180 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6182 // FOREIGN FUNCTION ITEM
6183 if self.check_keyword(keywords::Fn) {
6184 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6186 // FOREIGN TYPE ITEM
6187 if self.check_keyword(keywords::Type) {
6188 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
6191 // FIXME #5668: this will occur for a macro invocation:
6192 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
6194 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
6200 /// This is the fall-through for parsing items.
6201 fn parse_macro_use_or_failure(
6203 attrs: Vec<Attribute> ,
6204 macros_allowed: bool,
6205 attributes_allowed: bool,
6207 visibility: Visibility
6208 ) -> PResult<'a, Option<P<Item>>> {
6209 if macros_allowed && self.token.is_path_start() {
6210 // MACRO INVOCATION ITEM
6212 let prev_span = self.prev_span;
6213 self.complain_if_pub_macro(&visibility, prev_span);
6215 let mac_lo = self.span;
6218 let pth = self.parse_path(PathStyle::Mod)?;
6219 self.expect(&token::Not)?;
6221 // a 'special' identifier (like what `macro_rules!` uses)
6222 // is optional. We should eventually unify invoc syntax
6224 let id = if self.token.is_ident() {
6227 keywords::Invalid.ident() // no special identifier
6229 // eat a matched-delimiter token tree:
6230 let (delim, tts) = self.expect_delimited_token_tree()?;
6231 if delim != token::Brace {
6232 if !self.eat(&token::Semi) {
6233 self.span_err(self.prev_span,
6234 "macros that expand to items must either \
6235 be surrounded with braces or followed by \
6240 let hi = self.prev_span;
6241 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6242 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6243 return Ok(Some(item));
6246 // FAILURE TO PARSE ITEM
6248 Visibility::Inherited => {}
6250 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
6254 if !attributes_allowed && !attrs.is_empty() {
6255 self.expected_item_err(&attrs);
6260 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
6261 where F: FnOnce(&mut Self) -> PResult<'a, R>
6263 // Record all tokens we parse when parsing this item.
6264 let mut tokens = Vec::new();
6265 match self.token_cursor.frame.last_token {
6266 LastToken::Collecting(_) => {
6267 panic!("cannot collect tokens recursively yet")
6269 LastToken::Was(ref mut last) => tokens.extend(last.take()),
6271 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
6272 let prev = self.token_cursor.stack.len();
6274 let last_token = if self.token_cursor.stack.len() == prev {
6275 &mut self.token_cursor.frame.last_token
6277 &mut self.token_cursor.stack[prev].last_token
6279 let mut tokens = match *last_token {
6280 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
6281 LastToken::Was(_) => panic!("our vector went away?"),
6284 // If we're not at EOF our current token wasn't actually consumed by
6285 // `f`, but it'll still be in our list that we pulled out. In that case
6287 if self.token == token::Eof {
6288 *last_token = LastToken::Was(None);
6290 *last_token = LastToken::Was(tokens.pop());
6293 Ok((ret?, tokens.into_iter().collect()))
6296 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6297 let attrs = self.parse_outer_attributes()?;
6299 let (ret, tokens) = self.collect_tokens(|this| {
6300 this.parse_item_(attrs, true, false)
6303 // Once we've parsed an item and recorded the tokens we got while
6304 // parsing we may want to store `tokens` into the item we're about to
6305 // return. Note, though, that we specifically didn't capture tokens
6306 // related to outer attributes. The `tokens` field here may later be
6307 // used with procedural macros to convert this item back into a token
6308 // stream, but during expansion we may be removing attributes as we go
6311 // If we've got inner attributes then the `tokens` we've got above holds
6312 // these inner attributes. If an inner attribute is expanded we won't
6313 // actually remove it from the token stream, so we'll just keep yielding
6314 // it (bad!). To work around this case for now we just avoid recording
6315 // `tokens` if we detect any inner attributes. This should help keep
6316 // expansion correct, but we should fix this bug one day!
6319 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6320 i.tokens = Some(tokens);
6327 fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> {
6328 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
6329 &token::CloseDelim(token::Brace),
6330 SeqSep::trailing_allowed(token::Comma), |this| {
6332 let ident = if this.eat_keyword(keywords::SelfValue) {
6333 keywords::SelfValue.ident()
6337 let rename = this.parse_rename()?;
6338 let node = ast::PathListItem_ {
6341 id: ast::DUMMY_NODE_ID
6343 Ok(respan(lo.to(this.prev_span), node))
6348 fn is_import_coupler(&mut self) -> bool {
6349 self.check(&token::ModSep) &&
6350 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6351 *t == token::BinOp(token::Star))
6354 /// Matches ViewPath:
6355 /// MOD_SEP? non_global_path
6356 /// MOD_SEP? non_global_path as IDENT
6357 /// MOD_SEP? non_global_path MOD_SEP STAR
6358 /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE
6359 /// MOD_SEP? LBRACE item_seq RBRACE
6360 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
6362 if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) ||
6363 self.is_import_coupler() {
6364 // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`.
6365 self.eat(&token::ModSep);
6366 let prefix = ast::Path {
6367 segments: vec![PathSegment::crate_root(lo)],
6368 span: lo.to(self.span),
6370 let view_path_kind = if self.eat(&token::BinOp(token::Star)) {
6371 ViewPathGlob(prefix)
6373 ViewPathList(prefix, self.parse_path_list_items()?)
6375 Ok(P(respan(lo.to(self.span), view_path_kind)))
6377 let prefix = self.parse_path(PathStyle::Mod)?.default_to_global();
6378 if self.is_import_coupler() {
6379 // `foo::bar::{a, b}` or `foo::bar::*`
6381 if self.check(&token::BinOp(token::Star)) {
6383 Ok(P(respan(lo.to(self.span), ViewPathGlob(prefix))))
6385 let items = self.parse_path_list_items()?;
6386 Ok(P(respan(lo.to(self.span), ViewPathList(prefix, items))))
6389 // `foo::bar` or `foo::bar as baz`
6390 let rename = self.parse_rename()?.
6391 unwrap_or(prefix.segments.last().unwrap().identifier);
6392 Ok(P(respan(lo.to(self.prev_span), ViewPathSimple(rename, prefix))))
6397 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6398 if self.eat_keyword(keywords::As) {
6399 self.parse_ident().map(Some)
6405 /// Parses a source module as a crate. This is the main
6406 /// entry point for the parser.
6407 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6410 attrs: self.parse_inner_attributes()?,
6411 module: self.parse_mod_items(&token::Eof, lo)?,
6412 span: lo.to(self.span),
6416 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6417 let ret = match self.token {
6418 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6419 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6426 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6427 match self.parse_optional_str() {
6428 Some((s, style, suf)) => {
6429 let sp = self.prev_span;
6430 self.expect_no_suffix(sp, "string literal", suf);
6433 _ => Err(self.fatal("expected string literal"))