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, Movability};
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::GenericParam;
25 use ast::{Ident, ImplItem, IsAuto, Item, ItemKind};
26 use ast::{Label, Lifetime, LifetimeDef, Lit, LitKind, UintTy};
28 use ast::MacStmtStyle;
30 use ast::{MutTy, Mutability};
31 use ast::{Pat, PatKind, PathSegment};
32 use ast::{PolyTraitRef, QSelf};
33 use ast::{Stmt, StmtKind};
34 use ast::{VariantData, StructField};
37 use ast::{TraitItem, TraitRef, TraitObjectSyntax};
38 use ast::{Ty, TyKind, TypeBinding, TyParam, TyParamBounds};
39 use ast::{Visibility, WhereClause, CrateSugar};
40 use ast::{UseTree, UseTreeKind};
41 use ast::{BinOpKind, UnOp};
42 use ast::{RangeEnd, RangeSyntax};
44 use codemap::{self, CodeMap, Spanned, respan};
45 use syntax_pos::{self, Span, MultiSpan, BytePos, FileName, DUMMY_SP};
46 use errors::{self, DiagnosticBuilder};
47 use parse::{self, classify, token};
48 use parse::common::SeqSep;
49 use parse::lexer::TokenAndSpan;
50 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
51 use parse::obsolete::ObsoleteSyntax;
52 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
53 use util::parser::{AssocOp, Fixity};
57 use tokenstream::{self, Delimited, ThinTokenStream, TokenTree, TokenStream};
58 use symbol::{Symbol, keywords};
62 use std::collections::HashSet;
64 use std::path::{self, Path, PathBuf};
68 pub struct Restrictions: u8 {
69 const STMT_EXPR = 1 << 0;
70 const NO_STRUCT_LITERAL = 1 << 1;
74 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
76 /// How to parse a path.
77 #[derive(Copy, Clone, PartialEq)]
79 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
80 /// with something else. For example, in expressions `segment < ....` can be interpreted
81 /// as a comparison and `segment ( ....` can be interpreted as a function call.
82 /// In all such contexts the non-path interpretation is preferred by default for practical
83 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
84 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
86 /// In other contexts, notably in types, no ambiguity exists and paths can be written
87 /// without the disambiguator, e.g. `x<y>` - unambiguously a path.
88 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
90 /// A path with generic arguments disallowed, e.g. `foo::bar::Baz`, used in imports,
91 /// visibilities or attributes.
92 /// Technically, this variant is unnecessary and e.g. `Expr` can be used instead
93 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
94 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
95 /// tokens when something goes wrong.
99 #[derive(Clone, Copy, Debug, PartialEq)]
100 pub enum SemiColonMode {
105 #[derive(Clone, Copy, Debug, PartialEq)]
111 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
112 /// dropped into the token stream, which happens while parsing the result of
113 /// macro expansion). Placement of these is not as complex as I feared it would
114 /// be. The important thing is to make sure that lookahead doesn't balk at
115 /// `token::Interpolated` tokens.
116 macro_rules! maybe_whole_expr {
118 if let token::Interpolated(nt) = $p.token.clone() {
120 token::NtExpr(ref e) => {
122 return Ok((*e).clone());
124 token::NtPath(ref path) => {
127 let kind = ExprKind::Path(None, (*path).clone());
128 return Ok($p.mk_expr(span, kind, ThinVec::new()));
130 token::NtBlock(ref block) => {
133 let kind = ExprKind::Block((*block).clone());
134 return Ok($p.mk_expr(span, kind, ThinVec::new()));
142 /// As maybe_whole_expr, but for things other than expressions
143 macro_rules! maybe_whole {
144 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
145 if let token::Interpolated(nt) = $p.token.clone() {
146 if let token::$constructor($x) = nt.0.clone() {
154 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
155 if let Some(ref mut rhs) = rhs {
161 #[derive(Debug, Clone, Copy, PartialEq)]
172 trait RecoverQPath: Sized {
173 const PATH_STYLE: PathStyle = PathStyle::Expr;
174 fn to_ty(&self) -> Option<P<Ty>>;
175 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self;
176 fn to_string(&self) -> String;
179 impl RecoverQPath for Ty {
180 const PATH_STYLE: PathStyle = PathStyle::Type;
181 fn to_ty(&self) -> Option<P<Ty>> {
182 Some(P(self.clone()))
184 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
185 Self { span: path.span, node: TyKind::Path(qself, path), id: self.id }
187 fn to_string(&self) -> String {
188 pprust::ty_to_string(self)
192 impl RecoverQPath for Pat {
193 fn to_ty(&self) -> Option<P<Ty>> {
196 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
197 Self { span: path.span, node: PatKind::Path(qself, path), id: self.id }
199 fn to_string(&self) -> String {
200 pprust::pat_to_string(self)
204 impl RecoverQPath for Expr {
205 fn to_ty(&self) -> Option<P<Ty>> {
208 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
209 Self { span: path.span, node: ExprKind::Path(qself, path),
210 id: self.id, attrs: self.attrs.clone() }
212 fn to_string(&self) -> String {
213 pprust::expr_to_string(self)
217 /* ident is handled by common.rs */
220 pub struct Parser<'a> {
221 pub sess: &'a ParseSess,
222 /// the current token:
223 pub token: token::Token,
224 /// the span of the current token:
226 /// the span of the previous token:
227 pub meta_var_span: Option<Span>,
229 /// the previous token kind
230 prev_token_kind: PrevTokenKind,
231 pub restrictions: Restrictions,
232 /// The set of seen errors about obsolete syntax. Used to suppress
233 /// extra detail when the same error is seen twice
234 pub obsolete_set: HashSet<ObsoleteSyntax>,
235 /// Used to determine the path to externally loaded source files
236 pub directory: Directory,
237 /// Whether to parse sub-modules in other files.
238 pub recurse_into_file_modules: bool,
239 /// Name of the root module this parser originated from. If `None`, then the
240 /// name is not known. This does not change while the parser is descending
241 /// into modules, and sub-parsers have new values for this name.
242 pub root_module_name: Option<String>,
243 pub expected_tokens: Vec<TokenType>,
244 token_cursor: TokenCursor,
245 pub desugar_doc_comments: bool,
246 /// Whether we should configure out of line modules as we parse.
253 frame: TokenCursorFrame,
254 stack: Vec<TokenCursorFrame>,
258 struct TokenCursorFrame {
259 delim: token::DelimToken,
262 tree_cursor: tokenstream::Cursor,
264 last_token: LastToken,
267 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
268 /// by the parser, and then that's transitively used to record the tokens that
269 /// each parse AST item is created with.
271 /// Right now this has two states, either collecting tokens or not collecting
272 /// tokens. If we're collecting tokens we just save everything off into a local
273 /// `Vec`. This should eventually though likely save tokens from the original
274 /// token stream and just use slicing of token streams to avoid creation of a
275 /// whole new vector.
277 /// The second state is where we're passively not recording tokens, but the last
278 /// token is still tracked for when we want to start recording tokens. This
279 /// "last token" means that when we start recording tokens we'll want to ensure
280 /// that this, the first token, is included in the output.
282 /// You can find some more example usage of this in the `collect_tokens` method
286 Collecting(Vec<TokenTree>),
287 Was(Option<TokenTree>),
290 impl TokenCursorFrame {
291 fn new(sp: Span, delimited: &Delimited) -> Self {
293 delim: delimited.delim,
295 open_delim: delimited.delim == token::NoDelim,
296 tree_cursor: delimited.stream().into_trees(),
297 close_delim: delimited.delim == token::NoDelim,
298 last_token: LastToken::Was(None),
304 fn next(&mut self) -> TokenAndSpan {
306 let tree = if !self.frame.open_delim {
307 self.frame.open_delim = true;
308 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
309 .open_tt(self.frame.span)
310 } else if let Some(tree) = self.frame.tree_cursor.next() {
312 } else if !self.frame.close_delim {
313 self.frame.close_delim = true;
314 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
315 .close_tt(self.frame.span)
316 } else if let Some(frame) = self.stack.pop() {
320 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
323 match self.frame.last_token {
324 LastToken::Collecting(ref mut v) => v.push(tree.clone()),
325 LastToken::Was(ref mut t) => *t = Some(tree.clone()),
329 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
330 TokenTree::Delimited(sp, ref delimited) => {
331 let frame = TokenCursorFrame::new(sp, delimited);
332 self.stack.push(mem::replace(&mut self.frame, frame));
338 fn next_desugared(&mut self) -> TokenAndSpan {
339 let (sp, name) = match self.next() {
340 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
344 let stripped = strip_doc_comment_decoration(&name.as_str());
346 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
347 // required to wrap the text.
348 let mut num_of_hashes = 0;
350 for ch in stripped.chars() {
353 '#' if count > 0 => count + 1,
356 num_of_hashes = cmp::max(num_of_hashes, count);
359 let body = TokenTree::Delimited(sp, Delimited {
360 delim: token::Bracket,
361 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"))),
362 TokenTree::Token(sp, token::Eq),
363 TokenTree::Token(sp, token::Literal(
364 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
365 .iter().cloned().collect::<TokenStream>().into(),
368 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
369 delim: token::NoDelim,
370 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
371 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
372 .iter().cloned().collect::<TokenStream>().into()
374 [TokenTree::Token(sp, token::Pound), body]
375 .iter().cloned().collect::<TokenStream>().into()
383 #[derive(PartialEq, Eq, Clone)]
386 Keyword(keywords::Keyword),
395 fn to_string(&self) -> String {
397 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
398 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
399 TokenType::Operator => "an operator".to_string(),
400 TokenType::Lifetime => "lifetime".to_string(),
401 TokenType::Ident => "identifier".to_string(),
402 TokenType::Path => "path".to_string(),
403 TokenType::Type => "type".to_string(),
408 // Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
409 // `IDENT<<u8 as Trait>::AssocTy>`, `IDENT(u8, u8) -> u8`.
410 fn can_continue_type_after_ident(t: &token::Token) -> bool {
411 t == &token::ModSep || t == &token::Lt ||
412 t == &token::BinOp(token::Shl) || t == &token::OpenDelim(token::Paren)
415 /// Information about the path to a module.
416 pub struct ModulePath {
418 pub path_exists: bool,
419 pub result: Result<ModulePathSuccess, Error>,
422 pub struct ModulePathSuccess {
424 pub directory_ownership: DirectoryOwnership,
428 pub struct ModulePathError {
430 pub help_msg: String,
434 FileNotFoundForModule {
436 default_path: String,
437 secondary_path: String,
442 default_path: String,
443 secondary_path: String,
446 InclusiveRangeWithNoEnd,
450 pub fn span_err<S: Into<MultiSpan>>(self,
452 handler: &errors::Handler) -> DiagnosticBuilder {
454 Error::FileNotFoundForModule { ref mod_name,
458 let mut err = struct_span_err!(handler, sp, E0583,
459 "file not found for module `{}`", mod_name);
460 err.help(&format!("name the file either {} or {} inside the directory {:?}",
466 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
467 let mut err = struct_span_err!(handler, sp, E0584,
468 "file for module `{}` found at both {} and {}",
472 err.help("delete or rename one of them to remove the ambiguity");
475 Error::UselessDocComment => {
476 let mut err = struct_span_err!(handler, sp, E0585,
477 "found a documentation comment that doesn't document anything");
478 err.help("doc comments must come before what they document, maybe a comment was \
479 intended with `//`?");
482 Error::InclusiveRangeWithNoEnd => {
483 let mut err = struct_span_err!(handler, sp, E0586,
484 "inclusive range with no end");
485 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
495 AttributesParsed(ThinVec<Attribute>),
496 AlreadyParsed(P<Expr>),
499 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
500 fn from(o: Option<ThinVec<Attribute>>) -> Self {
501 if let Some(attrs) = o {
502 LhsExpr::AttributesParsed(attrs)
504 LhsExpr::NotYetParsed
509 impl From<P<Expr>> for LhsExpr {
510 fn from(expr: P<Expr>) -> Self {
511 LhsExpr::AlreadyParsed(expr)
515 /// Create a placeholder argument.
516 fn dummy_arg(span: Span) -> Arg {
517 let spanned = Spanned {
519 node: keywords::Invalid.ident()
522 id: ast::DUMMY_NODE_ID,
523 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), spanned, None),
529 id: ast::DUMMY_NODE_ID
531 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
534 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
535 enum TokenExpectType {
540 impl<'a> Parser<'a> {
541 pub fn new(sess: &'a ParseSess,
543 directory: Option<Directory>,
544 recurse_into_file_modules: bool,
545 desugar_doc_comments: bool)
547 let mut parser = Parser {
549 token: token::Underscore,
550 span: syntax_pos::DUMMY_SP,
551 prev_span: syntax_pos::DUMMY_SP,
553 prev_token_kind: PrevTokenKind::Other,
554 restrictions: Restrictions::empty(),
555 obsolete_set: HashSet::new(),
556 recurse_into_file_modules,
557 directory: Directory {
558 path: PathBuf::new(),
559 ownership: DirectoryOwnership::Owned { relative: None }
561 root_module_name: None,
562 expected_tokens: Vec::new(),
563 token_cursor: TokenCursor {
564 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
565 delim: token::NoDelim,
570 desugar_doc_comments,
574 let tok = parser.next_tok();
575 parser.token = tok.tok;
576 parser.span = tok.sp;
578 if let Some(directory) = directory {
579 parser.directory = directory;
580 } else if !parser.span.source_equal(&DUMMY_SP) {
581 if let FileName::Real(path) = sess.codemap().span_to_unmapped_path(parser.span) {
582 parser.directory.path = path;
583 parser.directory.path.pop();
587 parser.process_potential_macro_variable();
591 fn next_tok(&mut self) -> TokenAndSpan {
592 let mut next = if self.desugar_doc_comments {
593 self.token_cursor.next_desugared()
595 self.token_cursor.next()
597 if next.sp == syntax_pos::DUMMY_SP {
598 next.sp = self.prev_span;
603 /// Convert a token to a string using self's reader
604 pub fn token_to_string(token: &token::Token) -> String {
605 pprust::token_to_string(token)
608 /// Convert the current token to a string using self's reader
609 pub fn this_token_to_string(&self) -> String {
610 Parser::token_to_string(&self.token)
613 pub fn token_descr(&self) -> Option<&'static str> {
614 Some(match &self.token {
615 t if t.is_special_ident() => "reserved identifier",
616 t if t.is_used_keyword() => "keyword",
617 t if t.is_unused_keyword() => "reserved keyword",
622 pub fn this_token_descr(&self) -> String {
623 if let Some(prefix) = self.token_descr() {
624 format!("{} `{}`", prefix, self.this_token_to_string())
626 format!("`{}`", self.this_token_to_string())
630 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
631 let token_str = Parser::token_to_string(t);
632 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
635 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
636 match self.expect_one_of(&[], &[]) {
638 Ok(_) => unreachable!(),
642 /// Expect and consume the token t. Signal an error if
643 /// the next token is not t.
644 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
645 if self.expected_tokens.is_empty() {
646 if self.token == *t {
650 let token_str = Parser::token_to_string(t);
651 let this_token_str = self.this_token_to_string();
652 Err(self.fatal(&format!("expected `{}`, found `{}`",
657 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
661 /// Expect next token to be edible or inedible token. If edible,
662 /// then consume it; if inedible, then return without consuming
663 /// anything. Signal a fatal error if next token is unexpected.
664 pub fn expect_one_of(&mut self,
665 edible: &[token::Token],
666 inedible: &[token::Token]) -> PResult<'a, ()>{
667 fn tokens_to_string(tokens: &[TokenType]) -> String {
668 let mut i = tokens.iter();
669 // This might be a sign we need a connect method on Iterator.
671 .map_or("".to_string(), |t| t.to_string());
672 i.enumerate().fold(b, |mut b, (i, a)| {
673 if tokens.len() > 2 && i == tokens.len() - 2 {
675 } else if tokens.len() == 2 && i == tokens.len() - 2 {
680 b.push_str(&a.to_string());
684 if edible.contains(&self.token) {
687 } else if inedible.contains(&self.token) {
688 // leave it in the input
691 let mut expected = edible.iter()
692 .map(|x| TokenType::Token(x.clone()))
693 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
694 .chain(self.expected_tokens.iter().cloned())
695 .collect::<Vec<_>>();
696 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
698 let expect = tokens_to_string(&expected[..]);
699 let actual = self.this_token_to_string();
700 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
701 let short_expect = if expected.len() > 6 {
702 format!("{} possible tokens", expected.len())
706 (format!("expected one of {}, found `{}`", expect, actual),
707 (self.sess.codemap().next_point(self.prev_span),
708 format!("expected one of {} here", short_expect)))
709 } else if expected.is_empty() {
710 (format!("unexpected token: `{}`", actual),
711 (self.prev_span, "unexpected token after this".to_string()))
713 (format!("expected {}, found `{}`", expect, actual),
714 (self.sess.codemap().next_point(self.prev_span),
715 format!("expected {} here", expect)))
717 let mut err = self.fatal(&msg_exp);
718 let sp = if self.token == token::Token::Eof {
719 // This is EOF, don't want to point at the following char, but rather the last token
725 let cm = self.sess.codemap();
726 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
727 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
728 // When the spans are in the same line, it means that the only content between
729 // them is whitespace, point at the found token in that case:
731 // X | () => { syntax error };
732 // | ^^^^^ expected one of 8 possible tokens here
734 // instead of having:
736 // X | () => { syntax error };
737 // | -^^^^^ unexpected token
739 // | expected one of 8 possible tokens here
740 err.span_label(self.span, label_exp);
743 err.span_label(sp, label_exp);
744 err.span_label(self.span, "unexpected token");
751 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
752 fn interpolated_or_expr_span(&self,
753 expr: PResult<'a, P<Expr>>)
754 -> PResult<'a, (Span, P<Expr>)> {
756 if self.prev_token_kind == PrevTokenKind::Interpolated {
764 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
765 let mut err = self.struct_span_err(self.span,
766 &format!("expected identifier, found {}",
767 self.this_token_descr()));
768 if let Some(token_descr) = self.token_descr() {
769 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
771 err.span_label(self.span, "expected identifier");
776 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
777 self.parse_ident_common(true)
780 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
783 if self.token.is_reserved_ident() {
784 let mut err = self.expected_ident_found();
795 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
796 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
798 let mut err = self.expected_ident_found();
799 if self.token == token::Underscore {
800 err.note("`_` is a wildcard pattern, not an identifier");
808 /// Check if the next token is `tok`, and return `true` if so.
810 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
812 pub fn check(&mut self, tok: &token::Token) -> bool {
813 let is_present = self.token == *tok;
814 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
818 /// Consume token 'tok' if it exists. Returns true if the given
819 /// token was present, false otherwise.
820 pub fn eat(&mut self, tok: &token::Token) -> bool {
821 let is_present = self.check(tok);
822 if is_present { self.bump() }
826 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
827 self.expected_tokens.push(TokenType::Keyword(kw));
828 self.token.is_keyword(kw)
831 /// If the next token is the given keyword, eat it and return
832 /// true. Otherwise, return false.
833 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
834 if self.check_keyword(kw) {
842 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
843 if self.token.is_keyword(kw) {
851 /// If the given word is not a keyword, signal an error.
852 /// If the next token is not the given word, signal an error.
853 /// Otherwise, eat it.
854 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
855 if !self.eat_keyword(kw) {
862 fn check_ident(&mut self) -> bool {
863 if self.token.is_ident() {
866 self.expected_tokens.push(TokenType::Ident);
871 fn check_path(&mut self) -> bool {
872 if self.token.is_path_start() {
875 self.expected_tokens.push(TokenType::Path);
880 fn check_type(&mut self) -> bool {
881 if self.token.can_begin_type() {
884 self.expected_tokens.push(TokenType::Type);
889 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
890 /// `&` and continue. If an `&` is not seen, signal an error.
891 fn expect_and(&mut self) -> PResult<'a, ()> {
892 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
894 token::BinOp(token::And) => {
899 let span = self.span.with_lo(self.span.lo() + BytePos(1));
900 Ok(self.bump_with(token::BinOp(token::And), span))
902 _ => self.unexpected()
906 /// Expect and consume an `|`. If `||` is seen, replace it with a single
907 /// `|` and continue. If an `|` is not seen, signal an error.
908 fn expect_or(&mut self) -> PResult<'a, ()> {
909 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
911 token::BinOp(token::Or) => {
916 let span = self.span.with_lo(self.span.lo() + BytePos(1));
917 Ok(self.bump_with(token::BinOp(token::Or), span))
919 _ => self.unexpected()
923 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
925 None => {/* everything ok */}
927 let text = suf.as_str();
929 self.span_bug(sp, "found empty literal suffix in Some")
931 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
936 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
937 /// `<` and continue. If a `<` is not seen, return false.
939 /// This is meant to be used when parsing generics on a path to get the
941 fn eat_lt(&mut self) -> bool {
942 self.expected_tokens.push(TokenType::Token(token::Lt));
948 token::BinOp(token::Shl) => {
949 let span = self.span.with_lo(self.span.lo() + BytePos(1));
950 self.bump_with(token::Lt, span);
957 fn expect_lt(&mut self) -> PResult<'a, ()> {
965 /// Expect and consume a GT. if a >> is seen, replace it
966 /// with a single > and continue. If a GT is not seen,
968 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
969 self.expected_tokens.push(TokenType::Token(token::Gt));
975 token::BinOp(token::Shr) => {
976 let span = self.span.with_lo(self.span.lo() + BytePos(1));
977 Ok(self.bump_with(token::Gt, span))
979 token::BinOpEq(token::Shr) => {
980 let span = self.span.with_lo(self.span.lo() + BytePos(1));
981 Ok(self.bump_with(token::Ge, span))
984 let span = self.span.with_lo(self.span.lo() + BytePos(1));
985 Ok(self.bump_with(token::Eq, span))
987 _ => self.unexpected()
991 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
992 sep: Option<token::Token>,
994 -> PResult<'a, (Vec<T>, bool)>
995 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
997 let mut v = Vec::new();
998 // This loop works by alternating back and forth between parsing types
999 // and commas. For example, given a string `A, B,>`, the parser would
1000 // first parse `A`, then a comma, then `B`, then a comma. After that it
1001 // would encounter a `>` and stop. This lets the parser handle trailing
1002 // commas in generic parameters, because it can stop either after
1003 // parsing a type or after parsing a comma.
1005 if self.check(&token::Gt)
1006 || self.token == token::BinOp(token::Shr)
1007 || self.token == token::Ge
1008 || self.token == token::BinOpEq(token::Shr) {
1014 Some(result) => v.push(result),
1015 None => return Ok((v, true))
1018 if let Some(t) = sep.as_ref() {
1024 return Ok((v, false));
1027 /// Parse a sequence bracketed by '<' and '>', stopping
1029 pub fn parse_seq_to_before_gt<T, F>(&mut self,
1030 sep: Option<token::Token>,
1032 -> PResult<'a, Vec<T>> where
1033 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1035 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
1036 |p| Ok(Some(f(p)?)))?;
1041 pub fn parse_seq_to_gt<T, F>(&mut self,
1042 sep: Option<token::Token>,
1044 -> PResult<'a, Vec<T>> where
1045 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1047 let v = self.parse_seq_to_before_gt(sep, f)?;
1052 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
1053 sep: Option<token::Token>,
1055 -> PResult<'a, (Vec<T>, bool)> where
1056 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
1058 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
1062 return Ok((v, returned));
1065 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1066 /// passes through any errors encountered. Used for error recovery.
1067 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1068 let handler = self.diagnostic();
1070 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1072 TokenExpectType::Expect,
1073 |p| Ok(p.parse_token_tree())) {
1074 handler.cancel(err);
1078 /// Parse a sequence, including the closing delimiter. The function
1079 /// f must consume tokens until reaching the next separator or
1080 /// closing bracket.
1081 pub fn parse_seq_to_end<T, F>(&mut self,
1085 -> PResult<'a, Vec<T>> where
1086 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1088 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1093 /// Parse a sequence, not including the closing delimiter. The function
1094 /// f must consume tokens until reaching the next separator or
1095 /// closing bracket.
1096 pub fn parse_seq_to_before_end<T, F>(&mut self,
1100 -> PResult<'a, Vec<T>>
1101 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1103 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1106 fn parse_seq_to_before_tokens<T, F>(&mut self,
1107 kets: &[&token::Token],
1109 expect: TokenExpectType,
1111 -> PResult<'a, Vec<T>>
1112 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1114 let mut first: bool = true;
1116 while !kets.contains(&&self.token) {
1118 token::CloseDelim(..) | token::Eof => break,
1121 if let Some(ref t) = sep.sep {
1125 if let Err(mut e) = self.expect(t) {
1126 // Attempt to keep parsing if it was a similar separator
1127 if let Some(ref tokens) = t.similar_tokens() {
1128 if tokens.contains(&self.token) {
1133 // Attempt to keep parsing if it was an omitted separator
1147 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1149 TokenExpectType::Expect => self.check(k),
1150 TokenExpectType::NoExpect => self.token == **k,
1163 /// Parse a sequence, including the closing delimiter. The function
1164 /// f must consume tokens until reaching the next separator or
1165 /// closing bracket.
1166 pub fn parse_unspanned_seq<T, F>(&mut self,
1171 -> PResult<'a, Vec<T>> where
1172 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1175 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1176 if self.token == *ket {
1182 // NB: Do not use this function unless you actually plan to place the
1183 // spanned list in the AST.
1184 pub fn parse_seq<T, F>(&mut self,
1189 -> PResult<'a, Spanned<Vec<T>>> where
1190 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1194 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1197 Ok(respan(lo.to(hi), result))
1200 /// Advance the parser by one token
1201 pub fn bump(&mut self) {
1202 if self.prev_token_kind == PrevTokenKind::Eof {
1203 // Bumping after EOF is a bad sign, usually an infinite loop.
1204 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1207 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1209 // Record last token kind for possible error recovery.
1210 self.prev_token_kind = match self.token {
1211 token::DocComment(..) => PrevTokenKind::DocComment,
1212 token::Comma => PrevTokenKind::Comma,
1213 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1214 token::Interpolated(..) => PrevTokenKind::Interpolated,
1215 token::Eof => PrevTokenKind::Eof,
1216 token::Ident(..) => PrevTokenKind::Ident,
1217 _ => PrevTokenKind::Other,
1220 let next = self.next_tok();
1221 self.span = next.sp;
1222 self.token = next.tok;
1223 self.expected_tokens.clear();
1224 // check after each token
1225 self.process_potential_macro_variable();
1228 /// Advance the parser using provided token as a next one. Use this when
1229 /// consuming a part of a token. For example a single `<` from `<<`.
1230 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1231 self.prev_span = self.span.with_hi(span.lo());
1232 // It would be incorrect to record the kind of the current token, but
1233 // fortunately for tokens currently using `bump_with`, the
1234 // prev_token_kind will be of no use anyway.
1235 self.prev_token_kind = PrevTokenKind::Other;
1238 self.expected_tokens.clear();
1241 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1242 F: FnOnce(&token::Token) -> R,
1245 return f(&self.token)
1248 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1249 Some(tree) => match tree {
1250 TokenTree::Token(_, tok) => tok,
1251 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1253 None => token::CloseDelim(self.token_cursor.frame.delim),
1257 fn look_ahead_span(&self, dist: usize) -> Span {
1262 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1263 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1264 None => self.look_ahead_span(dist - 1),
1267 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1268 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1270 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1271 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1273 pub fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1274 err.span_err(sp, self.diagnostic())
1276 pub fn span_fatal_help<S: Into<MultiSpan>>(&self,
1279 help: &str) -> DiagnosticBuilder<'a> {
1280 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1284 pub fn bug(&self, m: &str) -> ! {
1285 self.sess.span_diagnostic.span_bug(self.span, m)
1287 pub fn warn(&self, m: &str) {
1288 self.sess.span_diagnostic.span_warn(self.span, m)
1290 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1291 self.sess.span_diagnostic.span_warn(sp, m)
1293 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1294 self.sess.span_diagnostic.span_err(sp, m)
1296 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1297 self.sess.span_diagnostic.struct_span_err(sp, m)
1299 pub fn span_err_help<S: Into<MultiSpan>>(&self, sp: S, m: &str, h: &str) {
1300 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1304 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1305 self.sess.span_diagnostic.span_bug(sp, m)
1307 pub fn abort_if_errors(&self) {
1308 self.sess.span_diagnostic.abort_if_errors();
1311 fn cancel(&self, err: &mut DiagnosticBuilder) {
1312 self.sess.span_diagnostic.cancel(err)
1315 pub fn diagnostic(&self) -> &'a errors::Handler {
1316 &self.sess.span_diagnostic
1319 /// Is the current token one of the keywords that signals a bare function
1321 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1322 self.check_keyword(keywords::Fn) ||
1323 self.check_keyword(keywords::Unsafe) ||
1324 self.check_keyword(keywords::Extern)
1327 fn eat_label(&mut self) -> Option<Label> {
1328 let ident = match self.token {
1329 token::Lifetime(ref ident) => *ident,
1330 token::Interpolated(ref nt) => match nt.0 {
1331 token::NtLifetime(lifetime) => lifetime.ident,
1337 Some(Label { ident, span: self.prev_span })
1340 /// parse a TyKind::BareFn type:
1341 pub fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>)
1342 -> PResult<'a, TyKind> {
1345 [unsafe] [extern "ABI"] fn (S) -> T
1355 let unsafety = self.parse_unsafety();
1356 let abi = if self.eat_keyword(keywords::Extern) {
1357 self.parse_opt_abi()?.unwrap_or(Abi::C)
1362 self.expect_keyword(keywords::Fn)?;
1363 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1364 let ret_ty = self.parse_ret_ty(false)?;
1365 let decl = P(FnDecl {
1370 Ok(TyKind::BareFn(P(BareFnTy {
1378 /// Parse unsafety: `unsafe` or nothing.
1379 fn parse_unsafety(&mut self) -> Unsafety {
1380 if self.eat_keyword(keywords::Unsafe) {
1387 /// Parse the items in a trait declaration
1388 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1389 maybe_whole!(self, NtTraitItem, |x| x);
1390 let attrs = self.parse_outer_attributes()?;
1391 let (mut item, tokens) = self.collect_tokens(|this| {
1392 this.parse_trait_item_(at_end, attrs)
1394 // See `parse_item` for why this clause is here.
1395 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1396 item.tokens = Some(tokens);
1401 fn parse_trait_item_(&mut self,
1403 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1406 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1407 let (generics, TyParam {ident, bounds, default, ..}) =
1408 self.parse_trait_item_assoc_ty(vec![])?;
1409 (ident, TraitItemKind::Type(bounds, default), generics)
1410 } else if self.is_const_item() {
1411 self.expect_keyword(keywords::Const)?;
1412 let ident = self.parse_ident()?;
1413 self.expect(&token::Colon)?;
1414 let ty = self.parse_ty()?;
1415 let default = if self.check(&token::Eq) {
1417 let expr = self.parse_expr()?;
1418 self.expect(&token::Semi)?;
1421 self.expect(&token::Semi)?;
1424 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1425 } else if self.token.is_path_start() && !self.is_extern_non_path() {
1426 // trait item macro.
1427 // code copied from parse_macro_use_or_failure... abstraction!
1428 let prev_span = self.prev_span;
1430 let pth = self.parse_path(PathStyle::Mod)?;
1432 if pth.segments.len() == 1 {
1433 if !self.eat(&token::Not) {
1434 return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1437 self.expect(&token::Not)?;
1440 // eat a matched-delimiter token tree:
1441 let (delim, tts) = self.expect_delimited_token_tree()?;
1442 if delim != token::Brace {
1443 self.expect(&token::Semi)?
1446 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1447 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1449 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
1451 let ident = self.parse_ident()?;
1452 let mut generics = self.parse_generics()?;
1454 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1455 // This is somewhat dubious; We don't want to allow
1456 // argument names to be left off if there is a
1458 p.parse_arg_general(false)
1460 generics.where_clause = self.parse_where_clause()?;
1462 let sig = ast::MethodSig {
1469 let body = match self.token {
1473 debug!("parse_trait_methods(): parsing required method");
1476 token::OpenDelim(token::Brace) => {
1477 debug!("parse_trait_methods(): parsing provided method");
1479 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1480 attrs.extend(inner_attrs.iter().cloned());
1484 let token_str = self.this_token_to_string();
1485 return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1488 (ident, ast::TraitItemKind::Method(sig, body), generics)
1492 id: ast::DUMMY_NODE_ID,
1497 span: lo.to(self.prev_span),
1502 /// Parse optional return type [ -> TY ] in function decl
1503 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1504 if self.eat(&token::RArrow) {
1505 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1507 Ok(FunctionRetTy::Default(self.span.with_hi(self.span.lo())))
1512 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1513 self.parse_ty_common(true, true)
1516 /// Parse a type in restricted contexts where `+` is not permitted.
1517 /// Example 1: `&'a TYPE`
1518 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1519 /// Example 2: `value1 as TYPE + value2`
1520 /// `+` is prohibited to avoid interactions with expression grammar.
1521 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1522 self.parse_ty_common(false, true)
1525 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1526 -> PResult<'a, P<Ty>> {
1527 maybe_whole!(self, NtTy, |x| x);
1530 let mut impl_dyn_multi = false;
1531 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1532 // `(TYPE)` is a parenthesized type.
1533 // `(TYPE,)` is a tuple with a single field of type TYPE.
1534 let mut ts = vec![];
1535 let mut last_comma = false;
1536 while self.token != token::CloseDelim(token::Paren) {
1537 ts.push(self.parse_ty()?);
1538 if self.eat(&token::Comma) {
1545 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1546 self.expect(&token::CloseDelim(token::Paren))?;
1548 if ts.len() == 1 && !last_comma {
1549 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1550 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1552 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1553 TyKind::Path(None, ref path) if maybe_bounds => {
1554 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1556 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1557 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1558 let path = match bounds[0] {
1559 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1560 _ => self.bug("unexpected lifetime bound"),
1562 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1565 _ => TyKind::Paren(P(ty))
1570 } else if self.eat(&token::Not) {
1573 } else if self.eat(&token::BinOp(token::Star)) {
1575 TyKind::Ptr(self.parse_ptr()?)
1576 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1578 let t = self.parse_ty()?;
1579 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1580 let t = match self.maybe_parse_fixed_length_of_vec()? {
1581 None => TyKind::Slice(t),
1582 Some(suffix) => TyKind::Array(t, suffix),
1584 self.expect(&token::CloseDelim(token::Bracket))?;
1586 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1589 self.parse_borrowed_pointee()?
1590 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1592 // In order to not be ambiguous, the type must be surrounded by parens.
1593 self.expect(&token::OpenDelim(token::Paren))?;
1594 let e = self.parse_expr()?;
1595 self.expect(&token::CloseDelim(token::Paren))?;
1597 } else if self.eat(&token::Underscore) {
1598 // A type to be inferred `_`
1600 } else if self.token_is_bare_fn_keyword() {
1601 // Function pointer type
1602 self.parse_ty_bare_fn(Vec::new())?
1603 } else if self.check_keyword(keywords::For) {
1604 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1605 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1606 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1608 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1609 if self.token_is_bare_fn_keyword() {
1610 self.parse_ty_bare_fn(lifetime_defs)?
1612 let path = self.parse_path(PathStyle::Type)?;
1613 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1614 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1616 } else if self.eat_keyword(keywords::Impl) {
1617 // Always parse bounds greedily for better error recovery.
1618 let bounds = self.parse_ty_param_bounds()?;
1619 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1620 TyKind::ImplTrait(bounds)
1621 } else if self.check_keyword(keywords::Dyn) &&
1622 self.look_ahead(1, |t| t.can_begin_bound() && !can_continue_type_after_ident(t)) {
1623 self.bump(); // `dyn`
1624 // Always parse bounds greedily for better error recovery.
1625 let bounds = self.parse_ty_param_bounds()?;
1626 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1627 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1628 } else if self.check(&token::Question) ||
1629 self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)) {
1630 // Bound list (trait object type)
1631 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?,
1632 TraitObjectSyntax::None)
1633 } else if self.eat_lt() {
1635 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1636 TyKind::Path(Some(qself), path)
1637 } else if self.token.is_path_start() {
1639 let path = self.parse_path(PathStyle::Type)?;
1640 if self.eat(&token::Not) {
1641 // Macro invocation in type position
1642 let (_, tts) = self.expect_delimited_token_tree()?;
1643 TyKind::Mac(respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts }))
1645 // Just a type path or bound list (trait object type) starting with a trait.
1647 // `Trait1 + Trait2 + 'a`
1648 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1649 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1651 TyKind::Path(None, path)
1655 let msg = format!("expected type, found {}", self.this_token_descr());
1656 return Err(self.fatal(&msg));
1659 let span = lo.to(self.prev_span);
1660 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1662 // Try to recover from use of `+` with incorrect priority.
1663 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1664 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1665 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1670 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1671 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1672 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1673 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1676 bounds.append(&mut self.parse_ty_param_bounds()?);
1678 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1681 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1682 if !allow_plus && impl_dyn_multi {
1683 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1684 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1685 .span_suggestion(ty.span, "use parentheses to disambiguate", sum_with_parens)
1690 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1691 // Do not add `+` to expected tokens.
1692 if !allow_plus || self.token != token::BinOp(token::Plus) {
1697 let bounds = self.parse_ty_param_bounds()?;
1698 let sum_span = ty.span.to(self.prev_span);
1700 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1701 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1704 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1705 let sum_with_parens = pprust::to_string(|s| {
1706 use print::pprust::PrintState;
1709 s.print_opt_lifetime(lifetime)?;
1710 s.print_mutability(mut_ty.mutbl)?;
1712 s.print_type(&mut_ty.ty)?;
1713 s.print_bounds(" +", &bounds)?;
1716 err.span_suggestion(sum_span, "try adding parentheses", sum_with_parens);
1718 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1719 err.span_label(sum_span, "perhaps you forgot parentheses?");
1722 err.span_label(sum_span, "expected a path");
1729 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1730 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1732 // Do not add `::` to expected tokens.
1733 if !allow_recovery || self.token != token::ModSep {
1736 let ty = match base.to_ty() {
1738 None => return Ok(base),
1741 self.bump(); // `::`
1742 let mut segments = Vec::new();
1743 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1745 let span = ty.span.to(self.prev_span);
1747 base.to_recovered(Some(QSelf { ty, position: 0 }), ast::Path { segments, span });
1750 .struct_span_err(span, "missing angle brackets in associated item path")
1751 .span_suggestion(span, "try", recovered.to_string()).emit();
1756 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1757 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1758 let mutbl = self.parse_mutability();
1759 let ty = self.parse_ty_no_plus()?;
1760 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1763 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1764 let mutbl = if self.eat_keyword(keywords::Mut) {
1766 } else if self.eat_keyword(keywords::Const) {
1767 Mutability::Immutable
1769 let span = self.prev_span;
1771 "expected mut or const in raw pointer type (use \
1772 `*mut T` or `*const T` as appropriate)");
1773 Mutability::Immutable
1775 let t = self.parse_ty_no_plus()?;
1776 Ok(MutTy { ty: t, mutbl: mutbl })
1779 fn is_named_argument(&mut self) -> bool {
1780 let offset = match self.token {
1781 token::Interpolated(ref nt) => match nt.0 {
1782 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1785 token::BinOp(token::And) | token::AndAnd => 1,
1786 _ if self.token.is_keyword(keywords::Mut) => 1,
1790 self.look_ahead(offset, |t| t.is_ident() || t == &token::Underscore) &&
1791 self.look_ahead(offset + 1, |t| t == &token::Colon)
1794 /// This version of parse arg doesn't necessarily require
1795 /// identifier names.
1796 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1797 maybe_whole!(self, NtArg, |x| x);
1799 let pat = if require_name || self.is_named_argument() {
1800 debug!("parse_arg_general parse_pat (require_name:{})",
1802 let pat = self.parse_pat()?;
1804 self.expect(&token::Colon)?;
1807 debug!("parse_arg_general ident_to_pat");
1808 let sp = self.prev_span;
1809 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1811 id: ast::DUMMY_NODE_ID,
1812 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1818 let t = self.parse_ty()?;
1823 id: ast::DUMMY_NODE_ID,
1827 /// Parse a single function argument
1828 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1829 self.parse_arg_general(true)
1832 /// Parse an argument in a lambda header e.g. |arg, arg|
1833 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1834 let pat = self.parse_pat()?;
1835 let t = if self.eat(&token::Colon) {
1839 id: ast::DUMMY_NODE_ID,
1840 node: TyKind::Infer,
1847 id: ast::DUMMY_NODE_ID
1851 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1852 if self.eat(&token::Semi) {
1853 Ok(Some(self.parse_expr()?))
1859 /// Matches token_lit = LIT_INTEGER | ...
1860 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1861 let out = match self.token {
1862 token::Interpolated(ref nt) => match nt.0 {
1863 token::NtExpr(ref v) => match v.node {
1864 ExprKind::Lit(ref lit) => { lit.node.clone() }
1865 _ => { return self.unexpected_last(&self.token); }
1867 _ => { return self.unexpected_last(&self.token); }
1869 token::Literal(lit, suf) => {
1870 let diag = Some((self.span, &self.sess.span_diagnostic));
1871 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1875 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1880 _ => { return self.unexpected_last(&self.token); }
1887 /// Matches lit = true | false | token_lit
1888 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1890 let lit = if self.eat_keyword(keywords::True) {
1892 } else if self.eat_keyword(keywords::False) {
1893 LitKind::Bool(false)
1895 let lit = self.parse_lit_token()?;
1898 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1901 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1902 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1903 maybe_whole_expr!(self);
1905 let minus_lo = self.span;
1906 let minus_present = self.eat(&token::BinOp(token::Minus));
1908 let literal = P(self.parse_lit()?);
1909 let hi = self.prev_span;
1910 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1913 let minus_hi = self.prev_span;
1914 let unary = self.mk_unary(UnOp::Neg, expr);
1915 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1921 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1923 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1927 _ => self.parse_ident(),
1931 /// Parses qualified path.
1932 /// Assumes that the leading `<` has been parsed already.
1934 /// `qualified_path = <type [as trait_ref]>::path`
1938 /// `<T as U>::F::a<S>` (without disambiguator)
1939 /// `<T as U>::F::a::<S>` (with disambiguator)
1940 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1941 let lo = self.prev_span;
1942 let ty = self.parse_ty()?;
1943 let mut path = if self.eat_keyword(keywords::As) {
1944 self.parse_path(PathStyle::Type)?
1946 ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP }
1948 self.expect(&token::Gt)?;
1949 self.expect(&token::ModSep)?;
1951 let qself = QSelf { ty, position: path.segments.len() };
1952 self.parse_path_segments(&mut path.segments, style, true)?;
1954 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1957 /// Parses simple paths.
1959 /// `path = [::] segment+`
1960 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1963 /// `a::b::C<D>` (without disambiguator)
1964 /// `a::b::C::<D>` (with disambiguator)
1965 /// `Fn(Args)` (without disambiguator)
1966 /// `Fn::(Args)` (with disambiguator)
1967 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1968 self.parse_path_common(style, true)
1971 pub fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1972 -> PResult<'a, ast::Path> {
1973 maybe_whole!(self, NtPath, |path| {
1974 if style == PathStyle::Mod &&
1975 path.segments.iter().any(|segment| segment.parameters.is_some()) {
1976 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1981 let lo = self.meta_var_span.unwrap_or(self.span);
1982 let mut segments = Vec::new();
1983 if self.eat(&token::ModSep) {
1984 segments.push(PathSegment::crate_root(lo));
1986 self.parse_path_segments(&mut segments, style, enable_warning)?;
1988 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1991 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1992 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1993 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1994 let meta_ident = match self.token {
1995 token::Interpolated(ref nt) => match nt.0 {
1996 token::NtMeta(ref meta) => match meta.node {
1997 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
2004 if let Some(ident) = meta_ident {
2006 return Ok(ast::Path::from_ident(self.prev_span, ident));
2008 self.parse_path(style)
2011 fn parse_path_segments(&mut self,
2012 segments: &mut Vec<PathSegment>,
2014 enable_warning: bool)
2015 -> PResult<'a, ()> {
2017 segments.push(self.parse_path_segment(style, enable_warning)?);
2019 if self.is_import_coupler(false) || !self.eat(&token::ModSep) {
2025 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2026 -> PResult<'a, PathSegment> {
2027 let ident_span = self.span;
2028 let ident = self.parse_path_segment_ident()?;
2030 let is_args_start = |token: &token::Token| match *token {
2031 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2034 let check_args_start = |this: &mut Self| {
2035 this.expected_tokens.extend_from_slice(
2036 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2038 is_args_start(&this.token)
2041 Ok(if style == PathStyle::Type && check_args_start(self) ||
2042 style != PathStyle::Mod && self.check(&token::ModSep)
2043 && self.look_ahead(1, |t| is_args_start(t)) {
2044 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2046 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2047 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2048 .span_label(self.prev_span, "try removing `::`").emit();
2051 let parameters = if self.eat_lt() {
2053 let (lifetimes, types, bindings) = self.parse_generic_args()?;
2055 let span = lo.to(self.prev_span);
2056 AngleBracketedParameterData { lifetimes, types, bindings, span }.into()
2060 let inputs = self.parse_seq_to_before_tokens(
2061 &[&token::CloseDelim(token::Paren)],
2062 SeqSep::trailing_allowed(token::Comma),
2063 TokenExpectType::Expect,
2066 let output = if self.eat(&token::RArrow) {
2067 Some(self.parse_ty_common(false, false)?)
2071 let span = lo.to(self.prev_span);
2072 ParenthesizedParameterData { inputs, output, span }.into()
2075 PathSegment { identifier: ident, span: ident_span, parameters }
2077 // Generic arguments are not found.
2078 PathSegment::from_ident(ident, ident_span)
2082 fn check_lifetime(&mut self) -> bool {
2083 self.expected_tokens.push(TokenType::Lifetime);
2084 self.token.is_lifetime()
2087 /// Parse single lifetime 'a or panic.
2088 pub fn expect_lifetime(&mut self) -> Lifetime {
2089 if let Some(lifetime) = self.token.lifetime(self.span) {
2093 self.span_bug(self.span, "not a lifetime")
2097 /// Parse mutability (`mut` or nothing).
2098 fn parse_mutability(&mut self) -> Mutability {
2099 if self.eat_keyword(keywords::Mut) {
2102 Mutability::Immutable
2106 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2107 if let token::Literal(token::Integer(name), None) = self.token {
2109 Ok(Ident::with_empty_ctxt(name))
2111 self.parse_ident_common(false)
2115 /// Parse ident (COLON expr)?
2116 pub fn parse_field(&mut self) -> PResult<'a, Field> {
2117 let attrs = self.parse_outer_attributes()?;
2121 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2122 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2123 let fieldname = self.parse_field_name()?;
2125 hi = self.prev_span;
2126 (fieldname, self.parse_expr()?, false)
2128 let fieldname = self.parse_ident_common(false)?;
2129 hi = self.prev_span;
2131 // Mimic `x: x` for the `x` field shorthand.
2132 let path = ast::Path::from_ident(lo.to(hi), fieldname);
2133 (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
2136 ident: respan(lo.to(hi), fieldname),
2137 span: lo.to(expr.span),
2140 attrs: attrs.into(),
2144 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2145 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2148 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2149 ExprKind::Unary(unop, expr)
2152 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2153 ExprKind::Binary(binop, lhs, rhs)
2156 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2157 ExprKind::Call(f, args)
2160 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2161 ExprKind::Index(expr, idx)
2164 pub fn mk_range(&mut self,
2165 start: Option<P<Expr>>,
2166 end: Option<P<Expr>>,
2167 limits: RangeLimits)
2168 -> PResult<'a, ast::ExprKind> {
2169 if end.is_none() && limits == RangeLimits::Closed {
2170 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2172 Ok(ExprKind::Range(start, end, limits))
2176 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2177 ExprKind::TupField(expr, idx)
2180 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2181 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2182 ExprKind::AssignOp(binop, lhs, rhs)
2185 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2187 id: ast::DUMMY_NODE_ID,
2188 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2194 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2195 let span = &self.span;
2196 let lv_lit = P(codemap::Spanned {
2197 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2202 id: ast::DUMMY_NODE_ID,
2203 node: ExprKind::Lit(lv_lit),
2209 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2211 token::OpenDelim(delim) => match self.parse_token_tree() {
2212 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2213 _ => unreachable!(),
2215 _ => Err(self.fatal("expected open delimiter")),
2219 /// At the bottom (top?) of the precedence hierarchy,
2220 /// parse things like parenthesized exprs,
2221 /// macros, return, etc.
2223 /// NB: This does not parse outer attributes,
2224 /// and is private because it only works
2225 /// correctly if called from parse_dot_or_call_expr().
2226 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2227 maybe_whole_expr!(self);
2229 // Outer attributes are already parsed and will be
2230 // added to the return value after the fact.
2232 // Therefore, prevent sub-parser from parsing
2233 // attributes by giving them a empty "already parsed" list.
2234 let mut attrs = ThinVec::new();
2237 let mut hi = self.span;
2241 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2243 token::OpenDelim(token::Paren) => {
2246 attrs.extend(self.parse_inner_attributes()?);
2248 // (e) is parenthesized e
2249 // (e,) is a tuple with only one field, e
2250 let mut es = vec![];
2251 let mut trailing_comma = false;
2252 while self.token != token::CloseDelim(token::Paren) {
2253 es.push(self.parse_expr()?);
2254 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2255 if self.check(&token::Comma) {
2256 trailing_comma = true;
2260 trailing_comma = false;
2266 hi = self.prev_span;
2267 ex = if es.len() == 1 && !trailing_comma {
2268 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2273 token::OpenDelim(token::Brace) => {
2274 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2276 token::BinOp(token::Or) | token::OrOr => {
2277 return self.parse_lambda_expr(attrs);
2279 token::OpenDelim(token::Bracket) => {
2282 attrs.extend(self.parse_inner_attributes()?);
2284 if self.check(&token::CloseDelim(token::Bracket)) {
2287 ex = ExprKind::Array(Vec::new());
2290 let first_expr = self.parse_expr()?;
2291 if self.check(&token::Semi) {
2292 // Repeating array syntax: [ 0; 512 ]
2294 let count = self.parse_expr()?;
2295 self.expect(&token::CloseDelim(token::Bracket))?;
2296 ex = ExprKind::Repeat(first_expr, count);
2297 } else if self.check(&token::Comma) {
2298 // Vector with two or more elements.
2300 let remaining_exprs = self.parse_seq_to_end(
2301 &token::CloseDelim(token::Bracket),
2302 SeqSep::trailing_allowed(token::Comma),
2303 |p| Ok(p.parse_expr()?)
2305 let mut exprs = vec![first_expr];
2306 exprs.extend(remaining_exprs);
2307 ex = ExprKind::Array(exprs);
2309 // Vector with one element.
2310 self.expect(&token::CloseDelim(token::Bracket))?;
2311 ex = ExprKind::Array(vec![first_expr]);
2314 hi = self.prev_span;
2318 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2320 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2322 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2323 return self.parse_lambda_expr(attrs);
2325 if self.eat_keyword(keywords::If) {
2326 return self.parse_if_expr(attrs);
2328 if self.eat_keyword(keywords::For) {
2329 let lo = self.prev_span;
2330 return self.parse_for_expr(None, lo, attrs);
2332 if self.eat_keyword(keywords::While) {
2333 let lo = self.prev_span;
2334 return self.parse_while_expr(None, lo, attrs);
2336 if let Some(label) = self.eat_label() {
2337 let lo = label.span;
2338 self.expect(&token::Colon)?;
2339 if self.eat_keyword(keywords::While) {
2340 return self.parse_while_expr(Some(label), lo, attrs)
2342 if self.eat_keyword(keywords::For) {
2343 return self.parse_for_expr(Some(label), lo, attrs)
2345 if self.eat_keyword(keywords::Loop) {
2346 return self.parse_loop_expr(Some(label), lo, attrs)
2348 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2350 if self.eat_keyword(keywords::Loop) {
2351 let lo = self.prev_span;
2352 return self.parse_loop_expr(None, lo, attrs);
2354 if self.eat_keyword(keywords::Continue) {
2355 let label = self.eat_label();
2356 let ex = ExprKind::Continue(label);
2357 let hi = self.prev_span;
2358 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2360 if self.eat_keyword(keywords::Match) {
2361 return self.parse_match_expr(attrs);
2363 if self.eat_keyword(keywords::Unsafe) {
2364 return self.parse_block_expr(
2366 BlockCheckMode::Unsafe(ast::UserProvided),
2369 if self.is_catch_expr() {
2371 assert!(self.eat_keyword(keywords::Do));
2372 assert!(self.eat_keyword(keywords::Catch));
2373 return self.parse_catch_expr(lo, attrs);
2375 if self.eat_keyword(keywords::Return) {
2376 if self.token.can_begin_expr() {
2377 let e = self.parse_expr()?;
2379 ex = ExprKind::Ret(Some(e));
2381 ex = ExprKind::Ret(None);
2383 } else if self.eat_keyword(keywords::Break) {
2384 let label = self.eat_label();
2385 let e = if self.token.can_begin_expr()
2386 && !(self.token == token::OpenDelim(token::Brace)
2387 && self.restrictions.contains(
2388 Restrictions::NO_STRUCT_LITERAL)) {
2389 Some(self.parse_expr()?)
2393 ex = ExprKind::Break(label, e);
2394 hi = self.prev_span;
2395 } else if self.eat_keyword(keywords::Yield) {
2396 if self.token.can_begin_expr() {
2397 let e = self.parse_expr()?;
2399 ex = ExprKind::Yield(Some(e));
2401 ex = ExprKind::Yield(None);
2403 } else if self.token.is_keyword(keywords::Let) {
2404 // Catch this syntax error here, instead of in `parse_ident`, so
2405 // that we can explicitly mention that let is not to be used as an expression
2406 let mut db = self.fatal("expected expression, found statement (`let`)");
2407 db.note("variable declaration using `let` is a statement");
2409 } else if self.token.is_path_start() {
2410 let pth = self.parse_path(PathStyle::Expr)?;
2412 // `!`, as an operator, is prefix, so we know this isn't that
2413 if self.eat(&token::Not) {
2414 // MACRO INVOCATION expression
2415 let (_, tts) = self.expect_delimited_token_tree()?;
2416 let hi = self.prev_span;
2417 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2419 if self.check(&token::OpenDelim(token::Brace)) {
2420 // This is a struct literal, unless we're prohibited
2421 // from parsing struct literals here.
2422 let prohibited = self.restrictions.contains(
2423 Restrictions::NO_STRUCT_LITERAL
2426 return self.parse_struct_expr(lo, pth, attrs);
2431 ex = ExprKind::Path(None, pth);
2433 match self.parse_lit() {
2436 ex = ExprKind::Lit(P(lit));
2439 self.cancel(&mut err);
2440 let msg = format!("expected expression, found {}",
2441 self.this_token_descr());
2442 return Err(self.fatal(&msg));
2449 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2450 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2455 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2456 -> PResult<'a, P<Expr>> {
2457 let struct_sp = lo.to(self.prev_span);
2459 let mut fields = Vec::new();
2460 let mut base = None;
2462 attrs.extend(self.parse_inner_attributes()?);
2464 while self.token != token::CloseDelim(token::Brace) {
2465 if self.eat(&token::DotDot) {
2466 let exp_span = self.prev_span;
2467 match self.parse_expr() {
2473 self.recover_stmt();
2476 if self.token == token::Comma {
2477 let mut err = self.sess.span_diagnostic.mut_span_err(
2478 exp_span.to(self.prev_span),
2479 "cannot use a comma after the base struct",
2481 err.span_suggestion_short(self.span, "remove this comma", "".to_owned());
2482 err.note("the base struct must always be the last field");
2484 self.recover_stmt();
2489 match self.parse_field() {
2490 Ok(f) => fields.push(f),
2492 e.span_label(struct_sp, "while parsing this struct");
2494 self.recover_stmt();
2499 match self.expect_one_of(&[token::Comma],
2500 &[token::CloseDelim(token::Brace)]) {
2504 self.recover_stmt();
2510 let span = lo.to(self.span);
2511 self.expect(&token::CloseDelim(token::Brace))?;
2512 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2515 fn parse_or_use_outer_attributes(&mut self,
2516 already_parsed_attrs: Option<ThinVec<Attribute>>)
2517 -> PResult<'a, ThinVec<Attribute>> {
2518 if let Some(attrs) = already_parsed_attrs {
2521 self.parse_outer_attributes().map(|a| a.into())
2525 /// Parse a block or unsafe block
2526 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2527 outer_attrs: ThinVec<Attribute>)
2528 -> PResult<'a, P<Expr>> {
2529 self.expect(&token::OpenDelim(token::Brace))?;
2531 let mut attrs = outer_attrs;
2532 attrs.extend(self.parse_inner_attributes()?);
2534 let blk = self.parse_block_tail(lo, blk_mode)?;
2535 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2538 /// parse a.b or a(13) or a[4] or just a
2539 pub fn parse_dot_or_call_expr(&mut self,
2540 already_parsed_attrs: Option<ThinVec<Attribute>>)
2541 -> PResult<'a, P<Expr>> {
2542 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2544 let b = self.parse_bottom_expr();
2545 let (span, b) = self.interpolated_or_expr_span(b)?;
2546 self.parse_dot_or_call_expr_with(b, span, attrs)
2549 pub fn parse_dot_or_call_expr_with(&mut self,
2552 mut attrs: ThinVec<Attribute>)
2553 -> PResult<'a, P<Expr>> {
2554 // Stitch the list of outer attributes onto the return value.
2555 // A little bit ugly, but the best way given the current code
2557 self.parse_dot_or_call_expr_with_(e0, lo)
2559 expr.map(|mut expr| {
2560 attrs.extend::<Vec<_>>(expr.attrs.into());
2563 ExprKind::If(..) | ExprKind::IfLet(..) => {
2564 if !expr.attrs.is_empty() {
2565 // Just point to the first attribute in there...
2566 let span = expr.attrs[0].span;
2569 "attributes are not yet allowed on `if` \
2580 // Assuming we have just parsed `.`, continue parsing into an expression.
2581 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2582 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2583 Ok(match self.token {
2584 token::OpenDelim(token::Paren) => {
2585 // Method call `expr.f()`
2586 let mut args = self.parse_unspanned_seq(
2587 &token::OpenDelim(token::Paren),
2588 &token::CloseDelim(token::Paren),
2589 SeqSep::trailing_allowed(token::Comma),
2590 |p| Ok(p.parse_expr()?)
2592 args.insert(0, self_arg);
2594 let span = lo.to(self.prev_span);
2595 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2598 // Field access `expr.f`
2599 if let Some(parameters) = segment.parameters {
2600 self.span_err(parameters.span(),
2601 "field expressions may not have generic arguments");
2604 let span = lo.to(self.prev_span);
2605 let ident = respan(segment.span, segment.identifier);
2606 self.mk_expr(span, ExprKind::Field(self_arg, ident), ThinVec::new())
2611 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2616 while self.eat(&token::Question) {
2617 let hi = self.prev_span;
2618 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2622 if self.eat(&token::Dot) {
2624 token::Ident(..) => {
2625 e = self.parse_dot_suffix(e, lo)?;
2627 token::Literal(token::Integer(index_ident), suf) => {
2630 // A tuple index may not have a suffix
2631 self.expect_no_suffix(sp, "tuple index", suf);
2633 let dot_span = self.prev_span;
2637 let invalid_msg = "invalid tuple or struct index";
2639 let index = index_ident.as_str().parse::<usize>().ok();
2642 if n.to_string() != index_ident.as_str() {
2643 let mut err = self.struct_span_err(self.prev_span, invalid_msg);
2644 err.span_suggestion(self.prev_span,
2645 "try simplifying the index",
2649 let id = respan(dot_span.to(hi), n);
2650 let field = self.mk_tup_field(e, id);
2651 e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2654 let prev_span = self.prev_span;
2655 self.span_err(prev_span, invalid_msg);
2659 token::Literal(token::Float(n), _suf) => {
2661 let fstr = n.as_str();
2662 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2663 &format!("unexpected token: `{}`", n));
2664 err.span_label(self.prev_span, "unexpected token");
2665 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2666 let float = match fstr.parse::<f64>().ok() {
2670 let sugg = pprust::to_string(|s| {
2671 use print::pprust::PrintState;
2675 s.print_usize(float.trunc() as usize)?;
2678 s.s.word(fstr.splitn(2, ".").last().unwrap())
2680 err.span_suggestion(
2681 lo.to(self.prev_span),
2682 "try parenthesizing the first index",
2689 // FIXME Could factor this out into non_fatal_unexpected or something.
2690 let actual = self.this_token_to_string();
2691 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2696 if self.expr_is_complete(&e) { break; }
2699 token::OpenDelim(token::Paren) => {
2700 let es = self.parse_unspanned_seq(
2701 &token::OpenDelim(token::Paren),
2702 &token::CloseDelim(token::Paren),
2703 SeqSep::trailing_allowed(token::Comma),
2704 |p| Ok(p.parse_expr()?)
2706 hi = self.prev_span;
2708 let nd = self.mk_call(e, es);
2709 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2713 // Could be either an index expression or a slicing expression.
2714 token::OpenDelim(token::Bracket) => {
2716 let ix = self.parse_expr()?;
2718 self.expect(&token::CloseDelim(token::Bracket))?;
2719 let index = self.mk_index(e, ix);
2720 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2728 pub fn process_potential_macro_variable(&mut self) {
2729 let ident = match self.token {
2730 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2731 self.look_ahead(1, |t| t.is_ident()) => {
2733 let name = match self.token { token::Ident(ident) => ident, _ => unreachable!() };
2734 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2737 token::Interpolated(ref nt) => {
2738 self.meta_var_span = Some(self.span);
2740 token::NtIdent(ident) => ident,
2746 self.token = token::Ident(ident.node);
2747 self.span = ident.span;
2750 /// parse a single token tree from the input.
2751 pub fn parse_token_tree(&mut self) -> TokenTree {
2753 token::OpenDelim(..) => {
2754 let frame = mem::replace(&mut self.token_cursor.frame,
2755 self.token_cursor.stack.pop().unwrap());
2756 self.span = frame.span;
2758 TokenTree::Delimited(frame.span, Delimited {
2760 tts: frame.tree_cursor.original_stream().into(),
2763 token::CloseDelim(_) | token::Eof => unreachable!(),
2765 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2767 TokenTree::Token(span, token)
2772 // parse a stream of tokens into a list of TokenTree's,
2774 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2775 let mut tts = Vec::new();
2776 while self.token != token::Eof {
2777 tts.push(self.parse_token_tree());
2782 pub fn parse_tokens(&mut self) -> TokenStream {
2783 let mut result = Vec::new();
2786 token::Eof | token::CloseDelim(..) => break,
2787 _ => result.push(self.parse_token_tree().into()),
2790 TokenStream::concat(result)
2793 /// Parse a prefix-unary-operator expr
2794 pub fn parse_prefix_expr(&mut self,
2795 already_parsed_attrs: Option<ThinVec<Attribute>>)
2796 -> PResult<'a, P<Expr>> {
2797 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2799 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2800 let (hi, ex) = match self.token {
2803 let e = self.parse_prefix_expr(None);
2804 let (span, e) = self.interpolated_or_expr_span(e)?;
2805 (lo.to(span), self.mk_unary(UnOp::Not, e))
2807 // Suggest `!` for bitwise negation when encountering a `~`
2810 let e = self.parse_prefix_expr(None);
2811 let (span, e) = self.interpolated_or_expr_span(e)?;
2812 let span_of_tilde = lo;
2813 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2814 "`~` can not be used as a unary operator");
2815 err.span_label(span_of_tilde, "did you mean `!`?");
2816 err.help("use `!` instead of `~` if you meant to perform bitwise negation");
2818 (lo.to(span), self.mk_unary(UnOp::Not, e))
2820 token::BinOp(token::Minus) => {
2822 let e = self.parse_prefix_expr(None);
2823 let (span, e) = self.interpolated_or_expr_span(e)?;
2824 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2826 token::BinOp(token::Star) => {
2828 let e = self.parse_prefix_expr(None);
2829 let (span, e) = self.interpolated_or_expr_span(e)?;
2830 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2832 token::BinOp(token::And) | token::AndAnd => {
2834 let m = self.parse_mutability();
2835 let e = self.parse_prefix_expr(None);
2836 let (span, e) = self.interpolated_or_expr_span(e)?;
2837 (lo.to(span), ExprKind::AddrOf(m, e))
2839 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2841 let place = self.parse_expr_res(
2842 Restrictions::NO_STRUCT_LITERAL,
2845 let blk = self.parse_block()?;
2846 let span = blk.span;
2847 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2848 (lo.to(span), ExprKind::InPlace(place, blk_expr))
2850 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2852 let e = self.parse_prefix_expr(None);
2853 let (span, e) = self.interpolated_or_expr_span(e)?;
2854 (lo.to(span), ExprKind::Box(e))
2856 _ => return self.parse_dot_or_call_expr(Some(attrs))
2858 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2861 /// Parse an associative expression
2863 /// This parses an expression accounting for associativity and precedence of the operators in
2865 pub fn parse_assoc_expr(&mut self,
2866 already_parsed_attrs: Option<ThinVec<Attribute>>)
2867 -> PResult<'a, P<Expr>> {
2868 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2871 /// Parse an associative expression with operators of at least `min_prec` precedence
2872 pub fn parse_assoc_expr_with(&mut self,
2875 -> PResult<'a, P<Expr>> {
2876 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2879 let attrs = match lhs {
2880 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2883 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2884 return self.parse_prefix_range_expr(attrs);
2886 self.parse_prefix_expr(attrs)?
2890 if self.expr_is_complete(&lhs) {
2891 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2894 self.expected_tokens.push(TokenType::Operator);
2895 while let Some(op) = AssocOp::from_token(&self.token) {
2897 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2898 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2899 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2900 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2901 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2902 (PrevTokenKind::Interpolated, _) => self.prev_span,
2903 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2904 if path.segments.len() == 1 => self.prev_span,
2908 let cur_op_span = self.span;
2909 let restrictions = if op.is_assign_like() {
2910 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2914 if op.precedence() < min_prec {
2917 // Check for deprecated `...` syntax
2918 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2919 self.err_dotdotdot_syntax(self.span);
2923 if op.is_comparison() {
2924 self.check_no_chained_comparison(&lhs, &op);
2927 if op == AssocOp::As {
2928 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2930 } else if op == AssocOp::Colon {
2931 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2934 err.span_label(self.span,
2935 "expecting a type here because of type ascription");
2936 let cm = self.sess.codemap();
2937 let cur_pos = cm.lookup_char_pos(self.span.lo());
2938 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
2939 if cur_pos.line != op_pos.line {
2940 err.span_suggestion_short(cur_op_span,
2941 "did you mean to use `;` here?",
2948 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2949 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2950 // generalise it to the Fixity::None code.
2952 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2953 // two variants are handled with `parse_prefix_range_expr` call above.
2954 let rhs = if self.is_at_start_of_range_notation_rhs() {
2955 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2956 LhsExpr::NotYetParsed)?)
2960 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2965 let limits = if op == AssocOp::DotDot {
2966 RangeLimits::HalfOpen
2971 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2972 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2976 let rhs = match op.fixity() {
2977 Fixity::Right => self.with_res(
2978 restrictions - Restrictions::STMT_EXPR,
2980 this.parse_assoc_expr_with(op.precedence(),
2981 LhsExpr::NotYetParsed)
2983 Fixity::Left => self.with_res(
2984 restrictions - Restrictions::STMT_EXPR,
2986 this.parse_assoc_expr_with(op.precedence() + 1,
2987 LhsExpr::NotYetParsed)
2989 // We currently have no non-associative operators that are not handled above by
2990 // the special cases. The code is here only for future convenience.
2991 Fixity::None => self.with_res(
2992 restrictions - Restrictions::STMT_EXPR,
2994 this.parse_assoc_expr_with(op.precedence() + 1,
2995 LhsExpr::NotYetParsed)
2999 let span = lhs_span.to(rhs.span);
3001 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3002 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3003 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3004 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3005 AssocOp::Greater | AssocOp::GreaterEqual => {
3006 let ast_op = op.to_ast_binop().unwrap();
3007 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
3008 self.mk_expr(span, binary, ThinVec::new())
3011 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3013 self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
3014 AssocOp::AssignOp(k) => {
3016 token::Plus => BinOpKind::Add,
3017 token::Minus => BinOpKind::Sub,
3018 token::Star => BinOpKind::Mul,
3019 token::Slash => BinOpKind::Div,
3020 token::Percent => BinOpKind::Rem,
3021 token::Caret => BinOpKind::BitXor,
3022 token::And => BinOpKind::BitAnd,
3023 token::Or => BinOpKind::BitOr,
3024 token::Shl => BinOpKind::Shl,
3025 token::Shr => BinOpKind::Shr,
3027 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
3028 self.mk_expr(span, aopexpr, ThinVec::new())
3030 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3031 self.bug("AssocOp should have been handled by special case")
3035 if op.fixity() == Fixity::None { break }
3040 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3041 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3042 -> PResult<'a, P<Expr>> {
3043 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3044 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3047 // Save the state of the parser before parsing type normally, in case there is a
3048 // LessThan comparison after this cast.
3049 let parser_snapshot_before_type = self.clone();
3050 match self.parse_ty_no_plus() {
3052 Ok(mk_expr(self, rhs))
3054 Err(mut type_err) => {
3055 // Rewind to before attempting to parse the type with generics, to recover
3056 // from situations like `x as usize < y` in which we first tried to parse
3057 // `usize < y` as a type with generic arguments.
3058 let parser_snapshot_after_type = self.clone();
3059 mem::replace(self, parser_snapshot_before_type);
3061 match self.parse_path(PathStyle::Expr) {
3063 let (op_noun, op_verb) = match self.token {
3064 token::Lt => ("comparison", "comparing"),
3065 token::BinOp(token::Shl) => ("shift", "shifting"),
3067 // We can end up here even without `<` being the next token, for
3068 // example because `parse_ty_no_plus` returns `Err` on keywords,
3069 // but `parse_path` returns `Ok` on them due to error recovery.
3070 // Return original error and parser state.
3071 mem::replace(self, parser_snapshot_after_type);
3072 return Err(type_err);
3076 // Successfully parsed the type path leaving a `<` yet to parse.
3079 // Report non-fatal diagnostics, keep `x as usize` as an expression
3080 // in AST and continue parsing.
3081 let msg = format!("`<` is interpreted as a start of generic \
3082 arguments for `{}`, not a {}", path, op_noun);
3083 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3084 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3085 "interpreted as generic arguments");
3086 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3088 let expr = mk_expr(self, P(Ty {
3090 node: TyKind::Path(None, path),
3091 id: ast::DUMMY_NODE_ID
3094 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
3095 .unwrap_or(pprust::expr_to_string(&expr));
3096 err.span_suggestion(expr.span,
3097 &format!("try {} the casted value", op_verb),
3098 format!("({})", expr_str));
3103 Err(mut path_err) => {
3104 // Couldn't parse as a path, return original error and parser state.
3106 mem::replace(self, parser_snapshot_after_type);
3114 /// Produce an error if comparison operators are chained (RFC #558).
3115 /// We only need to check lhs, not rhs, because all comparison ops
3116 /// have same precedence and are left-associative
3117 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3118 debug_assert!(outer_op.is_comparison(),
3119 "check_no_chained_comparison: {:?} is not comparison",
3122 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3123 // respan to include both operators
3124 let op_span = op.span.to(self.span);
3125 let mut err = self.diagnostic().struct_span_err(op_span,
3126 "chained comparison operators require parentheses");
3127 if op.node == BinOpKind::Lt &&
3128 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3129 *outer_op == AssocOp::Greater // even in a case like the following:
3130 { // Foo<Bar<Baz<Qux, ()>>>
3132 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3133 err.help("or use `(...)` if you meant to specify fn arguments");
3141 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3142 fn parse_prefix_range_expr(&mut self,
3143 already_parsed_attrs: Option<ThinVec<Attribute>>)
3144 -> PResult<'a, P<Expr>> {
3145 // Check for deprecated `...` syntax
3146 if self.token == token::DotDotDot {
3147 self.err_dotdotdot_syntax(self.span);
3150 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3151 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3153 let tok = self.token.clone();
3154 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3156 let mut hi = self.span;
3158 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3159 // RHS must be parsed with more associativity than the dots.
3160 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3161 Some(self.parse_assoc_expr_with(next_prec,
3162 LhsExpr::NotYetParsed)
3170 let limits = if tok == token::DotDot {
3171 RangeLimits::HalfOpen
3176 let r = try!(self.mk_range(None,
3179 Ok(self.mk_expr(lo.to(hi), r, attrs))
3182 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3183 if self.token.can_begin_expr() {
3184 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3185 if self.token == token::OpenDelim(token::Brace) {
3186 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3194 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3195 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3196 if self.check_keyword(keywords::Let) {
3197 return self.parse_if_let_expr(attrs);
3199 let lo = self.prev_span;
3200 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3202 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3203 // verify that the last statement is either an implicit return (no `;`) or an explicit
3204 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3205 // the dead code lint.
3206 if self.eat_keyword(keywords::Else) || !cond.returns() {
3207 let sp = self.sess.codemap().next_point(lo);
3208 let mut err = self.diagnostic()
3209 .struct_span_err(sp, "missing condition for `if` statemement");
3210 err.span_label(sp, "expected if condition here");
3213 let thn = self.parse_block()?;
3214 let mut els: Option<P<Expr>> = None;
3215 let mut hi = thn.span;
3216 if self.eat_keyword(keywords::Else) {
3217 let elexpr = self.parse_else_expr()?;
3221 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3224 /// Parse an 'if let' expression ('if' token already eaten)
3225 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3226 -> PResult<'a, P<Expr>> {
3227 let lo = self.prev_span;
3228 self.expect_keyword(keywords::Let)?;
3229 let pat = self.parse_pat()?;
3230 self.expect(&token::Eq)?;
3231 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3232 let thn = self.parse_block()?;
3233 let (hi, els) = if self.eat_keyword(keywords::Else) {
3234 let expr = self.parse_else_expr()?;
3235 (expr.span, Some(expr))
3239 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
3242 // `move |args| expr`
3243 pub fn parse_lambda_expr(&mut self,
3244 attrs: ThinVec<Attribute>)
3245 -> PResult<'a, P<Expr>>
3248 let movability = if self.eat_keyword(keywords::Static) {
3253 let capture_clause = if self.eat_keyword(keywords::Move) {
3258 let decl = self.parse_fn_block_decl()?;
3259 let decl_hi = self.prev_span;
3260 let body = match decl.output {
3261 FunctionRetTy::Default(_) => {
3262 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3263 self.parse_expr_res(restrictions, None)?
3266 // If an explicit return type is given, require a
3267 // block to appear (RFC 968).
3268 let body_lo = self.span;
3269 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3275 ExprKind::Closure(capture_clause, movability, decl, body, lo.to(decl_hi)),
3279 // `else` token already eaten
3280 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3281 if self.eat_keyword(keywords::If) {
3282 return self.parse_if_expr(ThinVec::new());
3284 let blk = self.parse_block()?;
3285 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3289 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3290 pub fn parse_for_expr(&mut self, opt_label: Option<Label>,
3292 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3293 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3295 let pat = self.parse_pat()?;
3296 if !self.eat_keyword(keywords::In) {
3297 let in_span = self.prev_span.between(self.span);
3298 let mut err = self.sess.span_diagnostic
3299 .struct_span_err(in_span, "missing `in` in `for` loop");
3300 err.span_suggestion_short(in_span, "try adding `in` here", " in ".into());
3303 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3304 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3305 attrs.extend(iattrs);
3307 let hi = self.prev_span;
3308 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3311 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3312 pub fn parse_while_expr(&mut self, opt_label: Option<Label>,
3314 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3315 if self.token.is_keyword(keywords::Let) {
3316 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3318 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3319 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3320 attrs.extend(iattrs);
3321 let span = span_lo.to(body.span);
3322 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3325 /// Parse a 'while let' expression ('while' token already eaten)
3326 pub fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3328 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3329 self.expect_keyword(keywords::Let)?;
3330 let pat = self.parse_pat()?;
3331 self.expect(&token::Eq)?;
3332 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3333 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3334 attrs.extend(iattrs);
3335 let span = span_lo.to(body.span);
3336 return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_label), attrs));
3339 // parse `loop {...}`, `loop` token already eaten
3340 pub fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3342 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3343 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3344 attrs.extend(iattrs);
3345 let span = span_lo.to(body.span);
3346 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3349 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3350 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3351 -> PResult<'a, P<Expr>>
3353 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3354 attrs.extend(iattrs);
3355 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3358 // `match` token already eaten
3359 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3360 let match_span = self.prev_span;
3361 let lo = self.prev_span;
3362 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3364 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3365 if self.token == token::Token::Semi {
3366 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3370 attrs.extend(self.parse_inner_attributes()?);
3372 let mut arms: Vec<Arm> = Vec::new();
3373 while self.token != token::CloseDelim(token::Brace) {
3374 match self.parse_arm() {
3375 Ok(arm) => arms.push(arm),
3377 // Recover by skipping to the end of the block.
3379 self.recover_stmt();
3380 let span = lo.to(self.span);
3381 if self.token == token::CloseDelim(token::Brace) {
3384 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3390 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3393 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3394 maybe_whole!(self, NtArm, |x| x);
3396 let attrs = self.parse_outer_attributes()?;
3397 // Allow a '|' before the pats (RFC 1925)
3398 self.eat(&token::BinOp(token::Or));
3399 let pats = self.parse_pats()?;
3400 let guard = if self.eat_keyword(keywords::If) {
3401 Some(self.parse_expr()?)
3405 self.expect(&token::FatArrow)?;
3406 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)?;
3408 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3409 && self.token != token::CloseDelim(token::Brace);
3412 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3414 self.eat(&token::Comma);
3425 /// Parse an expression
3426 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3427 self.parse_expr_res(Restrictions::empty(), None)
3430 /// Evaluate the closure with restrictions in place.
3432 /// After the closure is evaluated, restrictions are reset.
3433 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3434 where F: FnOnce(&mut Self) -> T
3436 let old = self.restrictions;
3437 self.restrictions = r;
3439 self.restrictions = old;
3444 /// Parse an expression, subject to the given restrictions
3445 pub fn parse_expr_res(&mut self, r: Restrictions,
3446 already_parsed_attrs: Option<ThinVec<Attribute>>)
3447 -> PResult<'a, P<Expr>> {
3448 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3451 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3452 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3453 if self.check(&token::Eq) {
3455 Ok(Some(self.parse_expr()?))
3457 Ok(Some(self.parse_expr()?))
3463 /// Parse patterns, separated by '|' s
3464 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3465 let mut pats = Vec::new();
3467 pats.push(self.parse_pat()?);
3469 if self.token == token::OrOr {
3470 let mut err = self.struct_span_err(self.span,
3471 "unexpected token `||` after pattern");
3472 err.span_suggestion(self.span,
3473 "use a single `|` to specify multiple patterns",
3477 } else if self.check(&token::BinOp(token::Or)) {
3485 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3486 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3487 let mut fields = vec![];
3488 let mut ddpos = None;
3490 while !self.check(&token::CloseDelim(token::Paren)) {
3491 if ddpos.is_none() && self.eat(&token::DotDot) {
3492 ddpos = Some(fields.len());
3493 if self.eat(&token::Comma) {
3494 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3495 fields.push(self.parse_pat()?);
3497 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3498 // Emit a friendly error, ignore `..` and continue parsing
3499 self.span_err(self.prev_span, "`..` can only be used once per \
3500 tuple or tuple struct pattern");
3502 fields.push(self.parse_pat()?);
3505 if !self.check(&token::CloseDelim(token::Paren)) ||
3506 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3507 self.expect(&token::Comma)?;
3514 fn parse_pat_vec_elements(
3516 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3517 let mut before = Vec::new();
3518 let mut slice = None;
3519 let mut after = Vec::new();
3520 let mut first = true;
3521 let mut before_slice = true;
3523 while self.token != token::CloseDelim(token::Bracket) {
3527 self.expect(&token::Comma)?;
3529 if self.token == token::CloseDelim(token::Bracket)
3530 && (before_slice || !after.is_empty()) {
3536 if self.eat(&token::DotDot) {
3538 if self.check(&token::Comma) ||
3539 self.check(&token::CloseDelim(token::Bracket)) {
3540 slice = Some(P(Pat {
3541 id: ast::DUMMY_NODE_ID,
3542 node: PatKind::Wild,
3545 before_slice = false;
3551 let subpat = self.parse_pat()?;
3552 if before_slice && self.eat(&token::DotDot) {
3553 slice = Some(subpat);
3554 before_slice = false;
3555 } else if before_slice {
3556 before.push(subpat);
3562 Ok((before, slice, after))
3565 /// Parse the fields of a struct-like pattern
3566 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3567 let mut fields = Vec::new();
3568 let mut etc = false;
3569 let mut first = true;
3570 while self.token != token::CloseDelim(token::Brace) {
3574 self.expect(&token::Comma)?;
3575 // accept trailing commas
3576 if self.check(&token::CloseDelim(token::Brace)) { break }
3579 let attrs = self.parse_outer_attributes()?;
3583 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3584 if self.token == token::DotDotDot { // Issue #46718
3585 let mut err = self.struct_span_err(self.span,
3586 "expected field pattern, found `...`");
3587 err.span_suggestion(self.span,
3588 "to omit remaining fields, use one fewer `.`",
3594 if self.token != token::CloseDelim(token::Brace) {
3595 let token_str = self.this_token_to_string();
3596 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3603 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3604 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3605 // Parsing a pattern of the form "fieldname: pat"
3606 let fieldname = self.parse_field_name()?;
3608 let pat = self.parse_pat()?;
3610 (pat, fieldname, false)
3612 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3613 let is_box = self.eat_keyword(keywords::Box);
3614 let boxed_span = self.span;
3615 let is_ref = self.eat_keyword(keywords::Ref);
3616 let is_mut = self.eat_keyword(keywords::Mut);
3617 let fieldname = self.parse_ident()?;
3618 hi = self.prev_span;
3620 let bind_type = match (is_ref, is_mut) {
3621 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3622 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3623 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3624 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3626 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3627 let fieldpat = P(Pat {
3628 id: ast::DUMMY_NODE_ID,
3629 node: PatKind::Ident(bind_type, fieldpath, None),
3630 span: boxed_span.to(hi),
3633 let subpat = if is_box {
3635 id: ast::DUMMY_NODE_ID,
3636 node: PatKind::Box(fieldpat),
3642 (subpat, fieldname, true)
3645 fields.push(codemap::Spanned { span: lo.to(hi),
3646 node: ast::FieldPat {
3650 attrs: attrs.into(),
3654 return Ok((fields, etc));
3657 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3658 if self.token.is_path_start() {
3660 let (qself, path) = if self.eat_lt() {
3661 // Parse a qualified path
3662 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3665 // Parse an unqualified path
3666 (None, self.parse_path(PathStyle::Expr)?)
3668 let hi = self.prev_span;
3669 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3671 self.parse_pat_literal_maybe_minus()
3675 // helper function to decide whether to parse as ident binding or to try to do
3676 // something more complex like range patterns
3677 fn parse_as_ident(&mut self) -> bool {
3678 self.look_ahead(1, |t| match *t {
3679 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3680 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3681 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3682 // range pattern branch
3683 token::DotDot => None,
3685 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3686 token::Comma | token::CloseDelim(token::Bracket) => true,
3691 /// Parse a pattern.
3692 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3693 maybe_whole!(self, NtPat, |x| x);
3698 token::Underscore => {
3701 pat = PatKind::Wild;
3703 token::BinOp(token::And) | token::AndAnd => {
3704 // Parse &pat / &mut pat
3706 let mutbl = self.parse_mutability();
3707 if let token::Lifetime(ident) = self.token {
3708 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3710 let subpat = self.parse_pat()?;
3711 pat = PatKind::Ref(subpat, mutbl);
3713 token::OpenDelim(token::Paren) => {
3714 // Parse (pat,pat,pat,...) as tuple pattern
3716 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3717 self.expect(&token::CloseDelim(token::Paren))?;
3718 pat = PatKind::Tuple(fields, ddpos);
3720 token::OpenDelim(token::Bracket) => {
3721 // Parse [pat,pat,...] as slice pattern
3723 let (before, slice, after) = self.parse_pat_vec_elements()?;
3724 self.expect(&token::CloseDelim(token::Bracket))?;
3725 pat = PatKind::Slice(before, slice, after);
3727 // At this point, token != _, &, &&, (, [
3728 _ => if self.eat_keyword(keywords::Mut) {
3729 // Parse mut ident @ pat / mut ref ident @ pat
3730 let mutref_span = self.prev_span.to(self.span);
3731 let binding_mode = if self.eat_keyword(keywords::Ref) {
3733 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3734 .span_suggestion(mutref_span, "try switching the order", "ref mut".into())
3736 BindingMode::ByRef(Mutability::Mutable)
3738 BindingMode::ByValue(Mutability::Mutable)
3740 pat = self.parse_pat_ident(binding_mode)?;
3741 } else if self.eat_keyword(keywords::Ref) {
3742 // Parse ref ident @ pat / ref mut ident @ pat
3743 let mutbl = self.parse_mutability();
3744 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3745 } else if self.eat_keyword(keywords::Box) {
3747 let subpat = self.parse_pat()?;
3748 pat = PatKind::Box(subpat);
3749 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3750 self.parse_as_ident() {
3751 // Parse ident @ pat
3752 // This can give false positives and parse nullary enums,
3753 // they are dealt with later in resolve
3754 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3755 pat = self.parse_pat_ident(binding_mode)?;
3756 } else if self.token.is_path_start() {
3757 // Parse pattern starting with a path
3758 let (qself, path) = if self.eat_lt() {
3759 // Parse a qualified path
3760 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3763 // Parse an unqualified path
3764 (None, self.parse_path(PathStyle::Expr)?)
3767 token::Not if qself.is_none() => {
3768 // Parse macro invocation
3770 let (_, tts) = self.expect_delimited_token_tree()?;
3771 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3772 pat = PatKind::Mac(mac);
3774 token::DotDotDot | token::DotDotEq | token::DotDot => {
3775 let end_kind = match self.token {
3776 token::DotDot => RangeEnd::Excluded,
3777 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
3778 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
3779 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
3783 let span = lo.to(self.prev_span);
3784 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3786 let end = self.parse_pat_range_end()?;
3787 pat = PatKind::Range(begin, end, end_kind);
3789 token::OpenDelim(token::Brace) => {
3790 if qself.is_some() {
3791 return Err(self.fatal("unexpected `{` after qualified path"));
3793 // Parse struct pattern
3795 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3797 self.recover_stmt();
3801 pat = PatKind::Struct(path, fields, etc);
3803 token::OpenDelim(token::Paren) => {
3804 if qself.is_some() {
3805 return Err(self.fatal("unexpected `(` after qualified path"));
3807 // Parse tuple struct or enum pattern
3809 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3810 self.expect(&token::CloseDelim(token::Paren))?;
3811 pat = PatKind::TupleStruct(path, fields, ddpos)
3813 _ => pat = PatKind::Path(qself, path),
3816 // Try to parse everything else as literal with optional minus
3817 match self.parse_pat_literal_maybe_minus() {
3819 if self.eat(&token::DotDotDot) {
3820 let end = self.parse_pat_range_end()?;
3821 pat = PatKind::Range(begin, end,
3822 RangeEnd::Included(RangeSyntax::DotDotDot));
3823 } else if self.eat(&token::DotDotEq) {
3824 let end = self.parse_pat_range_end()?;
3825 pat = PatKind::Range(begin, end,
3826 RangeEnd::Included(RangeSyntax::DotDotEq));
3827 } else if self.eat(&token::DotDot) {
3828 let end = self.parse_pat_range_end()?;
3829 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3831 pat = PatKind::Lit(begin);
3835 self.cancel(&mut err);
3836 let msg = format!("expected pattern, found {}", self.this_token_descr());
3837 return Err(self.fatal(&msg));
3843 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
3844 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
3849 /// Parse ident or ident @ pat
3850 /// used by the copy foo and ref foo patterns to give a good
3851 /// error message when parsing mistakes like ref foo(a,b)
3852 fn parse_pat_ident(&mut self,
3853 binding_mode: ast::BindingMode)
3854 -> PResult<'a, PatKind> {
3855 let ident_span = self.span;
3856 let ident = self.parse_ident()?;
3857 let name = codemap::Spanned{span: ident_span, node: ident};
3858 let sub = if self.eat(&token::At) {
3859 Some(self.parse_pat()?)
3864 // just to be friendly, if they write something like
3866 // we end up here with ( as the current token. This shortly
3867 // leads to a parse error. Note that if there is no explicit
3868 // binding mode then we do not end up here, because the lookahead
3869 // will direct us over to parse_enum_variant()
3870 if self.token == token::OpenDelim(token::Paren) {
3871 return Err(self.span_fatal(
3873 "expected identifier, found enum pattern"))
3876 Ok(PatKind::Ident(binding_mode, name, sub))
3879 /// Parse a local variable declaration
3880 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3881 let lo = self.prev_span;
3882 let pat = self.parse_pat()?;
3884 let (err, ty) = if self.eat(&token::Colon) {
3885 // Save the state of the parser before parsing type normally, in case there is a `:`
3886 // instead of an `=` typo.
3887 let parser_snapshot_before_type = self.clone();
3888 let colon_sp = self.prev_span;
3889 match self.parse_ty() {
3890 Ok(ty) => (None, Some(ty)),
3892 // Rewind to before attempting to parse the type and continue parsing
3893 let parser_snapshot_after_type = self.clone();
3894 mem::replace(self, parser_snapshot_before_type);
3896 let snippet = self.sess.codemap().span_to_snippet(pat.span).unwrap();
3897 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
3898 (Some((parser_snapshot_after_type, colon_sp, err)), None)
3904 let init = match (self.parse_initializer(err.is_some()), err) {
3905 (Ok(init), None) => { // init parsed, ty parsed
3908 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
3909 // Could parse the type as if it were the initializer, it is likely there was a
3910 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
3911 err.span_suggestion_short(colon_sp,
3912 "use `=` if you meant to assign",
3915 // As this was parsed successfuly, continue as if the code has been fixed for the
3916 // rest of the file. It will still fail due to the emitted error, but we avoid
3920 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
3922 // Couldn't parse the type nor the initializer, only raise the type error and
3923 // return to the parser state before parsing the type as the initializer.
3924 // let x: <parse_error>;
3925 mem::replace(self, snapshot);
3928 (Err(err), None) => { // init error, ty parsed
3929 // Couldn't parse the initializer and we're not attempting to recover a failed
3930 // parse of the type, return the error.
3934 let hi = if self.token == token::Semi {
3943 id: ast::DUMMY_NODE_ID,
3949 /// Parse a structure field
3950 fn parse_name_and_ty(&mut self,
3953 attrs: Vec<Attribute>)
3954 -> PResult<'a, StructField> {
3955 let name = self.parse_ident()?;
3956 self.expect(&token::Colon)?;
3957 let ty = self.parse_ty()?;
3959 span: lo.to(self.prev_span),
3962 id: ast::DUMMY_NODE_ID,
3968 /// Emit an expected item after attributes error.
3969 fn expected_item_err(&self, attrs: &[Attribute]) {
3970 let message = match attrs.last() {
3971 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3972 _ => "expected item after attributes",
3975 self.span_err(self.prev_span, message);
3978 /// Parse a statement. This stops just before trailing semicolons on everything but items.
3979 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3980 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3981 Ok(self.parse_stmt_(true))
3984 // Eat tokens until we can be relatively sure we reached the end of the
3985 // statement. This is something of a best-effort heuristic.
3987 // We terminate when we find an unmatched `}` (without consuming it).
3988 fn recover_stmt(&mut self) {
3989 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
3992 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3993 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3994 // approximate - it can mean we break too early due to macros, but that
3995 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3997 // If `break_on_block` is `Break`, then we will stop consuming tokens
3998 // after finding (and consuming) a brace-delimited block.
3999 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4000 let mut brace_depth = 0;
4001 let mut bracket_depth = 0;
4002 let mut in_block = false;
4003 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4004 break_on_semi, break_on_block);
4006 debug!("recover_stmt_ loop {:?}", self.token);
4008 token::OpenDelim(token::DelimToken::Brace) => {
4011 if break_on_block == BlockMode::Break &&
4013 bracket_depth == 0 {
4017 token::OpenDelim(token::DelimToken::Bracket) => {
4021 token::CloseDelim(token::DelimToken::Brace) => {
4022 if brace_depth == 0 {
4023 debug!("recover_stmt_ return - close delim {:?}", self.token);
4028 if in_block && bracket_depth == 0 && brace_depth == 0 {
4029 debug!("recover_stmt_ return - block end {:?}", self.token);
4033 token::CloseDelim(token::DelimToken::Bracket) => {
4035 if bracket_depth < 0 {
4041 debug!("recover_stmt_ return - Eof");
4046 if break_on_semi == SemiColonMode::Break &&
4048 bracket_depth == 0 {
4049 debug!("recover_stmt_ return - Semi");
4060 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4061 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4063 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4068 fn is_catch_expr(&mut self) -> bool {
4069 self.token.is_keyword(keywords::Do) &&
4070 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4071 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4073 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
4074 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4077 fn is_union_item(&self) -> bool {
4078 self.token.is_keyword(keywords::Union) &&
4079 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4082 fn is_crate_vis(&self) -> bool {
4083 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4086 fn is_extern_non_path(&self) -> bool {
4087 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4090 fn is_auto_trait_item(&mut self) -> bool {
4092 (self.token.is_keyword(keywords::Auto)
4093 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4094 || // unsafe auto trait
4095 (self.token.is_keyword(keywords::Unsafe) &&
4096 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4097 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4100 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4101 -> PResult<'a, Option<P<Item>>> {
4102 let token_lo = self.span;
4103 let (ident, def) = match self.token {
4104 token::Ident(ident) if ident.name == keywords::Macro.name() => {
4106 let ident = self.parse_ident()?;
4107 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4108 match self.parse_token_tree() {
4109 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4110 _ => unreachable!(),
4112 } else if self.check(&token::OpenDelim(token::Paren)) {
4113 let args = self.parse_token_tree();
4114 let body = if self.check(&token::OpenDelim(token::Brace)) {
4115 self.parse_token_tree()
4120 TokenStream::concat(vec![
4122 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4130 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4132 token::Ident(ident) if ident.name == "macro_rules" &&
4133 self.look_ahead(1, |t| *t == token::Not) => {
4134 let prev_span = self.prev_span;
4135 self.complain_if_pub_macro(vis, prev_span);
4139 let ident = self.parse_ident()?;
4140 let (delim, tokens) = self.expect_delimited_token_tree()?;
4141 if delim != token::Brace {
4142 if !self.eat(&token::Semi) {
4143 let msg = "macros that expand to items must either \
4144 be surrounded with braces or followed by a semicolon";
4145 self.span_err(self.prev_span, msg);
4149 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4151 _ => return Ok(None),
4154 let span = lo.to(self.prev_span);
4155 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4158 fn parse_stmt_without_recovery(&mut self,
4159 macro_legacy_warnings: bool)
4160 -> PResult<'a, Option<Stmt>> {
4161 maybe_whole!(self, NtStmt, |x| Some(x));
4163 let attrs = self.parse_outer_attributes()?;
4166 Ok(Some(if self.eat_keyword(keywords::Let) {
4168 id: ast::DUMMY_NODE_ID,
4169 node: StmtKind::Local(self.parse_local(attrs.into())?),
4170 span: lo.to(self.prev_span),
4172 } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited, lo)? {
4174 id: ast::DUMMY_NODE_ID,
4175 node: StmtKind::Item(macro_def),
4176 span: lo.to(self.prev_span),
4178 // Starts like a simple path, being careful to avoid contextual keywords
4179 // such as a union items, item with `crate` visibility or auto trait items.
4180 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4181 // like a path (1 token), but it fact not a path.
4182 // `union::b::c` - path, `union U { ... }` - not a path.
4183 // `crate::b::c` - path, `crate struct S;` - not a path.
4184 // `extern::b::c` - path, `extern crate c;` - not a path.
4185 } else if self.token.is_path_start() &&
4186 !self.token.is_qpath_start() &&
4187 !self.is_union_item() &&
4188 !self.is_crate_vis() &&
4189 !self.is_extern_non_path() &&
4190 !self.is_auto_trait_item() {
4191 let pth = self.parse_path(PathStyle::Expr)?;
4193 if !self.eat(&token::Not) {
4194 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4195 self.parse_struct_expr(lo, pth, ThinVec::new())?
4197 let hi = self.prev_span;
4198 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4201 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4202 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4203 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4206 return Ok(Some(Stmt {
4207 id: ast::DUMMY_NODE_ID,
4208 node: StmtKind::Expr(expr),
4209 span: lo.to(self.prev_span),
4213 // it's a macro invocation
4214 let id = match self.token {
4215 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4216 _ => self.parse_ident()?,
4219 // check that we're pointing at delimiters (need to check
4220 // again after the `if`, because of `parse_ident`
4221 // consuming more tokens).
4222 let delim = match self.token {
4223 token::OpenDelim(delim) => delim,
4225 // we only expect an ident if we didn't parse one
4227 let ident_str = if id.name == keywords::Invalid.name() {
4232 let tok_str = self.this_token_to_string();
4233 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4239 let (_, tts) = self.expect_delimited_token_tree()?;
4240 let hi = self.prev_span;
4242 let style = if delim == token::Brace {
4243 MacStmtStyle::Braces
4245 MacStmtStyle::NoBraces
4248 if id.name == keywords::Invalid.name() {
4249 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
4250 let node = if delim == token::Brace ||
4251 self.token == token::Semi || self.token == token::Eof {
4252 StmtKind::Mac(P((mac, style, attrs.into())))
4254 // We used to incorrectly stop parsing macro-expanded statements here.
4255 // If the next token will be an error anyway but could have parsed with the
4256 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4257 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4258 // These can continue an expression, so we can't stop parsing and warn.
4259 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4260 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4261 token::BinOp(token::And) | token::BinOp(token::Or) |
4262 token::AndAnd | token::OrOr |
4263 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4266 self.warn_missing_semicolon();
4267 StmtKind::Mac(P((mac, style, attrs.into())))
4269 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4270 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4271 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4275 id: ast::DUMMY_NODE_ID,
4280 // if it has a special ident, it's definitely an item
4282 // Require a semicolon or braces.
4283 if style != MacStmtStyle::Braces {
4284 if !self.eat(&token::Semi) {
4285 self.span_err(self.prev_span,
4286 "macros that expand to items must \
4287 either be surrounded with braces or \
4288 followed by a semicolon");
4291 let span = lo.to(hi);
4293 id: ast::DUMMY_NODE_ID,
4295 node: StmtKind::Item({
4297 span, id /*id is good here*/,
4298 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
4299 Visibility::Inherited,
4305 // FIXME: Bad copy of attrs
4306 let old_directory_ownership =
4307 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4308 let item = self.parse_item_(attrs.clone(), false, true)?;
4309 self.directory.ownership = old_directory_ownership;
4313 id: ast::DUMMY_NODE_ID,
4314 span: lo.to(i.span),
4315 node: StmtKind::Item(i),
4318 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4319 if !attrs.is_empty() {
4320 if s.prev_token_kind == PrevTokenKind::DocComment {
4321 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4322 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4323 s.span_err(s.span, "expected statement after outer attribute");
4328 // Do not attempt to parse an expression if we're done here.
4329 if self.token == token::Semi {
4330 unused_attrs(&attrs, self);
4335 if self.token == token::CloseDelim(token::Brace) {
4336 unused_attrs(&attrs, self);
4340 // Remainder are line-expr stmts.
4341 let e = self.parse_expr_res(
4342 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4344 id: ast::DUMMY_NODE_ID,
4345 span: lo.to(e.span),
4346 node: StmtKind::Expr(e),
4353 /// Is this expression a successfully-parsed statement?
4354 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4355 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4356 !classify::expr_requires_semi_to_be_stmt(e)
4359 /// Parse a block. No inner attrs are allowed.
4360 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4361 maybe_whole!(self, NtBlock, |x| x);
4365 if !self.eat(&token::OpenDelim(token::Brace)) {
4367 let tok = self.this_token_to_string();
4368 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4370 // Check to see if the user has written something like
4375 // Which is valid in other languages, but not Rust.
4376 match self.parse_stmt_without_recovery(false) {
4378 let mut stmt_span = stmt.span;
4379 // expand the span to include the semicolon, if it exists
4380 if self.eat(&token::Semi) {
4381 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4383 let sugg = pprust::to_string(|s| {
4384 use print::pprust::{PrintState, INDENT_UNIT};
4385 s.ibox(INDENT_UNIT)?;
4387 s.print_stmt(&stmt)?;
4388 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4390 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4393 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4394 self.cancel(&mut e);
4401 self.parse_block_tail(lo, BlockCheckMode::Default)
4404 /// Parse a block. Inner attrs are allowed.
4405 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4406 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4409 self.expect(&token::OpenDelim(token::Brace))?;
4410 Ok((self.parse_inner_attributes()?,
4411 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4414 /// Parse the rest of a block expression or function body
4415 /// Precondition: already parsed the '{'.
4416 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4417 let mut stmts = vec![];
4418 let mut recovered = false;
4420 while !self.eat(&token::CloseDelim(token::Brace)) {
4421 let stmt = match self.parse_full_stmt(false) {
4424 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4425 self.eat(&token::CloseDelim(token::Brace));
4431 if let Some(stmt) = stmt {
4433 } else if self.token == token::Eof {
4436 // Found only `;` or `}`.
4442 id: ast::DUMMY_NODE_ID,
4444 span: lo.to(self.prev_span),
4449 /// Parse a statement, including the trailing semicolon.
4450 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4451 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4453 None => return Ok(None),
4457 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4458 // expression without semicolon
4459 if classify::expr_requires_semi_to_be_stmt(expr) {
4460 // Just check for errors and recover; do not eat semicolon yet.
4462 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4465 self.recover_stmt();
4469 StmtKind::Local(..) => {
4470 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4471 if macro_legacy_warnings && self.token != token::Semi {
4472 self.warn_missing_semicolon();
4474 self.expect_one_of(&[token::Semi], &[])?;
4480 if self.eat(&token::Semi) {
4481 stmt = stmt.add_trailing_semicolon();
4484 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4488 fn warn_missing_semicolon(&self) {
4489 self.diagnostic().struct_span_warn(self.span, {
4490 &format!("expected `;`, found `{}`", self.this_token_to_string())
4492 "This was erroneously allowed and will become a hard error in a future release"
4496 fn err_dotdotdot_syntax(&self, span: Span) {
4497 self.diagnostic().struct_span_err(span, {
4498 "`...` syntax cannot be used in expressions"
4500 "Use `..` if you need an exclusive range (a < b)"
4502 "or `..=` if you need an inclusive range (a <= b)"
4506 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4507 // BOUND = TY_BOUND | LT_BOUND
4508 // LT_BOUND = LIFETIME (e.g. `'a`)
4509 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4510 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4511 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4512 let mut bounds = Vec::new();
4514 // This needs to be syncronized with `Token::can_begin_bound`.
4515 let is_bound_start = self.check_path() || self.check_lifetime() ||
4516 self.check(&token::Question) ||
4517 self.check_keyword(keywords::For) ||
4518 self.check(&token::OpenDelim(token::Paren));
4520 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4521 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4522 if self.token.is_lifetime() {
4523 if let Some(question_span) = question {
4524 self.span_err(question_span,
4525 "`?` may only modify trait bounds, not lifetime bounds");
4527 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4530 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4531 let path = self.parse_path(PathStyle::Type)?;
4532 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4533 let modifier = if question.is_some() {
4534 TraitBoundModifier::Maybe
4536 TraitBoundModifier::None
4538 bounds.push(TraitTyParamBound(poly_trait, modifier));
4541 self.expect(&token::CloseDelim(token::Paren))?;
4542 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4543 self.span_err(self.prev_span,
4544 "parenthesized lifetime bounds are not supported");
4551 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4559 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4560 self.parse_ty_param_bounds_common(true)
4563 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4564 // BOUND = LT_BOUND (e.g. `'a`)
4565 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4566 let mut lifetimes = Vec::new();
4567 while self.check_lifetime() {
4568 lifetimes.push(self.expect_lifetime());
4570 if !self.eat(&token::BinOp(token::Plus)) {
4577 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4578 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4579 let span = self.span;
4580 let ident = self.parse_ident()?;
4582 // Parse optional colon and param bounds.
4583 let bounds = if self.eat(&token::Colon) {
4584 self.parse_ty_param_bounds()?
4589 let default = if self.eat(&token::Eq) {
4590 Some(self.parse_ty()?)
4596 attrs: preceding_attrs.into(),
4598 id: ast::DUMMY_NODE_ID,
4605 /// Parses the following grammar:
4606 /// TraitItemAssocTy = Ident ["<"...">"] [":" [TyParamBounds]] ["where" ...] ["=" Ty]
4607 fn parse_trait_item_assoc_ty(&mut self, preceding_attrs: Vec<Attribute>)
4608 -> PResult<'a, (ast::Generics, TyParam)> {
4609 let span = self.span;
4610 let ident = self.parse_ident()?;
4611 let mut generics = self.parse_generics()?;
4613 // Parse optional colon and param bounds.
4614 let bounds = if self.eat(&token::Colon) {
4615 self.parse_ty_param_bounds()?
4619 generics.where_clause = self.parse_where_clause()?;
4621 let default = if self.eat(&token::Eq) {
4622 Some(self.parse_ty()?)
4626 self.expect(&token::Semi)?;
4628 Ok((generics, TyParam {
4629 attrs: preceding_attrs.into(),
4631 id: ast::DUMMY_NODE_ID,
4638 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4639 /// trailing comma and erroneous trailing attributes.
4640 pub fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4641 let mut params = Vec::new();
4642 let mut seen_ty_param = false;
4644 let attrs = self.parse_outer_attributes()?;
4645 if self.check_lifetime() {
4646 let lifetime = self.expect_lifetime();
4647 // Parse lifetime parameter.
4648 let bounds = if self.eat(&token::Colon) {
4649 self.parse_lt_param_bounds()
4653 params.push(ast::GenericParam::Lifetime(LifetimeDef {
4654 attrs: attrs.into(),
4659 self.span_err(self.prev_span,
4660 "lifetime parameters must be declared prior to type parameters");
4662 } else if self.check_ident() {
4663 // Parse type parameter.
4664 params.push(ast::GenericParam::Type(self.parse_ty_param(attrs)?));
4665 seen_ty_param = true;
4667 // Check for trailing attributes and stop parsing.
4668 if !attrs.is_empty() {
4669 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4670 self.span_err(attrs[0].span,
4671 &format!("trailing attribute after {} parameters", param_kind));
4676 if !self.eat(&token::Comma) {
4683 /// Parse a set of optional generic type parameter declarations. Where
4684 /// clauses are not parsed here, and must be added later via
4685 /// `parse_where_clause()`.
4687 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4688 /// | ( < lifetimes , typaramseq ( , )? > )
4689 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4690 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4691 maybe_whole!(self, NtGenerics, |x| x);
4693 let span_lo = self.span;
4695 let params = self.parse_generic_params()?;
4699 where_clause: WhereClause {
4700 id: ast::DUMMY_NODE_ID,
4701 predicates: Vec::new(),
4702 span: syntax_pos::DUMMY_SP,
4704 span: span_lo.to(self.prev_span),
4707 Ok(ast::Generics::default())
4711 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4712 /// possibly including trailing comma.
4713 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4714 let mut lifetimes = Vec::new();
4715 let mut types = Vec::new();
4716 let mut bindings = Vec::new();
4717 let mut seen_type = false;
4718 let mut seen_binding = false;
4720 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4721 // Parse lifetime argument.
4722 lifetimes.push(self.expect_lifetime());
4723 if seen_type || seen_binding {
4724 self.span_err(self.prev_span,
4725 "lifetime parameters must be declared prior to type parameters");
4727 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4728 // Parse associated type binding.
4730 let ident = self.parse_ident()?;
4732 let ty = self.parse_ty()?;
4733 bindings.push(TypeBinding {
4734 id: ast::DUMMY_NODE_ID,
4737 span: lo.to(self.prev_span),
4739 seen_binding = true;
4740 } else if self.check_type() {
4741 // Parse type argument.
4742 types.push(self.parse_ty()?);
4744 self.span_err(types[types.len() - 1].span,
4745 "type parameters must be declared prior to associated type bindings");
4752 if !self.eat(&token::Comma) {
4756 Ok((lifetimes, types, bindings))
4759 /// Parses an optional `where` clause and places it in `generics`.
4761 /// ```ignore (only-for-syntax-highlight)
4762 /// where T : Trait<U, V> + 'b, 'a : 'b
4764 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4765 maybe_whole!(self, NtWhereClause, |x| x);
4767 let mut where_clause = WhereClause {
4768 id: ast::DUMMY_NODE_ID,
4769 predicates: Vec::new(),
4770 span: syntax_pos::DUMMY_SP,
4773 if !self.eat_keyword(keywords::Where) {
4774 return Ok(where_clause);
4776 let lo = self.prev_span;
4778 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4779 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4780 // change we parse those generics now, but report an error.
4781 if self.choose_generics_over_qpath() {
4782 let generics = self.parse_generics()?;
4783 self.span_err(generics.span,
4784 "generic parameters on `where` clauses are reserved for future use");
4789 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4790 let lifetime = self.expect_lifetime();
4791 // Bounds starting with a colon are mandatory, but possibly empty.
4792 self.expect(&token::Colon)?;
4793 let bounds = self.parse_lt_param_bounds();
4794 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4795 ast::WhereRegionPredicate {
4796 span: lo.to(self.prev_span),
4801 } else if self.check_type() {
4802 // Parse optional `for<'a, 'b>`.
4803 // This `for` is parsed greedily and applies to the whole predicate,
4804 // the bounded type can have its own `for` applying only to it.
4805 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4806 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4807 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4808 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4810 // Parse type with mandatory colon and (possibly empty) bounds,
4811 // or with mandatory equality sign and the second type.
4812 let ty = self.parse_ty()?;
4813 if self.eat(&token::Colon) {
4814 let bounds = self.parse_ty_param_bounds()?;
4815 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4816 ast::WhereBoundPredicate {
4817 span: lo.to(self.prev_span),
4818 bound_generic_params: lifetime_defs,
4823 // FIXME: Decide what should be used here, `=` or `==`.
4824 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4825 let rhs_ty = self.parse_ty()?;
4826 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4827 ast::WhereEqPredicate {
4828 span: lo.to(self.prev_span),
4831 id: ast::DUMMY_NODE_ID,
4835 return self.unexpected();
4841 if !self.eat(&token::Comma) {
4846 where_clause.span = lo.to(self.prev_span);
4850 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4851 -> PResult<'a, (Vec<Arg> , bool)> {
4853 let mut variadic = false;
4854 let args: Vec<Option<Arg>> =
4855 self.parse_unspanned_seq(
4856 &token::OpenDelim(token::Paren),
4857 &token::CloseDelim(token::Paren),
4858 SeqSep::trailing_allowed(token::Comma),
4860 if p.token == token::DotDotDot {
4863 if p.token != token::CloseDelim(token::Paren) {
4866 "`...` must be last in argument list for variadic function");
4871 "only foreign functions are allowed to be variadic");
4876 match p.parse_arg_general(named_args) {
4877 Ok(arg) => Ok(Some(arg)),
4880 let lo = p.prev_span;
4881 // Skip every token until next possible arg or end.
4882 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4883 // Create a placeholder argument for proper arg count (#34264).
4884 let span = lo.to(p.prev_span);
4885 Ok(Some(dummy_arg(span)))
4892 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4894 if variadic && args.is_empty() {
4896 "variadic function must be declared with at least one named argument");
4899 Ok((args, variadic))
4902 /// Parse the argument list and result type of a function declaration
4903 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4905 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4906 let ret_ty = self.parse_ret_ty(true)?;
4915 /// Returns the parsed optional self argument and whether a self shortcut was used.
4916 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4917 let expect_ident = |this: &mut Self| match this.token {
4918 // Preserve hygienic context.
4919 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4922 let isolated_self = |this: &mut Self, n| {
4923 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4924 this.look_ahead(n + 1, |t| t != &token::ModSep)
4927 // Parse optional self parameter of a method.
4928 // Only a limited set of initial token sequences is considered self parameters, anything
4929 // else is parsed as a normal function parameter list, so some lookahead is required.
4930 let eself_lo = self.span;
4931 let (eself, eself_ident) = match self.token {
4932 token::BinOp(token::And) => {
4938 if isolated_self(self, 1) {
4940 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4941 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4942 isolated_self(self, 2) {
4945 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4946 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4947 isolated_self(self, 2) {
4949 let lt = self.expect_lifetime();
4950 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4951 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4952 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4953 isolated_self(self, 3) {
4955 let lt = self.expect_lifetime();
4957 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4962 token::BinOp(token::Star) => {
4967 // Emit special error for `self` cases.
4968 if isolated_self(self, 1) {
4970 self.span_err(self.span, "cannot pass `self` by raw pointer");
4971 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4972 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4973 isolated_self(self, 2) {
4976 self.span_err(self.span, "cannot pass `self` by raw pointer");
4977 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4982 token::Ident(..) => {
4983 if isolated_self(self, 0) {
4986 let eself_ident = expect_ident(self);
4987 if self.eat(&token::Colon) {
4988 let ty = self.parse_ty()?;
4989 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4991 (SelfKind::Value(Mutability::Immutable), eself_ident)
4993 } else if self.token.is_keyword(keywords::Mut) &&
4994 isolated_self(self, 1) {
4998 let eself_ident = expect_ident(self);
4999 if self.eat(&token::Colon) {
5000 let ty = self.parse_ty()?;
5001 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
5003 (SelfKind::Value(Mutability::Mutable), eself_ident)
5009 _ => return Ok(None),
5012 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
5013 Ok(Some(Arg::from_self(eself, eself_ident)))
5016 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5017 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5018 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5020 self.expect(&token::OpenDelim(token::Paren))?;
5022 // Parse optional self argument
5023 let self_arg = self.parse_self_arg()?;
5025 // Parse the rest of the function parameter list.
5026 let sep = SeqSep::trailing_allowed(token::Comma);
5027 let fn_inputs = if let Some(self_arg) = self_arg {
5028 if self.check(&token::CloseDelim(token::Paren)) {
5030 } else if self.eat(&token::Comma) {
5031 let mut fn_inputs = vec![self_arg];
5032 fn_inputs.append(&mut self.parse_seq_to_before_end(
5033 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5037 return self.unexpected();
5040 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5043 // Parse closing paren and return type.
5044 self.expect(&token::CloseDelim(token::Paren))?;
5047 output: self.parse_ret_ty(true)?,
5052 // parse the |arg, arg| header on a lambda
5053 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5054 let inputs_captures = {
5055 if self.eat(&token::OrOr) {
5058 self.expect(&token::BinOp(token::Or))?;
5059 let args = self.parse_seq_to_before_tokens(
5060 &[&token::BinOp(token::Or), &token::OrOr],
5061 SeqSep::trailing_allowed(token::Comma),
5062 TokenExpectType::NoExpect,
5063 |p| p.parse_fn_block_arg()
5069 let output = self.parse_ret_ty(true)?;
5072 inputs: inputs_captures,
5078 /// Parse the name and optional generic types of a function header.
5079 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5080 let id = self.parse_ident()?;
5081 let generics = self.parse_generics()?;
5085 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5086 attrs: Vec<Attribute>) -> P<Item> {
5090 id: ast::DUMMY_NODE_ID,
5098 /// Parse an item-position function declaration.
5099 fn parse_item_fn(&mut self,
5101 constness: Spanned<Constness>,
5103 -> PResult<'a, ItemInfo> {
5104 let (ident, mut generics) = self.parse_fn_header()?;
5105 let decl = self.parse_fn_decl(false)?;
5106 generics.where_clause = self.parse_where_clause()?;
5107 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5108 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
5111 /// true if we are looking at `const ID`, false for things like `const fn` etc
5112 pub fn is_const_item(&mut self) -> bool {
5113 self.token.is_keyword(keywords::Const) &&
5114 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5115 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5118 /// parses all the "front matter" for a `fn` declaration, up to
5119 /// and including the `fn` keyword:
5123 /// - `const unsafe fn`
5126 pub fn parse_fn_front_matter(&mut self) -> PResult<'a, (Spanned<Constness>, Unsafety, Abi)> {
5127 let is_const_fn = self.eat_keyword(keywords::Const);
5128 let const_span = self.prev_span;
5129 let unsafety = self.parse_unsafety();
5130 let (constness, unsafety, abi) = if is_const_fn {
5131 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5133 let abi = if self.eat_keyword(keywords::Extern) {
5134 self.parse_opt_abi()?.unwrap_or(Abi::C)
5138 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5140 self.expect_keyword(keywords::Fn)?;
5141 Ok((constness, unsafety, abi))
5144 /// Parse an impl item.
5145 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5146 maybe_whole!(self, NtImplItem, |x| x);
5147 let attrs = self.parse_outer_attributes()?;
5148 let (mut item, tokens) = self.collect_tokens(|this| {
5149 this.parse_impl_item_(at_end, attrs)
5152 // See `parse_item` for why this clause is here.
5153 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5154 item.tokens = Some(tokens);
5159 fn parse_impl_item_(&mut self,
5161 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5163 let vis = self.parse_visibility(false)?;
5164 let defaultness = self.parse_defaultness();
5165 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
5166 // This parses the grammar:
5167 // ImplItemAssocTy = Ident ["<"...">"] ["where" ...] "=" Ty ";"
5168 let name = self.parse_ident()?;
5169 let mut generics = self.parse_generics()?;
5170 generics.where_clause = self.parse_where_clause()?;
5171 self.expect(&token::Eq)?;
5172 let typ = self.parse_ty()?;
5173 self.expect(&token::Semi)?;
5174 (name, ast::ImplItemKind::Type(typ), generics)
5175 } else if self.is_const_item() {
5176 // This parses the grammar:
5177 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5178 self.expect_keyword(keywords::Const)?;
5179 let name = self.parse_ident()?;
5180 self.expect(&token::Colon)?;
5181 let typ = self.parse_ty()?;
5182 self.expect(&token::Eq)?;
5183 let expr = self.parse_expr()?;
5184 self.expect(&token::Semi)?;
5185 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5187 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5188 attrs.extend(inner_attrs);
5189 (name, node, generics)
5193 id: ast::DUMMY_NODE_ID,
5194 span: lo.to(self.prev_span),
5205 fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
5206 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5211 fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
5213 Visibility::Inherited => Ok(()),
5215 let is_macro_rules: bool = match self.token {
5216 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
5220 let mut err = self.diagnostic()
5221 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5222 err.help("did you mean #[macro_export]?");
5225 let mut err = self.diagnostic()
5226 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5227 err.help("try adjusting the macro to put `pub` inside the invocation");
5234 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5235 -> DiagnosticBuilder<'a>
5237 // Given this code `path(`, it seems like this is not
5238 // setting the visibility of a macro invocation, but rather
5239 // a mistyped method declaration.
5240 // Create a diagnostic pointing out that `fn` is missing.
5242 // x | pub path(&self) {
5243 // | ^ missing `fn`, `type`, or `const`
5245 // ^^ `sp` below will point to this
5246 let sp = prev_span.between(self.prev_span);
5247 let mut err = self.diagnostic().struct_span_err(
5249 &format!("missing `fn`, `type`, or `const` for {}-item declaration",
5251 err.span_label(sp, "missing `fn`, `type`, or `const`");
5255 /// Parse a method or a macro invocation in a trait impl.
5256 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5257 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5258 ast::ImplItemKind)> {
5259 // code copied from parse_macro_use_or_failure... abstraction!
5260 if self.token.is_path_start() && !self.is_extern_non_path() {
5263 let prev_span = self.prev_span;
5266 let pth = self.parse_path(PathStyle::Mod)?;
5267 if pth.segments.len() == 1 {
5268 if !self.eat(&token::Not) {
5269 return Err(self.missing_assoc_item_kind_err("impl", prev_span));
5272 self.expect(&token::Not)?;
5275 self.complain_if_pub_macro(vis, prev_span);
5277 // eat a matched-delimiter token tree:
5279 let (delim, tts) = self.expect_delimited_token_tree()?;
5280 if delim != token::Brace {
5281 self.expect(&token::Semi)?
5284 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
5285 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5286 ast::ImplItemKind::Macro(mac)))
5288 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
5289 let ident = self.parse_ident()?;
5290 let mut generics = self.parse_generics()?;
5291 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5292 generics.where_clause = self.parse_where_clause()?;
5294 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5295 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(ast::MethodSig {
5304 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5305 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5306 let ident = self.parse_ident()?;
5307 let mut tps = self.parse_generics()?;
5309 // Parse optional colon and supertrait bounds.
5310 let bounds = if self.eat(&token::Colon) {
5311 self.parse_ty_param_bounds()?
5316 if self.eat(&token::Eq) {
5317 // it's a trait alias
5318 let bounds = self.parse_ty_param_bounds()?;
5319 tps.where_clause = self.parse_where_clause()?;
5320 self.expect(&token::Semi)?;
5321 if unsafety != Unsafety::Normal {
5322 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5324 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5326 // it's a normal trait
5327 tps.where_clause = self.parse_where_clause()?;
5328 self.expect(&token::OpenDelim(token::Brace))?;
5329 let mut trait_items = vec![];
5330 while !self.eat(&token::CloseDelim(token::Brace)) {
5331 let mut at_end = false;
5332 match self.parse_trait_item(&mut at_end) {
5333 Ok(item) => trait_items.push(item),
5337 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5342 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5346 fn choose_generics_over_qpath(&self) -> bool {
5347 // There's an ambiguity between generic parameters and qualified paths in impls.
5348 // If we see `<` it may start both, so we have to inspect some following tokens.
5349 // The following combinations can only start generics,
5350 // but not qualified paths (with one exception):
5351 // `<` `>` - empty generic parameters
5352 // `<` `#` - generic parameters with attributes
5353 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5354 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5355 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5356 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5357 // The only truly ambiguous case is
5358 // `<` IDENT `>` `::` IDENT ...
5359 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5360 // because this is what almost always expected in practice, qualified paths in impls
5361 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5362 self.token == token::Lt &&
5363 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5364 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5365 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5366 t == &token::Colon || t == &token::Eq))
5369 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5370 self.expect(&token::OpenDelim(token::Brace))?;
5371 let attrs = self.parse_inner_attributes()?;
5373 let mut impl_items = Vec::new();
5374 while !self.eat(&token::CloseDelim(token::Brace)) {
5375 let mut at_end = false;
5376 match self.parse_impl_item(&mut at_end) {
5377 Ok(impl_item) => impl_items.push(impl_item),
5381 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5386 Ok((impl_items, attrs))
5389 /// Parses an implementation item, `impl` keyword is already parsed.
5390 /// impl<'a, T> TYPE { /* impl items */ }
5391 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5392 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5393 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5394 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5395 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5396 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5397 -> PResult<'a, ItemInfo> {
5398 // First, parse generic parameters if necessary.
5399 let mut generics = if self.choose_generics_over_qpath() {
5400 self.parse_generics()?
5402 ast::Generics::default()
5405 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5406 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5408 ast::ImplPolarity::Negative
5410 ast::ImplPolarity::Positive
5413 // Parse both types and traits as a type, then reinterpret if necessary.
5414 let ty_first = self.parse_ty()?;
5416 // If `for` is missing we try to recover.
5417 let has_for = self.eat_keyword(keywords::For);
5418 let missing_for_span = self.prev_span.between(self.span);
5420 let ty_second = if self.token == token::DotDot {
5421 // We need to report this error after `cfg` expansion for compatibility reasons
5422 self.bump(); // `..`, do not add it to expected tokens
5423 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5424 } else if has_for || self.token.can_begin_type() {
5425 Some(self.parse_ty()?)
5430 generics.where_clause = self.parse_where_clause()?;
5432 let (impl_items, attrs) = self.parse_impl_body()?;
5434 let item_kind = match ty_second {
5435 Some(ty_second) => {
5436 // impl Trait for Type
5438 self.span_err(missing_for_span, "missing `for` in a trait impl");
5441 let ty_first = ty_first.into_inner();
5442 let path = match ty_first.node {
5443 // This notably includes paths passed through `ty` macro fragments (#46438).
5444 TyKind::Path(None, path) => path,
5446 self.span_err(ty_first.span, "expected a trait, found type");
5447 ast::Path::from_ident(ty_first.span, keywords::Invalid.ident())
5450 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5452 ItemKind::Impl(unsafety, polarity, defaultness,
5453 generics, Some(trait_ref), ty_second, impl_items)
5457 ItemKind::Impl(unsafety, polarity, defaultness,
5458 generics, None, ty_first, impl_items)
5462 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5465 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5466 if self.eat_keyword(keywords::For) {
5468 let params = self.parse_generic_params()?;
5471 let first_non_lifetime_param_span = params.iter()
5472 .filter_map(|param| match *param {
5473 ast::GenericParam::Lifetime(_) => None,
5474 ast::GenericParam::Type(ref t) => Some(t.span),
5478 if let Some(span) = first_non_lifetime_param_span {
5479 self.span_err(span, "only lifetime parameters can be used in this context");
5488 /// Parse struct Foo { ... }
5489 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5490 let class_name = self.parse_ident()?;
5492 let mut generics = self.parse_generics()?;
5494 // There is a special case worth noting here, as reported in issue #17904.
5495 // If we are parsing a tuple struct it is the case that the where clause
5496 // should follow the field list. Like so:
5498 // struct Foo<T>(T) where T: Copy;
5500 // If we are parsing a normal record-style struct it is the case
5501 // that the where clause comes before the body, and after the generics.
5502 // So if we look ahead and see a brace or a where-clause we begin
5503 // parsing a record style struct.
5505 // Otherwise if we look ahead and see a paren we parse a tuple-style
5508 let vdata = if self.token.is_keyword(keywords::Where) {
5509 generics.where_clause = self.parse_where_clause()?;
5510 if self.eat(&token::Semi) {
5511 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5512 VariantData::Unit(ast::DUMMY_NODE_ID)
5514 // If we see: `struct Foo<T> where T: Copy { ... }`
5515 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5517 // No `where` so: `struct Foo<T>;`
5518 } else if self.eat(&token::Semi) {
5519 VariantData::Unit(ast::DUMMY_NODE_ID)
5520 // Record-style struct definition
5521 } else if self.token == token::OpenDelim(token::Brace) {
5522 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5523 // Tuple-style struct definition with optional where-clause.
5524 } else if self.token == token::OpenDelim(token::Paren) {
5525 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5526 generics.where_clause = self.parse_where_clause()?;
5527 self.expect(&token::Semi)?;
5530 let token_str = self.this_token_to_string();
5531 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5532 name, found `{}`", token_str)))
5535 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5538 /// Parse union Foo { ... }
5539 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5540 let class_name = self.parse_ident()?;
5542 let mut generics = self.parse_generics()?;
5544 let vdata = if self.token.is_keyword(keywords::Where) {
5545 generics.where_clause = self.parse_where_clause()?;
5546 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5547 } else if self.token == token::OpenDelim(token::Brace) {
5548 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5550 let token_str = self.this_token_to_string();
5551 return Err(self.fatal(&format!("expected `where` or `{{` after union \
5552 name, found `{}`", token_str)))
5555 Ok((class_name, ItemKind::Union(vdata, generics), None))
5558 fn consume_block(&mut self, delim: token::DelimToken) {
5559 let mut brace_depth = 0;
5560 if !self.eat(&token::OpenDelim(delim)) {
5564 if self.eat(&token::OpenDelim(delim)) {
5566 } else if self.eat(&token::CloseDelim(delim)) {
5567 if brace_depth == 0 {
5573 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5581 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5582 let mut fields = Vec::new();
5583 if self.eat(&token::OpenDelim(token::Brace)) {
5584 while self.token != token::CloseDelim(token::Brace) {
5585 let field = self.parse_struct_decl_field().map_err(|e| {
5586 self.recover_stmt();
5590 Ok(field) => fields.push(field),
5596 self.eat(&token::CloseDelim(token::Brace));
5598 let token_str = self.this_token_to_string();
5599 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5607 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5608 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5609 // Unit like structs are handled in parse_item_struct function
5610 let fields = self.parse_unspanned_seq(
5611 &token::OpenDelim(token::Paren),
5612 &token::CloseDelim(token::Paren),
5613 SeqSep::trailing_allowed(token::Comma),
5615 let attrs = p.parse_outer_attributes()?;
5617 let vis = p.parse_visibility(true)?;
5618 let ty = p.parse_ty()?;
5620 span: lo.to(p.span),
5623 id: ast::DUMMY_NODE_ID,
5632 /// Parse a structure field declaration
5633 pub fn parse_single_struct_field(&mut self,
5636 attrs: Vec<Attribute> )
5637 -> PResult<'a, StructField> {
5638 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5643 token::CloseDelim(token::Brace) => {}
5644 token::DocComment(_) => {
5645 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
5646 self.bump(); // consume the doc comment
5647 if self.eat(&token::Comma) || self.token == token::CloseDelim(token::Brace) {
5653 _ => return Err(self.span_fatal_help(self.span,
5654 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5655 "struct fields should be separated by commas")),
5660 /// Parse an element of a struct definition
5661 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5662 let attrs = self.parse_outer_attributes()?;
5664 let vis = self.parse_visibility(false)?;
5665 self.parse_single_struct_field(lo, vis, attrs)
5668 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5669 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5670 /// a function definition, it's not a tuple struct field) and the contents within the parens
5671 /// isn't valid, emit a proper diagnostic.
5672 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5673 maybe_whole!(self, NtVis, |x| x);
5675 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
5676 if self.is_crate_vis() {
5677 self.bump(); // `crate`
5678 return Ok(Visibility::Crate(self.prev_span, CrateSugar::JustCrate));
5681 if !self.eat_keyword(keywords::Pub) {
5682 return Ok(Visibility::Inherited)
5685 if self.check(&token::OpenDelim(token::Paren)) {
5686 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5687 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5688 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5689 // by the following tokens.
5690 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5693 self.bump(); // `crate`
5694 let vis = Visibility::Crate(self.prev_span, CrateSugar::PubCrate);
5695 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5697 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5700 self.bump(); // `in`
5701 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5702 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5703 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5705 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5706 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5707 t.is_keyword(keywords::SelfValue)) {
5708 // `pub(self)` or `pub(super)`
5710 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5711 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5712 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5714 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5715 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5717 let msg = "incorrect visibility restriction";
5718 let suggestion = r##"some possible visibility restrictions are:
5719 `pub(crate)`: visible only on the current crate
5720 `pub(super)`: visible only in the current module's parent
5721 `pub(in path::to::module)`: visible only on the specified path"##;
5722 let path = self.parse_path(PathStyle::Mod)?;
5723 let path_span = self.prev_span;
5724 let help_msg = format!("make this visible only to module `{}` with `in`", path);
5725 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5726 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5727 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5728 err.emit(); // emit diagnostic, but continue with public visibility
5732 Ok(Visibility::Public)
5735 /// Parse defaultness: `default` or nothing.
5736 fn parse_defaultness(&mut self) -> Defaultness {
5737 // `pub` is included for better error messages
5738 if self.check_keyword(keywords::Default) &&
5739 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
5740 t.is_keyword(keywords::Const) ||
5741 t.is_keyword(keywords::Fn) ||
5742 t.is_keyword(keywords::Unsafe) ||
5743 t.is_keyword(keywords::Extern) ||
5744 t.is_keyword(keywords::Type) ||
5745 t.is_keyword(keywords::Pub)) {
5746 self.bump(); // `default`
5747 Defaultness::Default
5753 /// Given a termination token, parse all of the items in a module
5754 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5755 let mut items = vec![];
5756 while let Some(item) = self.parse_item()? {
5760 if !self.eat(term) {
5761 let token_str = self.this_token_to_string();
5762 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
5763 let msg = "consider removing this semicolon";
5764 if token_str == ";" {
5765 err.span_suggestion_short(self.span, msg, "".to_string());
5770 let hi = if self.span == syntax_pos::DUMMY_SP {
5777 inner: inner_lo.to(hi),
5782 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5783 let id = self.parse_ident()?;
5784 self.expect(&token::Colon)?;
5785 let ty = self.parse_ty()?;
5786 self.expect(&token::Eq)?;
5787 let e = self.parse_expr()?;
5788 self.expect(&token::Semi)?;
5789 let item = match m {
5790 Some(m) => ItemKind::Static(ty, m, e),
5791 None => ItemKind::Const(ty, e),
5793 Ok((id, item, None))
5796 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5797 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5798 let (in_cfg, outer_attrs) = {
5799 let mut strip_unconfigured = ::config::StripUnconfigured {
5801 should_test: false, // irrelevant
5802 features: None, // don't perform gated feature checking
5804 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5805 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5808 let id_span = self.span;
5809 let id = self.parse_ident()?;
5810 if self.check(&token::Semi) {
5812 if in_cfg && self.recurse_into_file_modules {
5813 // This mod is in an external file. Let's go get it!
5814 let ModulePathSuccess { path, directory_ownership, warn } =
5815 self.submod_path(id, &outer_attrs, id_span)?;
5816 let (module, mut attrs) =
5817 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5819 let attr = Attribute {
5820 id: attr::mk_attr_id(),
5821 style: ast::AttrStyle::Outer,
5822 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5823 Ident::from_str("warn_directory_ownership")),
5824 tokens: TokenStream::empty(),
5825 is_sugared_doc: false,
5826 span: syntax_pos::DUMMY_SP,
5828 attr::mark_known(&attr);
5831 Ok((id, module, Some(attrs)))
5833 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5834 Ok((id, ItemKind::Mod(placeholder), None))
5837 let old_directory = self.directory.clone();
5838 self.push_directory(id, &outer_attrs);
5840 self.expect(&token::OpenDelim(token::Brace))?;
5841 let mod_inner_lo = self.span;
5842 let attrs = self.parse_inner_attributes()?;
5843 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5845 self.directory = old_directory;
5846 Ok((id, ItemKind::Mod(module), Some(attrs)))
5850 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5851 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5852 self.directory.path.push(&path.as_str());
5853 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
5855 self.directory.path.push(&id.name.as_str());
5859 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
5860 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5863 /// Returns either a path to a module, or .
5864 pub fn default_submod_path(
5866 relative: Option<ast::Ident>,
5868 codemap: &CodeMap) -> ModulePath
5870 // If we're in a foo.rs file instead of a mod.rs file,
5871 // we need to look for submodules in
5872 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
5873 // `./<id>.rs` and `./<id>/mod.rs`.
5874 let relative_prefix_string;
5875 let relative_prefix = if let Some(ident) = relative {
5876 relative_prefix_string = format!("{}{}", ident.name.as_str(), path::MAIN_SEPARATOR);
5877 &relative_prefix_string
5882 let mod_name = id.to_string();
5883 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
5884 let secondary_path_str = format!("{}{}{}mod.rs",
5885 relative_prefix, mod_name, path::MAIN_SEPARATOR);
5886 let default_path = dir_path.join(&default_path_str);
5887 let secondary_path = dir_path.join(&secondary_path_str);
5888 let default_exists = codemap.file_exists(&default_path);
5889 let secondary_exists = codemap.file_exists(&secondary_path);
5891 let result = match (default_exists, secondary_exists) {
5892 (true, false) => Ok(ModulePathSuccess {
5894 directory_ownership: DirectoryOwnership::Owned {
5899 (false, true) => Ok(ModulePathSuccess {
5900 path: secondary_path,
5901 directory_ownership: DirectoryOwnership::Owned {
5906 (false, false) => Err(Error::FileNotFoundForModule {
5907 mod_name: mod_name.clone(),
5908 default_path: default_path_str,
5909 secondary_path: secondary_path_str,
5910 dir_path: format!("{}", dir_path.display()),
5912 (true, true) => Err(Error::DuplicatePaths {
5913 mod_name: mod_name.clone(),
5914 default_path: default_path_str,
5915 secondary_path: secondary_path_str,
5921 path_exists: default_exists || secondary_exists,
5926 fn submod_path(&mut self,
5928 outer_attrs: &[Attribute],
5930 -> PResult<'a, ModulePathSuccess> {
5931 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5932 return Ok(ModulePathSuccess {
5933 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5934 // All `#[path]` files are treated as though they are a `mod.rs` file.
5935 // This means that `mod foo;` declarations inside `#[path]`-included
5936 // files are siblings,
5938 // Note that this will produce weirdness when a file named `foo.rs` is
5939 // `#[path]` included and contains a `mod foo;` declaration.
5940 // If you encounter this, it's your own darn fault :P
5941 Some(_) => DirectoryOwnership::Owned { relative: None },
5942 _ => DirectoryOwnership::UnownedViaMod(true),
5949 let relative = match self.directory.ownership {
5950 DirectoryOwnership::Owned { relative } => {
5951 // Push the usage onto the list of non-mod.rs mod uses.
5952 // This is used later for feature-gate error reporting.
5953 if let Some(cur_file_ident) = relative {
5955 .non_modrs_mods.borrow_mut()
5956 .push((cur_file_ident, id_sp));
5960 DirectoryOwnership::UnownedViaBlock |
5961 DirectoryOwnership::UnownedViaMod(_) => None,
5963 let paths = Parser::default_submod_path(
5964 id, relative, &self.directory.path, self.sess.codemap());
5966 match self.directory.ownership {
5967 DirectoryOwnership::Owned { .. } => {
5968 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5970 DirectoryOwnership::UnownedViaBlock => {
5972 "Cannot declare a non-inline module inside a block \
5973 unless it has a path attribute";
5974 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5975 if paths.path_exists {
5976 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5978 err.span_note(id_sp, &msg);
5982 DirectoryOwnership::UnownedViaMod(warn) => {
5984 if let Ok(result) = paths.result {
5985 return Ok(ModulePathSuccess { warn: true, ..result });
5988 let mut err = self.diagnostic().struct_span_err(id_sp,
5989 "cannot declare a new module at this location");
5990 if id_sp != syntax_pos::DUMMY_SP {
5991 let src_path = self.sess.codemap().span_to_filename(id_sp);
5992 if let FileName::Real(src_path) = src_path {
5993 if let Some(stem) = src_path.file_stem() {
5994 let mut dest_path = src_path.clone();
5995 dest_path.set_file_name(stem);
5996 dest_path.push("mod.rs");
5997 err.span_note(id_sp,
5998 &format!("maybe move this module `{}` to its own \
5999 directory via `{}`", src_path.display(),
6000 dest_path.display()));
6004 if paths.path_exists {
6005 err.span_note(id_sp,
6006 &format!("... or maybe `use` the module `{}` instead \
6007 of possibly redeclaring it",
6015 /// Read a module from a source file.
6016 fn eval_src_mod(&mut self,
6018 directory_ownership: DirectoryOwnership,
6021 -> PResult<'a, (ast::ItemKind, Vec<Attribute> )> {
6022 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6023 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6024 let mut err = String::from("circular modules: ");
6025 let len = included_mod_stack.len();
6026 for p in &included_mod_stack[i.. len] {
6027 err.push_str(&p.to_string_lossy());
6028 err.push_str(" -> ");
6030 err.push_str(&path.to_string_lossy());
6031 return Err(self.span_fatal(id_sp, &err[..]));
6033 included_mod_stack.push(path.clone());
6034 drop(included_mod_stack);
6037 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6038 p0.cfg_mods = self.cfg_mods;
6039 let mod_inner_lo = p0.span;
6040 let mod_attrs = p0.parse_inner_attributes()?;
6041 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6042 self.sess.included_mod_stack.borrow_mut().pop();
6043 Ok((ast::ItemKind::Mod(m0), mod_attrs))
6046 /// Parse a function declaration from a foreign module
6047 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6048 -> PResult<'a, ForeignItem> {
6049 self.expect_keyword(keywords::Fn)?;
6051 let (ident, mut generics) = self.parse_fn_header()?;
6052 let decl = self.parse_fn_decl(true)?;
6053 generics.where_clause = self.parse_where_clause()?;
6055 self.expect(&token::Semi)?;
6056 Ok(ast::ForeignItem {
6059 node: ForeignItemKind::Fn(decl, generics),
6060 id: ast::DUMMY_NODE_ID,
6066 /// Parse a static item from a foreign module.
6067 /// Assumes that the `static` keyword is already parsed.
6068 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6069 -> PResult<'a, ForeignItem> {
6070 let mutbl = self.eat_keyword(keywords::Mut);
6071 let ident = self.parse_ident()?;
6072 self.expect(&token::Colon)?;
6073 let ty = self.parse_ty()?;
6075 self.expect(&token::Semi)?;
6079 node: ForeignItemKind::Static(ty, mutbl),
6080 id: ast::DUMMY_NODE_ID,
6086 /// Parse a type from a foreign module
6087 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6088 -> PResult<'a, ForeignItem> {
6089 self.expect_keyword(keywords::Type)?;
6091 let ident = self.parse_ident()?;
6093 self.expect(&token::Semi)?;
6094 Ok(ast::ForeignItem {
6097 node: ForeignItemKind::Ty,
6098 id: ast::DUMMY_NODE_ID,
6104 /// Parse extern crate links
6108 /// extern crate foo;
6109 /// extern crate bar as foo;
6110 fn parse_item_extern_crate(&mut self,
6112 visibility: Visibility,
6113 attrs: Vec<Attribute>)
6114 -> PResult<'a, P<Item>> {
6116 let crate_name = self.parse_ident()?;
6117 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
6118 (Some(crate_name.name), ident)
6122 self.expect(&token::Semi)?;
6124 let prev_span = self.prev_span;
6126 Ok(self.mk_item(lo.to(prev_span),
6128 ItemKind::ExternCrate(maybe_path),
6133 /// Parse `extern` for foreign ABIs
6136 /// `extern` is expected to have been
6137 /// consumed before calling this method
6143 fn parse_item_foreign_mod(&mut self,
6145 opt_abi: Option<Abi>,
6146 visibility: Visibility,
6147 mut attrs: Vec<Attribute>)
6148 -> PResult<'a, P<Item>> {
6149 self.expect(&token::OpenDelim(token::Brace))?;
6151 let abi = opt_abi.unwrap_or(Abi::C);
6153 attrs.extend(self.parse_inner_attributes()?);
6155 let mut foreign_items = vec![];
6156 while let Some(item) = self.parse_foreign_item()? {
6157 foreign_items.push(item);
6159 self.expect(&token::CloseDelim(token::Brace))?;
6161 let prev_span = self.prev_span;
6162 let m = ast::ForeignMod {
6164 items: foreign_items
6166 let invalid = keywords::Invalid.ident();
6167 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6170 /// Parse type Foo = Bar;
6171 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
6172 let ident = self.parse_ident()?;
6173 let mut tps = self.parse_generics()?;
6174 tps.where_clause = self.parse_where_clause()?;
6175 self.expect(&token::Eq)?;
6176 let ty = self.parse_ty()?;
6177 self.expect(&token::Semi)?;
6178 Ok((ident, ItemKind::Ty(ty, tps), None))
6181 /// Parse the part of an "enum" decl following the '{'
6182 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6183 let mut variants = Vec::new();
6184 let mut all_nullary = true;
6185 let mut any_disr = None;
6186 while self.token != token::CloseDelim(token::Brace) {
6187 let variant_attrs = self.parse_outer_attributes()?;
6188 let vlo = self.span;
6191 let mut disr_expr = None;
6192 let ident = self.parse_ident()?;
6193 if self.check(&token::OpenDelim(token::Brace)) {
6194 // Parse a struct variant.
6195 all_nullary = false;
6196 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6197 ast::DUMMY_NODE_ID);
6198 } else if self.check(&token::OpenDelim(token::Paren)) {
6199 all_nullary = false;
6200 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6201 ast::DUMMY_NODE_ID);
6202 } else if self.eat(&token::Eq) {
6203 disr_expr = Some(self.parse_expr()?);
6204 any_disr = disr_expr.as_ref().map(|expr| expr.span);
6205 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6207 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6210 let vr = ast::Variant_ {
6212 attrs: variant_attrs,
6216 variants.push(respan(vlo.to(self.prev_span), vr));
6218 if !self.eat(&token::Comma) { break; }
6220 self.expect(&token::CloseDelim(token::Brace))?;
6222 Some(disr_span) if !all_nullary =>
6223 self.span_err(disr_span,
6224 "discriminator values can only be used with a field-less enum"),
6228 Ok(ast::EnumDef { variants: variants })
6231 /// Parse an "enum" declaration
6232 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6233 let id = self.parse_ident()?;
6234 let mut generics = self.parse_generics()?;
6235 generics.where_clause = self.parse_where_clause()?;
6236 self.expect(&token::OpenDelim(token::Brace))?;
6238 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6239 self.recover_stmt();
6240 self.eat(&token::CloseDelim(token::Brace));
6243 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6246 /// Parses a string as an ABI spec on an extern type or module. Consumes
6247 /// the `extern` keyword, if one is found.
6248 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6250 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6252 self.expect_no_suffix(sp, "ABI spec", suf);
6254 match abi::lookup(&s.as_str()) {
6255 Some(abi) => Ok(Some(abi)),
6257 let prev_span = self.prev_span;
6260 &format!("invalid ABI: expected one of [{}], \
6262 abi::all_names().join(", "),
6273 fn is_static_global(&mut self) -> bool {
6274 if self.check_keyword(keywords::Static) {
6275 // Check if this could be a closure
6276 !self.look_ahead(1, |token| {
6277 if token.is_keyword(keywords::Move) {
6281 token::BinOp(token::Or) | token::OrOr => true,
6290 /// Parse one of the items allowed by the flags.
6291 /// NB: this function no longer parses the items inside an
6293 fn parse_item_(&mut self, attrs: Vec<Attribute>,
6294 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
6295 maybe_whole!(self, NtItem, |item| {
6296 let mut item = item.into_inner();
6297 let mut attrs = attrs;
6298 mem::swap(&mut item.attrs, &mut attrs);
6299 item.attrs.extend(attrs);
6305 let visibility = self.parse_visibility(false)?;
6307 if self.eat_keyword(keywords::Use) {
6309 let item_ = ItemKind::Use(P(self.parse_use_tree(false)?));
6310 self.expect(&token::Semi)?;
6312 let prev_span = self.prev_span;
6313 let invalid = keywords::Invalid.ident();
6314 let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
6315 return Ok(Some(item));
6318 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6319 self.bump(); // `extern`
6320 if self.eat_keyword(keywords::Crate) {
6321 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6324 let opt_abi = self.parse_opt_abi()?;
6326 if self.eat_keyword(keywords::Fn) {
6327 // EXTERN FUNCTION ITEM
6328 let fn_span = self.prev_span;
6329 let abi = opt_abi.unwrap_or(Abi::C);
6330 let (ident, item_, extra_attrs) =
6331 self.parse_item_fn(Unsafety::Normal,
6332 respan(fn_span, Constness::NotConst),
6334 let prev_span = self.prev_span;
6335 let item = self.mk_item(lo.to(prev_span),
6339 maybe_append(attrs, extra_attrs));
6340 return Ok(Some(item));
6341 } else if self.check(&token::OpenDelim(token::Brace)) {
6342 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6348 if self.is_static_global() {
6351 let m = if self.eat_keyword(keywords::Mut) {
6354 Mutability::Immutable
6356 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6357 let prev_span = self.prev_span;
6358 let item = self.mk_item(lo.to(prev_span),
6362 maybe_append(attrs, extra_attrs));
6363 return Ok(Some(item));
6365 if self.eat_keyword(keywords::Const) {
6366 let const_span = self.prev_span;
6367 if self.check_keyword(keywords::Fn)
6368 || (self.check_keyword(keywords::Unsafe)
6369 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6370 // CONST FUNCTION ITEM
6371 let unsafety = self.parse_unsafety();
6373 let (ident, item_, extra_attrs) =
6374 self.parse_item_fn(unsafety,
6375 respan(const_span, Constness::Const),
6377 let prev_span = self.prev_span;
6378 let item = self.mk_item(lo.to(prev_span),
6382 maybe_append(attrs, extra_attrs));
6383 return Ok(Some(item));
6387 if self.eat_keyword(keywords::Mut) {
6388 let prev_span = self.prev_span;
6389 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6390 .help("did you mean to declare a static?")
6393 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6394 let prev_span = self.prev_span;
6395 let item = self.mk_item(lo.to(prev_span),
6399 maybe_append(attrs, extra_attrs));
6400 return Ok(Some(item));
6402 if self.check_keyword(keywords::Unsafe) &&
6403 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
6404 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
6406 // UNSAFE TRAIT ITEM
6407 self.bump(); // `unsafe`
6408 let is_auto = if self.eat_keyword(keywords::Trait) {
6411 self.expect_keyword(keywords::Auto)?;
6412 self.expect_keyword(keywords::Trait)?;
6415 let (ident, item_, extra_attrs) =
6416 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
6417 let prev_span = self.prev_span;
6418 let item = self.mk_item(lo.to(prev_span),
6422 maybe_append(attrs, extra_attrs));
6423 return Ok(Some(item));
6425 if self.check_keyword(keywords::Impl) ||
6426 self.check_keyword(keywords::Unsafe) &&
6427 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6428 self.check_keyword(keywords::Default) &&
6429 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6430 self.check_keyword(keywords::Default) &&
6431 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
6433 let defaultness = self.parse_defaultness();
6434 let unsafety = self.parse_unsafety();
6435 self.expect_keyword(keywords::Impl)?;
6436 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
6437 let span = lo.to(self.prev_span);
6438 return Ok(Some(self.mk_item(span, ident, item, visibility,
6439 maybe_append(attrs, extra_attrs))));
6441 if self.check_keyword(keywords::Fn) {
6444 let fn_span = self.prev_span;
6445 let (ident, item_, extra_attrs) =
6446 self.parse_item_fn(Unsafety::Normal,
6447 respan(fn_span, Constness::NotConst),
6449 let prev_span = self.prev_span;
6450 let item = self.mk_item(lo.to(prev_span),
6454 maybe_append(attrs, extra_attrs));
6455 return Ok(Some(item));
6457 if self.check_keyword(keywords::Unsafe)
6458 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
6459 // UNSAFE FUNCTION ITEM
6460 self.bump(); // `unsafe`
6461 let abi = if self.eat_keyword(keywords::Extern) {
6462 self.parse_opt_abi()?.unwrap_or(Abi::C)
6466 self.expect_keyword(keywords::Fn)?;
6467 let fn_span = self.prev_span;
6468 let (ident, item_, extra_attrs) =
6469 self.parse_item_fn(Unsafety::Unsafe,
6470 respan(fn_span, Constness::NotConst),
6472 let prev_span = self.prev_span;
6473 let item = self.mk_item(lo.to(prev_span),
6477 maybe_append(attrs, extra_attrs));
6478 return Ok(Some(item));
6480 if self.eat_keyword(keywords::Mod) {
6482 let (ident, item_, extra_attrs) =
6483 self.parse_item_mod(&attrs[..])?;
6484 let prev_span = self.prev_span;
6485 let item = self.mk_item(lo.to(prev_span),
6489 maybe_append(attrs, extra_attrs));
6490 return Ok(Some(item));
6492 if self.eat_keyword(keywords::Type) {
6494 let (ident, item_, extra_attrs) = self.parse_item_type()?;
6495 let prev_span = self.prev_span;
6496 let item = self.mk_item(lo.to(prev_span),
6500 maybe_append(attrs, extra_attrs));
6501 return Ok(Some(item));
6503 if self.eat_keyword(keywords::Enum) {
6505 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
6506 let prev_span = self.prev_span;
6507 let item = self.mk_item(lo.to(prev_span),
6511 maybe_append(attrs, extra_attrs));
6512 return Ok(Some(item));
6514 if self.check_keyword(keywords::Trait)
6515 || (self.check_keyword(keywords::Auto)
6516 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
6518 let is_auto = if self.eat_keyword(keywords::Trait) {
6521 self.expect_keyword(keywords::Auto)?;
6522 self.expect_keyword(keywords::Trait)?;
6526 let (ident, item_, extra_attrs) =
6527 self.parse_item_trait(is_auto, Unsafety::Normal)?;
6528 let prev_span = self.prev_span;
6529 let item = self.mk_item(lo.to(prev_span),
6533 maybe_append(attrs, extra_attrs));
6534 return Ok(Some(item));
6536 if self.eat_keyword(keywords::Struct) {
6538 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6539 let prev_span = self.prev_span;
6540 let item = self.mk_item(lo.to(prev_span),
6544 maybe_append(attrs, extra_attrs));
6545 return Ok(Some(item));
6547 if self.is_union_item() {
6550 let (ident, item_, extra_attrs) = self.parse_item_union()?;
6551 let prev_span = self.prev_span;
6552 let item = self.mk_item(lo.to(prev_span),
6556 maybe_append(attrs, extra_attrs));
6557 return Ok(Some(item));
6559 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
6560 return Ok(Some(macro_def));
6563 // Verify wether we have encountered a struct or method definition where the user forgot to
6564 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
6565 if visibility == Visibility::Public &&
6566 self.check_ident() &&
6567 self.look_ahead(1, |t| *t != token::Not)
6569 // Space between `pub` keyword and the identifier
6572 // ^^^ `sp` points here
6573 let sp = self.prev_span.between(self.span);
6574 let full_sp = self.prev_span.to(self.span);
6575 let ident_sp = self.span;
6576 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
6577 // possible public struct definition where `struct` was forgotten
6578 let ident = self.parse_ident().unwrap();
6579 let msg = format!("add `struct` here to parse `{}` as a public struct",
6581 let mut err = self.diagnostic()
6582 .struct_span_err(sp, "missing `struct` for struct definition");
6583 err.span_suggestion_short(sp, &msg, " struct ".into());
6585 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
6586 let ident = self.parse_ident().unwrap();
6587 self.consume_block(token::Paren);
6588 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
6589 self.check(&token::OpenDelim(token::Brace))
6591 ("fn", "method", false)
6592 } else if self.check(&token::Colon) {
6596 ("fn` or `struct", "method or struct", true)
6599 let msg = format!("missing `{}` for {} definition", kw, kw_name);
6600 let mut err = self.diagnostic().struct_span_err(sp, &msg);
6602 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
6606 err.span_suggestion_short(sp, &suggestion, format!(" {} ", kw));
6608 if let Ok(snippet) = self.sess.codemap().span_to_snippet(ident_sp) {
6609 err.span_suggestion(
6611 "if you meant to call a macro, write instead",
6612 format!("{}!", snippet));
6614 err.help("if you meant to call a macro, remove the `pub` \
6615 and add a trailing `!` after the identifier");
6621 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
6624 /// Parse a foreign item.
6625 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
6626 let attrs = self.parse_outer_attributes()?;
6628 let visibility = self.parse_visibility(false)?;
6630 // FOREIGN STATIC ITEM
6631 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
6632 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
6633 if self.token.is_keyword(keywords::Const) {
6635 .struct_span_err(self.span, "extern items cannot be `const`")
6636 .span_suggestion(self.span, "instead try using", "static".to_owned())
6639 self.bump(); // `static` or `const`
6640 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6642 // FOREIGN FUNCTION ITEM
6643 if self.check_keyword(keywords::Fn) {
6644 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6646 // FOREIGN TYPE ITEM
6647 if self.check_keyword(keywords::Type) {
6648 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
6651 // FIXME #5668: this will occur for a macro invocation:
6652 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
6654 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
6660 /// This is the fall-through for parsing items.
6661 fn parse_macro_use_or_failure(
6663 attrs: Vec<Attribute> ,
6664 macros_allowed: bool,
6665 attributes_allowed: bool,
6667 visibility: Visibility
6668 ) -> PResult<'a, Option<P<Item>>> {
6669 if macros_allowed && self.token.is_path_start() {
6670 // MACRO INVOCATION ITEM
6672 let prev_span = self.prev_span;
6673 self.complain_if_pub_macro(&visibility, prev_span);
6675 let mac_lo = self.span;
6678 let pth = self.parse_path(PathStyle::Mod)?;
6679 self.expect(&token::Not)?;
6681 // a 'special' identifier (like what `macro_rules!` uses)
6682 // is optional. We should eventually unify invoc syntax
6684 let id = if self.token.is_ident() {
6687 keywords::Invalid.ident() // no special identifier
6689 // eat a matched-delimiter token tree:
6690 let (delim, tts) = self.expect_delimited_token_tree()?;
6691 if delim != token::Brace {
6692 if !self.eat(&token::Semi) {
6693 self.span_err(self.prev_span,
6694 "macros that expand to items must either \
6695 be surrounded with braces or followed by \
6700 let hi = self.prev_span;
6701 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6702 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6703 return Ok(Some(item));
6706 // FAILURE TO PARSE ITEM
6708 Visibility::Inherited => {}
6710 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
6714 if !attributes_allowed && !attrs.is_empty() {
6715 self.expected_item_err(&attrs);
6720 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
6721 where F: FnOnce(&mut Self) -> PResult<'a, R>
6723 // Record all tokens we parse when parsing this item.
6724 let mut tokens = Vec::new();
6725 match self.token_cursor.frame.last_token {
6726 LastToken::Collecting(_) => {
6727 panic!("cannot collect tokens recursively yet")
6729 LastToken::Was(ref mut last) => tokens.extend(last.take()),
6731 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
6732 let prev = self.token_cursor.stack.len();
6734 let last_token = if self.token_cursor.stack.len() == prev {
6735 &mut self.token_cursor.frame.last_token
6737 &mut self.token_cursor.stack[prev].last_token
6739 let mut tokens = match *last_token {
6740 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
6741 LastToken::Was(_) => panic!("our vector went away?"),
6744 // If we're not at EOF our current token wasn't actually consumed by
6745 // `f`, but it'll still be in our list that we pulled out. In that case
6747 if self.token == token::Eof {
6748 *last_token = LastToken::Was(None);
6750 *last_token = LastToken::Was(tokens.pop());
6753 Ok((ret?, tokens.into_iter().collect()))
6756 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6757 let attrs = self.parse_outer_attributes()?;
6759 let (ret, tokens) = self.collect_tokens(|this| {
6760 this.parse_item_(attrs, true, false)
6763 // Once we've parsed an item and recorded the tokens we got while
6764 // parsing we may want to store `tokens` into the item we're about to
6765 // return. Note, though, that we specifically didn't capture tokens
6766 // related to outer attributes. The `tokens` field here may later be
6767 // used with procedural macros to convert this item back into a token
6768 // stream, but during expansion we may be removing attributes as we go
6771 // If we've got inner attributes then the `tokens` we've got above holds
6772 // these inner attributes. If an inner attribute is expanded we won't
6773 // actually remove it from the token stream, so we'll just keep yielding
6774 // it (bad!). To work around this case for now we just avoid recording
6775 // `tokens` if we detect any inner attributes. This should help keep
6776 // expansion correct, but we should fix this bug one day!
6779 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6780 i.tokens = Some(tokens);
6787 /// `{` or `::{` or `*` or `::*`
6788 /// `::{` or `::*` (also `{` or `*` if unprefixed is true)
6789 fn is_import_coupler(&mut self, unprefixed: bool) -> bool {
6790 self.is_import_coupler_inner(&token::OpenDelim(token::Brace), unprefixed) ||
6791 self.is_import_coupler_inner(&token::BinOp(token::Star), unprefixed)
6794 fn is_import_coupler_inner(&mut self, token: &token::Token, unprefixed: bool) -> bool {
6795 if self.check(&token::ModSep) {
6796 self.look_ahead(1, |t| t == token)
6797 } else if unprefixed {
6806 /// USE_TREE = `*` |
6807 /// `{` USE_TREE_LIST `}` |
6809 /// PATH `::` `{` USE_TREE_LIST `}` |
6810 /// PATH [`as` IDENT]
6811 fn parse_use_tree(&mut self, nested: bool) -> PResult<'a, UseTree> {
6814 let mut prefix = ast::Path {
6816 span: lo.to(self.span),
6819 let kind = if self.is_import_coupler(true) {
6820 // `use *;` or `use ::*;` or `use {...};` `use ::{...};`
6822 // Remove the first `::`
6823 if self.eat(&token::ModSep) {
6824 prefix.segments.push(PathSegment::crate_root(self.prev_span));
6826 prefix.segments.push(PathSegment::crate_root(self.span));
6829 if self.eat(&token::BinOp(token::Star)) {
6832 } else if self.check(&token::OpenDelim(token::Brace)) {
6834 UseTreeKind::Nested(self.parse_use_tree_list()?)
6836 return self.unexpected();
6840 let mut parsed = self.parse_path(PathStyle::Mod)?;
6842 parsed = parsed.default_to_global();
6845 prefix.segments.append(&mut parsed.segments);
6846 prefix.span = prefix.span.to(parsed.span);
6848 if self.eat(&token::ModSep) {
6849 if self.eat(&token::BinOp(token::Star)) {
6852 } else if self.check(&token::OpenDelim(token::Brace)) {
6853 // `use path::{...};`
6854 UseTreeKind::Nested(self.parse_use_tree_list()?)
6856 return self.unexpected();
6859 // `use path::foo;` or `use path::foo as bar;`
6860 let rename = self.parse_rename()?.
6861 unwrap_or(prefix.segments.last().unwrap().identifier);
6862 UseTreeKind::Simple(rename)
6867 span: lo.to(self.prev_span),
6873 /// Parse UseTreeKind::Nested(list)
6875 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
6876 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
6877 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
6878 &token::CloseDelim(token::Brace),
6879 SeqSep::trailing_allowed(token::Comma), |this| {
6880 Ok((this.parse_use_tree(true)?, ast::DUMMY_NODE_ID))
6884 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6885 if self.eat_keyword(keywords::As) {
6886 self.parse_ident().map(Some)
6892 /// Parses a source module as a crate. This is the main
6893 /// entry point for the parser.
6894 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6897 attrs: self.parse_inner_attributes()?,
6898 module: self.parse_mod_items(&token::Eof, lo)?,
6899 span: lo.to(self.span),
6903 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6904 let ret = match self.token {
6905 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6906 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6913 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6914 match self.parse_optional_str() {
6915 Some((s, style, suf)) => {
6916 let sp = self.prev_span;
6917 self.expect_no_suffix(sp, "string literal", suf);
6920 _ => Err(self.fatal("expected string literal"))