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 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
765 self.parse_ident_common(true)
768 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
771 if self.token.is_reserved_ident() {
772 let mut err = self.struct_span_err(self.span,
773 &format!("expected identifier, found {}",
774 self.this_token_descr()));
775 if let Some(token_descr) = self.token_descr() {
776 err.span_label(self.span, format!("expected identifier, found {}",
779 err.span_label(self.span, "expected identifier");
791 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
792 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
794 let mut err = self.fatal(&format!("expected identifier, found `{}`",
795 self.this_token_to_string()));
796 if let Some(token_descr) = self.token_descr() {
797 err.span_label(self.span, format!("expected identifier, found {}",
800 err.span_label(self.span, "expected identifier");
802 if self.token == token::Underscore {
803 err.note("`_` is a wildcard pattern, not an identifier");
811 /// Check if the next token is `tok`, and return `true` if so.
813 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
815 pub fn check(&mut self, tok: &token::Token) -> bool {
816 let is_present = self.token == *tok;
817 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
821 /// Consume token 'tok' if it exists. Returns true if the given
822 /// token was present, false otherwise.
823 pub fn eat(&mut self, tok: &token::Token) -> bool {
824 let is_present = self.check(tok);
825 if is_present { self.bump() }
829 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
830 self.expected_tokens.push(TokenType::Keyword(kw));
831 self.token.is_keyword(kw)
834 /// If the next token is the given keyword, eat it and return
835 /// true. Otherwise, return false.
836 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
837 if self.check_keyword(kw) {
845 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
846 if self.token.is_keyword(kw) {
854 /// If the given word is not a keyword, signal an error.
855 /// If the next token is not the given word, signal an error.
856 /// Otherwise, eat it.
857 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
858 if !self.eat_keyword(kw) {
865 fn check_ident(&mut self) -> bool {
866 if self.token.is_ident() {
869 self.expected_tokens.push(TokenType::Ident);
874 fn check_path(&mut self) -> bool {
875 if self.token.is_path_start() {
878 self.expected_tokens.push(TokenType::Path);
883 fn check_type(&mut self) -> bool {
884 if self.token.can_begin_type() {
887 self.expected_tokens.push(TokenType::Type);
892 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
893 /// `&` and continue. If an `&` is not seen, signal an error.
894 fn expect_and(&mut self) -> PResult<'a, ()> {
895 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
897 token::BinOp(token::And) => {
902 let span = self.span.with_lo(self.span.lo() + BytePos(1));
903 Ok(self.bump_with(token::BinOp(token::And), span))
905 _ => self.unexpected()
909 /// Expect and consume an `|`. If `||` is seen, replace it with a single
910 /// `|` and continue. If an `|` is not seen, signal an error.
911 fn expect_or(&mut self) -> PResult<'a, ()> {
912 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
914 token::BinOp(token::Or) => {
919 let span = self.span.with_lo(self.span.lo() + BytePos(1));
920 Ok(self.bump_with(token::BinOp(token::Or), span))
922 _ => self.unexpected()
926 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
928 None => {/* everything ok */}
930 let text = suf.as_str();
932 self.span_bug(sp, "found empty literal suffix in Some")
934 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
939 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
940 /// `<` and continue. If a `<` is not seen, return false.
942 /// This is meant to be used when parsing generics on a path to get the
944 fn eat_lt(&mut self) -> bool {
945 self.expected_tokens.push(TokenType::Token(token::Lt));
951 token::BinOp(token::Shl) => {
952 let span = self.span.with_lo(self.span.lo() + BytePos(1));
953 self.bump_with(token::Lt, span);
960 fn expect_lt(&mut self) -> PResult<'a, ()> {
968 /// Expect and consume a GT. if a >> is seen, replace it
969 /// with a single > and continue. If a GT is not seen,
971 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
972 self.expected_tokens.push(TokenType::Token(token::Gt));
978 token::BinOp(token::Shr) => {
979 let span = self.span.with_lo(self.span.lo() + BytePos(1));
980 Ok(self.bump_with(token::Gt, span))
982 token::BinOpEq(token::Shr) => {
983 let span = self.span.with_lo(self.span.lo() + BytePos(1));
984 Ok(self.bump_with(token::Ge, span))
987 let span = self.span.with_lo(self.span.lo() + BytePos(1));
988 Ok(self.bump_with(token::Eq, span))
990 _ => self.unexpected()
994 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
995 sep: Option<token::Token>,
997 -> PResult<'a, (Vec<T>, bool)>
998 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
1000 let mut v = Vec::new();
1001 // This loop works by alternating back and forth between parsing types
1002 // and commas. For example, given a string `A, B,>`, the parser would
1003 // first parse `A`, then a comma, then `B`, then a comma. After that it
1004 // would encounter a `>` and stop. This lets the parser handle trailing
1005 // commas in generic parameters, because it can stop either after
1006 // parsing a type or after parsing a comma.
1008 if self.check(&token::Gt)
1009 || self.token == token::BinOp(token::Shr)
1010 || self.token == token::Ge
1011 || self.token == token::BinOpEq(token::Shr) {
1017 Some(result) => v.push(result),
1018 None => return Ok((v, true))
1021 if let Some(t) = sep.as_ref() {
1027 return Ok((v, false));
1030 /// Parse a sequence bracketed by '<' and '>', stopping
1032 pub fn parse_seq_to_before_gt<T, F>(&mut self,
1033 sep: Option<token::Token>,
1035 -> PResult<'a, Vec<T>> where
1036 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1038 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
1039 |p| Ok(Some(f(p)?)))?;
1044 pub fn parse_seq_to_gt<T, F>(&mut self,
1045 sep: Option<token::Token>,
1047 -> PResult<'a, Vec<T>> where
1048 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1050 let v = self.parse_seq_to_before_gt(sep, f)?;
1055 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
1056 sep: Option<token::Token>,
1058 -> PResult<'a, (Vec<T>, bool)> where
1059 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
1061 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
1065 return Ok((v, returned));
1068 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1069 /// passes through any errors encountered. Used for error recovery.
1070 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1071 let handler = self.diagnostic();
1073 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1075 TokenExpectType::Expect,
1076 |p| Ok(p.parse_token_tree())) {
1077 handler.cancel(err);
1081 /// Parse a sequence, including the closing delimiter. The function
1082 /// f must consume tokens until reaching the next separator or
1083 /// closing bracket.
1084 pub fn parse_seq_to_end<T, F>(&mut self,
1088 -> PResult<'a, Vec<T>> where
1089 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1091 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1096 /// Parse a sequence, not including the closing delimiter. The function
1097 /// f must consume tokens until reaching the next separator or
1098 /// closing bracket.
1099 pub fn parse_seq_to_before_end<T, F>(&mut self,
1103 -> PResult<'a, Vec<T>>
1104 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1106 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1109 fn parse_seq_to_before_tokens<T, F>(&mut self,
1110 kets: &[&token::Token],
1112 expect: TokenExpectType,
1114 -> PResult<'a, Vec<T>>
1115 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1117 let mut first: bool = true;
1119 while !kets.contains(&&self.token) {
1121 token::CloseDelim(..) | token::Eof => break,
1124 if let Some(ref t) = sep.sep {
1128 if let Err(mut e) = self.expect(t) {
1129 // Attempt to keep parsing if it was a similar separator
1130 if let Some(ref tokens) = t.similar_tokens() {
1131 if tokens.contains(&self.token) {
1136 // Attempt to keep parsing if it was an omitted separator
1150 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1152 TokenExpectType::Expect => self.check(k),
1153 TokenExpectType::NoExpect => self.token == **k,
1166 /// Parse a sequence, including the closing delimiter. The function
1167 /// f must consume tokens until reaching the next separator or
1168 /// closing bracket.
1169 pub fn parse_unspanned_seq<T, F>(&mut self,
1174 -> PResult<'a, Vec<T>> where
1175 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1178 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1179 if self.token == *ket {
1185 // NB: Do not use this function unless you actually plan to place the
1186 // spanned list in the AST.
1187 pub fn parse_seq<T, F>(&mut self,
1192 -> PResult<'a, Spanned<Vec<T>>> where
1193 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1197 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1200 Ok(respan(lo.to(hi), result))
1203 /// Advance the parser by one token
1204 pub fn bump(&mut self) {
1205 if self.prev_token_kind == PrevTokenKind::Eof {
1206 // Bumping after EOF is a bad sign, usually an infinite loop.
1207 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1210 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1212 // Record last token kind for possible error recovery.
1213 self.prev_token_kind = match self.token {
1214 token::DocComment(..) => PrevTokenKind::DocComment,
1215 token::Comma => PrevTokenKind::Comma,
1216 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1217 token::Interpolated(..) => PrevTokenKind::Interpolated,
1218 token::Eof => PrevTokenKind::Eof,
1219 token::Ident(..) => PrevTokenKind::Ident,
1220 _ => PrevTokenKind::Other,
1223 let next = self.next_tok();
1224 self.span = next.sp;
1225 self.token = next.tok;
1226 self.expected_tokens.clear();
1227 // check after each token
1228 self.process_potential_macro_variable();
1231 /// Advance the parser using provided token as a next one. Use this when
1232 /// consuming a part of a token. For example a single `<` from `<<`.
1233 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1234 self.prev_span = self.span.with_hi(span.lo());
1235 // It would be incorrect to record the kind of the current token, but
1236 // fortunately for tokens currently using `bump_with`, the
1237 // prev_token_kind will be of no use anyway.
1238 self.prev_token_kind = PrevTokenKind::Other;
1241 self.expected_tokens.clear();
1244 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1245 F: FnOnce(&token::Token) -> R,
1248 return f(&self.token)
1251 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1252 Some(tree) => match tree {
1253 TokenTree::Token(_, tok) => tok,
1254 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1256 None => token::CloseDelim(self.token_cursor.frame.delim),
1260 fn look_ahead_span(&self, dist: usize) -> Span {
1265 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1266 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1267 None => self.look_ahead_span(dist - 1),
1270 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1271 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1273 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1274 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1276 pub fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1277 err.span_err(sp, self.diagnostic())
1279 pub fn span_fatal_help<S: Into<MultiSpan>>(&self,
1282 help: &str) -> DiagnosticBuilder<'a> {
1283 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1287 pub fn bug(&self, m: &str) -> ! {
1288 self.sess.span_diagnostic.span_bug(self.span, m)
1290 pub fn warn(&self, m: &str) {
1291 self.sess.span_diagnostic.span_warn(self.span, m)
1293 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1294 self.sess.span_diagnostic.span_warn(sp, m)
1296 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1297 self.sess.span_diagnostic.span_err(sp, m)
1299 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1300 self.sess.span_diagnostic.struct_span_err(sp, m)
1302 pub fn span_err_help<S: Into<MultiSpan>>(&self, sp: S, m: &str, h: &str) {
1303 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1307 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1308 self.sess.span_diagnostic.span_bug(sp, m)
1310 pub fn abort_if_errors(&self) {
1311 self.sess.span_diagnostic.abort_if_errors();
1314 fn cancel(&self, err: &mut DiagnosticBuilder) {
1315 self.sess.span_diagnostic.cancel(err)
1318 pub fn diagnostic(&self) -> &'a errors::Handler {
1319 &self.sess.span_diagnostic
1322 /// Is the current token one of the keywords that signals a bare function
1324 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1325 self.check_keyword(keywords::Fn) ||
1326 self.check_keyword(keywords::Unsafe) ||
1327 self.check_keyword(keywords::Extern)
1330 fn eat_label(&mut self) -> Option<Label> {
1331 let ident = match self.token {
1332 token::Lifetime(ref ident) => *ident,
1333 token::Interpolated(ref nt) => match nt.0 {
1334 token::NtLifetime(lifetime) => lifetime.ident,
1340 Some(Label { ident, span: self.prev_span })
1343 /// parse a TyKind::BareFn type:
1344 pub fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>)
1345 -> PResult<'a, TyKind> {
1348 [unsafe] [extern "ABI"] fn (S) -> T
1358 let unsafety = self.parse_unsafety();
1359 let abi = if self.eat_keyword(keywords::Extern) {
1360 self.parse_opt_abi()?.unwrap_or(Abi::C)
1365 self.expect_keyword(keywords::Fn)?;
1366 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1367 let ret_ty = self.parse_ret_ty(false)?;
1368 let decl = P(FnDecl {
1373 Ok(TyKind::BareFn(P(BareFnTy {
1381 /// Parse unsafety: `unsafe` or nothing.
1382 fn parse_unsafety(&mut self) -> Unsafety {
1383 if self.eat_keyword(keywords::Unsafe) {
1390 /// Parse the items in a trait declaration
1391 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1392 maybe_whole!(self, NtTraitItem, |x| x);
1393 let attrs = self.parse_outer_attributes()?;
1394 let (mut item, tokens) = self.collect_tokens(|this| {
1395 this.parse_trait_item_(at_end, attrs)
1397 // See `parse_item` for why this clause is here.
1398 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1399 item.tokens = Some(tokens);
1404 fn parse_trait_item_(&mut self,
1406 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1409 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1410 let (generics, TyParam {ident, bounds, default, ..}) =
1411 self.parse_trait_item_assoc_ty(vec![])?;
1412 (ident, TraitItemKind::Type(bounds, default), generics)
1413 } else if self.is_const_item() {
1414 self.expect_keyword(keywords::Const)?;
1415 let ident = self.parse_ident()?;
1416 self.expect(&token::Colon)?;
1417 let ty = self.parse_ty()?;
1418 let default = if self.check(&token::Eq) {
1420 let expr = self.parse_expr()?;
1421 self.expect(&token::Semi)?;
1424 self.expect(&token::Semi)?;
1427 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1428 } else if self.token.is_path_start() && !self.is_extern_non_path() {
1429 // trait item macro.
1430 // code copied from parse_macro_use_or_failure... abstraction!
1431 let prev_span = self.prev_span;
1433 let pth = self.parse_path(PathStyle::Mod)?;
1435 if pth.segments.len() == 1 {
1436 if !self.eat(&token::Not) {
1437 return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1440 self.expect(&token::Not)?;
1443 // eat a matched-delimiter token tree:
1444 let (delim, tts) = self.expect_delimited_token_tree()?;
1445 if delim != token::Brace {
1446 self.expect(&token::Semi)?
1449 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1450 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1452 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
1454 let ident = self.parse_ident()?;
1455 let mut generics = self.parse_generics()?;
1457 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1458 // This is somewhat dubious; We don't want to allow
1459 // argument names to be left off if there is a
1461 p.parse_arg_general(false)
1463 generics.where_clause = self.parse_where_clause()?;
1465 let sig = ast::MethodSig {
1472 let body = match self.token {
1476 debug!("parse_trait_methods(): parsing required method");
1479 token::OpenDelim(token::Brace) => {
1480 debug!("parse_trait_methods(): parsing provided method");
1482 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1483 attrs.extend(inner_attrs.iter().cloned());
1487 let token_str = self.this_token_to_string();
1488 return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1491 (ident, ast::TraitItemKind::Method(sig, body), generics)
1495 id: ast::DUMMY_NODE_ID,
1500 span: lo.to(self.prev_span),
1505 /// Parse optional return type [ -> TY ] in function decl
1506 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1507 if self.eat(&token::RArrow) {
1508 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1510 Ok(FunctionRetTy::Default(self.span.with_hi(self.span.lo())))
1515 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1516 self.parse_ty_common(true, true)
1519 /// Parse a type in restricted contexts where `+` is not permitted.
1520 /// Example 1: `&'a TYPE`
1521 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1522 /// Example 2: `value1 as TYPE + value2`
1523 /// `+` is prohibited to avoid interactions with expression grammar.
1524 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1525 self.parse_ty_common(false, true)
1528 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1529 -> PResult<'a, P<Ty>> {
1530 maybe_whole!(self, NtTy, |x| x);
1533 let mut impl_dyn_multi = false;
1534 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1535 // `(TYPE)` is a parenthesized type.
1536 // `(TYPE,)` is a tuple with a single field of type TYPE.
1537 let mut ts = vec![];
1538 let mut last_comma = false;
1539 while self.token != token::CloseDelim(token::Paren) {
1540 ts.push(self.parse_ty()?);
1541 if self.eat(&token::Comma) {
1548 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1549 self.expect(&token::CloseDelim(token::Paren))?;
1551 if ts.len() == 1 && !last_comma {
1552 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1553 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1555 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1556 TyKind::Path(None, ref path) if maybe_bounds => {
1557 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1559 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1560 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1561 let path = match bounds[0] {
1562 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1563 _ => self.bug("unexpected lifetime bound"),
1565 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1568 _ => TyKind::Paren(P(ty))
1573 } else if self.eat(&token::Not) {
1576 } else if self.eat(&token::BinOp(token::Star)) {
1578 TyKind::Ptr(self.parse_ptr()?)
1579 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1581 let t = self.parse_ty()?;
1582 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1583 let t = match self.maybe_parse_fixed_length_of_vec()? {
1584 None => TyKind::Slice(t),
1585 Some(suffix) => TyKind::Array(t, suffix),
1587 self.expect(&token::CloseDelim(token::Bracket))?;
1589 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1592 self.parse_borrowed_pointee()?
1593 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1595 // In order to not be ambiguous, the type must be surrounded by parens.
1596 self.expect(&token::OpenDelim(token::Paren))?;
1597 let e = self.parse_expr()?;
1598 self.expect(&token::CloseDelim(token::Paren))?;
1600 } else if self.eat(&token::Underscore) {
1601 // A type to be inferred `_`
1603 } else if self.token_is_bare_fn_keyword() {
1604 // Function pointer type
1605 self.parse_ty_bare_fn(Vec::new())?
1606 } else if self.check_keyword(keywords::For) {
1607 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1608 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1609 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1611 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1612 if self.token_is_bare_fn_keyword() {
1613 self.parse_ty_bare_fn(lifetime_defs)?
1615 let path = self.parse_path(PathStyle::Type)?;
1616 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1617 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1619 } else if self.eat_keyword(keywords::Impl) {
1620 // Always parse bounds greedily for better error recovery.
1621 let bounds = self.parse_ty_param_bounds()?;
1622 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1623 TyKind::ImplTrait(bounds)
1624 } else if self.check_keyword(keywords::Dyn) &&
1625 self.look_ahead(1, |t| t.can_begin_bound() && !can_continue_type_after_ident(t)) {
1626 self.bump(); // `dyn`
1627 // Always parse bounds greedily for better error recovery.
1628 let bounds = self.parse_ty_param_bounds()?;
1629 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1630 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1631 } else if self.check(&token::Question) ||
1632 self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)) {
1633 // Bound list (trait object type)
1634 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?,
1635 TraitObjectSyntax::None)
1636 } else if self.eat_lt() {
1638 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1639 TyKind::Path(Some(qself), path)
1640 } else if self.token.is_path_start() {
1642 let path = self.parse_path(PathStyle::Type)?;
1643 if self.eat(&token::Not) {
1644 // Macro invocation in type position
1645 let (_, tts) = self.expect_delimited_token_tree()?;
1646 TyKind::Mac(respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts }))
1648 // Just a type path or bound list (trait object type) starting with a trait.
1650 // `Trait1 + Trait2 + 'a`
1651 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1652 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1654 TyKind::Path(None, path)
1658 let msg = format!("expected type, found {}", self.this_token_descr());
1659 return Err(self.fatal(&msg));
1662 let span = lo.to(self.prev_span);
1663 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1665 // Try to recover from use of `+` with incorrect priority.
1666 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1667 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1668 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1673 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1674 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1675 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1676 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1679 bounds.append(&mut self.parse_ty_param_bounds()?);
1681 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1684 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1685 if !allow_plus && impl_dyn_multi {
1686 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1687 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1688 .span_suggestion(ty.span, "use parentheses to disambiguate", sum_with_parens)
1693 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1694 // Do not add `+` to expected tokens.
1695 if !allow_plus || self.token != token::BinOp(token::Plus) {
1700 let bounds = self.parse_ty_param_bounds()?;
1701 let sum_span = ty.span.to(self.prev_span);
1703 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1704 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1707 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1708 let sum_with_parens = pprust::to_string(|s| {
1709 use print::pprust::PrintState;
1712 s.print_opt_lifetime(lifetime)?;
1713 s.print_mutability(mut_ty.mutbl)?;
1715 s.print_type(&mut_ty.ty)?;
1716 s.print_bounds(" +", &bounds)?;
1719 err.span_suggestion(sum_span, "try adding parentheses", sum_with_parens);
1721 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1722 err.span_label(sum_span, "perhaps you forgot parentheses?");
1725 err.span_label(sum_span, "expected a path");
1732 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1733 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1735 // Do not add `::` to expected tokens.
1736 if !allow_recovery || self.token != token::ModSep {
1739 let ty = match base.to_ty() {
1741 None => return Ok(base),
1744 self.bump(); // `::`
1745 let mut segments = Vec::new();
1746 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1748 let span = ty.span.to(self.prev_span);
1750 base.to_recovered(Some(QSelf { ty, position: 0 }), ast::Path { segments, span });
1753 .struct_span_err(span, "missing angle brackets in associated item path")
1754 .span_suggestion(span, "try", recovered.to_string()).emit();
1759 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1760 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1761 let mutbl = self.parse_mutability();
1762 let ty = self.parse_ty_no_plus()?;
1763 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1766 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1767 let mutbl = if self.eat_keyword(keywords::Mut) {
1769 } else if self.eat_keyword(keywords::Const) {
1770 Mutability::Immutable
1772 let span = self.prev_span;
1774 "expected mut or const in raw pointer type (use \
1775 `*mut T` or `*const T` as appropriate)");
1776 Mutability::Immutable
1778 let t = self.parse_ty_no_plus()?;
1779 Ok(MutTy { ty: t, mutbl: mutbl })
1782 fn is_named_argument(&mut self) -> bool {
1783 let offset = match self.token {
1784 token::Interpolated(ref nt) => match nt.0 {
1785 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1788 token::BinOp(token::And) | token::AndAnd => 1,
1789 _ if self.token.is_keyword(keywords::Mut) => 1,
1793 self.look_ahead(offset, |t| t.is_ident() || t == &token::Underscore) &&
1794 self.look_ahead(offset + 1, |t| t == &token::Colon)
1797 /// This version of parse arg doesn't necessarily require
1798 /// identifier names.
1799 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1800 maybe_whole!(self, NtArg, |x| x);
1802 let pat = if require_name || self.is_named_argument() {
1803 debug!("parse_arg_general parse_pat (require_name:{})",
1805 let pat = self.parse_pat()?;
1807 self.expect(&token::Colon)?;
1810 debug!("parse_arg_general ident_to_pat");
1811 let sp = self.prev_span;
1812 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1814 id: ast::DUMMY_NODE_ID,
1815 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1821 let t = self.parse_ty()?;
1826 id: ast::DUMMY_NODE_ID,
1830 /// Parse a single function argument
1831 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1832 self.parse_arg_general(true)
1835 /// Parse an argument in a lambda header e.g. |arg, arg|
1836 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1837 let pat = self.parse_pat()?;
1838 let t = if self.eat(&token::Colon) {
1842 id: ast::DUMMY_NODE_ID,
1843 node: TyKind::Infer,
1850 id: ast::DUMMY_NODE_ID
1854 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1855 if self.eat(&token::Semi) {
1856 Ok(Some(self.parse_expr()?))
1862 /// Matches token_lit = LIT_INTEGER | ...
1863 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1864 let out = match self.token {
1865 token::Interpolated(ref nt) => match nt.0 {
1866 token::NtExpr(ref v) => match v.node {
1867 ExprKind::Lit(ref lit) => { lit.node.clone() }
1868 _ => { return self.unexpected_last(&self.token); }
1870 _ => { return self.unexpected_last(&self.token); }
1872 token::Literal(lit, suf) => {
1873 let diag = Some((self.span, &self.sess.span_diagnostic));
1874 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1878 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1883 _ => { return self.unexpected_last(&self.token); }
1890 /// Matches lit = true | false | token_lit
1891 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1893 let lit = if self.eat_keyword(keywords::True) {
1895 } else if self.eat_keyword(keywords::False) {
1896 LitKind::Bool(false)
1898 let lit = self.parse_lit_token()?;
1901 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1904 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1905 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1906 maybe_whole_expr!(self);
1908 let minus_lo = self.span;
1909 let minus_present = self.eat(&token::BinOp(token::Minus));
1911 let literal = P(self.parse_lit()?);
1912 let hi = self.prev_span;
1913 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1916 let minus_hi = self.prev_span;
1917 let unary = self.mk_unary(UnOp::Neg, expr);
1918 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1924 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1926 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1930 _ => self.parse_ident(),
1934 /// Parses qualified path.
1935 /// Assumes that the leading `<` has been parsed already.
1937 /// `qualified_path = <type [as trait_ref]>::path`
1941 /// `<T as U>::F::a<S>` (without disambiguator)
1942 /// `<T as U>::F::a::<S>` (with disambiguator)
1943 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1944 let lo = self.prev_span;
1945 let ty = self.parse_ty()?;
1946 let mut path = if self.eat_keyword(keywords::As) {
1947 self.parse_path(PathStyle::Type)?
1949 ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP }
1951 self.expect(&token::Gt)?;
1952 self.expect(&token::ModSep)?;
1954 let qself = QSelf { ty, position: path.segments.len() };
1955 self.parse_path_segments(&mut path.segments, style, true)?;
1957 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1960 /// Parses simple paths.
1962 /// `path = [::] segment+`
1963 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1966 /// `a::b::C<D>` (without disambiguator)
1967 /// `a::b::C::<D>` (with disambiguator)
1968 /// `Fn(Args)` (without disambiguator)
1969 /// `Fn::(Args)` (with disambiguator)
1970 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1971 self.parse_path_common(style, true)
1974 pub fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1975 -> PResult<'a, ast::Path> {
1976 maybe_whole!(self, NtPath, |path| {
1977 if style == PathStyle::Mod &&
1978 path.segments.iter().any(|segment| segment.parameters.is_some()) {
1979 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1984 let lo = self.meta_var_span.unwrap_or(self.span);
1985 let mut segments = Vec::new();
1986 if self.eat(&token::ModSep) {
1987 segments.push(PathSegment::crate_root(lo));
1989 self.parse_path_segments(&mut segments, style, enable_warning)?;
1991 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1994 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1995 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1996 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1997 let meta_ident = match self.token {
1998 token::Interpolated(ref nt) => match nt.0 {
1999 token::NtMeta(ref meta) => match meta.node {
2000 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
2007 if let Some(ident) = meta_ident {
2009 return Ok(ast::Path::from_ident(self.prev_span, ident));
2011 self.parse_path(style)
2014 fn parse_path_segments(&mut self,
2015 segments: &mut Vec<PathSegment>,
2017 enable_warning: bool)
2018 -> PResult<'a, ()> {
2020 segments.push(self.parse_path_segment(style, enable_warning)?);
2022 if self.is_import_coupler(false) || !self.eat(&token::ModSep) {
2028 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2029 -> PResult<'a, PathSegment> {
2030 let ident_span = self.span;
2031 let ident = self.parse_path_segment_ident()?;
2033 let is_args_start = |token: &token::Token| match *token {
2034 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2037 let check_args_start = |this: &mut Self| {
2038 this.expected_tokens.extend_from_slice(
2039 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2041 is_args_start(&this.token)
2044 Ok(if style == PathStyle::Type && check_args_start(self) ||
2045 style != PathStyle::Mod && self.check(&token::ModSep)
2046 && self.look_ahead(1, |t| is_args_start(t)) {
2047 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2049 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2050 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2051 .span_label(self.prev_span, "try removing `::`").emit();
2054 let parameters = if self.eat_lt() {
2056 let (lifetimes, types, bindings) = self.parse_generic_args()?;
2058 let span = lo.to(self.prev_span);
2059 AngleBracketedParameterData { lifetimes, types, bindings, span }.into()
2063 let inputs = self.parse_seq_to_before_tokens(
2064 &[&token::CloseDelim(token::Paren)],
2065 SeqSep::trailing_allowed(token::Comma),
2066 TokenExpectType::Expect,
2069 let output = if self.eat(&token::RArrow) {
2070 Some(self.parse_ty_common(false, false)?)
2074 let span = lo.to(self.prev_span);
2075 ParenthesizedParameterData { inputs, output, span }.into()
2078 PathSegment { identifier: ident, span: ident_span, parameters }
2080 // Generic arguments are not found.
2081 PathSegment::from_ident(ident, ident_span)
2085 fn check_lifetime(&mut self) -> bool {
2086 self.expected_tokens.push(TokenType::Lifetime);
2087 self.token.is_lifetime()
2090 /// Parse single lifetime 'a or panic.
2091 pub fn expect_lifetime(&mut self) -> Lifetime {
2092 if let Some(lifetime) = self.token.lifetime(self.span) {
2096 self.span_bug(self.span, "not a lifetime")
2100 /// Parse mutability (`mut` or nothing).
2101 fn parse_mutability(&mut self) -> Mutability {
2102 if self.eat_keyword(keywords::Mut) {
2105 Mutability::Immutable
2109 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2110 if let token::Literal(token::Integer(name), None) = self.token {
2112 Ok(Ident::with_empty_ctxt(name))
2114 self.parse_ident_common(false)
2118 /// Parse ident (COLON expr)?
2119 pub fn parse_field(&mut self) -> PResult<'a, Field> {
2120 let attrs = self.parse_outer_attributes()?;
2124 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2125 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2126 let fieldname = self.parse_field_name()?;
2128 hi = self.prev_span;
2129 (fieldname, self.parse_expr()?, false)
2131 let fieldname = self.parse_ident_common(false)?;
2132 hi = self.prev_span;
2134 // Mimic `x: x` for the `x` field shorthand.
2135 let path = ast::Path::from_ident(lo.to(hi), fieldname);
2136 (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
2139 ident: respan(lo.to(hi), fieldname),
2140 span: lo.to(expr.span),
2143 attrs: attrs.into(),
2147 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2148 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2151 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2152 ExprKind::Unary(unop, expr)
2155 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2156 ExprKind::Binary(binop, lhs, rhs)
2159 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2160 ExprKind::Call(f, args)
2163 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2164 ExprKind::Index(expr, idx)
2167 pub fn mk_range(&mut self,
2168 start: Option<P<Expr>>,
2169 end: Option<P<Expr>>,
2170 limits: RangeLimits)
2171 -> PResult<'a, ast::ExprKind> {
2172 if end.is_none() && limits == RangeLimits::Closed {
2173 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2175 Ok(ExprKind::Range(start, end, limits))
2179 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2180 ExprKind::TupField(expr, idx)
2183 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2184 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2185 ExprKind::AssignOp(binop, lhs, rhs)
2188 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2190 id: ast::DUMMY_NODE_ID,
2191 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2197 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2198 let span = &self.span;
2199 let lv_lit = P(codemap::Spanned {
2200 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2205 id: ast::DUMMY_NODE_ID,
2206 node: ExprKind::Lit(lv_lit),
2212 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2214 token::OpenDelim(delim) => match self.parse_token_tree() {
2215 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2216 _ => unreachable!(),
2218 _ => Err(self.fatal("expected open delimiter")),
2222 /// At the bottom (top?) of the precedence hierarchy,
2223 /// parse things like parenthesized exprs,
2224 /// macros, return, etc.
2226 /// NB: This does not parse outer attributes,
2227 /// and is private because it only works
2228 /// correctly if called from parse_dot_or_call_expr().
2229 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2230 maybe_whole_expr!(self);
2232 // Outer attributes are already parsed and will be
2233 // added to the return value after the fact.
2235 // Therefore, prevent sub-parser from parsing
2236 // attributes by giving them a empty "already parsed" list.
2237 let mut attrs = ThinVec::new();
2240 let mut hi = self.span;
2244 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2246 token::OpenDelim(token::Paren) => {
2249 attrs.extend(self.parse_inner_attributes()?);
2251 // (e) is parenthesized e
2252 // (e,) is a tuple with only one field, e
2253 let mut es = vec![];
2254 let mut trailing_comma = false;
2255 while self.token != token::CloseDelim(token::Paren) {
2256 es.push(self.parse_expr()?);
2257 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2258 if self.check(&token::Comma) {
2259 trailing_comma = true;
2263 trailing_comma = false;
2269 hi = self.prev_span;
2270 ex = if es.len() == 1 && !trailing_comma {
2271 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2276 token::OpenDelim(token::Brace) => {
2277 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2279 token::BinOp(token::Or) | token::OrOr => {
2280 return self.parse_lambda_expr(attrs);
2282 token::OpenDelim(token::Bracket) => {
2285 attrs.extend(self.parse_inner_attributes()?);
2287 if self.check(&token::CloseDelim(token::Bracket)) {
2290 ex = ExprKind::Array(Vec::new());
2293 let first_expr = self.parse_expr()?;
2294 if self.check(&token::Semi) {
2295 // Repeating array syntax: [ 0; 512 ]
2297 let count = self.parse_expr()?;
2298 self.expect(&token::CloseDelim(token::Bracket))?;
2299 ex = ExprKind::Repeat(first_expr, count);
2300 } else if self.check(&token::Comma) {
2301 // Vector with two or more elements.
2303 let remaining_exprs = self.parse_seq_to_end(
2304 &token::CloseDelim(token::Bracket),
2305 SeqSep::trailing_allowed(token::Comma),
2306 |p| Ok(p.parse_expr()?)
2308 let mut exprs = vec![first_expr];
2309 exprs.extend(remaining_exprs);
2310 ex = ExprKind::Array(exprs);
2312 // Vector with one element.
2313 self.expect(&token::CloseDelim(token::Bracket))?;
2314 ex = ExprKind::Array(vec![first_expr]);
2317 hi = self.prev_span;
2321 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2323 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2325 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2326 return self.parse_lambda_expr(attrs);
2328 if self.eat_keyword(keywords::If) {
2329 return self.parse_if_expr(attrs);
2331 if self.eat_keyword(keywords::For) {
2332 let lo = self.prev_span;
2333 return self.parse_for_expr(None, lo, attrs);
2335 if self.eat_keyword(keywords::While) {
2336 let lo = self.prev_span;
2337 return self.parse_while_expr(None, lo, attrs);
2339 if let Some(label) = self.eat_label() {
2340 let lo = label.span;
2341 self.expect(&token::Colon)?;
2342 if self.eat_keyword(keywords::While) {
2343 return self.parse_while_expr(Some(label), lo, attrs)
2345 if self.eat_keyword(keywords::For) {
2346 return self.parse_for_expr(Some(label), lo, attrs)
2348 if self.eat_keyword(keywords::Loop) {
2349 return self.parse_loop_expr(Some(label), lo, attrs)
2351 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2353 if self.eat_keyword(keywords::Loop) {
2354 let lo = self.prev_span;
2355 return self.parse_loop_expr(None, lo, attrs);
2357 if self.eat_keyword(keywords::Continue) {
2358 let label = self.eat_label();
2359 let ex = ExprKind::Continue(label);
2360 let hi = self.prev_span;
2361 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2363 if self.eat_keyword(keywords::Match) {
2364 return self.parse_match_expr(attrs);
2366 if self.eat_keyword(keywords::Unsafe) {
2367 return self.parse_block_expr(
2369 BlockCheckMode::Unsafe(ast::UserProvided),
2372 if self.is_catch_expr() {
2374 assert!(self.eat_keyword(keywords::Do));
2375 assert!(self.eat_keyword(keywords::Catch));
2376 return self.parse_catch_expr(lo, attrs);
2378 if self.eat_keyword(keywords::Return) {
2379 if self.token.can_begin_expr() {
2380 let e = self.parse_expr()?;
2382 ex = ExprKind::Ret(Some(e));
2384 ex = ExprKind::Ret(None);
2386 } else if self.eat_keyword(keywords::Break) {
2387 let label = self.eat_label();
2388 let e = if self.token.can_begin_expr()
2389 && !(self.token == token::OpenDelim(token::Brace)
2390 && self.restrictions.contains(
2391 Restrictions::NO_STRUCT_LITERAL)) {
2392 Some(self.parse_expr()?)
2396 ex = ExprKind::Break(label, e);
2397 hi = self.prev_span;
2398 } else if self.eat_keyword(keywords::Yield) {
2399 if self.token.can_begin_expr() {
2400 let e = self.parse_expr()?;
2402 ex = ExprKind::Yield(Some(e));
2404 ex = ExprKind::Yield(None);
2406 } else if self.token.is_keyword(keywords::Let) {
2407 // Catch this syntax error here, instead of in `parse_ident`, so
2408 // that we can explicitly mention that let is not to be used as an expression
2409 let mut db = self.fatal("expected expression, found statement (`let`)");
2410 db.note("variable declaration using `let` is a statement");
2412 } else if self.token.is_path_start() {
2413 let pth = self.parse_path(PathStyle::Expr)?;
2415 // `!`, as an operator, is prefix, so we know this isn't that
2416 if self.eat(&token::Not) {
2417 // MACRO INVOCATION expression
2418 let (_, tts) = self.expect_delimited_token_tree()?;
2419 let hi = self.prev_span;
2420 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2422 if self.check(&token::OpenDelim(token::Brace)) {
2423 // This is a struct literal, unless we're prohibited
2424 // from parsing struct literals here.
2425 let prohibited = self.restrictions.contains(
2426 Restrictions::NO_STRUCT_LITERAL
2429 return self.parse_struct_expr(lo, pth, attrs);
2434 ex = ExprKind::Path(None, pth);
2436 match self.parse_lit() {
2439 ex = ExprKind::Lit(P(lit));
2442 self.cancel(&mut err);
2443 let msg = format!("expected expression, found {}",
2444 self.this_token_descr());
2445 return Err(self.fatal(&msg));
2452 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2453 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2458 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2459 -> PResult<'a, P<Expr>> {
2460 let struct_sp = lo.to(self.prev_span);
2462 let mut fields = Vec::new();
2463 let mut base = None;
2465 attrs.extend(self.parse_inner_attributes()?);
2467 while self.token != token::CloseDelim(token::Brace) {
2468 if self.eat(&token::DotDot) {
2469 let exp_span = self.prev_span;
2470 match self.parse_expr() {
2476 self.recover_stmt();
2479 if self.token == token::Comma {
2480 let mut err = self.sess.span_diagnostic.mut_span_err(
2481 exp_span.to(self.prev_span),
2482 "cannot use a comma after the base struct",
2484 err.span_suggestion_short(self.span, "remove this comma", "".to_owned());
2485 err.note("the base struct must always be the last field");
2487 self.recover_stmt();
2492 match self.parse_field() {
2493 Ok(f) => fields.push(f),
2495 e.span_label(struct_sp, "while parsing this struct");
2497 self.recover_stmt();
2502 match self.expect_one_of(&[token::Comma],
2503 &[token::CloseDelim(token::Brace)]) {
2507 self.recover_stmt();
2513 let span = lo.to(self.span);
2514 self.expect(&token::CloseDelim(token::Brace))?;
2515 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2518 fn parse_or_use_outer_attributes(&mut self,
2519 already_parsed_attrs: Option<ThinVec<Attribute>>)
2520 -> PResult<'a, ThinVec<Attribute>> {
2521 if let Some(attrs) = already_parsed_attrs {
2524 self.parse_outer_attributes().map(|a| a.into())
2528 /// Parse a block or unsafe block
2529 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2530 outer_attrs: ThinVec<Attribute>)
2531 -> PResult<'a, P<Expr>> {
2532 self.expect(&token::OpenDelim(token::Brace))?;
2534 let mut attrs = outer_attrs;
2535 attrs.extend(self.parse_inner_attributes()?);
2537 let blk = self.parse_block_tail(lo, blk_mode)?;
2538 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2541 /// parse a.b or a(13) or a[4] or just a
2542 pub fn parse_dot_or_call_expr(&mut self,
2543 already_parsed_attrs: Option<ThinVec<Attribute>>)
2544 -> PResult<'a, P<Expr>> {
2545 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2547 let b = self.parse_bottom_expr();
2548 let (span, b) = self.interpolated_or_expr_span(b)?;
2549 self.parse_dot_or_call_expr_with(b, span, attrs)
2552 pub fn parse_dot_or_call_expr_with(&mut self,
2555 mut attrs: ThinVec<Attribute>)
2556 -> PResult<'a, P<Expr>> {
2557 // Stitch the list of outer attributes onto the return value.
2558 // A little bit ugly, but the best way given the current code
2560 self.parse_dot_or_call_expr_with_(e0, lo)
2562 expr.map(|mut expr| {
2563 attrs.extend::<Vec<_>>(expr.attrs.into());
2566 ExprKind::If(..) | ExprKind::IfLet(..) => {
2567 if !expr.attrs.is_empty() {
2568 // Just point to the first attribute in there...
2569 let span = expr.attrs[0].span;
2572 "attributes are not yet allowed on `if` \
2583 // Assuming we have just parsed `.`, continue parsing into an expression.
2584 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2585 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2586 Ok(match self.token {
2587 token::OpenDelim(token::Paren) => {
2588 // Method call `expr.f()`
2589 let mut args = self.parse_unspanned_seq(
2590 &token::OpenDelim(token::Paren),
2591 &token::CloseDelim(token::Paren),
2592 SeqSep::trailing_allowed(token::Comma),
2593 |p| Ok(p.parse_expr()?)
2595 args.insert(0, self_arg);
2597 let span = lo.to(self.prev_span);
2598 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2601 // Field access `expr.f`
2602 if let Some(parameters) = segment.parameters {
2603 self.span_err(parameters.span(),
2604 "field expressions may not have generic arguments");
2607 let span = lo.to(self.prev_span);
2608 let ident = respan(segment.span, segment.identifier);
2609 self.mk_expr(span, ExprKind::Field(self_arg, ident), ThinVec::new())
2614 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2619 while self.eat(&token::Question) {
2620 let hi = self.prev_span;
2621 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2625 if self.eat(&token::Dot) {
2627 token::Ident(..) => {
2628 e = self.parse_dot_suffix(e, lo)?;
2630 token::Literal(token::Integer(index_ident), suf) => {
2633 // A tuple index may not have a suffix
2634 self.expect_no_suffix(sp, "tuple index", suf);
2636 let dot_span = self.prev_span;
2640 let invalid_msg = "invalid tuple or struct index";
2642 let index = index_ident.as_str().parse::<usize>().ok();
2645 if n.to_string() != index_ident.as_str() {
2646 let mut err = self.struct_span_err(self.prev_span, invalid_msg);
2647 err.span_suggestion(self.prev_span,
2648 "try simplifying the index",
2652 let id = respan(dot_span.to(hi), n);
2653 let field = self.mk_tup_field(e, id);
2654 e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2657 let prev_span = self.prev_span;
2658 self.span_err(prev_span, invalid_msg);
2662 token::Literal(token::Float(n), _suf) => {
2664 let fstr = n.as_str();
2665 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2666 &format!("unexpected token: `{}`", n));
2667 err.span_label(self.prev_span, "unexpected token");
2668 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2669 let float = match fstr.parse::<f64>().ok() {
2673 let sugg = pprust::to_string(|s| {
2674 use print::pprust::PrintState;
2678 s.print_usize(float.trunc() as usize)?;
2681 s.s.word(fstr.splitn(2, ".").last().unwrap())
2683 err.span_suggestion(
2684 lo.to(self.prev_span),
2685 "try parenthesizing the first index",
2692 // FIXME Could factor this out into non_fatal_unexpected or something.
2693 let actual = self.this_token_to_string();
2694 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2699 if self.expr_is_complete(&e) { break; }
2702 token::OpenDelim(token::Paren) => {
2703 let es = self.parse_unspanned_seq(
2704 &token::OpenDelim(token::Paren),
2705 &token::CloseDelim(token::Paren),
2706 SeqSep::trailing_allowed(token::Comma),
2707 |p| Ok(p.parse_expr()?)
2709 hi = self.prev_span;
2711 let nd = self.mk_call(e, es);
2712 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2716 // Could be either an index expression or a slicing expression.
2717 token::OpenDelim(token::Bracket) => {
2719 let ix = self.parse_expr()?;
2721 self.expect(&token::CloseDelim(token::Bracket))?;
2722 let index = self.mk_index(e, ix);
2723 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2731 pub fn process_potential_macro_variable(&mut self) {
2732 let ident = match self.token {
2733 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2734 self.look_ahead(1, |t| t.is_ident()) => {
2736 let name = match self.token { token::Ident(ident) => ident, _ => unreachable!() };
2737 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2740 token::Interpolated(ref nt) => {
2741 self.meta_var_span = Some(self.span);
2743 token::NtIdent(ident) => ident,
2749 self.token = token::Ident(ident.node);
2750 self.span = ident.span;
2753 /// parse a single token tree from the input.
2754 pub fn parse_token_tree(&mut self) -> TokenTree {
2756 token::OpenDelim(..) => {
2757 let frame = mem::replace(&mut self.token_cursor.frame,
2758 self.token_cursor.stack.pop().unwrap());
2759 self.span = frame.span;
2761 TokenTree::Delimited(frame.span, Delimited {
2763 tts: frame.tree_cursor.original_stream().into(),
2766 token::CloseDelim(_) | token::Eof => unreachable!(),
2768 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2770 TokenTree::Token(span, token)
2775 // parse a stream of tokens into a list of TokenTree's,
2777 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2778 let mut tts = Vec::new();
2779 while self.token != token::Eof {
2780 tts.push(self.parse_token_tree());
2785 pub fn parse_tokens(&mut self) -> TokenStream {
2786 let mut result = Vec::new();
2789 token::Eof | token::CloseDelim(..) => break,
2790 _ => result.push(self.parse_token_tree().into()),
2793 TokenStream::concat(result)
2796 /// Parse a prefix-unary-operator expr
2797 pub fn parse_prefix_expr(&mut self,
2798 already_parsed_attrs: Option<ThinVec<Attribute>>)
2799 -> PResult<'a, P<Expr>> {
2800 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2802 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2803 let (hi, ex) = match self.token {
2806 let e = self.parse_prefix_expr(None);
2807 let (span, e) = self.interpolated_or_expr_span(e)?;
2808 (lo.to(span), self.mk_unary(UnOp::Not, e))
2810 // Suggest `!` for bitwise negation when encountering a `~`
2813 let e = self.parse_prefix_expr(None);
2814 let (span, e) = self.interpolated_or_expr_span(e)?;
2815 let span_of_tilde = lo;
2816 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2817 "`~` can not be used as a unary operator");
2818 err.span_label(span_of_tilde, "did you mean `!`?");
2819 err.help("use `!` instead of `~` if you meant to perform bitwise negation");
2821 (lo.to(span), self.mk_unary(UnOp::Not, e))
2823 token::BinOp(token::Minus) => {
2825 let e = self.parse_prefix_expr(None);
2826 let (span, e) = self.interpolated_or_expr_span(e)?;
2827 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2829 token::BinOp(token::Star) => {
2831 let e = self.parse_prefix_expr(None);
2832 let (span, e) = self.interpolated_or_expr_span(e)?;
2833 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2835 token::BinOp(token::And) | token::AndAnd => {
2837 let m = self.parse_mutability();
2838 let e = self.parse_prefix_expr(None);
2839 let (span, e) = self.interpolated_or_expr_span(e)?;
2840 (lo.to(span), ExprKind::AddrOf(m, e))
2842 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2844 let place = self.parse_expr_res(
2845 Restrictions::NO_STRUCT_LITERAL,
2848 let blk = self.parse_block()?;
2849 let span = blk.span;
2850 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2851 (lo.to(span), ExprKind::InPlace(place, blk_expr))
2853 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2855 let e = self.parse_prefix_expr(None);
2856 let (span, e) = self.interpolated_or_expr_span(e)?;
2857 (lo.to(span), ExprKind::Box(e))
2859 _ => return self.parse_dot_or_call_expr(Some(attrs))
2861 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2864 /// Parse an associative expression
2866 /// This parses an expression accounting for associativity and precedence of the operators in
2868 pub fn parse_assoc_expr(&mut self,
2869 already_parsed_attrs: Option<ThinVec<Attribute>>)
2870 -> PResult<'a, P<Expr>> {
2871 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2874 /// Parse an associative expression with operators of at least `min_prec` precedence
2875 pub fn parse_assoc_expr_with(&mut self,
2878 -> PResult<'a, P<Expr>> {
2879 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2882 let attrs = match lhs {
2883 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2886 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2887 return self.parse_prefix_range_expr(attrs);
2889 self.parse_prefix_expr(attrs)?
2893 if self.expr_is_complete(&lhs) {
2894 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2897 self.expected_tokens.push(TokenType::Operator);
2898 while let Some(op) = AssocOp::from_token(&self.token) {
2900 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2901 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2902 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2903 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2904 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2905 (PrevTokenKind::Interpolated, _) => self.prev_span,
2906 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2907 if path.segments.len() == 1 => self.prev_span,
2911 let cur_op_span = self.span;
2912 let restrictions = if op.is_assign_like() {
2913 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2917 if op.precedence() < min_prec {
2920 // Check for deprecated `...` syntax
2921 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2922 self.err_dotdotdot_syntax(self.span);
2926 if op.is_comparison() {
2927 self.check_no_chained_comparison(&lhs, &op);
2930 if op == AssocOp::As {
2931 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2933 } else if op == AssocOp::Colon {
2934 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2937 err.span_label(self.span,
2938 "expecting a type here because of type ascription");
2939 let cm = self.sess.codemap();
2940 let cur_pos = cm.lookup_char_pos(self.span.lo());
2941 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
2942 if cur_pos.line != op_pos.line {
2943 err.span_suggestion_short(cur_op_span,
2944 "did you mean to use `;` here?",
2951 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2952 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2953 // generalise it to the Fixity::None code.
2955 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2956 // two variants are handled with `parse_prefix_range_expr` call above.
2957 let rhs = if self.is_at_start_of_range_notation_rhs() {
2958 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2959 LhsExpr::NotYetParsed)?)
2963 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2968 let limits = if op == AssocOp::DotDot {
2969 RangeLimits::HalfOpen
2974 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2975 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2979 let rhs = match op.fixity() {
2980 Fixity::Right => self.with_res(
2981 restrictions - Restrictions::STMT_EXPR,
2983 this.parse_assoc_expr_with(op.precedence(),
2984 LhsExpr::NotYetParsed)
2986 Fixity::Left => self.with_res(
2987 restrictions - Restrictions::STMT_EXPR,
2989 this.parse_assoc_expr_with(op.precedence() + 1,
2990 LhsExpr::NotYetParsed)
2992 // We currently have no non-associative operators that are not handled above by
2993 // the special cases. The code is here only for future convenience.
2994 Fixity::None => self.with_res(
2995 restrictions - Restrictions::STMT_EXPR,
2997 this.parse_assoc_expr_with(op.precedence() + 1,
2998 LhsExpr::NotYetParsed)
3002 let span = lhs_span.to(rhs.span);
3004 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3005 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3006 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3007 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3008 AssocOp::Greater | AssocOp::GreaterEqual => {
3009 let ast_op = op.to_ast_binop().unwrap();
3010 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
3011 self.mk_expr(span, binary, ThinVec::new())
3014 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3016 self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
3017 AssocOp::AssignOp(k) => {
3019 token::Plus => BinOpKind::Add,
3020 token::Minus => BinOpKind::Sub,
3021 token::Star => BinOpKind::Mul,
3022 token::Slash => BinOpKind::Div,
3023 token::Percent => BinOpKind::Rem,
3024 token::Caret => BinOpKind::BitXor,
3025 token::And => BinOpKind::BitAnd,
3026 token::Or => BinOpKind::BitOr,
3027 token::Shl => BinOpKind::Shl,
3028 token::Shr => BinOpKind::Shr,
3030 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
3031 self.mk_expr(span, aopexpr, ThinVec::new())
3033 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3034 self.bug("AssocOp should have been handled by special case")
3038 if op.fixity() == Fixity::None { break }
3043 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3044 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3045 -> PResult<'a, P<Expr>> {
3046 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3047 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3050 // Save the state of the parser before parsing type normally, in case there is a
3051 // LessThan comparison after this cast.
3052 let parser_snapshot_before_type = self.clone();
3053 match self.parse_ty_no_plus() {
3055 Ok(mk_expr(self, rhs))
3057 Err(mut type_err) => {
3058 // Rewind to before attempting to parse the type with generics, to recover
3059 // from situations like `x as usize < y` in which we first tried to parse
3060 // `usize < y` as a type with generic arguments.
3061 let parser_snapshot_after_type = self.clone();
3062 mem::replace(self, parser_snapshot_before_type);
3064 match self.parse_path(PathStyle::Expr) {
3066 let (op_noun, op_verb) = match self.token {
3067 token::Lt => ("comparison", "comparing"),
3068 token::BinOp(token::Shl) => ("shift", "shifting"),
3070 // We can end up here even without `<` being the next token, for
3071 // example because `parse_ty_no_plus` returns `Err` on keywords,
3072 // but `parse_path` returns `Ok` on them due to error recovery.
3073 // Return original error and parser state.
3074 mem::replace(self, parser_snapshot_after_type);
3075 return Err(type_err);
3079 // Successfully parsed the type path leaving a `<` yet to parse.
3082 // Report non-fatal diagnostics, keep `x as usize` as an expression
3083 // in AST and continue parsing.
3084 let msg = format!("`<` is interpreted as a start of generic \
3085 arguments for `{}`, not a {}", path, op_noun);
3086 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3087 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3088 "interpreted as generic arguments");
3089 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3091 let expr = mk_expr(self, P(Ty {
3093 node: TyKind::Path(None, path),
3094 id: ast::DUMMY_NODE_ID
3097 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
3098 .unwrap_or(pprust::expr_to_string(&expr));
3099 err.span_suggestion(expr.span,
3100 &format!("try {} the casted value", op_verb),
3101 format!("({})", expr_str));
3106 Err(mut path_err) => {
3107 // Couldn't parse as a path, return original error and parser state.
3109 mem::replace(self, parser_snapshot_after_type);
3117 /// Produce an error if comparison operators are chained (RFC #558).
3118 /// We only need to check lhs, not rhs, because all comparison ops
3119 /// have same precedence and are left-associative
3120 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3121 debug_assert!(outer_op.is_comparison(),
3122 "check_no_chained_comparison: {:?} is not comparison",
3125 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3126 // respan to include both operators
3127 let op_span = op.span.to(self.span);
3128 let mut err = self.diagnostic().struct_span_err(op_span,
3129 "chained comparison operators require parentheses");
3130 if op.node == BinOpKind::Lt &&
3131 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3132 *outer_op == AssocOp::Greater // even in a case like the following:
3133 { // Foo<Bar<Baz<Qux, ()>>>
3135 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3136 err.help("or use `(...)` if you meant to specify fn arguments");
3144 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3145 fn parse_prefix_range_expr(&mut self,
3146 already_parsed_attrs: Option<ThinVec<Attribute>>)
3147 -> PResult<'a, P<Expr>> {
3148 // Check for deprecated `...` syntax
3149 if self.token == token::DotDotDot {
3150 self.err_dotdotdot_syntax(self.span);
3153 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3154 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3156 let tok = self.token.clone();
3157 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3159 let mut hi = self.span;
3161 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3162 // RHS must be parsed with more associativity than the dots.
3163 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3164 Some(self.parse_assoc_expr_with(next_prec,
3165 LhsExpr::NotYetParsed)
3173 let limits = if tok == token::DotDot {
3174 RangeLimits::HalfOpen
3179 let r = try!(self.mk_range(None,
3182 Ok(self.mk_expr(lo.to(hi), r, attrs))
3185 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3186 if self.token.can_begin_expr() {
3187 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3188 if self.token == token::OpenDelim(token::Brace) {
3189 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3197 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3198 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3199 if self.check_keyword(keywords::Let) {
3200 return self.parse_if_let_expr(attrs);
3202 let lo = self.prev_span;
3203 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3205 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3206 // verify that the last statement is either an implicit return (no `;`) or an explicit
3207 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3208 // the dead code lint.
3209 if self.eat_keyword(keywords::Else) || !cond.returns() {
3210 let sp = self.sess.codemap().next_point(lo);
3211 let mut err = self.diagnostic()
3212 .struct_span_err(sp, "missing condition for `if` statemement");
3213 err.span_label(sp, "expected if condition here");
3216 let thn = self.parse_block()?;
3217 let mut els: Option<P<Expr>> = None;
3218 let mut hi = thn.span;
3219 if self.eat_keyword(keywords::Else) {
3220 let elexpr = self.parse_else_expr()?;
3224 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3227 /// Parse an 'if let' expression ('if' token already eaten)
3228 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3229 -> PResult<'a, P<Expr>> {
3230 let lo = self.prev_span;
3231 self.expect_keyword(keywords::Let)?;
3232 let pat = self.parse_pat()?;
3233 self.expect(&token::Eq)?;
3234 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3235 let thn = self.parse_block()?;
3236 let (hi, els) = if self.eat_keyword(keywords::Else) {
3237 let expr = self.parse_else_expr()?;
3238 (expr.span, Some(expr))
3242 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
3245 // `move |args| expr`
3246 pub fn parse_lambda_expr(&mut self,
3247 attrs: ThinVec<Attribute>)
3248 -> PResult<'a, P<Expr>>
3251 let movability = if self.eat_keyword(keywords::Static) {
3256 let capture_clause = if self.eat_keyword(keywords::Move) {
3261 let decl = self.parse_fn_block_decl()?;
3262 let decl_hi = self.prev_span;
3263 let body = match decl.output {
3264 FunctionRetTy::Default(_) => {
3265 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3266 self.parse_expr_res(restrictions, None)?
3269 // If an explicit return type is given, require a
3270 // block to appear (RFC 968).
3271 let body_lo = self.span;
3272 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3278 ExprKind::Closure(capture_clause, movability, decl, body, lo.to(decl_hi)),
3282 // `else` token already eaten
3283 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3284 if self.eat_keyword(keywords::If) {
3285 return self.parse_if_expr(ThinVec::new());
3287 let blk = self.parse_block()?;
3288 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3292 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3293 pub fn parse_for_expr(&mut self, opt_label: Option<Label>,
3295 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3296 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3298 let pat = self.parse_pat()?;
3299 if !self.eat_keyword(keywords::In) {
3300 let in_span = self.prev_span.between(self.span);
3301 let mut err = self.sess.span_diagnostic
3302 .struct_span_err(in_span, "missing `in` in `for` loop");
3303 err.span_suggestion_short(in_span, "try adding `in` here", " in ".into());
3306 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3307 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3308 attrs.extend(iattrs);
3310 let hi = self.prev_span;
3311 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3314 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3315 pub fn parse_while_expr(&mut self, opt_label: Option<Label>,
3317 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3318 if self.token.is_keyword(keywords::Let) {
3319 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3321 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3322 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3323 attrs.extend(iattrs);
3324 let span = span_lo.to(body.span);
3325 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3328 /// Parse a 'while let' expression ('while' token already eaten)
3329 pub fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3331 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3332 self.expect_keyword(keywords::Let)?;
3333 let pat = self.parse_pat()?;
3334 self.expect(&token::Eq)?;
3335 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3336 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3337 attrs.extend(iattrs);
3338 let span = span_lo.to(body.span);
3339 return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_label), attrs));
3342 // parse `loop {...}`, `loop` token already eaten
3343 pub fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3345 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3346 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3347 attrs.extend(iattrs);
3348 let span = span_lo.to(body.span);
3349 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3352 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3353 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3354 -> PResult<'a, P<Expr>>
3356 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3357 attrs.extend(iattrs);
3358 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3361 // `match` token already eaten
3362 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3363 let match_span = self.prev_span;
3364 let lo = self.prev_span;
3365 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3367 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3368 if self.token == token::Token::Semi {
3369 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3373 attrs.extend(self.parse_inner_attributes()?);
3375 let mut arms: Vec<Arm> = Vec::new();
3376 while self.token != token::CloseDelim(token::Brace) {
3377 match self.parse_arm() {
3378 Ok(arm) => arms.push(arm),
3380 // Recover by skipping to the end of the block.
3382 self.recover_stmt();
3383 let span = lo.to(self.span);
3384 if self.token == token::CloseDelim(token::Brace) {
3387 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3393 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3396 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3397 maybe_whole!(self, NtArm, |x| x);
3399 let attrs = self.parse_outer_attributes()?;
3400 // Allow a '|' before the pats (RFC 1925)
3401 let beginning_vert = if self.eat(&token::BinOp(token::Or)) {
3402 Some(self.prev_span)
3406 let pats = self.parse_pats()?;
3407 let guard = if self.eat_keyword(keywords::If) {
3408 Some(self.parse_expr()?)
3412 self.expect(&token::FatArrow)?;
3413 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)?;
3415 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3416 && self.token != token::CloseDelim(token::Brace);
3419 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3421 self.eat(&token::Comma);
3433 /// Parse an expression
3434 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3435 self.parse_expr_res(Restrictions::empty(), None)
3438 /// Evaluate the closure with restrictions in place.
3440 /// After the closure is evaluated, restrictions are reset.
3441 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3442 where F: FnOnce(&mut Self) -> T
3444 let old = self.restrictions;
3445 self.restrictions = r;
3447 self.restrictions = old;
3452 /// Parse an expression, subject to the given restrictions
3453 pub fn parse_expr_res(&mut self, r: Restrictions,
3454 already_parsed_attrs: Option<ThinVec<Attribute>>)
3455 -> PResult<'a, P<Expr>> {
3456 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3459 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3460 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3461 if self.check(&token::Eq) {
3463 Ok(Some(self.parse_expr()?))
3465 Ok(Some(self.parse_expr()?))
3471 /// Parse patterns, separated by '|' s
3472 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3473 let mut pats = Vec::new();
3475 pats.push(self.parse_pat()?);
3477 if self.token == token::OrOr {
3478 let mut err = self.struct_span_err(self.span,
3479 "unexpected token `||` after pattern");
3480 err.span_suggestion(self.span,
3481 "use a single `|` to specify multiple patterns",
3485 } else if self.check(&token::BinOp(token::Or)) {
3493 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3494 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3495 let mut fields = vec![];
3496 let mut ddpos = None;
3498 while !self.check(&token::CloseDelim(token::Paren)) {
3499 if ddpos.is_none() && self.eat(&token::DotDot) {
3500 ddpos = Some(fields.len());
3501 if self.eat(&token::Comma) {
3502 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3503 fields.push(self.parse_pat()?);
3505 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3506 // Emit a friendly error, ignore `..` and continue parsing
3507 self.span_err(self.prev_span, "`..` can only be used once per \
3508 tuple or tuple struct pattern");
3510 fields.push(self.parse_pat()?);
3513 if !self.check(&token::CloseDelim(token::Paren)) ||
3514 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3515 self.expect(&token::Comma)?;
3522 fn parse_pat_vec_elements(
3524 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3525 let mut before = Vec::new();
3526 let mut slice = None;
3527 let mut after = Vec::new();
3528 let mut first = true;
3529 let mut before_slice = true;
3531 while self.token != token::CloseDelim(token::Bracket) {
3535 self.expect(&token::Comma)?;
3537 if self.token == token::CloseDelim(token::Bracket)
3538 && (before_slice || !after.is_empty()) {
3544 if self.eat(&token::DotDot) {
3546 if self.check(&token::Comma) ||
3547 self.check(&token::CloseDelim(token::Bracket)) {
3548 slice = Some(P(Pat {
3549 id: ast::DUMMY_NODE_ID,
3550 node: PatKind::Wild,
3553 before_slice = false;
3559 let subpat = self.parse_pat()?;
3560 if before_slice && self.eat(&token::DotDot) {
3561 slice = Some(subpat);
3562 before_slice = false;
3563 } else if before_slice {
3564 before.push(subpat);
3570 Ok((before, slice, after))
3573 /// Parse the fields of a struct-like pattern
3574 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3575 let mut fields = Vec::new();
3576 let mut etc = false;
3577 let mut first = true;
3578 while self.token != token::CloseDelim(token::Brace) {
3582 self.expect(&token::Comma)?;
3583 // accept trailing commas
3584 if self.check(&token::CloseDelim(token::Brace)) { break }
3587 let attrs = self.parse_outer_attributes()?;
3591 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3592 if self.token == token::DotDotDot { // Issue #46718
3593 let mut err = self.struct_span_err(self.span,
3594 "expected field pattern, found `...`");
3595 err.span_suggestion(self.span,
3596 "to omit remaining fields, use one fewer `.`",
3602 if self.token != token::CloseDelim(token::Brace) {
3603 let token_str = self.this_token_to_string();
3604 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3611 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3612 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3613 // Parsing a pattern of the form "fieldname: pat"
3614 let fieldname = self.parse_field_name()?;
3616 let pat = self.parse_pat()?;
3618 (pat, fieldname, false)
3620 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3621 let is_box = self.eat_keyword(keywords::Box);
3622 let boxed_span = self.span;
3623 let is_ref = self.eat_keyword(keywords::Ref);
3624 let is_mut = self.eat_keyword(keywords::Mut);
3625 let fieldname = self.parse_ident()?;
3626 hi = self.prev_span;
3628 let bind_type = match (is_ref, is_mut) {
3629 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3630 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3631 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3632 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3634 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3635 let fieldpat = P(Pat {
3636 id: ast::DUMMY_NODE_ID,
3637 node: PatKind::Ident(bind_type, fieldpath, None),
3638 span: boxed_span.to(hi),
3641 let subpat = if is_box {
3643 id: ast::DUMMY_NODE_ID,
3644 node: PatKind::Box(fieldpat),
3650 (subpat, fieldname, true)
3653 fields.push(codemap::Spanned { span: lo.to(hi),
3654 node: ast::FieldPat {
3658 attrs: attrs.into(),
3662 return Ok((fields, etc));
3665 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3666 if self.token.is_path_start() {
3668 let (qself, path) = if self.eat_lt() {
3669 // Parse a qualified path
3670 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3673 // Parse an unqualified path
3674 (None, self.parse_path(PathStyle::Expr)?)
3676 let hi = self.prev_span;
3677 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3679 self.parse_pat_literal_maybe_minus()
3683 // helper function to decide whether to parse as ident binding or to try to do
3684 // something more complex like range patterns
3685 fn parse_as_ident(&mut self) -> bool {
3686 self.look_ahead(1, |t| match *t {
3687 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3688 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3689 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3690 // range pattern branch
3691 token::DotDot => None,
3693 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3694 token::Comma | token::CloseDelim(token::Bracket) => true,
3699 /// Parse a pattern.
3700 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3701 maybe_whole!(self, NtPat, |x| x);
3706 token::Underscore => {
3709 pat = PatKind::Wild;
3711 token::BinOp(token::And) | token::AndAnd => {
3712 // Parse &pat / &mut pat
3714 let mutbl = self.parse_mutability();
3715 if let token::Lifetime(ident) = self.token {
3716 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3718 let subpat = self.parse_pat()?;
3719 pat = PatKind::Ref(subpat, mutbl);
3721 token::OpenDelim(token::Paren) => {
3722 // Parse (pat,pat,pat,...) as tuple pattern
3724 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3725 self.expect(&token::CloseDelim(token::Paren))?;
3726 pat = PatKind::Tuple(fields, ddpos);
3728 token::OpenDelim(token::Bracket) => {
3729 // Parse [pat,pat,...] as slice pattern
3731 let (before, slice, after) = self.parse_pat_vec_elements()?;
3732 self.expect(&token::CloseDelim(token::Bracket))?;
3733 pat = PatKind::Slice(before, slice, after);
3735 // At this point, token != _, &, &&, (, [
3736 _ => if self.eat_keyword(keywords::Mut) {
3737 // Parse mut ident @ pat / mut ref ident @ pat
3738 let mutref_span = self.prev_span.to(self.span);
3739 let binding_mode = if self.eat_keyword(keywords::Ref) {
3741 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3742 .span_suggestion(mutref_span, "try switching the order", "ref mut".into())
3744 BindingMode::ByRef(Mutability::Mutable)
3746 BindingMode::ByValue(Mutability::Mutable)
3748 pat = self.parse_pat_ident(binding_mode)?;
3749 } else if self.eat_keyword(keywords::Ref) {
3750 // Parse ref ident @ pat / ref mut ident @ pat
3751 let mutbl = self.parse_mutability();
3752 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3753 } else if self.eat_keyword(keywords::Box) {
3755 let subpat = self.parse_pat()?;
3756 pat = PatKind::Box(subpat);
3757 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3758 self.parse_as_ident() {
3759 // Parse ident @ pat
3760 // This can give false positives and parse nullary enums,
3761 // they are dealt with later in resolve
3762 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3763 pat = self.parse_pat_ident(binding_mode)?;
3764 } else if self.token.is_path_start() {
3765 // Parse pattern starting with a path
3766 let (qself, path) = if self.eat_lt() {
3767 // Parse a qualified path
3768 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3771 // Parse an unqualified path
3772 (None, self.parse_path(PathStyle::Expr)?)
3775 token::Not if qself.is_none() => {
3776 // Parse macro invocation
3778 let (_, tts) = self.expect_delimited_token_tree()?;
3779 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3780 pat = PatKind::Mac(mac);
3782 token::DotDotDot | token::DotDotEq | token::DotDot => {
3783 let end_kind = match self.token {
3784 token::DotDot => RangeEnd::Excluded,
3785 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
3786 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
3787 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
3791 let span = lo.to(self.prev_span);
3792 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3794 let end = self.parse_pat_range_end()?;
3795 pat = PatKind::Range(begin, end, end_kind);
3797 token::OpenDelim(token::Brace) => {
3798 if qself.is_some() {
3799 return Err(self.fatal("unexpected `{` after qualified path"));
3801 // Parse struct pattern
3803 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3805 self.recover_stmt();
3809 pat = PatKind::Struct(path, fields, etc);
3811 token::OpenDelim(token::Paren) => {
3812 if qself.is_some() {
3813 return Err(self.fatal("unexpected `(` after qualified path"));
3815 // Parse tuple struct or enum pattern
3817 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3818 self.expect(&token::CloseDelim(token::Paren))?;
3819 pat = PatKind::TupleStruct(path, fields, ddpos)
3821 _ => pat = PatKind::Path(qself, path),
3824 // Try to parse everything else as literal with optional minus
3825 match self.parse_pat_literal_maybe_minus() {
3827 if self.eat(&token::DotDotDot) {
3828 let end = self.parse_pat_range_end()?;
3829 pat = PatKind::Range(begin, end,
3830 RangeEnd::Included(RangeSyntax::DotDotDot));
3831 } else if self.eat(&token::DotDotEq) {
3832 let end = self.parse_pat_range_end()?;
3833 pat = PatKind::Range(begin, end,
3834 RangeEnd::Included(RangeSyntax::DotDotEq));
3835 } else if self.eat(&token::DotDot) {
3836 let end = self.parse_pat_range_end()?;
3837 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3839 pat = PatKind::Lit(begin);
3843 self.cancel(&mut err);
3844 let msg = format!("expected pattern, found {}", self.this_token_descr());
3845 return Err(self.fatal(&msg));
3851 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
3852 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
3857 /// Parse ident or ident @ pat
3858 /// used by the copy foo and ref foo patterns to give a good
3859 /// error message when parsing mistakes like ref foo(a,b)
3860 fn parse_pat_ident(&mut self,
3861 binding_mode: ast::BindingMode)
3862 -> PResult<'a, PatKind> {
3863 let ident_span = self.span;
3864 let ident = self.parse_ident()?;
3865 let name = codemap::Spanned{span: ident_span, node: ident};
3866 let sub = if self.eat(&token::At) {
3867 Some(self.parse_pat()?)
3872 // just to be friendly, if they write something like
3874 // we end up here with ( as the current token. This shortly
3875 // leads to a parse error. Note that if there is no explicit
3876 // binding mode then we do not end up here, because the lookahead
3877 // will direct us over to parse_enum_variant()
3878 if self.token == token::OpenDelim(token::Paren) {
3879 return Err(self.span_fatal(
3881 "expected identifier, found enum pattern"))
3884 Ok(PatKind::Ident(binding_mode, name, sub))
3887 /// Parse a local variable declaration
3888 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3889 let lo = self.prev_span;
3890 let pat = self.parse_pat()?;
3892 let (err, ty) = if self.eat(&token::Colon) {
3893 // Save the state of the parser before parsing type normally, in case there is a `:`
3894 // instead of an `=` typo.
3895 let parser_snapshot_before_type = self.clone();
3896 let colon_sp = self.prev_span;
3897 match self.parse_ty() {
3898 Ok(ty) => (None, Some(ty)),
3900 // Rewind to before attempting to parse the type and continue parsing
3901 let parser_snapshot_after_type = self.clone();
3902 mem::replace(self, parser_snapshot_before_type);
3904 let snippet = self.sess.codemap().span_to_snippet(pat.span).unwrap();
3905 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
3906 (Some((parser_snapshot_after_type, colon_sp, err)), None)
3912 let init = match (self.parse_initializer(err.is_some()), err) {
3913 (Ok(init), None) => { // init parsed, ty parsed
3916 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
3917 // Could parse the type as if it were the initializer, it is likely there was a
3918 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
3919 err.span_suggestion_short(colon_sp,
3920 "use `=` if you meant to assign",
3923 // As this was parsed successfuly, continue as if the code has been fixed for the
3924 // rest of the file. It will still fail due to the emitted error, but we avoid
3928 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
3930 // Couldn't parse the type nor the initializer, only raise the type error and
3931 // return to the parser state before parsing the type as the initializer.
3932 // let x: <parse_error>;
3933 mem::replace(self, snapshot);
3936 (Err(err), None) => { // init error, ty parsed
3937 // Couldn't parse the initializer and we're not attempting to recover a failed
3938 // parse of the type, return the error.
3942 let hi = if self.token == token::Semi {
3951 id: ast::DUMMY_NODE_ID,
3957 /// Parse a structure field
3958 fn parse_name_and_ty(&mut self,
3961 attrs: Vec<Attribute>)
3962 -> PResult<'a, StructField> {
3963 let name = self.parse_ident()?;
3964 self.expect(&token::Colon)?;
3965 let ty = self.parse_ty()?;
3967 span: lo.to(self.prev_span),
3970 id: ast::DUMMY_NODE_ID,
3976 /// Emit an expected item after attributes error.
3977 fn expected_item_err(&self, attrs: &[Attribute]) {
3978 let message = match attrs.last() {
3979 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3980 _ => "expected item after attributes",
3983 self.span_err(self.prev_span, message);
3986 /// Parse a statement. This stops just before trailing semicolons on everything but items.
3987 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3988 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3989 Ok(self.parse_stmt_(true))
3992 // Eat tokens until we can be relatively sure we reached the end of the
3993 // statement. This is something of a best-effort heuristic.
3995 // We terminate when we find an unmatched `}` (without consuming it).
3996 fn recover_stmt(&mut self) {
3997 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4000 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4001 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4002 // approximate - it can mean we break too early due to macros, but that
4003 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
4005 // If `break_on_block` is `Break`, then we will stop consuming tokens
4006 // after finding (and consuming) a brace-delimited block.
4007 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4008 let mut brace_depth = 0;
4009 let mut bracket_depth = 0;
4010 let mut in_block = false;
4011 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4012 break_on_semi, break_on_block);
4014 debug!("recover_stmt_ loop {:?}", self.token);
4016 token::OpenDelim(token::DelimToken::Brace) => {
4019 if break_on_block == BlockMode::Break &&
4021 bracket_depth == 0 {
4025 token::OpenDelim(token::DelimToken::Bracket) => {
4029 token::CloseDelim(token::DelimToken::Brace) => {
4030 if brace_depth == 0 {
4031 debug!("recover_stmt_ return - close delim {:?}", self.token);
4036 if in_block && bracket_depth == 0 && brace_depth == 0 {
4037 debug!("recover_stmt_ return - block end {:?}", self.token);
4041 token::CloseDelim(token::DelimToken::Bracket) => {
4043 if bracket_depth < 0 {
4049 debug!("recover_stmt_ return - Eof");
4054 if break_on_semi == SemiColonMode::Break &&
4056 bracket_depth == 0 {
4057 debug!("recover_stmt_ return - Semi");
4068 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4069 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4071 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4076 fn is_catch_expr(&mut self) -> bool {
4077 self.token.is_keyword(keywords::Do) &&
4078 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4079 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4081 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
4082 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4085 fn is_union_item(&self) -> bool {
4086 self.token.is_keyword(keywords::Union) &&
4087 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4090 fn is_crate_vis(&self) -> bool {
4091 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4094 fn is_extern_non_path(&self) -> bool {
4095 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4098 fn is_auto_trait_item(&mut self) -> bool {
4100 (self.token.is_keyword(keywords::Auto)
4101 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4102 || // unsafe auto trait
4103 (self.token.is_keyword(keywords::Unsafe) &&
4104 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4105 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4108 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4109 -> PResult<'a, Option<P<Item>>> {
4110 let token_lo = self.span;
4111 let (ident, def) = match self.token {
4112 token::Ident(ident) if ident.name == keywords::Macro.name() => {
4114 let ident = self.parse_ident()?;
4115 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4116 match self.parse_token_tree() {
4117 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4118 _ => unreachable!(),
4120 } else if self.check(&token::OpenDelim(token::Paren)) {
4121 let args = self.parse_token_tree();
4122 let body = if self.check(&token::OpenDelim(token::Brace)) {
4123 self.parse_token_tree()
4128 TokenStream::concat(vec![
4130 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4138 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4140 token::Ident(ident) if ident.name == "macro_rules" &&
4141 self.look_ahead(1, |t| *t == token::Not) => {
4142 let prev_span = self.prev_span;
4143 self.complain_if_pub_macro(vis, prev_span);
4147 let ident = self.parse_ident()?;
4148 let (delim, tokens) = self.expect_delimited_token_tree()?;
4149 if delim != token::Brace {
4150 if !self.eat(&token::Semi) {
4151 let msg = "macros that expand to items must either \
4152 be surrounded with braces or followed by a semicolon";
4153 self.span_err(self.prev_span, msg);
4157 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4159 _ => return Ok(None),
4162 let span = lo.to(self.prev_span);
4163 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4166 fn parse_stmt_without_recovery(&mut self,
4167 macro_legacy_warnings: bool)
4168 -> PResult<'a, Option<Stmt>> {
4169 maybe_whole!(self, NtStmt, |x| Some(x));
4171 let attrs = self.parse_outer_attributes()?;
4174 Ok(Some(if self.eat_keyword(keywords::Let) {
4176 id: ast::DUMMY_NODE_ID,
4177 node: StmtKind::Local(self.parse_local(attrs.into())?),
4178 span: lo.to(self.prev_span),
4180 } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited, lo)? {
4182 id: ast::DUMMY_NODE_ID,
4183 node: StmtKind::Item(macro_def),
4184 span: lo.to(self.prev_span),
4186 // Starts like a simple path, being careful to avoid contextual keywords
4187 // such as a union items, item with `crate` visibility or auto trait items.
4188 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4189 // like a path (1 token), but it fact not a path.
4190 // `union::b::c` - path, `union U { ... }` - not a path.
4191 // `crate::b::c` - path, `crate struct S;` - not a path.
4192 // `extern::b::c` - path, `extern crate c;` - not a path.
4193 } else if self.token.is_path_start() &&
4194 !self.token.is_qpath_start() &&
4195 !self.is_union_item() &&
4196 !self.is_crate_vis() &&
4197 !self.is_extern_non_path() &&
4198 !self.is_auto_trait_item() {
4199 let pth = self.parse_path(PathStyle::Expr)?;
4201 if !self.eat(&token::Not) {
4202 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4203 self.parse_struct_expr(lo, pth, ThinVec::new())?
4205 let hi = self.prev_span;
4206 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4209 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4210 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4211 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4214 return Ok(Some(Stmt {
4215 id: ast::DUMMY_NODE_ID,
4216 node: StmtKind::Expr(expr),
4217 span: lo.to(self.prev_span),
4221 // it's a macro invocation
4222 let id = match self.token {
4223 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4224 _ => self.parse_ident()?,
4227 // check that we're pointing at delimiters (need to check
4228 // again after the `if`, because of `parse_ident`
4229 // consuming more tokens).
4230 let delim = match self.token {
4231 token::OpenDelim(delim) => delim,
4233 // we only expect an ident if we didn't parse one
4235 let ident_str = if id.name == keywords::Invalid.name() {
4240 let tok_str = self.this_token_to_string();
4241 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4247 let (_, tts) = self.expect_delimited_token_tree()?;
4248 let hi = self.prev_span;
4250 let style = if delim == token::Brace {
4251 MacStmtStyle::Braces
4253 MacStmtStyle::NoBraces
4256 if id.name == keywords::Invalid.name() {
4257 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
4258 let node = if delim == token::Brace ||
4259 self.token == token::Semi || self.token == token::Eof {
4260 StmtKind::Mac(P((mac, style, attrs.into())))
4262 // We used to incorrectly stop parsing macro-expanded statements here.
4263 // If the next token will be an error anyway but could have parsed with the
4264 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4265 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4266 // These can continue an expression, so we can't stop parsing and warn.
4267 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4268 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4269 token::BinOp(token::And) | token::BinOp(token::Or) |
4270 token::AndAnd | token::OrOr |
4271 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4274 self.warn_missing_semicolon();
4275 StmtKind::Mac(P((mac, style, attrs.into())))
4277 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4278 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4279 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4283 id: ast::DUMMY_NODE_ID,
4288 // if it has a special ident, it's definitely an item
4290 // Require a semicolon or braces.
4291 if style != MacStmtStyle::Braces {
4292 if !self.eat(&token::Semi) {
4293 self.span_err(self.prev_span,
4294 "macros that expand to items must \
4295 either be surrounded with braces or \
4296 followed by a semicolon");
4299 let span = lo.to(hi);
4301 id: ast::DUMMY_NODE_ID,
4303 node: StmtKind::Item({
4305 span, id /*id is good here*/,
4306 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
4307 Visibility::Inherited,
4313 // FIXME: Bad copy of attrs
4314 let old_directory_ownership =
4315 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4316 let item = self.parse_item_(attrs.clone(), false, true)?;
4317 self.directory.ownership = old_directory_ownership;
4321 id: ast::DUMMY_NODE_ID,
4322 span: lo.to(i.span),
4323 node: StmtKind::Item(i),
4326 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4327 if !attrs.is_empty() {
4328 if s.prev_token_kind == PrevTokenKind::DocComment {
4329 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4330 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4331 s.span_err(s.span, "expected statement after outer attribute");
4336 // Do not attempt to parse an expression if we're done here.
4337 if self.token == token::Semi {
4338 unused_attrs(&attrs, self);
4343 if self.token == token::CloseDelim(token::Brace) {
4344 unused_attrs(&attrs, self);
4348 // Remainder are line-expr stmts.
4349 let e = self.parse_expr_res(
4350 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4352 id: ast::DUMMY_NODE_ID,
4353 span: lo.to(e.span),
4354 node: StmtKind::Expr(e),
4361 /// Is this expression a successfully-parsed statement?
4362 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4363 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4364 !classify::expr_requires_semi_to_be_stmt(e)
4367 /// Parse a block. No inner attrs are allowed.
4368 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4369 maybe_whole!(self, NtBlock, |x| x);
4373 if !self.eat(&token::OpenDelim(token::Brace)) {
4375 let tok = self.this_token_to_string();
4376 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4378 // Check to see if the user has written something like
4383 // Which is valid in other languages, but not Rust.
4384 match self.parse_stmt_without_recovery(false) {
4386 let mut stmt_span = stmt.span;
4387 // expand the span to include the semicolon, if it exists
4388 if self.eat(&token::Semi) {
4389 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4391 let sugg = pprust::to_string(|s| {
4392 use print::pprust::{PrintState, INDENT_UNIT};
4393 s.ibox(INDENT_UNIT)?;
4395 s.print_stmt(&stmt)?;
4396 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4398 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4401 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4402 self.cancel(&mut e);
4409 self.parse_block_tail(lo, BlockCheckMode::Default)
4412 /// Parse a block. Inner attrs are allowed.
4413 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4414 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4417 self.expect(&token::OpenDelim(token::Brace))?;
4418 Ok((self.parse_inner_attributes()?,
4419 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4422 /// Parse the rest of a block expression or function body
4423 /// Precondition: already parsed the '{'.
4424 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4425 let mut stmts = vec![];
4426 let mut recovered = false;
4428 while !self.eat(&token::CloseDelim(token::Brace)) {
4429 let stmt = match self.parse_full_stmt(false) {
4432 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4433 self.eat(&token::CloseDelim(token::Brace));
4439 if let Some(stmt) = stmt {
4441 } else if self.token == token::Eof {
4444 // Found only `;` or `}`.
4450 id: ast::DUMMY_NODE_ID,
4452 span: lo.to(self.prev_span),
4457 /// Parse a statement, including the trailing semicolon.
4458 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4459 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4461 None => return Ok(None),
4465 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4466 // expression without semicolon
4467 if classify::expr_requires_semi_to_be_stmt(expr) {
4468 // Just check for errors and recover; do not eat semicolon yet.
4470 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4473 self.recover_stmt();
4477 StmtKind::Local(..) => {
4478 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4479 if macro_legacy_warnings && self.token != token::Semi {
4480 self.warn_missing_semicolon();
4482 self.expect_one_of(&[token::Semi], &[])?;
4488 if self.eat(&token::Semi) {
4489 stmt = stmt.add_trailing_semicolon();
4492 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4496 fn warn_missing_semicolon(&self) {
4497 self.diagnostic().struct_span_warn(self.span, {
4498 &format!("expected `;`, found `{}`", self.this_token_to_string())
4500 "This was erroneously allowed and will become a hard error in a future release"
4504 fn err_dotdotdot_syntax(&self, span: Span) {
4505 self.diagnostic().struct_span_err(span, {
4506 "`...` syntax cannot be used in expressions"
4508 "Use `..` if you need an exclusive range (a < b)"
4510 "or `..=` if you need an inclusive range (a <= b)"
4514 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4515 // BOUND = TY_BOUND | LT_BOUND
4516 // LT_BOUND = LIFETIME (e.g. `'a`)
4517 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4518 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4519 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4520 let mut bounds = Vec::new();
4522 // This needs to be syncronized with `Token::can_begin_bound`.
4523 let is_bound_start = self.check_path() || self.check_lifetime() ||
4524 self.check(&token::Question) ||
4525 self.check_keyword(keywords::For) ||
4526 self.check(&token::OpenDelim(token::Paren));
4528 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4529 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4530 if self.token.is_lifetime() {
4531 if let Some(question_span) = question {
4532 self.span_err(question_span,
4533 "`?` may only modify trait bounds, not lifetime bounds");
4535 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4538 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4539 let path = self.parse_path(PathStyle::Type)?;
4540 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4541 let modifier = if question.is_some() {
4542 TraitBoundModifier::Maybe
4544 TraitBoundModifier::None
4546 bounds.push(TraitTyParamBound(poly_trait, modifier));
4549 self.expect(&token::CloseDelim(token::Paren))?;
4550 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4551 self.span_err(self.prev_span,
4552 "parenthesized lifetime bounds are not supported");
4559 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4567 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4568 self.parse_ty_param_bounds_common(true)
4571 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4572 // BOUND = LT_BOUND (e.g. `'a`)
4573 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4574 let mut lifetimes = Vec::new();
4575 while self.check_lifetime() {
4576 lifetimes.push(self.expect_lifetime());
4578 if !self.eat(&token::BinOp(token::Plus)) {
4585 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4586 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4587 let span = self.span;
4588 let ident = self.parse_ident()?;
4590 // Parse optional colon and param bounds.
4591 let bounds = if self.eat(&token::Colon) {
4592 self.parse_ty_param_bounds()?
4597 let default = if self.eat(&token::Eq) {
4598 Some(self.parse_ty()?)
4604 attrs: preceding_attrs.into(),
4606 id: ast::DUMMY_NODE_ID,
4613 /// Parses the following grammar:
4614 /// TraitItemAssocTy = Ident ["<"...">"] [":" [TyParamBounds]] ["where" ...] ["=" Ty]
4615 fn parse_trait_item_assoc_ty(&mut self, preceding_attrs: Vec<Attribute>)
4616 -> PResult<'a, (ast::Generics, TyParam)> {
4617 let span = self.span;
4618 let ident = self.parse_ident()?;
4619 let mut generics = self.parse_generics()?;
4621 // Parse optional colon and param bounds.
4622 let bounds = if self.eat(&token::Colon) {
4623 self.parse_ty_param_bounds()?
4627 generics.where_clause = self.parse_where_clause()?;
4629 let default = if self.eat(&token::Eq) {
4630 Some(self.parse_ty()?)
4634 self.expect(&token::Semi)?;
4636 Ok((generics, TyParam {
4637 attrs: preceding_attrs.into(),
4639 id: ast::DUMMY_NODE_ID,
4646 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4647 /// trailing comma and erroneous trailing attributes.
4648 pub fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4649 let mut params = Vec::new();
4650 let mut seen_ty_param = false;
4652 let attrs = self.parse_outer_attributes()?;
4653 if self.check_lifetime() {
4654 let lifetime = self.expect_lifetime();
4655 // Parse lifetime parameter.
4656 let bounds = if self.eat(&token::Colon) {
4657 self.parse_lt_param_bounds()
4661 params.push(ast::GenericParam::Lifetime(LifetimeDef {
4662 attrs: attrs.into(),
4667 self.span_err(self.prev_span,
4668 "lifetime parameters must be declared prior to type parameters");
4670 } else if self.check_ident() {
4671 // Parse type parameter.
4672 params.push(ast::GenericParam::Type(self.parse_ty_param(attrs)?));
4673 seen_ty_param = true;
4675 // Check for trailing attributes and stop parsing.
4676 if !attrs.is_empty() {
4677 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4678 self.span_err(attrs[0].span,
4679 &format!("trailing attribute after {} parameters", param_kind));
4684 if !self.eat(&token::Comma) {
4691 /// Parse a set of optional generic type parameter declarations. Where
4692 /// clauses are not parsed here, and must be added later via
4693 /// `parse_where_clause()`.
4695 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4696 /// | ( < lifetimes , typaramseq ( , )? > )
4697 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4698 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4699 maybe_whole!(self, NtGenerics, |x| x);
4701 let span_lo = self.span;
4703 let params = self.parse_generic_params()?;
4707 where_clause: WhereClause {
4708 id: ast::DUMMY_NODE_ID,
4709 predicates: Vec::new(),
4710 span: syntax_pos::DUMMY_SP,
4712 span: span_lo.to(self.prev_span),
4715 Ok(ast::Generics::default())
4719 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4720 /// possibly including trailing comma.
4721 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4722 let mut lifetimes = Vec::new();
4723 let mut types = Vec::new();
4724 let mut bindings = Vec::new();
4725 let mut seen_type = false;
4726 let mut seen_binding = false;
4728 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4729 // Parse lifetime argument.
4730 lifetimes.push(self.expect_lifetime());
4731 if seen_type || seen_binding {
4732 self.span_err(self.prev_span,
4733 "lifetime parameters must be declared prior to type parameters");
4735 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4736 // Parse associated type binding.
4738 let ident = self.parse_ident()?;
4740 let ty = self.parse_ty()?;
4741 bindings.push(TypeBinding {
4742 id: ast::DUMMY_NODE_ID,
4745 span: lo.to(self.prev_span),
4747 seen_binding = true;
4748 } else if self.check_type() {
4749 // Parse type argument.
4750 types.push(self.parse_ty()?);
4752 self.span_err(types[types.len() - 1].span,
4753 "type parameters must be declared prior to associated type bindings");
4760 if !self.eat(&token::Comma) {
4764 Ok((lifetimes, types, bindings))
4767 /// Parses an optional `where` clause and places it in `generics`.
4769 /// ```ignore (only-for-syntax-highlight)
4770 /// where T : Trait<U, V> + 'b, 'a : 'b
4772 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4773 maybe_whole!(self, NtWhereClause, |x| x);
4775 let mut where_clause = WhereClause {
4776 id: ast::DUMMY_NODE_ID,
4777 predicates: Vec::new(),
4778 span: syntax_pos::DUMMY_SP,
4781 if !self.eat_keyword(keywords::Where) {
4782 return Ok(where_clause);
4784 let lo = self.prev_span;
4786 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4787 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4788 // change we parse those generics now, but report an error.
4789 if self.choose_generics_over_qpath() {
4790 let generics = self.parse_generics()?;
4791 self.span_err(generics.span,
4792 "generic parameters on `where` clauses are reserved for future use");
4797 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4798 let lifetime = self.expect_lifetime();
4799 // Bounds starting with a colon are mandatory, but possibly empty.
4800 self.expect(&token::Colon)?;
4801 let bounds = self.parse_lt_param_bounds();
4802 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4803 ast::WhereRegionPredicate {
4804 span: lo.to(self.prev_span),
4809 } else if self.check_type() {
4810 // Parse optional `for<'a, 'b>`.
4811 // This `for` is parsed greedily and applies to the whole predicate,
4812 // the bounded type can have its own `for` applying only to it.
4813 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4814 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4815 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4816 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4818 // Parse type with mandatory colon and (possibly empty) bounds,
4819 // or with mandatory equality sign and the second type.
4820 let ty = self.parse_ty()?;
4821 if self.eat(&token::Colon) {
4822 let bounds = self.parse_ty_param_bounds()?;
4823 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4824 ast::WhereBoundPredicate {
4825 span: lo.to(self.prev_span),
4826 bound_generic_params: lifetime_defs,
4831 // FIXME: Decide what should be used here, `=` or `==`.
4832 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4833 let rhs_ty = self.parse_ty()?;
4834 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4835 ast::WhereEqPredicate {
4836 span: lo.to(self.prev_span),
4839 id: ast::DUMMY_NODE_ID,
4843 return self.unexpected();
4849 if !self.eat(&token::Comma) {
4854 where_clause.span = lo.to(self.prev_span);
4858 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4859 -> PResult<'a, (Vec<Arg> , bool)> {
4861 let mut variadic = false;
4862 let args: Vec<Option<Arg>> =
4863 self.parse_unspanned_seq(
4864 &token::OpenDelim(token::Paren),
4865 &token::CloseDelim(token::Paren),
4866 SeqSep::trailing_allowed(token::Comma),
4868 if p.token == token::DotDotDot {
4871 if p.token != token::CloseDelim(token::Paren) {
4874 "`...` must be last in argument list for variadic function");
4879 "only foreign functions are allowed to be variadic");
4884 match p.parse_arg_general(named_args) {
4885 Ok(arg) => Ok(Some(arg)),
4888 let lo = p.prev_span;
4889 // Skip every token until next possible arg or end.
4890 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4891 // Create a placeholder argument for proper arg count (#34264).
4892 let span = lo.to(p.prev_span);
4893 Ok(Some(dummy_arg(span)))
4900 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4902 if variadic && args.is_empty() {
4904 "variadic function must be declared with at least one named argument");
4907 Ok((args, variadic))
4910 /// Parse the argument list and result type of a function declaration
4911 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4913 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4914 let ret_ty = self.parse_ret_ty(true)?;
4923 /// Returns the parsed optional self argument and whether a self shortcut was used.
4924 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4925 let expect_ident = |this: &mut Self| match this.token {
4926 // Preserve hygienic context.
4927 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4930 let isolated_self = |this: &mut Self, n| {
4931 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4932 this.look_ahead(n + 1, |t| t != &token::ModSep)
4935 // Parse optional self parameter of a method.
4936 // Only a limited set of initial token sequences is considered self parameters, anything
4937 // else is parsed as a normal function parameter list, so some lookahead is required.
4938 let eself_lo = self.span;
4939 let (eself, eself_ident) = match self.token {
4940 token::BinOp(token::And) => {
4946 if isolated_self(self, 1) {
4948 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4949 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4950 isolated_self(self, 2) {
4953 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4954 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4955 isolated_self(self, 2) {
4957 let lt = self.expect_lifetime();
4958 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4959 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4960 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4961 isolated_self(self, 3) {
4963 let lt = self.expect_lifetime();
4965 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4970 token::BinOp(token::Star) => {
4975 // Emit special error for `self` cases.
4976 if isolated_self(self, 1) {
4978 self.span_err(self.span, "cannot pass `self` by raw pointer");
4979 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4980 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4981 isolated_self(self, 2) {
4984 self.span_err(self.span, "cannot pass `self` by raw pointer");
4985 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4990 token::Ident(..) => {
4991 if isolated_self(self, 0) {
4994 let eself_ident = expect_ident(self);
4995 if self.eat(&token::Colon) {
4996 let ty = self.parse_ty()?;
4997 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4999 (SelfKind::Value(Mutability::Immutable), eself_ident)
5001 } else if self.token.is_keyword(keywords::Mut) &&
5002 isolated_self(self, 1) {
5006 let eself_ident = expect_ident(self);
5007 if self.eat(&token::Colon) {
5008 let ty = self.parse_ty()?;
5009 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
5011 (SelfKind::Value(Mutability::Mutable), eself_ident)
5017 _ => return Ok(None),
5020 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
5021 Ok(Some(Arg::from_self(eself, eself_ident)))
5024 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5025 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5026 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5028 self.expect(&token::OpenDelim(token::Paren))?;
5030 // Parse optional self argument
5031 let self_arg = self.parse_self_arg()?;
5033 // Parse the rest of the function parameter list.
5034 let sep = SeqSep::trailing_allowed(token::Comma);
5035 let fn_inputs = if let Some(self_arg) = self_arg {
5036 if self.check(&token::CloseDelim(token::Paren)) {
5038 } else if self.eat(&token::Comma) {
5039 let mut fn_inputs = vec![self_arg];
5040 fn_inputs.append(&mut self.parse_seq_to_before_end(
5041 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5045 return self.unexpected();
5048 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5051 // Parse closing paren and return type.
5052 self.expect(&token::CloseDelim(token::Paren))?;
5055 output: self.parse_ret_ty(true)?,
5060 // parse the |arg, arg| header on a lambda
5061 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5062 let inputs_captures = {
5063 if self.eat(&token::OrOr) {
5066 self.expect(&token::BinOp(token::Or))?;
5067 let args = self.parse_seq_to_before_tokens(
5068 &[&token::BinOp(token::Or), &token::OrOr],
5069 SeqSep::trailing_allowed(token::Comma),
5070 TokenExpectType::NoExpect,
5071 |p| p.parse_fn_block_arg()
5077 let output = self.parse_ret_ty(true)?;
5080 inputs: inputs_captures,
5086 /// Parse the name and optional generic types of a function header.
5087 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5088 let id = self.parse_ident()?;
5089 let generics = self.parse_generics()?;
5093 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5094 attrs: Vec<Attribute>) -> P<Item> {
5098 id: ast::DUMMY_NODE_ID,
5106 /// Parse an item-position function declaration.
5107 fn parse_item_fn(&mut self,
5109 constness: Spanned<Constness>,
5111 -> PResult<'a, ItemInfo> {
5112 let (ident, mut generics) = self.parse_fn_header()?;
5113 let decl = self.parse_fn_decl(false)?;
5114 generics.where_clause = self.parse_where_clause()?;
5115 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5116 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
5119 /// true if we are looking at `const ID`, false for things like `const fn` etc
5120 pub fn is_const_item(&mut self) -> bool {
5121 self.token.is_keyword(keywords::Const) &&
5122 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5123 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5126 /// parses all the "front matter" for a `fn` declaration, up to
5127 /// and including the `fn` keyword:
5131 /// - `const unsafe fn`
5134 pub fn parse_fn_front_matter(&mut self) -> PResult<'a, (Spanned<Constness>, Unsafety, Abi)> {
5135 let is_const_fn = self.eat_keyword(keywords::Const);
5136 let const_span = self.prev_span;
5137 let unsafety = self.parse_unsafety();
5138 let (constness, unsafety, abi) = if is_const_fn {
5139 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5141 let abi = if self.eat_keyword(keywords::Extern) {
5142 self.parse_opt_abi()?.unwrap_or(Abi::C)
5146 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5148 self.expect_keyword(keywords::Fn)?;
5149 Ok((constness, unsafety, abi))
5152 /// Parse an impl item.
5153 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5154 maybe_whole!(self, NtImplItem, |x| x);
5155 let attrs = self.parse_outer_attributes()?;
5156 let (mut item, tokens) = self.collect_tokens(|this| {
5157 this.parse_impl_item_(at_end, attrs)
5160 // See `parse_item` for why this clause is here.
5161 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5162 item.tokens = Some(tokens);
5167 fn parse_impl_item_(&mut self,
5169 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5171 let vis = self.parse_visibility(false)?;
5172 let defaultness = self.parse_defaultness();
5173 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
5174 // This parses the grammar:
5175 // ImplItemAssocTy = Ident ["<"...">"] ["where" ...] "=" Ty ";"
5176 let name = self.parse_ident()?;
5177 let mut generics = self.parse_generics()?;
5178 generics.where_clause = self.parse_where_clause()?;
5179 self.expect(&token::Eq)?;
5180 let typ = self.parse_ty()?;
5181 self.expect(&token::Semi)?;
5182 (name, ast::ImplItemKind::Type(typ), generics)
5183 } else if self.is_const_item() {
5184 // This parses the grammar:
5185 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5186 self.expect_keyword(keywords::Const)?;
5187 let name = self.parse_ident()?;
5188 self.expect(&token::Colon)?;
5189 let typ = self.parse_ty()?;
5190 self.expect(&token::Eq)?;
5191 let expr = self.parse_expr()?;
5192 self.expect(&token::Semi)?;
5193 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5195 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5196 attrs.extend(inner_attrs);
5197 (name, node, generics)
5201 id: ast::DUMMY_NODE_ID,
5202 span: lo.to(self.prev_span),
5213 fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
5214 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5219 fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
5221 Visibility::Inherited => Ok(()),
5223 let is_macro_rules: bool = match self.token {
5224 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
5228 let mut err = self.diagnostic()
5229 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5230 err.help("did you mean #[macro_export]?");
5233 let mut err = self.diagnostic()
5234 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5235 err.help("try adjusting the macro to put `pub` inside the invocation");
5242 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5243 -> DiagnosticBuilder<'a>
5245 // Given this code `path(`, it seems like this is not
5246 // setting the visibility of a macro invocation, but rather
5247 // a mistyped method declaration.
5248 // Create a diagnostic pointing out that `fn` is missing.
5250 // x | pub path(&self) {
5251 // | ^ missing `fn`, `type`, or `const`
5253 // ^^ `sp` below will point to this
5254 let sp = prev_span.between(self.prev_span);
5255 let mut err = self.diagnostic().struct_span_err(
5257 &format!("missing `fn`, `type`, or `const` for {}-item declaration",
5259 err.span_label(sp, "missing `fn`, `type`, or `const`");
5263 /// Parse a method or a macro invocation in a trait impl.
5264 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5265 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5266 ast::ImplItemKind)> {
5267 // code copied from parse_macro_use_or_failure... abstraction!
5268 if self.token.is_path_start() && !self.is_extern_non_path() {
5271 let prev_span = self.prev_span;
5274 let pth = self.parse_path(PathStyle::Mod)?;
5275 if pth.segments.len() == 1 {
5276 if !self.eat(&token::Not) {
5277 return Err(self.missing_assoc_item_kind_err("impl", prev_span));
5280 self.expect(&token::Not)?;
5283 self.complain_if_pub_macro(vis, prev_span);
5285 // eat a matched-delimiter token tree:
5287 let (delim, tts) = self.expect_delimited_token_tree()?;
5288 if delim != token::Brace {
5289 self.expect(&token::Semi)?
5292 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
5293 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5294 ast::ImplItemKind::Macro(mac)))
5296 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
5297 let ident = self.parse_ident()?;
5298 let mut generics = self.parse_generics()?;
5299 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5300 generics.where_clause = self.parse_where_clause()?;
5302 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5303 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(ast::MethodSig {
5312 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5313 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5314 let ident = self.parse_ident()?;
5315 let mut tps = self.parse_generics()?;
5317 // Parse optional colon and supertrait bounds.
5318 let bounds = if self.eat(&token::Colon) {
5319 self.parse_ty_param_bounds()?
5324 if self.eat(&token::Eq) {
5325 // it's a trait alias
5326 let bounds = self.parse_ty_param_bounds()?;
5327 tps.where_clause = self.parse_where_clause()?;
5328 self.expect(&token::Semi)?;
5329 if unsafety != Unsafety::Normal {
5330 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5332 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5334 // it's a normal trait
5335 tps.where_clause = self.parse_where_clause()?;
5336 self.expect(&token::OpenDelim(token::Brace))?;
5337 let mut trait_items = vec![];
5338 while !self.eat(&token::CloseDelim(token::Brace)) {
5339 let mut at_end = false;
5340 match self.parse_trait_item(&mut at_end) {
5341 Ok(item) => trait_items.push(item),
5345 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5350 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5354 fn choose_generics_over_qpath(&self) -> bool {
5355 // There's an ambiguity between generic parameters and qualified paths in impls.
5356 // If we see `<` it may start both, so we have to inspect some following tokens.
5357 // The following combinations can only start generics,
5358 // but not qualified paths (with one exception):
5359 // `<` `>` - empty generic parameters
5360 // `<` `#` - generic parameters with attributes
5361 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5362 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5363 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5364 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5365 // The only truly ambiguous case is
5366 // `<` IDENT `>` `::` IDENT ...
5367 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5368 // because this is what almost always expected in practice, qualified paths in impls
5369 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5370 self.token == token::Lt &&
5371 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5372 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5373 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5374 t == &token::Colon || t == &token::Eq))
5377 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5378 self.expect(&token::OpenDelim(token::Brace))?;
5379 let attrs = self.parse_inner_attributes()?;
5381 let mut impl_items = Vec::new();
5382 while !self.eat(&token::CloseDelim(token::Brace)) {
5383 let mut at_end = false;
5384 match self.parse_impl_item(&mut at_end) {
5385 Ok(impl_item) => impl_items.push(impl_item),
5389 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5394 Ok((impl_items, attrs))
5397 /// Parses an implementation item, `impl` keyword is already parsed.
5398 /// impl<'a, T> TYPE { /* impl items */ }
5399 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5400 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5401 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5402 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5403 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5404 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5405 -> PResult<'a, ItemInfo> {
5406 // First, parse generic parameters if necessary.
5407 let mut generics = if self.choose_generics_over_qpath() {
5408 self.parse_generics()?
5410 ast::Generics::default()
5413 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5414 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5416 ast::ImplPolarity::Negative
5418 ast::ImplPolarity::Positive
5421 // Parse both types and traits as a type, then reinterpret if necessary.
5422 let ty_first = self.parse_ty()?;
5424 // If `for` is missing we try to recover.
5425 let has_for = self.eat_keyword(keywords::For);
5426 let missing_for_span = self.prev_span.between(self.span);
5428 let ty_second = if self.token == token::DotDot {
5429 // We need to report this error after `cfg` expansion for compatibility reasons
5430 self.bump(); // `..`, do not add it to expected tokens
5431 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5432 } else if has_for || self.token.can_begin_type() {
5433 Some(self.parse_ty()?)
5438 generics.where_clause = self.parse_where_clause()?;
5440 let (impl_items, attrs) = self.parse_impl_body()?;
5442 let item_kind = match ty_second {
5443 Some(ty_second) => {
5444 // impl Trait for Type
5446 self.span_err(missing_for_span, "missing `for` in a trait impl");
5449 let ty_first = ty_first.into_inner();
5450 let path = match ty_first.node {
5451 // This notably includes paths passed through `ty` macro fragments (#46438).
5452 TyKind::Path(None, path) => path,
5454 self.span_err(ty_first.span, "expected a trait, found type");
5455 ast::Path::from_ident(ty_first.span, keywords::Invalid.ident())
5458 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5460 ItemKind::Impl(unsafety, polarity, defaultness,
5461 generics, Some(trait_ref), ty_second, impl_items)
5465 ItemKind::Impl(unsafety, polarity, defaultness,
5466 generics, None, ty_first, impl_items)
5470 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5473 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5474 if self.eat_keyword(keywords::For) {
5476 let params = self.parse_generic_params()?;
5479 let first_non_lifetime_param_span = params.iter()
5480 .filter_map(|param| match *param {
5481 ast::GenericParam::Lifetime(_) => None,
5482 ast::GenericParam::Type(ref t) => Some(t.span),
5486 if let Some(span) = first_non_lifetime_param_span {
5487 self.span_err(span, "only lifetime parameters can be used in this context");
5496 /// Parse struct Foo { ... }
5497 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5498 let class_name = self.parse_ident()?;
5500 let mut generics = self.parse_generics()?;
5502 // There is a special case worth noting here, as reported in issue #17904.
5503 // If we are parsing a tuple struct it is the case that the where clause
5504 // should follow the field list. Like so:
5506 // struct Foo<T>(T) where T: Copy;
5508 // If we are parsing a normal record-style struct it is the case
5509 // that the where clause comes before the body, and after the generics.
5510 // So if we look ahead and see a brace or a where-clause we begin
5511 // parsing a record style struct.
5513 // Otherwise if we look ahead and see a paren we parse a tuple-style
5516 let vdata = if self.token.is_keyword(keywords::Where) {
5517 generics.where_clause = self.parse_where_clause()?;
5518 if self.eat(&token::Semi) {
5519 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5520 VariantData::Unit(ast::DUMMY_NODE_ID)
5522 // If we see: `struct Foo<T> where T: Copy { ... }`
5523 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5525 // No `where` so: `struct Foo<T>;`
5526 } else if self.eat(&token::Semi) {
5527 VariantData::Unit(ast::DUMMY_NODE_ID)
5528 // Record-style struct definition
5529 } else if self.token == token::OpenDelim(token::Brace) {
5530 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5531 // Tuple-style struct definition with optional where-clause.
5532 } else if self.token == token::OpenDelim(token::Paren) {
5533 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5534 generics.where_clause = self.parse_where_clause()?;
5535 self.expect(&token::Semi)?;
5538 let token_str = self.this_token_to_string();
5539 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5540 name, found `{}`", token_str)))
5543 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5546 /// Parse union Foo { ... }
5547 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5548 let class_name = self.parse_ident()?;
5550 let mut generics = self.parse_generics()?;
5552 let vdata = if self.token.is_keyword(keywords::Where) {
5553 generics.where_clause = self.parse_where_clause()?;
5554 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5555 } else if self.token == token::OpenDelim(token::Brace) {
5556 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5558 let token_str = self.this_token_to_string();
5559 return Err(self.fatal(&format!("expected `where` or `{{` after union \
5560 name, found `{}`", token_str)))
5563 Ok((class_name, ItemKind::Union(vdata, generics), None))
5566 fn consume_block(&mut self, delim: token::DelimToken) {
5567 let mut brace_depth = 0;
5568 if !self.eat(&token::OpenDelim(delim)) {
5572 if self.eat(&token::OpenDelim(delim)) {
5574 } else if self.eat(&token::CloseDelim(delim)) {
5575 if brace_depth == 0 {
5581 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5589 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5590 let mut fields = Vec::new();
5591 if self.eat(&token::OpenDelim(token::Brace)) {
5592 while self.token != token::CloseDelim(token::Brace) {
5593 let field = self.parse_struct_decl_field().map_err(|e| {
5594 self.recover_stmt();
5598 Ok(field) => fields.push(field),
5604 self.eat(&token::CloseDelim(token::Brace));
5606 let token_str = self.this_token_to_string();
5607 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5615 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5616 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5617 // Unit like structs are handled in parse_item_struct function
5618 let fields = self.parse_unspanned_seq(
5619 &token::OpenDelim(token::Paren),
5620 &token::CloseDelim(token::Paren),
5621 SeqSep::trailing_allowed(token::Comma),
5623 let attrs = p.parse_outer_attributes()?;
5625 let vis = p.parse_visibility(true)?;
5626 let ty = p.parse_ty()?;
5628 span: lo.to(p.span),
5631 id: ast::DUMMY_NODE_ID,
5640 /// Parse a structure field declaration
5641 pub fn parse_single_struct_field(&mut self,
5644 attrs: Vec<Attribute> )
5645 -> PResult<'a, StructField> {
5646 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5651 token::CloseDelim(token::Brace) => {}
5652 token::DocComment(_) => {
5653 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
5654 self.bump(); // consume the doc comment
5655 if self.eat(&token::Comma) || self.token == token::CloseDelim(token::Brace) {
5661 _ => return Err(self.span_fatal_help(self.span,
5662 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5663 "struct fields should be separated by commas")),
5668 /// Parse an element of a struct definition
5669 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5670 let attrs = self.parse_outer_attributes()?;
5672 let vis = self.parse_visibility(false)?;
5673 self.parse_single_struct_field(lo, vis, attrs)
5676 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5677 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5678 /// a function definition, it's not a tuple struct field) and the contents within the parens
5679 /// isn't valid, emit a proper diagnostic.
5680 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5681 maybe_whole!(self, NtVis, |x| x);
5683 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
5684 if self.is_crate_vis() {
5685 self.bump(); // `crate`
5686 return Ok(Visibility::Crate(self.prev_span, CrateSugar::JustCrate));
5689 if !self.eat_keyword(keywords::Pub) {
5690 return Ok(Visibility::Inherited)
5693 if self.check(&token::OpenDelim(token::Paren)) {
5694 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5695 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5696 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5697 // by the following tokens.
5698 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5701 self.bump(); // `crate`
5702 let vis = Visibility::Crate(self.prev_span, CrateSugar::PubCrate);
5703 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5705 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5708 self.bump(); // `in`
5709 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5710 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5711 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5713 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5714 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5715 t.is_keyword(keywords::SelfValue)) {
5716 // `pub(self)` or `pub(super)`
5718 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5719 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5720 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5722 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5723 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5725 let msg = "incorrect visibility restriction";
5726 let suggestion = r##"some possible visibility restrictions are:
5727 `pub(crate)`: visible only on the current crate
5728 `pub(super)`: visible only in the current module's parent
5729 `pub(in path::to::module)`: visible only on the specified path"##;
5730 let path = self.parse_path(PathStyle::Mod)?;
5731 let path_span = self.prev_span;
5732 let help_msg = format!("make this visible only to module `{}` with `in`", path);
5733 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5734 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5735 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5736 err.emit(); // emit diagnostic, but continue with public visibility
5740 Ok(Visibility::Public)
5743 /// Parse defaultness: `default` or nothing.
5744 fn parse_defaultness(&mut self) -> Defaultness {
5745 // `pub` is included for better error messages
5746 if self.check_keyword(keywords::Default) &&
5747 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
5748 t.is_keyword(keywords::Const) ||
5749 t.is_keyword(keywords::Fn) ||
5750 t.is_keyword(keywords::Unsafe) ||
5751 t.is_keyword(keywords::Extern) ||
5752 t.is_keyword(keywords::Type) ||
5753 t.is_keyword(keywords::Pub)) {
5754 self.bump(); // `default`
5755 Defaultness::Default
5761 /// Given a termination token, parse all of the items in a module
5762 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5763 let mut items = vec![];
5764 while let Some(item) = self.parse_item()? {
5768 if !self.eat(term) {
5769 let token_str = self.this_token_to_string();
5770 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
5771 let msg = "consider removing this semicolon";
5772 if token_str == ";" {
5773 err.span_suggestion_short(self.span, msg, "".to_string());
5778 let hi = if self.span == syntax_pos::DUMMY_SP {
5785 inner: inner_lo.to(hi),
5790 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5791 let id = self.parse_ident()?;
5792 self.expect(&token::Colon)?;
5793 let ty = self.parse_ty()?;
5794 self.expect(&token::Eq)?;
5795 let e = self.parse_expr()?;
5796 self.expect(&token::Semi)?;
5797 let item = match m {
5798 Some(m) => ItemKind::Static(ty, m, e),
5799 None => ItemKind::Const(ty, e),
5801 Ok((id, item, None))
5804 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5805 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5806 let (in_cfg, outer_attrs) = {
5807 let mut strip_unconfigured = ::config::StripUnconfigured {
5809 should_test: false, // irrelevant
5810 features: None, // don't perform gated feature checking
5812 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5813 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5816 let id_span = self.span;
5817 let id = self.parse_ident()?;
5818 if self.check(&token::Semi) {
5820 if in_cfg && self.recurse_into_file_modules {
5821 // This mod is in an external file. Let's go get it!
5822 let ModulePathSuccess { path, directory_ownership, warn } =
5823 self.submod_path(id, &outer_attrs, id_span)?;
5824 let (module, mut attrs) =
5825 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5827 let attr = Attribute {
5828 id: attr::mk_attr_id(),
5829 style: ast::AttrStyle::Outer,
5830 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5831 Ident::from_str("warn_directory_ownership")),
5832 tokens: TokenStream::empty(),
5833 is_sugared_doc: false,
5834 span: syntax_pos::DUMMY_SP,
5836 attr::mark_known(&attr);
5839 Ok((id, module, Some(attrs)))
5841 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5842 Ok((id, ItemKind::Mod(placeholder), None))
5845 let old_directory = self.directory.clone();
5846 self.push_directory(id, &outer_attrs);
5848 self.expect(&token::OpenDelim(token::Brace))?;
5849 let mod_inner_lo = self.span;
5850 let attrs = self.parse_inner_attributes()?;
5851 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5853 self.directory = old_directory;
5854 Ok((id, ItemKind::Mod(module), Some(attrs)))
5858 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5859 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5860 self.directory.path.push(&path.as_str());
5861 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
5863 self.directory.path.push(&id.name.as_str());
5867 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
5868 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5871 /// Returns either a path to a module, or .
5872 pub fn default_submod_path(
5874 relative: Option<ast::Ident>,
5876 codemap: &CodeMap) -> ModulePath
5878 // If we're in a foo.rs file instead of a mod.rs file,
5879 // we need to look for submodules in
5880 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
5881 // `./<id>.rs` and `./<id>/mod.rs`.
5882 let relative_prefix_string;
5883 let relative_prefix = if let Some(ident) = relative {
5884 relative_prefix_string = format!("{}{}", ident.name.as_str(), path::MAIN_SEPARATOR);
5885 &relative_prefix_string
5890 let mod_name = id.to_string();
5891 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
5892 let secondary_path_str = format!("{}{}{}mod.rs",
5893 relative_prefix, mod_name, path::MAIN_SEPARATOR);
5894 let default_path = dir_path.join(&default_path_str);
5895 let secondary_path = dir_path.join(&secondary_path_str);
5896 let default_exists = codemap.file_exists(&default_path);
5897 let secondary_exists = codemap.file_exists(&secondary_path);
5899 let result = match (default_exists, secondary_exists) {
5900 (true, false) => Ok(ModulePathSuccess {
5902 directory_ownership: DirectoryOwnership::Owned {
5907 (false, true) => Ok(ModulePathSuccess {
5908 path: secondary_path,
5909 directory_ownership: DirectoryOwnership::Owned {
5914 (false, false) => Err(Error::FileNotFoundForModule {
5915 mod_name: mod_name.clone(),
5916 default_path: default_path_str,
5917 secondary_path: secondary_path_str,
5918 dir_path: format!("{}", dir_path.display()),
5920 (true, true) => Err(Error::DuplicatePaths {
5921 mod_name: mod_name.clone(),
5922 default_path: default_path_str,
5923 secondary_path: secondary_path_str,
5929 path_exists: default_exists || secondary_exists,
5934 fn submod_path(&mut self,
5936 outer_attrs: &[Attribute],
5938 -> PResult<'a, ModulePathSuccess> {
5939 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5940 return Ok(ModulePathSuccess {
5941 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5942 // All `#[path]` files are treated as though they are a `mod.rs` file.
5943 // This means that `mod foo;` declarations inside `#[path]`-included
5944 // files are siblings,
5946 // Note that this will produce weirdness when a file named `foo.rs` is
5947 // `#[path]` included and contains a `mod foo;` declaration.
5948 // If you encounter this, it's your own darn fault :P
5949 Some(_) => DirectoryOwnership::Owned { relative: None },
5950 _ => DirectoryOwnership::UnownedViaMod(true),
5957 let relative = match self.directory.ownership {
5958 DirectoryOwnership::Owned { relative } => {
5959 // Push the usage onto the list of non-mod.rs mod uses.
5960 // This is used later for feature-gate error reporting.
5961 if let Some(cur_file_ident) = relative {
5963 .non_modrs_mods.borrow_mut()
5964 .push((cur_file_ident, id_sp));
5968 DirectoryOwnership::UnownedViaBlock |
5969 DirectoryOwnership::UnownedViaMod(_) => None,
5971 let paths = Parser::default_submod_path(
5972 id, relative, &self.directory.path, self.sess.codemap());
5974 match self.directory.ownership {
5975 DirectoryOwnership::Owned { .. } => {
5976 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5978 DirectoryOwnership::UnownedViaBlock => {
5980 "Cannot declare a non-inline module inside a block \
5981 unless it has a path attribute";
5982 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5983 if paths.path_exists {
5984 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5986 err.span_note(id_sp, &msg);
5990 DirectoryOwnership::UnownedViaMod(warn) => {
5992 if let Ok(result) = paths.result {
5993 return Ok(ModulePathSuccess { warn: true, ..result });
5996 let mut err = self.diagnostic().struct_span_err(id_sp,
5997 "cannot declare a new module at this location");
5998 if id_sp != syntax_pos::DUMMY_SP {
5999 let src_path = self.sess.codemap().span_to_filename(id_sp);
6000 if let FileName::Real(src_path) = src_path {
6001 if let Some(stem) = src_path.file_stem() {
6002 let mut dest_path = src_path.clone();
6003 dest_path.set_file_name(stem);
6004 dest_path.push("mod.rs");
6005 err.span_note(id_sp,
6006 &format!("maybe move this module `{}` to its own \
6007 directory via `{}`", src_path.display(),
6008 dest_path.display()));
6012 if paths.path_exists {
6013 err.span_note(id_sp,
6014 &format!("... or maybe `use` the module `{}` instead \
6015 of possibly redeclaring it",
6023 /// Read a module from a source file.
6024 fn eval_src_mod(&mut self,
6026 directory_ownership: DirectoryOwnership,
6029 -> PResult<'a, (ast::ItemKind, Vec<Attribute> )> {
6030 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6031 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6032 let mut err = String::from("circular modules: ");
6033 let len = included_mod_stack.len();
6034 for p in &included_mod_stack[i.. len] {
6035 err.push_str(&p.to_string_lossy());
6036 err.push_str(" -> ");
6038 err.push_str(&path.to_string_lossy());
6039 return Err(self.span_fatal(id_sp, &err[..]));
6041 included_mod_stack.push(path.clone());
6042 drop(included_mod_stack);
6045 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6046 p0.cfg_mods = self.cfg_mods;
6047 let mod_inner_lo = p0.span;
6048 let mod_attrs = p0.parse_inner_attributes()?;
6049 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6050 self.sess.included_mod_stack.borrow_mut().pop();
6051 Ok((ast::ItemKind::Mod(m0), mod_attrs))
6054 /// Parse a function declaration from a foreign module
6055 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6056 -> PResult<'a, ForeignItem> {
6057 self.expect_keyword(keywords::Fn)?;
6059 let (ident, mut generics) = self.parse_fn_header()?;
6060 let decl = self.parse_fn_decl(true)?;
6061 generics.where_clause = self.parse_where_clause()?;
6063 self.expect(&token::Semi)?;
6064 Ok(ast::ForeignItem {
6067 node: ForeignItemKind::Fn(decl, generics),
6068 id: ast::DUMMY_NODE_ID,
6074 /// Parse a static item from a foreign module.
6075 /// Assumes that the `static` keyword is already parsed.
6076 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6077 -> PResult<'a, ForeignItem> {
6078 let mutbl = self.eat_keyword(keywords::Mut);
6079 let ident = self.parse_ident()?;
6080 self.expect(&token::Colon)?;
6081 let ty = self.parse_ty()?;
6083 self.expect(&token::Semi)?;
6087 node: ForeignItemKind::Static(ty, mutbl),
6088 id: ast::DUMMY_NODE_ID,
6094 /// Parse a type from a foreign module
6095 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6096 -> PResult<'a, ForeignItem> {
6097 self.expect_keyword(keywords::Type)?;
6099 let ident = self.parse_ident()?;
6101 self.expect(&token::Semi)?;
6102 Ok(ast::ForeignItem {
6105 node: ForeignItemKind::Ty,
6106 id: ast::DUMMY_NODE_ID,
6112 /// Parse extern crate links
6116 /// extern crate foo;
6117 /// extern crate bar as foo;
6118 fn parse_item_extern_crate(&mut self,
6120 visibility: Visibility,
6121 attrs: Vec<Attribute>)
6122 -> PResult<'a, P<Item>> {
6124 let crate_name = self.parse_ident()?;
6125 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
6126 (Some(crate_name.name), ident)
6130 self.expect(&token::Semi)?;
6132 let prev_span = self.prev_span;
6134 Ok(self.mk_item(lo.to(prev_span),
6136 ItemKind::ExternCrate(maybe_path),
6141 /// Parse `extern` for foreign ABIs
6144 /// `extern` is expected to have been
6145 /// consumed before calling this method
6151 fn parse_item_foreign_mod(&mut self,
6153 opt_abi: Option<Abi>,
6154 visibility: Visibility,
6155 mut attrs: Vec<Attribute>)
6156 -> PResult<'a, P<Item>> {
6157 self.expect(&token::OpenDelim(token::Brace))?;
6159 let abi = opt_abi.unwrap_or(Abi::C);
6161 attrs.extend(self.parse_inner_attributes()?);
6163 let mut foreign_items = vec![];
6164 while let Some(item) = self.parse_foreign_item()? {
6165 foreign_items.push(item);
6167 self.expect(&token::CloseDelim(token::Brace))?;
6169 let prev_span = self.prev_span;
6170 let m = ast::ForeignMod {
6172 items: foreign_items
6174 let invalid = keywords::Invalid.ident();
6175 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6178 /// Parse type Foo = Bar;
6179 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
6180 let ident = self.parse_ident()?;
6181 let mut tps = self.parse_generics()?;
6182 tps.where_clause = self.parse_where_clause()?;
6183 self.expect(&token::Eq)?;
6184 let ty = self.parse_ty()?;
6185 self.expect(&token::Semi)?;
6186 Ok((ident, ItemKind::Ty(ty, tps), None))
6189 /// Parse the part of an "enum" decl following the '{'
6190 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6191 let mut variants = Vec::new();
6192 let mut all_nullary = true;
6193 let mut any_disr = None;
6194 while self.token != token::CloseDelim(token::Brace) {
6195 let variant_attrs = self.parse_outer_attributes()?;
6196 let vlo = self.span;
6199 let mut disr_expr = None;
6200 let ident = self.parse_ident()?;
6201 if self.check(&token::OpenDelim(token::Brace)) {
6202 // Parse a struct variant.
6203 all_nullary = false;
6204 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6205 ast::DUMMY_NODE_ID);
6206 } else if self.check(&token::OpenDelim(token::Paren)) {
6207 all_nullary = false;
6208 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6209 ast::DUMMY_NODE_ID);
6210 } else if self.eat(&token::Eq) {
6211 disr_expr = Some(self.parse_expr()?);
6212 any_disr = disr_expr.as_ref().map(|expr| expr.span);
6213 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6215 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6218 let vr = ast::Variant_ {
6220 attrs: variant_attrs,
6224 variants.push(respan(vlo.to(self.prev_span), vr));
6226 if !self.eat(&token::Comma) { break; }
6228 self.expect(&token::CloseDelim(token::Brace))?;
6230 Some(disr_span) if !all_nullary =>
6231 self.span_err(disr_span,
6232 "discriminator values can only be used with a field-less enum"),
6236 Ok(ast::EnumDef { variants: variants })
6239 /// Parse an "enum" declaration
6240 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6241 let id = self.parse_ident()?;
6242 let mut generics = self.parse_generics()?;
6243 generics.where_clause = self.parse_where_clause()?;
6244 self.expect(&token::OpenDelim(token::Brace))?;
6246 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6247 self.recover_stmt();
6248 self.eat(&token::CloseDelim(token::Brace));
6251 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6254 /// Parses a string as an ABI spec on an extern type or module. Consumes
6255 /// the `extern` keyword, if one is found.
6256 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6258 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6260 self.expect_no_suffix(sp, "ABI spec", suf);
6262 match abi::lookup(&s.as_str()) {
6263 Some(abi) => Ok(Some(abi)),
6265 let prev_span = self.prev_span;
6268 &format!("invalid ABI: expected one of [{}], \
6270 abi::all_names().join(", "),
6281 fn is_static_global(&mut self) -> bool {
6282 if self.check_keyword(keywords::Static) {
6283 // Check if this could be a closure
6284 !self.look_ahead(1, |token| {
6285 if token.is_keyword(keywords::Move) {
6289 token::BinOp(token::Or) | token::OrOr => true,
6298 /// Parse one of the items allowed by the flags.
6299 /// NB: this function no longer parses the items inside an
6301 fn parse_item_(&mut self, attrs: Vec<Attribute>,
6302 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
6303 maybe_whole!(self, NtItem, |item| {
6304 let mut item = item.into_inner();
6305 let mut attrs = attrs;
6306 mem::swap(&mut item.attrs, &mut attrs);
6307 item.attrs.extend(attrs);
6313 let visibility = self.parse_visibility(false)?;
6315 if self.eat_keyword(keywords::Use) {
6317 let item_ = ItemKind::Use(P(self.parse_use_tree(false)?));
6318 self.expect(&token::Semi)?;
6320 let prev_span = self.prev_span;
6321 let invalid = keywords::Invalid.ident();
6322 let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
6323 return Ok(Some(item));
6326 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6327 self.bump(); // `extern`
6328 if self.eat_keyword(keywords::Crate) {
6329 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6332 let opt_abi = self.parse_opt_abi()?;
6334 if self.eat_keyword(keywords::Fn) {
6335 // EXTERN FUNCTION ITEM
6336 let fn_span = self.prev_span;
6337 let abi = opt_abi.unwrap_or(Abi::C);
6338 let (ident, item_, extra_attrs) =
6339 self.parse_item_fn(Unsafety::Normal,
6340 respan(fn_span, Constness::NotConst),
6342 let prev_span = self.prev_span;
6343 let item = self.mk_item(lo.to(prev_span),
6347 maybe_append(attrs, extra_attrs));
6348 return Ok(Some(item));
6349 } else if self.check(&token::OpenDelim(token::Brace)) {
6350 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6356 if self.is_static_global() {
6359 let m = if self.eat_keyword(keywords::Mut) {
6362 Mutability::Immutable
6364 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6365 let prev_span = self.prev_span;
6366 let item = self.mk_item(lo.to(prev_span),
6370 maybe_append(attrs, extra_attrs));
6371 return Ok(Some(item));
6373 if self.eat_keyword(keywords::Const) {
6374 let const_span = self.prev_span;
6375 if self.check_keyword(keywords::Fn)
6376 || (self.check_keyword(keywords::Unsafe)
6377 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6378 // CONST FUNCTION ITEM
6379 let unsafety = self.parse_unsafety();
6381 let (ident, item_, extra_attrs) =
6382 self.parse_item_fn(unsafety,
6383 respan(const_span, Constness::Const),
6385 let prev_span = self.prev_span;
6386 let item = self.mk_item(lo.to(prev_span),
6390 maybe_append(attrs, extra_attrs));
6391 return Ok(Some(item));
6395 if self.eat_keyword(keywords::Mut) {
6396 let prev_span = self.prev_span;
6397 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6398 .help("did you mean to declare a static?")
6401 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6402 let prev_span = self.prev_span;
6403 let item = self.mk_item(lo.to(prev_span),
6407 maybe_append(attrs, extra_attrs));
6408 return Ok(Some(item));
6410 if self.check_keyword(keywords::Unsafe) &&
6411 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
6412 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
6414 // UNSAFE TRAIT ITEM
6415 self.bump(); // `unsafe`
6416 let is_auto = if self.eat_keyword(keywords::Trait) {
6419 self.expect_keyword(keywords::Auto)?;
6420 self.expect_keyword(keywords::Trait)?;
6423 let (ident, item_, extra_attrs) =
6424 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
6425 let prev_span = self.prev_span;
6426 let item = self.mk_item(lo.to(prev_span),
6430 maybe_append(attrs, extra_attrs));
6431 return Ok(Some(item));
6433 if self.check_keyword(keywords::Impl) ||
6434 self.check_keyword(keywords::Unsafe) &&
6435 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6436 self.check_keyword(keywords::Default) &&
6437 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6438 self.check_keyword(keywords::Default) &&
6439 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
6441 let defaultness = self.parse_defaultness();
6442 let unsafety = self.parse_unsafety();
6443 self.expect_keyword(keywords::Impl)?;
6444 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
6445 let span = lo.to(self.prev_span);
6446 return Ok(Some(self.mk_item(span, ident, item, visibility,
6447 maybe_append(attrs, extra_attrs))));
6449 if self.check_keyword(keywords::Fn) {
6452 let fn_span = self.prev_span;
6453 let (ident, item_, extra_attrs) =
6454 self.parse_item_fn(Unsafety::Normal,
6455 respan(fn_span, Constness::NotConst),
6457 let prev_span = self.prev_span;
6458 let item = self.mk_item(lo.to(prev_span),
6462 maybe_append(attrs, extra_attrs));
6463 return Ok(Some(item));
6465 if self.check_keyword(keywords::Unsafe)
6466 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
6467 // UNSAFE FUNCTION ITEM
6468 self.bump(); // `unsafe`
6469 let abi = if self.eat_keyword(keywords::Extern) {
6470 self.parse_opt_abi()?.unwrap_or(Abi::C)
6474 self.expect_keyword(keywords::Fn)?;
6475 let fn_span = self.prev_span;
6476 let (ident, item_, extra_attrs) =
6477 self.parse_item_fn(Unsafety::Unsafe,
6478 respan(fn_span, Constness::NotConst),
6480 let prev_span = self.prev_span;
6481 let item = self.mk_item(lo.to(prev_span),
6485 maybe_append(attrs, extra_attrs));
6486 return Ok(Some(item));
6488 if self.eat_keyword(keywords::Mod) {
6490 let (ident, item_, extra_attrs) =
6491 self.parse_item_mod(&attrs[..])?;
6492 let prev_span = self.prev_span;
6493 let item = self.mk_item(lo.to(prev_span),
6497 maybe_append(attrs, extra_attrs));
6498 return Ok(Some(item));
6500 if self.eat_keyword(keywords::Type) {
6502 let (ident, item_, extra_attrs) = self.parse_item_type()?;
6503 let prev_span = self.prev_span;
6504 let item = self.mk_item(lo.to(prev_span),
6508 maybe_append(attrs, extra_attrs));
6509 return Ok(Some(item));
6511 if self.eat_keyword(keywords::Enum) {
6513 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
6514 let prev_span = self.prev_span;
6515 let item = self.mk_item(lo.to(prev_span),
6519 maybe_append(attrs, extra_attrs));
6520 return Ok(Some(item));
6522 if self.check_keyword(keywords::Trait)
6523 || (self.check_keyword(keywords::Auto)
6524 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
6526 let is_auto = if self.eat_keyword(keywords::Trait) {
6529 self.expect_keyword(keywords::Auto)?;
6530 self.expect_keyword(keywords::Trait)?;
6534 let (ident, item_, extra_attrs) =
6535 self.parse_item_trait(is_auto, Unsafety::Normal)?;
6536 let prev_span = self.prev_span;
6537 let item = self.mk_item(lo.to(prev_span),
6541 maybe_append(attrs, extra_attrs));
6542 return Ok(Some(item));
6544 if self.eat_keyword(keywords::Struct) {
6546 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6547 let prev_span = self.prev_span;
6548 let item = self.mk_item(lo.to(prev_span),
6552 maybe_append(attrs, extra_attrs));
6553 return Ok(Some(item));
6555 if self.is_union_item() {
6558 let (ident, item_, extra_attrs) = self.parse_item_union()?;
6559 let prev_span = self.prev_span;
6560 let item = self.mk_item(lo.to(prev_span),
6564 maybe_append(attrs, extra_attrs));
6565 return Ok(Some(item));
6567 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
6568 return Ok(Some(macro_def));
6571 // Verify wether we have encountered a struct or method definition where the user forgot to
6572 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
6573 if visibility == Visibility::Public &&
6574 self.check_ident() &&
6575 self.look_ahead(1, |t| *t != token::Not)
6577 // Space between `pub` keyword and the identifier
6580 // ^^^ `sp` points here
6581 let sp = self.prev_span.between(self.span);
6582 let full_sp = self.prev_span.to(self.span);
6583 let ident_sp = self.span;
6584 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
6585 // possible public struct definition where `struct` was forgotten
6586 let ident = self.parse_ident().unwrap();
6587 let msg = format!("add `struct` here to parse `{}` as a public struct",
6589 let mut err = self.diagnostic()
6590 .struct_span_err(sp, "missing `struct` for struct definition");
6591 err.span_suggestion_short(sp, &msg, " struct ".into());
6593 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
6594 let ident = self.parse_ident().unwrap();
6595 self.consume_block(token::Paren);
6596 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
6597 self.check(&token::OpenDelim(token::Brace))
6599 ("fn", "method", false)
6600 } else if self.check(&token::Colon) {
6604 ("fn` or `struct", "method or struct", true)
6607 let msg = format!("missing `{}` for {} definition", kw, kw_name);
6608 let mut err = self.diagnostic().struct_span_err(sp, &msg);
6610 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
6614 err.span_suggestion_short(sp, &suggestion, format!(" {} ", kw));
6616 if let Ok(snippet) = self.sess.codemap().span_to_snippet(ident_sp) {
6617 err.span_suggestion(
6619 "if you meant to call a macro, write instead",
6620 format!("{}!", snippet));
6622 err.help("if you meant to call a macro, remove the `pub` \
6623 and add a trailing `!` after the identifier");
6629 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
6632 /// Parse a foreign item.
6633 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
6634 let attrs = self.parse_outer_attributes()?;
6636 let visibility = self.parse_visibility(false)?;
6638 // FOREIGN STATIC ITEM
6639 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
6640 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
6641 if self.token.is_keyword(keywords::Const) {
6643 .struct_span_err(self.span, "extern items cannot be `const`")
6644 .span_suggestion(self.span, "instead try using", "static".to_owned())
6647 self.bump(); // `static` or `const`
6648 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6650 // FOREIGN FUNCTION ITEM
6651 if self.check_keyword(keywords::Fn) {
6652 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6654 // FOREIGN TYPE ITEM
6655 if self.check_keyword(keywords::Type) {
6656 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
6659 // FIXME #5668: this will occur for a macro invocation:
6660 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
6662 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
6668 /// This is the fall-through for parsing items.
6669 fn parse_macro_use_or_failure(
6671 attrs: Vec<Attribute> ,
6672 macros_allowed: bool,
6673 attributes_allowed: bool,
6675 visibility: Visibility
6676 ) -> PResult<'a, Option<P<Item>>> {
6677 if macros_allowed && self.token.is_path_start() {
6678 // MACRO INVOCATION ITEM
6680 let prev_span = self.prev_span;
6681 self.complain_if_pub_macro(&visibility, prev_span);
6683 let mac_lo = self.span;
6686 let pth = self.parse_path(PathStyle::Mod)?;
6687 self.expect(&token::Not)?;
6689 // a 'special' identifier (like what `macro_rules!` uses)
6690 // is optional. We should eventually unify invoc syntax
6692 let id = if self.token.is_ident() {
6695 keywords::Invalid.ident() // no special identifier
6697 // eat a matched-delimiter token tree:
6698 let (delim, tts) = self.expect_delimited_token_tree()?;
6699 if delim != token::Brace {
6700 if !self.eat(&token::Semi) {
6701 self.span_err(self.prev_span,
6702 "macros that expand to items must either \
6703 be surrounded with braces or followed by \
6708 let hi = self.prev_span;
6709 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6710 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6711 return Ok(Some(item));
6714 // FAILURE TO PARSE ITEM
6716 Visibility::Inherited => {}
6718 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
6722 if !attributes_allowed && !attrs.is_empty() {
6723 self.expected_item_err(&attrs);
6728 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
6729 where F: FnOnce(&mut Self) -> PResult<'a, R>
6731 // Record all tokens we parse when parsing this item.
6732 let mut tokens = Vec::new();
6733 match self.token_cursor.frame.last_token {
6734 LastToken::Collecting(_) => {
6735 panic!("cannot collect tokens recursively yet")
6737 LastToken::Was(ref mut last) => tokens.extend(last.take()),
6739 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
6740 let prev = self.token_cursor.stack.len();
6742 let last_token = if self.token_cursor.stack.len() == prev {
6743 &mut self.token_cursor.frame.last_token
6745 &mut self.token_cursor.stack[prev].last_token
6747 let mut tokens = match *last_token {
6748 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
6749 LastToken::Was(_) => panic!("our vector went away?"),
6752 // If we're not at EOF our current token wasn't actually consumed by
6753 // `f`, but it'll still be in our list that we pulled out. In that case
6755 if self.token == token::Eof {
6756 *last_token = LastToken::Was(None);
6758 *last_token = LastToken::Was(tokens.pop());
6761 Ok((ret?, tokens.into_iter().collect()))
6764 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6765 let attrs = self.parse_outer_attributes()?;
6767 let (ret, tokens) = self.collect_tokens(|this| {
6768 this.parse_item_(attrs, true, false)
6771 // Once we've parsed an item and recorded the tokens we got while
6772 // parsing we may want to store `tokens` into the item we're about to
6773 // return. Note, though, that we specifically didn't capture tokens
6774 // related to outer attributes. The `tokens` field here may later be
6775 // used with procedural macros to convert this item back into a token
6776 // stream, but during expansion we may be removing attributes as we go
6779 // If we've got inner attributes then the `tokens` we've got above holds
6780 // these inner attributes. If an inner attribute is expanded we won't
6781 // actually remove it from the token stream, so we'll just keep yielding
6782 // it (bad!). To work around this case for now we just avoid recording
6783 // `tokens` if we detect any inner attributes. This should help keep
6784 // expansion correct, but we should fix this bug one day!
6787 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6788 i.tokens = Some(tokens);
6795 /// `{` or `::{` or `*` or `::*`
6796 /// `::{` or `::*` (also `{` or `*` if unprefixed is true)
6797 fn is_import_coupler(&mut self, unprefixed: bool) -> bool {
6798 self.is_import_coupler_inner(&token::OpenDelim(token::Brace), unprefixed) ||
6799 self.is_import_coupler_inner(&token::BinOp(token::Star), unprefixed)
6802 fn is_import_coupler_inner(&mut self, token: &token::Token, unprefixed: bool) -> bool {
6803 if self.check(&token::ModSep) {
6804 self.look_ahead(1, |t| t == token)
6805 } else if unprefixed {
6814 /// USE_TREE = `*` |
6815 /// `{` USE_TREE_LIST `}` |
6817 /// PATH `::` `{` USE_TREE_LIST `}` |
6818 /// PATH [`as` IDENT]
6819 fn parse_use_tree(&mut self, nested: bool) -> PResult<'a, UseTree> {
6822 let mut prefix = ast::Path {
6824 span: lo.to(self.span),
6827 let kind = if self.is_import_coupler(true) {
6828 // `use *;` or `use ::*;` or `use {...};` `use ::{...};`
6830 // Remove the first `::`
6831 if self.eat(&token::ModSep) {
6832 prefix.segments.push(PathSegment::crate_root(self.prev_span));
6834 prefix.segments.push(PathSegment::crate_root(self.span));
6837 if self.eat(&token::BinOp(token::Star)) {
6840 } else if self.check(&token::OpenDelim(token::Brace)) {
6842 UseTreeKind::Nested(self.parse_use_tree_list()?)
6844 return self.unexpected();
6848 let mut parsed = self.parse_path(PathStyle::Mod)?;
6850 parsed = parsed.default_to_global();
6853 prefix.segments.append(&mut parsed.segments);
6854 prefix.span = prefix.span.to(parsed.span);
6856 if self.eat(&token::ModSep) {
6857 if self.eat(&token::BinOp(token::Star)) {
6860 } else if self.check(&token::OpenDelim(token::Brace)) {
6861 // `use path::{...};`
6862 UseTreeKind::Nested(self.parse_use_tree_list()?)
6864 return self.unexpected();
6867 // `use path::foo;` or `use path::foo as bar;`
6868 let rename = self.parse_rename()?.
6869 unwrap_or(prefix.segments.last().unwrap().identifier);
6870 UseTreeKind::Simple(rename)
6875 span: lo.to(self.prev_span),
6881 /// Parse UseTreeKind::Nested(list)
6883 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
6884 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
6885 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
6886 &token::CloseDelim(token::Brace),
6887 SeqSep::trailing_allowed(token::Comma), |this| {
6888 Ok((this.parse_use_tree(true)?, ast::DUMMY_NODE_ID))
6892 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6893 if self.eat_keyword(keywords::As) {
6894 self.parse_ident().map(Some)
6900 /// Parses a source module as a crate. This is the main
6901 /// entry point for the parser.
6902 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6905 attrs: self.parse_inner_attributes()?,
6906 module: self.parse_mod_items(&token::Eof, lo)?,
6907 span: lo.to(self.span),
6911 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6912 let ret = match self.token {
6913 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6914 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6921 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6922 match self.parse_optional_str() {
6923 Some((s, style, suf)) => {
6924 let sp = self.prev_span;
6925 self.expect_no_suffix(sp, "string literal", suf);
6928 _ => Err(self.fatal("expected string literal"))