1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use ast::{AngleBracketedParameterData, ParenthesizedParameterData, AttrStyle, BareFnTy};
13 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
15 use ast::{Mod, Arg, Arm, Attribute, BindingMode, TraitItemKind};
17 use ast::{BlockCheckMode, CaptureBy};
18 use ast::{Constness, Crate};
21 use ast::{Expr, ExprKind, RangeLimits};
22 use ast::{Field, FnDecl};
23 use ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
24 use ast::GenericParam;
25 use ast::{Ident, ImplItem, IsAuto, Item, ItemKind};
26 use ast::{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, 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>, rhs: Option<Vec<Attribute>>)
156 if let Some(ref attrs) = rhs {
157 lhs.extend(attrs.iter().cloned())
162 #[derive(Debug, Clone, Copy, PartialEq)]
173 trait RecoverQPath: Sized {
174 const PATH_STYLE: PathStyle = PathStyle::Expr;
175 fn to_ty(&self) -> Option<P<Ty>>;
176 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self;
177 fn to_string(&self) -> String;
180 impl RecoverQPath for Ty {
181 const PATH_STYLE: PathStyle = PathStyle::Type;
182 fn to_ty(&self) -> Option<P<Ty>> {
183 Some(P(self.clone()))
185 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
186 Self { span: path.span, node: TyKind::Path(qself, path), id: self.id }
188 fn to_string(&self) -> String {
189 pprust::ty_to_string(self)
193 impl RecoverQPath for Pat {
194 fn to_ty(&self) -> Option<P<Ty>> {
197 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
198 Self { span: path.span, node: PatKind::Path(qself, path), id: self.id }
200 fn to_string(&self) -> String {
201 pprust::pat_to_string(self)
205 impl RecoverQPath for Expr {
206 fn to_ty(&self) -> Option<P<Ty>> {
209 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
210 Self { span: path.span, node: ExprKind::Path(qself, path),
211 id: self.id, attrs: self.attrs.clone() }
213 fn to_string(&self) -> String {
214 pprust::expr_to_string(self)
218 /* ident is handled by common.rs */
221 pub struct Parser<'a> {
222 pub sess: &'a ParseSess,
223 /// the current token:
224 pub token: token::Token,
225 /// the span of the current token:
227 /// the span of the previous token:
228 pub meta_var_span: Option<Span>,
230 /// the previous token kind
231 prev_token_kind: PrevTokenKind,
232 pub restrictions: Restrictions,
233 /// The set of seen errors about obsolete syntax. Used to suppress
234 /// extra detail when the same error is seen twice
235 pub obsolete_set: HashSet<ObsoleteSyntax>,
236 /// Used to determine the path to externally loaded source files
237 pub directory: Directory,
238 /// Whether to parse sub-modules in other files.
239 pub recurse_into_file_modules: bool,
240 /// Name of the root module this parser originated from. If `None`, then the
241 /// name is not known. This does not change while the parser is descending
242 /// into modules, and sub-parsers have new values for this name.
243 pub root_module_name: Option<String>,
244 pub expected_tokens: Vec<TokenType>,
245 token_cursor: TokenCursor,
246 pub desugar_doc_comments: bool,
247 /// Whether we should configure out of line modules as we parse.
254 frame: TokenCursorFrame,
255 stack: Vec<TokenCursorFrame>,
259 struct TokenCursorFrame {
260 delim: token::DelimToken,
263 tree_cursor: tokenstream::Cursor,
265 last_token: LastToken,
268 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
269 /// by the parser, and then that's transitively used to record the tokens that
270 /// each parse AST item is created with.
272 /// Right now this has two states, either collecting tokens or not collecting
273 /// tokens. If we're collecting tokens we just save everything off into a local
274 /// `Vec`. This should eventually though likely save tokens from the original
275 /// token stream and just use slicing of token streams to avoid creation of a
276 /// whole new vector.
278 /// The second state is where we're passively not recording tokens, but the last
279 /// token is still tracked for when we want to start recording tokens. This
280 /// "last token" means that when we start recording tokens we'll want to ensure
281 /// that this, the first token, is included in the output.
283 /// You can find some more example usage of this in the `collect_tokens` method
287 Collecting(Vec<TokenTree>),
288 Was(Option<TokenTree>),
291 impl TokenCursorFrame {
292 fn new(sp: Span, delimited: &Delimited) -> Self {
294 delim: delimited.delim,
296 open_delim: delimited.delim == token::NoDelim,
297 tree_cursor: delimited.stream().into_trees(),
298 close_delim: delimited.delim == token::NoDelim,
299 last_token: LastToken::Was(None),
305 fn next(&mut self) -> TokenAndSpan {
307 let tree = if !self.frame.open_delim {
308 self.frame.open_delim = true;
309 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
310 .open_tt(self.frame.span)
311 } else if let Some(tree) = self.frame.tree_cursor.next() {
313 } else if !self.frame.close_delim {
314 self.frame.close_delim = true;
315 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
316 .close_tt(self.frame.span)
317 } else if let Some(frame) = self.stack.pop() {
321 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
324 match self.frame.last_token {
325 LastToken::Collecting(ref mut v) => v.push(tree.clone()),
326 LastToken::Was(ref mut t) => *t = Some(tree.clone()),
330 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
331 TokenTree::Delimited(sp, ref delimited) => {
332 let frame = TokenCursorFrame::new(sp, delimited);
333 self.stack.push(mem::replace(&mut self.frame, frame));
339 fn next_desugared(&mut self) -> TokenAndSpan {
340 let (sp, name) = match self.next() {
341 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
345 let stripped = strip_doc_comment_decoration(&name.as_str());
347 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
348 // required to wrap the text.
349 let mut num_of_hashes = 0;
351 for ch in stripped.chars() {
354 '#' if count > 0 => count + 1,
357 num_of_hashes = cmp::max(num_of_hashes, count);
360 let body = TokenTree::Delimited(sp, Delimited {
361 delim: token::Bracket,
362 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"))),
363 TokenTree::Token(sp, token::Eq),
364 TokenTree::Token(sp, token::Literal(
365 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
366 .iter().cloned().collect::<TokenStream>().into(),
369 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
370 delim: token::NoDelim,
371 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
372 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
373 .iter().cloned().collect::<TokenStream>().into()
375 [TokenTree::Token(sp, token::Pound), body]
376 .iter().cloned().collect::<TokenStream>().into()
384 #[derive(PartialEq, Eq, Clone)]
387 Keyword(keywords::Keyword),
396 fn to_string(&self) -> String {
398 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
399 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
400 TokenType::Operator => "an operator".to_string(),
401 TokenType::Lifetime => "lifetime".to_string(),
402 TokenType::Ident => "identifier".to_string(),
403 TokenType::Path => "path".to_string(),
404 TokenType::Type => "type".to_string(),
409 // Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
410 // `IDENT<<u8 as Trait>::AssocTy>`, `IDENT(u8, u8) -> u8`.
411 fn can_continue_type_after_ident(t: &token::Token) -> bool {
412 t == &token::ModSep || t == &token::Lt ||
413 t == &token::BinOp(token::Shl) || t == &token::OpenDelim(token::Paren)
416 /// Information about the path to a module.
417 pub struct ModulePath {
419 pub path_exists: bool,
420 pub result: Result<ModulePathSuccess, Error>,
423 pub struct ModulePathSuccess {
425 pub directory_ownership: DirectoryOwnership,
429 pub struct ModulePathError {
431 pub help_msg: String,
435 FileNotFoundForModule {
437 default_path: String,
438 secondary_path: String,
443 default_path: String,
444 secondary_path: String,
447 InclusiveRangeWithNoEnd,
451 pub fn span_err(self, sp: Span, handler: &errors::Handler) -> DiagnosticBuilder {
453 Error::FileNotFoundForModule { ref mod_name,
457 let mut err = struct_span_err!(handler, sp, E0583,
458 "file not found for module `{}`", mod_name);
459 err.help(&format!("name the file either {} or {} inside the directory {:?}",
465 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
466 let mut err = struct_span_err!(handler, sp, E0584,
467 "file for module `{}` found at both {} and {}",
471 err.help("delete or rename one of them to remove the ambiguity");
474 Error::UselessDocComment => {
475 let mut err = struct_span_err!(handler, sp, E0585,
476 "found a documentation comment that doesn't document anything");
477 err.help("doc comments must come before what they document, maybe a comment was \
478 intended with `//`?");
481 Error::InclusiveRangeWithNoEnd => {
482 let mut err = struct_span_err!(handler, sp, E0586,
483 "inclusive range with no end");
484 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
494 AttributesParsed(ThinVec<Attribute>),
495 AlreadyParsed(P<Expr>),
498 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
499 fn from(o: Option<ThinVec<Attribute>>) -> Self {
500 if let Some(attrs) = o {
501 LhsExpr::AttributesParsed(attrs)
503 LhsExpr::NotYetParsed
508 impl From<P<Expr>> for LhsExpr {
509 fn from(expr: P<Expr>) -> Self {
510 LhsExpr::AlreadyParsed(expr)
514 /// Create a placeholder argument.
515 fn dummy_arg(span: Span) -> Arg {
516 let spanned = Spanned {
518 node: keywords::Invalid.ident()
521 id: ast::DUMMY_NODE_ID,
522 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), spanned, None),
528 id: ast::DUMMY_NODE_ID
530 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
533 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
534 enum TokenExpectType {
539 impl<'a> Parser<'a> {
540 pub fn new(sess: &'a ParseSess,
542 directory: Option<Directory>,
543 recurse_into_file_modules: bool,
544 desugar_doc_comments: bool)
546 let mut parser = Parser {
548 token: token::Underscore,
549 span: syntax_pos::DUMMY_SP,
550 prev_span: syntax_pos::DUMMY_SP,
552 prev_token_kind: PrevTokenKind::Other,
553 restrictions: Restrictions::empty(),
554 obsolete_set: HashSet::new(),
555 recurse_into_file_modules,
556 directory: Directory {
557 path: PathBuf::new(),
558 ownership: DirectoryOwnership::Owned { relative: None }
560 root_module_name: None,
561 expected_tokens: Vec::new(),
562 token_cursor: TokenCursor {
563 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
564 delim: token::NoDelim,
569 desugar_doc_comments,
573 let tok = parser.next_tok();
574 parser.token = tok.tok;
575 parser.span = tok.sp;
577 if let Some(directory) = directory {
578 parser.directory = directory;
579 } else if !parser.span.source_equal(&DUMMY_SP) {
580 if let FileName::Real(path) = sess.codemap().span_to_unmapped_path(parser.span) {
581 parser.directory.path = path;
582 parser.directory.path.pop();
586 parser.process_potential_macro_variable();
590 fn next_tok(&mut self) -> TokenAndSpan {
591 let mut next = if self.desugar_doc_comments {
592 self.token_cursor.next_desugared()
594 self.token_cursor.next()
596 if next.sp == syntax_pos::DUMMY_SP {
597 next.sp = self.prev_span;
602 /// Convert a token to a string using self's reader
603 pub fn token_to_string(token: &token::Token) -> String {
604 pprust::token_to_string(token)
607 /// Convert the current token to a string using self's reader
608 pub fn this_token_to_string(&self) -> String {
609 Parser::token_to_string(&self.token)
612 pub fn this_token_descr(&self) -> String {
613 let prefix = match &self.token {
614 t if t.is_special_ident() => "reserved identifier ",
615 t if t.is_used_keyword() => "keyword ",
616 t if t.is_unused_keyword() => "reserved keyword ",
619 format!("{}`{}`", prefix, self.this_token_to_string())
622 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
623 let token_str = Parser::token_to_string(t);
624 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
627 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
628 match self.expect_one_of(&[], &[]) {
630 Ok(_) => unreachable!(),
634 /// Expect and consume the token t. Signal an error if
635 /// the next token is not t.
636 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
637 if self.expected_tokens.is_empty() {
638 if self.token == *t {
642 let token_str = Parser::token_to_string(t);
643 let this_token_str = self.this_token_to_string();
644 Err(self.fatal(&format!("expected `{}`, found `{}`",
649 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
653 /// Expect next token to be edible or inedible token. If edible,
654 /// then consume it; if inedible, then return without consuming
655 /// anything. Signal a fatal error if next token is unexpected.
656 pub fn expect_one_of(&mut self,
657 edible: &[token::Token],
658 inedible: &[token::Token]) -> PResult<'a, ()>{
659 fn tokens_to_string(tokens: &[TokenType]) -> String {
660 let mut i = tokens.iter();
661 // This might be a sign we need a connect method on Iterator.
663 .map_or("".to_string(), |t| t.to_string());
664 i.enumerate().fold(b, |mut b, (i, a)| {
665 if tokens.len() > 2 && i == tokens.len() - 2 {
667 } else if tokens.len() == 2 && i == tokens.len() - 2 {
672 b.push_str(&a.to_string());
676 if edible.contains(&self.token) {
679 } else if inedible.contains(&self.token) {
680 // leave it in the input
683 let mut expected = edible.iter()
684 .map(|x| TokenType::Token(x.clone()))
685 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
686 .chain(self.expected_tokens.iter().cloned())
687 .collect::<Vec<_>>();
688 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
690 let expect = tokens_to_string(&expected[..]);
691 let actual = self.this_token_to_string();
692 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
693 let short_expect = if expected.len() > 6 {
694 format!("{} possible tokens", expected.len())
698 (format!("expected one of {}, found `{}`", expect, actual),
699 (self.prev_span.next_point(), format!("expected one of {} here", short_expect)))
700 } else if expected.is_empty() {
701 (format!("unexpected token: `{}`", actual),
702 (self.prev_span, "unexpected token after this".to_string()))
704 (format!("expected {}, found `{}`", expect, actual),
705 (self.prev_span.next_point(), format!("expected {} here", expect)))
707 let mut err = self.fatal(&msg_exp);
708 let sp = if self.token == token::Token::Eof {
709 // This is EOF, don't want to point at the following char, but rather the last token
715 let cm = self.sess.codemap();
716 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
717 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
718 // When the spans are in the same line, it means that the only content between
719 // them is whitespace, point at the found token in that case:
721 // X | () => { syntax error };
722 // | ^^^^^ expected one of 8 possible tokens here
724 // instead of having:
726 // X | () => { syntax error };
727 // | -^^^^^ unexpected token
729 // | expected one of 8 possible tokens here
730 err.span_label(self.span, label_exp);
733 err.span_label(sp, label_exp);
734 err.span_label(self.span, "unexpected token");
741 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
742 fn interpolated_or_expr_span(&self,
743 expr: PResult<'a, P<Expr>>)
744 -> PResult<'a, (Span, P<Expr>)> {
746 if self.prev_token_kind == PrevTokenKind::Interpolated {
754 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
757 if self.token.is_reserved_ident() {
758 self.span_err(self.span, &format!("expected identifier, found {}",
759 self.this_token_descr()));
765 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
766 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
768 let mut err = self.fatal(&format!("expected identifier, found `{}`",
769 self.this_token_to_string()));
770 if self.token == token::Underscore {
771 err.note("`_` is a wildcard pattern, not an identifier");
779 /// Check if the next token is `tok`, and return `true` if so.
781 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
783 pub fn check(&mut self, tok: &token::Token) -> bool {
784 let is_present = self.token == *tok;
785 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
789 /// Consume token 'tok' if it exists. Returns true if the given
790 /// token was present, false otherwise.
791 pub fn eat(&mut self, tok: &token::Token) -> bool {
792 let is_present = self.check(tok);
793 if is_present { self.bump() }
797 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
798 self.expected_tokens.push(TokenType::Keyword(kw));
799 self.token.is_keyword(kw)
802 /// If the next token is the given keyword, eat it and return
803 /// true. Otherwise, return false.
804 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
805 if self.check_keyword(kw) {
813 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
814 if self.token.is_keyword(kw) {
822 /// If the given word is not a keyword, signal an error.
823 /// If the next token is not the given word, signal an error.
824 /// Otherwise, eat it.
825 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
826 if !self.eat_keyword(kw) {
833 fn check_ident(&mut self) -> bool {
834 if self.token.is_ident() {
837 self.expected_tokens.push(TokenType::Ident);
842 fn check_path(&mut self) -> bool {
843 if self.token.is_path_start() {
846 self.expected_tokens.push(TokenType::Path);
851 fn check_type(&mut self) -> bool {
852 if self.token.can_begin_type() {
855 self.expected_tokens.push(TokenType::Type);
860 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
861 /// `&` and continue. If an `&` is not seen, signal an error.
862 fn expect_and(&mut self) -> PResult<'a, ()> {
863 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
865 token::BinOp(token::And) => {
870 let span = self.span.with_lo(self.span.lo() + BytePos(1));
871 Ok(self.bump_with(token::BinOp(token::And), span))
873 _ => self.unexpected()
877 /// Expect and consume an `|`. If `||` is seen, replace it with a single
878 /// `|` and continue. If an `|` is not seen, signal an error.
879 fn expect_or(&mut self) -> PResult<'a, ()> {
880 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
882 token::BinOp(token::Or) => {
887 let span = self.span.with_lo(self.span.lo() + BytePos(1));
888 Ok(self.bump_with(token::BinOp(token::Or), span))
890 _ => self.unexpected()
894 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
896 None => {/* everything ok */}
898 let text = suf.as_str();
900 self.span_bug(sp, "found empty literal suffix in Some")
902 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
907 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
908 /// `<` and continue. If a `<` is not seen, return false.
910 /// This is meant to be used when parsing generics on a path to get the
912 fn eat_lt(&mut self) -> bool {
913 self.expected_tokens.push(TokenType::Token(token::Lt));
919 token::BinOp(token::Shl) => {
920 let span = self.span.with_lo(self.span.lo() + BytePos(1));
921 self.bump_with(token::Lt, span);
928 fn expect_lt(&mut self) -> PResult<'a, ()> {
936 /// Expect and consume a GT. if a >> is seen, replace it
937 /// with a single > and continue. If a GT is not seen,
939 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
940 self.expected_tokens.push(TokenType::Token(token::Gt));
946 token::BinOp(token::Shr) => {
947 let span = self.span.with_lo(self.span.lo() + BytePos(1));
948 Ok(self.bump_with(token::Gt, span))
950 token::BinOpEq(token::Shr) => {
951 let span = self.span.with_lo(self.span.lo() + BytePos(1));
952 Ok(self.bump_with(token::Ge, span))
955 let span = self.span.with_lo(self.span.lo() + BytePos(1));
956 Ok(self.bump_with(token::Eq, span))
958 _ => self.unexpected()
962 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
963 sep: Option<token::Token>,
965 -> PResult<'a, (Vec<T>, bool)>
966 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
968 let mut v = Vec::new();
969 // This loop works by alternating back and forth between parsing types
970 // and commas. For example, given a string `A, B,>`, the parser would
971 // first parse `A`, then a comma, then `B`, then a comma. After that it
972 // would encounter a `>` and stop. This lets the parser handle trailing
973 // commas in generic parameters, because it can stop either after
974 // parsing a type or after parsing a comma.
976 if self.check(&token::Gt)
977 || self.token == token::BinOp(token::Shr)
978 || self.token == token::Ge
979 || self.token == token::BinOpEq(token::Shr) {
985 Some(result) => v.push(result),
986 None => return Ok((v, true))
989 if let Some(t) = sep.as_ref() {
995 return Ok((v, false));
998 /// Parse a sequence bracketed by '<' and '>', stopping
1000 pub fn parse_seq_to_before_gt<T, F>(&mut self,
1001 sep: Option<token::Token>,
1003 -> PResult<'a, Vec<T>> where
1004 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1006 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
1007 |p| Ok(Some(f(p)?)))?;
1012 pub fn parse_seq_to_gt<T, F>(&mut self,
1013 sep: Option<token::Token>,
1015 -> PResult<'a, Vec<T>> where
1016 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1018 let v = self.parse_seq_to_before_gt(sep, f)?;
1023 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
1024 sep: Option<token::Token>,
1026 -> PResult<'a, (Vec<T>, bool)> where
1027 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
1029 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
1033 return Ok((v, returned));
1036 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1037 /// passes through any errors encountered. Used for error recovery.
1038 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1039 let handler = self.diagnostic();
1041 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1043 TokenExpectType::Expect,
1044 |p| Ok(p.parse_token_tree())) {
1045 handler.cancel(err);
1049 /// Parse a sequence, including the closing delimiter. The function
1050 /// f must consume tokens until reaching the next separator or
1051 /// closing bracket.
1052 pub fn parse_seq_to_end<T, F>(&mut self,
1056 -> PResult<'a, Vec<T>> where
1057 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1059 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1064 /// Parse a sequence, not including the closing delimiter. The function
1065 /// f must consume tokens until reaching the next separator or
1066 /// closing bracket.
1067 pub fn parse_seq_to_before_end<T, F>(&mut self,
1071 -> PResult<'a, Vec<T>>
1072 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1074 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1077 fn parse_seq_to_before_tokens<T, F>(&mut self,
1078 kets: &[&token::Token],
1080 expect: TokenExpectType,
1082 -> PResult<'a, Vec<T>>
1083 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1085 let mut first: bool = true;
1087 while !kets.contains(&&self.token) {
1089 token::CloseDelim(..) | token::Eof => break,
1092 if let Some(ref t) = sep.sep {
1096 if let Err(mut e) = self.expect(t) {
1097 // Attempt to keep parsing if it was a similar separator
1098 if let Some(ref tokens) = t.similar_tokens() {
1099 if tokens.contains(&self.token) {
1104 // Attempt to keep parsing if it was an omitted separator
1118 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1120 TokenExpectType::Expect => self.check(k),
1121 TokenExpectType::NoExpect => self.token == **k,
1134 /// Parse a sequence, including the closing delimiter. The function
1135 /// f must consume tokens until reaching the next separator or
1136 /// closing bracket.
1137 pub fn parse_unspanned_seq<T, F>(&mut self,
1142 -> PResult<'a, Vec<T>> where
1143 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1146 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1147 if self.token == *ket {
1153 // NB: Do not use this function unless you actually plan to place the
1154 // spanned list in the AST.
1155 pub fn parse_seq<T, F>(&mut self,
1160 -> PResult<'a, Spanned<Vec<T>>> where
1161 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1165 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1168 Ok(respan(lo.to(hi), result))
1171 /// Advance the parser by one token
1172 pub fn bump(&mut self) {
1173 if self.prev_token_kind == PrevTokenKind::Eof {
1174 // Bumping after EOF is a bad sign, usually an infinite loop.
1175 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1178 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1180 // Record last token kind for possible error recovery.
1181 self.prev_token_kind = match self.token {
1182 token::DocComment(..) => PrevTokenKind::DocComment,
1183 token::Comma => PrevTokenKind::Comma,
1184 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1185 token::Interpolated(..) => PrevTokenKind::Interpolated,
1186 token::Eof => PrevTokenKind::Eof,
1187 token::Ident(..) => PrevTokenKind::Ident,
1188 _ => PrevTokenKind::Other,
1191 let next = self.next_tok();
1192 self.span = next.sp;
1193 self.token = next.tok;
1194 self.expected_tokens.clear();
1195 // check after each token
1196 self.process_potential_macro_variable();
1199 /// Advance the parser using provided token as a next one. Use this when
1200 /// consuming a part of a token. For example a single `<` from `<<`.
1201 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1202 self.prev_span = self.span.with_hi(span.lo());
1203 // It would be incorrect to record the kind of the current token, but
1204 // fortunately for tokens currently using `bump_with`, the
1205 // prev_token_kind will be of no use anyway.
1206 self.prev_token_kind = PrevTokenKind::Other;
1209 self.expected_tokens.clear();
1212 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1213 F: FnOnce(&token::Token) -> R,
1216 return f(&self.token)
1219 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1220 Some(tree) => match tree {
1221 TokenTree::Token(_, tok) => tok,
1222 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1224 None => token::CloseDelim(self.token_cursor.frame.delim),
1228 fn look_ahead_span(&self, dist: usize) -> Span {
1233 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1234 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1235 None => self.look_ahead_span(dist - 1),
1238 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1239 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1241 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1242 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1244 pub fn span_fatal_err(&self, sp: Span, err: Error) -> DiagnosticBuilder<'a> {
1245 err.span_err(sp, self.diagnostic())
1247 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1248 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1252 pub fn bug(&self, m: &str) -> ! {
1253 self.sess.span_diagnostic.span_bug(self.span, m)
1255 pub fn warn(&self, m: &str) {
1256 self.sess.span_diagnostic.span_warn(self.span, m)
1258 pub fn span_warn(&self, sp: Span, m: &str) {
1259 self.sess.span_diagnostic.span_warn(sp, m)
1261 pub fn span_err(&self, sp: Span, m: &str) {
1262 self.sess.span_diagnostic.span_err(sp, m)
1264 pub fn struct_span_err(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1265 self.sess.span_diagnostic.struct_span_err(sp, m)
1267 pub fn span_err_help(&self, sp: Span, m: &str, h: &str) {
1268 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1272 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1273 self.sess.span_diagnostic.span_bug(sp, m)
1275 pub fn abort_if_errors(&self) {
1276 self.sess.span_diagnostic.abort_if_errors();
1279 fn cancel(&self, err: &mut DiagnosticBuilder) {
1280 self.sess.span_diagnostic.cancel(err)
1283 pub fn diagnostic(&self) -> &'a errors::Handler {
1284 &self.sess.span_diagnostic
1287 /// Is the current token one of the keywords that signals a bare function
1289 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1290 self.check_keyword(keywords::Fn) ||
1291 self.check_keyword(keywords::Unsafe) ||
1292 self.check_keyword(keywords::Extern)
1295 fn get_label(&mut self) -> ast::Ident {
1297 token::Lifetime(ref ident) => *ident,
1298 token::Interpolated(ref nt) => match nt.0 {
1299 token::NtLifetime(lifetime) => lifetime.ident,
1300 _ => self.bug("not a lifetime"),
1302 _ => self.bug("not a lifetime"),
1306 /// parse a TyKind::BareFn type:
1307 pub fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>)
1308 -> PResult<'a, TyKind> {
1311 [unsafe] [extern "ABI"] fn (S) -> T
1321 let unsafety = self.parse_unsafety()?;
1322 let abi = if self.eat_keyword(keywords::Extern) {
1323 self.parse_opt_abi()?.unwrap_or(Abi::C)
1328 self.expect_keyword(keywords::Fn)?;
1329 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1330 let ret_ty = self.parse_ret_ty()?;
1331 let decl = P(FnDecl {
1336 Ok(TyKind::BareFn(P(BareFnTy {
1344 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1345 if self.eat_keyword(keywords::Unsafe) {
1346 return Ok(Unsafety::Unsafe);
1348 return Ok(Unsafety::Normal);
1352 /// Parse the items in a trait declaration
1353 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1354 maybe_whole!(self, NtTraitItem, |x| x);
1355 let attrs = self.parse_outer_attributes()?;
1356 let (mut item, tokens) = self.collect_tokens(|this| {
1357 this.parse_trait_item_(at_end, attrs)
1359 // See `parse_item` for why this clause is here.
1360 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1361 item.tokens = Some(tokens);
1366 fn parse_trait_item_(&mut self,
1368 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1371 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1372 let (generics, TyParam {ident, bounds, default, ..}) =
1373 self.parse_trait_item_assoc_ty(vec![])?;
1374 (ident, TraitItemKind::Type(bounds, default), generics)
1375 } else if self.is_const_item() {
1376 self.expect_keyword(keywords::Const)?;
1377 let ident = self.parse_ident()?;
1378 self.expect(&token::Colon)?;
1379 let ty = self.parse_ty()?;
1380 let default = if self.check(&token::Eq) {
1382 let expr = self.parse_expr()?;
1383 self.expect(&token::Semi)?;
1386 self.expect(&token::Semi)?;
1389 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1390 } else if self.token.is_path_start() && !self.is_extern_non_path() {
1391 // trait item macro.
1392 // code copied from parse_macro_use_or_failure... abstraction!
1393 let prev_span = self.prev_span;
1395 let pth = self.parse_path(PathStyle::Mod)?;
1397 if pth.segments.len() == 1 {
1398 if !self.eat(&token::Not) {
1399 return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1402 self.expect(&token::Not)?;
1405 // eat a matched-delimiter token tree:
1406 let (delim, tts) = self.expect_delimited_token_tree()?;
1407 if delim != token::Brace {
1408 self.expect(&token::Semi)?
1411 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1412 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1414 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
1416 let ident = self.parse_ident()?;
1417 let mut generics = self.parse_generics()?;
1419 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1420 // This is somewhat dubious; We don't want to allow
1421 // argument names to be left off if there is a
1423 p.parse_arg_general(false)
1425 generics.where_clause = self.parse_where_clause()?;
1427 let sig = ast::MethodSig {
1434 let body = match self.token {
1438 debug!("parse_trait_methods(): parsing required method");
1441 token::OpenDelim(token::Brace) => {
1442 debug!("parse_trait_methods(): parsing provided method");
1444 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1445 attrs.extend(inner_attrs.iter().cloned());
1449 let token_str = self.this_token_to_string();
1450 return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1453 (ident, ast::TraitItemKind::Method(sig, body), generics)
1457 id: ast::DUMMY_NODE_ID,
1462 span: lo.to(self.prev_span),
1467 /// Parse optional return type [ -> TY ] in function decl
1468 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1469 if self.eat(&token::RArrow) {
1470 Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
1472 Ok(FunctionRetTy::Default(self.span.with_hi(self.span.lo())))
1477 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1478 self.parse_ty_common(true, true)
1481 /// Parse a type in restricted contexts where `+` is not permitted.
1482 /// Example 1: `&'a TYPE`
1483 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1484 /// Example 2: `value1 as TYPE + value2`
1485 /// `+` is prohibited to avoid interactions with expression grammar.
1486 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1487 self.parse_ty_common(false, true)
1490 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1491 -> PResult<'a, P<Ty>> {
1492 maybe_whole!(self, NtTy, |x| x);
1495 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1496 // `(TYPE)` is a parenthesized type.
1497 // `(TYPE,)` is a tuple with a single field of type TYPE.
1498 let mut ts = vec![];
1499 let mut last_comma = false;
1500 while self.token != token::CloseDelim(token::Paren) {
1501 ts.push(self.parse_ty()?);
1502 if self.eat(&token::Comma) {
1509 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1510 self.expect(&token::CloseDelim(token::Paren))?;
1512 if ts.len() == 1 && !last_comma {
1513 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1514 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1516 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1517 TyKind::Path(None, ref path) if maybe_bounds => {
1518 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1520 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1521 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1522 let path = match bounds[0] {
1523 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1524 _ => self.bug("unexpected lifetime bound"),
1526 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1529 _ => TyKind::Paren(P(ty))
1534 } else if self.eat(&token::Not) {
1537 } else if self.eat(&token::BinOp(token::Star)) {
1539 TyKind::Ptr(self.parse_ptr()?)
1540 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1542 let t = self.parse_ty()?;
1543 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1544 let t = match self.maybe_parse_fixed_length_of_vec()? {
1545 None => TyKind::Slice(t),
1546 Some(suffix) => TyKind::Array(t, suffix),
1548 self.expect(&token::CloseDelim(token::Bracket))?;
1550 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1553 self.parse_borrowed_pointee()?
1554 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1556 // In order to not be ambiguous, the type must be surrounded by parens.
1557 self.expect(&token::OpenDelim(token::Paren))?;
1558 let e = self.parse_expr()?;
1559 self.expect(&token::CloseDelim(token::Paren))?;
1561 } else if self.eat(&token::Underscore) {
1562 // A type to be inferred `_`
1564 } else if self.token_is_bare_fn_keyword() {
1565 // Function pointer type
1566 self.parse_ty_bare_fn(Vec::new())?
1567 } else if self.check_keyword(keywords::For) {
1568 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1569 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1570 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1572 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1573 if self.token_is_bare_fn_keyword() {
1574 self.parse_ty_bare_fn(lifetime_defs)?
1576 let path = self.parse_path(PathStyle::Type)?;
1577 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1578 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1580 } else if self.eat_keyword(keywords::Impl) {
1581 // FIXME: figure out priority of `+` in `impl Trait1 + Trait2` (#34511).
1582 TyKind::ImplTrait(self.parse_ty_param_bounds()?)
1583 } else if self.check_keyword(keywords::Dyn) &&
1584 self.look_ahead(1, |t| t.can_begin_bound() && !can_continue_type_after_ident(t)) {
1585 // FIXME: figure out priority of `+` in `dyn Trait1 + Trait2` (#34511).
1586 self.bump(); // `dyn`
1587 TyKind::TraitObject(self.parse_ty_param_bounds()?, TraitObjectSyntax::Dyn)
1588 } else if self.check(&token::Question) ||
1589 self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)) {
1590 // Bound list (trait object type)
1591 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?,
1592 TraitObjectSyntax::None)
1593 } else if self.eat_lt() {
1595 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1596 TyKind::Path(Some(qself), path)
1597 } else if self.token.is_path_start() {
1599 let path = self.parse_path(PathStyle::Type)?;
1600 if self.eat(&token::Not) {
1601 // Macro invocation in type position
1602 let (_, tts) = self.expect_delimited_token_tree()?;
1603 TyKind::Mac(respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts }))
1605 // Just a type path or bound list (trait object type) starting with a trait.
1607 // `Trait1 + Trait2 + 'a`
1608 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1609 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1611 TyKind::Path(None, path)
1615 let msg = format!("expected type, found {}", self.this_token_descr());
1616 return Err(self.fatal(&msg));
1619 let span = lo.to(self.prev_span);
1620 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1622 // Try to recover from use of `+` with incorrect priority.
1623 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1624 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1629 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1630 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1631 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1632 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1635 bounds.append(&mut self.parse_ty_param_bounds()?);
1637 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1640 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1641 // Do not add `+` to expected tokens.
1642 if !allow_plus || self.token != token::BinOp(token::Plus) {
1647 let bounds = self.parse_ty_param_bounds()?;
1648 let sum_span = ty.span.to(self.prev_span);
1650 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1651 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1654 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1655 let sum_with_parens = pprust::to_string(|s| {
1656 use print::pprust::PrintState;
1659 s.print_opt_lifetime(lifetime)?;
1660 s.print_mutability(mut_ty.mutbl)?;
1662 s.print_type(&mut_ty.ty)?;
1663 s.print_bounds(" +", &bounds)?;
1666 err.span_suggestion(sum_span, "try adding parentheses", sum_with_parens);
1668 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1669 err.span_label(sum_span, "perhaps you forgot parentheses?");
1672 err.span_label(sum_span, "expected a path");
1679 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1680 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1682 // Do not add `::` to expected tokens.
1683 if !allow_recovery || self.token != token::ModSep {
1686 let ty = match base.to_ty() {
1688 None => return Ok(base),
1691 self.bump(); // `::`
1692 let mut segments = Vec::new();
1693 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1695 let span = ty.span.to(self.prev_span);
1697 base.to_recovered(Some(QSelf { ty, position: 0 }), ast::Path { segments, span });
1700 .struct_span_err(span, "missing angle brackets in associated item path")
1701 .span_suggestion(span, "try", recovered.to_string()).emit();
1706 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1707 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1708 let mutbl = self.parse_mutability();
1709 let ty = self.parse_ty_no_plus()?;
1710 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1713 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1714 let mutbl = if self.eat_keyword(keywords::Mut) {
1716 } else if self.eat_keyword(keywords::Const) {
1717 Mutability::Immutable
1719 let span = self.prev_span;
1721 "expected mut or const in raw pointer type (use \
1722 `*mut T` or `*const T` as appropriate)");
1723 Mutability::Immutable
1725 let t = self.parse_ty_no_plus()?;
1726 Ok(MutTy { ty: t, mutbl: mutbl })
1729 fn is_named_argument(&mut self) -> bool {
1730 let offset = match self.token {
1731 token::Interpolated(ref nt) => match nt.0 {
1732 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1735 token::BinOp(token::And) | token::AndAnd => 1,
1736 _ if self.token.is_keyword(keywords::Mut) => 1,
1740 self.look_ahead(offset, |t| t.is_ident() || t == &token::Underscore) &&
1741 self.look_ahead(offset + 1, |t| t == &token::Colon)
1744 /// This version of parse arg doesn't necessarily require
1745 /// identifier names.
1746 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1747 maybe_whole!(self, NtArg, |x| x);
1749 let pat = if require_name || self.is_named_argument() {
1750 debug!("parse_arg_general parse_pat (require_name:{})",
1752 let pat = self.parse_pat()?;
1754 self.expect(&token::Colon)?;
1757 debug!("parse_arg_general ident_to_pat");
1758 let sp = self.prev_span;
1759 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1761 id: ast::DUMMY_NODE_ID,
1762 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1768 let t = self.parse_ty()?;
1773 id: ast::DUMMY_NODE_ID,
1777 /// Parse a single function argument
1778 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1779 self.parse_arg_general(true)
1782 /// Parse an argument in a lambda header e.g. |arg, arg|
1783 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1784 let pat = self.parse_pat()?;
1785 let t = if self.eat(&token::Colon) {
1789 id: ast::DUMMY_NODE_ID,
1790 node: TyKind::Infer,
1797 id: ast::DUMMY_NODE_ID
1801 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1802 if self.eat(&token::Semi) {
1803 Ok(Some(self.parse_expr()?))
1809 /// Matches token_lit = LIT_INTEGER | ...
1810 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1811 let out = match self.token {
1812 token::Interpolated(ref nt) => match nt.0 {
1813 token::NtExpr(ref v) => match v.node {
1814 ExprKind::Lit(ref lit) => { lit.node.clone() }
1815 _ => { return self.unexpected_last(&self.token); }
1817 _ => { return self.unexpected_last(&self.token); }
1819 token::Literal(lit, suf) => {
1820 let diag = Some((self.span, &self.sess.span_diagnostic));
1821 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1825 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1830 _ => { return self.unexpected_last(&self.token); }
1837 /// Matches lit = true | false | token_lit
1838 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1840 let lit = if self.eat_keyword(keywords::True) {
1842 } else if self.eat_keyword(keywords::False) {
1843 LitKind::Bool(false)
1845 let lit = self.parse_lit_token()?;
1848 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1851 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1852 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1853 maybe_whole_expr!(self);
1855 let minus_lo = self.span;
1856 let minus_present = self.eat(&token::BinOp(token::Minus));
1858 let literal = P(self.parse_lit()?);
1859 let hi = self.prev_span;
1860 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1863 let minus_hi = self.prev_span;
1864 let unary = self.mk_unary(UnOp::Neg, expr);
1865 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1871 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1873 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1877 _ => self.parse_ident(),
1881 /// Parses qualified path.
1882 /// Assumes that the leading `<` has been parsed already.
1884 /// `qualified_path = <type [as trait_ref]>::path`
1888 /// `<T as U>::F::a<S>` (without disambiguator)
1889 /// `<T as U>::F::a::<S>` (with disambiguator)
1890 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1891 let lo = self.prev_span;
1892 let ty = self.parse_ty()?;
1893 let mut path = if self.eat_keyword(keywords::As) {
1894 self.parse_path(PathStyle::Type)?
1896 ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP }
1898 self.expect(&token::Gt)?;
1899 self.expect(&token::ModSep)?;
1901 let qself = QSelf { ty, position: path.segments.len() };
1902 self.parse_path_segments(&mut path.segments, style, true)?;
1904 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1907 /// Parses simple paths.
1909 /// `path = [::] segment+`
1910 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1913 /// `a::b::C<D>` (without disambiguator)
1914 /// `a::b::C::<D>` (with disambiguator)
1915 /// `Fn(Args)` (without disambiguator)
1916 /// `Fn::(Args)` (with disambiguator)
1917 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1918 self.parse_path_common(style, true)
1921 pub fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1922 -> PResult<'a, ast::Path> {
1923 maybe_whole!(self, NtPath, |path| {
1924 if style == PathStyle::Mod &&
1925 path.segments.iter().any(|segment| segment.parameters.is_some()) {
1926 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1931 let lo = self.meta_var_span.unwrap_or(self.span);
1932 let mut segments = Vec::new();
1933 if self.eat(&token::ModSep) {
1934 segments.push(PathSegment::crate_root(lo));
1936 self.parse_path_segments(&mut segments, style, enable_warning)?;
1938 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1941 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1942 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1943 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1944 let meta_ident = match self.token {
1945 token::Interpolated(ref nt) => match nt.0 {
1946 token::NtMeta(ref meta) => match meta.node {
1947 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
1954 if let Some(ident) = meta_ident {
1956 return Ok(ast::Path::from_ident(self.prev_span, ident));
1958 self.parse_path(style)
1961 fn parse_path_segments(&mut self,
1962 segments: &mut Vec<PathSegment>,
1964 enable_warning: bool)
1965 -> PResult<'a, ()> {
1967 segments.push(self.parse_path_segment(style, enable_warning)?);
1969 if self.is_import_coupler(false) || !self.eat(&token::ModSep) {
1975 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
1976 -> PResult<'a, PathSegment> {
1977 let ident_span = self.span;
1978 let ident = self.parse_path_segment_ident()?;
1980 let is_args_start = |token: &token::Token| match *token {
1981 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
1984 let check_args_start = |this: &mut Self| {
1985 this.expected_tokens.extend_from_slice(
1986 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
1988 is_args_start(&this.token)
1991 Ok(if style == PathStyle::Type && check_args_start(self) ||
1992 style != PathStyle::Mod && self.check(&token::ModSep)
1993 && self.look_ahead(1, |t| is_args_start(t)) {
1994 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
1996 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
1997 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
1998 .span_label(self.prev_span, "try removing `::`").emit();
2001 let parameters = if self.eat_lt() {
2003 let (lifetimes, types, bindings) = self.parse_generic_args()?;
2005 let span = lo.to(self.prev_span);
2006 AngleBracketedParameterData { lifetimes, types, bindings, span }.into()
2010 let inputs = self.parse_seq_to_before_tokens(
2011 &[&token::CloseDelim(token::Paren)],
2012 SeqSep::trailing_allowed(token::Comma),
2013 TokenExpectType::Expect,
2016 let output = if self.eat(&token::RArrow) {
2017 Some(self.parse_ty_common(false, false)?)
2021 let span = lo.to(self.prev_span);
2022 ParenthesizedParameterData { inputs, output, span }.into()
2025 PathSegment { identifier: ident, span: ident_span, parameters }
2027 // Generic arguments are not found.
2028 PathSegment::from_ident(ident, ident_span)
2032 fn check_lifetime(&mut self) -> bool {
2033 self.expected_tokens.push(TokenType::Lifetime);
2034 self.token.is_lifetime()
2037 /// Parse single lifetime 'a or panic.
2038 pub fn expect_lifetime(&mut self) -> Lifetime {
2039 if let Some(lifetime) = self.token.lifetime(self.span) {
2043 self.span_bug(self.span, "not a lifetime")
2047 /// Parse mutability (`mut` or nothing).
2048 fn parse_mutability(&mut self) -> Mutability {
2049 if self.eat_keyword(keywords::Mut) {
2052 Mutability::Immutable
2056 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2057 if let token::Literal(token::Integer(name), None) = self.token {
2059 Ok(Ident::with_empty_ctxt(name))
2065 /// Parse ident (COLON expr)?
2066 pub fn parse_field(&mut self) -> PResult<'a, Field> {
2067 let attrs = self.parse_outer_attributes()?;
2071 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2072 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2073 let fieldname = self.parse_field_name()?;
2075 hi = self.prev_span;
2076 (fieldname, self.parse_expr()?, false)
2078 let fieldname = self.parse_ident()?;
2079 hi = self.prev_span;
2081 // Mimic `x: x` for the `x` field shorthand.
2082 let path = ast::Path::from_ident(lo.to(hi), fieldname);
2083 (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
2086 ident: respan(lo.to(hi), fieldname),
2087 span: lo.to(expr.span),
2090 attrs: attrs.into(),
2094 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2095 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2098 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2099 ExprKind::Unary(unop, expr)
2102 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2103 ExprKind::Binary(binop, lhs, rhs)
2106 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2107 ExprKind::Call(f, args)
2110 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2111 ExprKind::Index(expr, idx)
2114 pub fn mk_range(&mut self,
2115 start: Option<P<Expr>>,
2116 end: Option<P<Expr>>,
2117 limits: RangeLimits)
2118 -> PResult<'a, ast::ExprKind> {
2119 if end.is_none() && limits == RangeLimits::Closed {
2120 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2122 Ok(ExprKind::Range(start, end, limits))
2126 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2127 ExprKind::TupField(expr, idx)
2130 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2131 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2132 ExprKind::AssignOp(binop, lhs, rhs)
2135 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2137 id: ast::DUMMY_NODE_ID,
2138 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2144 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2145 let span = &self.span;
2146 let lv_lit = P(codemap::Spanned {
2147 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2152 id: ast::DUMMY_NODE_ID,
2153 node: ExprKind::Lit(lv_lit),
2159 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2161 token::OpenDelim(delim) => match self.parse_token_tree() {
2162 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2163 _ => unreachable!(),
2165 _ => Err(self.fatal("expected open delimiter")),
2169 /// At the bottom (top?) of the precedence hierarchy,
2170 /// parse things like parenthesized exprs,
2171 /// macros, return, etc.
2173 /// NB: This does not parse outer attributes,
2174 /// and is private because it only works
2175 /// correctly if called from parse_dot_or_call_expr().
2176 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2177 maybe_whole_expr!(self);
2179 // Outer attributes are already parsed and will be
2180 // added to the return value after the fact.
2182 // Therefore, prevent sub-parser from parsing
2183 // attributes by giving them a empty "already parsed" list.
2184 let mut attrs = ThinVec::new();
2187 let mut hi = self.span;
2191 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2193 token::OpenDelim(token::Paren) => {
2196 attrs.extend(self.parse_inner_attributes()?);
2198 // (e) is parenthesized e
2199 // (e,) is a tuple with only one field, e
2200 let mut es = vec![];
2201 let mut trailing_comma = false;
2202 while self.token != token::CloseDelim(token::Paren) {
2203 es.push(self.parse_expr()?);
2204 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2205 if self.check(&token::Comma) {
2206 trailing_comma = true;
2210 trailing_comma = false;
2216 hi = self.prev_span;
2217 ex = if es.len() == 1 && !trailing_comma {
2218 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2223 token::OpenDelim(token::Brace) => {
2224 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2226 token::BinOp(token::Or) | token::OrOr => {
2228 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2230 token::OpenDelim(token::Bracket) => {
2233 attrs.extend(self.parse_inner_attributes()?);
2235 if self.check(&token::CloseDelim(token::Bracket)) {
2238 ex = ExprKind::Array(Vec::new());
2241 let first_expr = self.parse_expr()?;
2242 if self.check(&token::Semi) {
2243 // Repeating array syntax: [ 0; 512 ]
2245 let count = self.parse_expr()?;
2246 self.expect(&token::CloseDelim(token::Bracket))?;
2247 ex = ExprKind::Repeat(first_expr, count);
2248 } else if self.check(&token::Comma) {
2249 // Vector with two or more elements.
2251 let remaining_exprs = self.parse_seq_to_end(
2252 &token::CloseDelim(token::Bracket),
2253 SeqSep::trailing_allowed(token::Comma),
2254 |p| Ok(p.parse_expr()?)
2256 let mut exprs = vec![first_expr];
2257 exprs.extend(remaining_exprs);
2258 ex = ExprKind::Array(exprs);
2260 // Vector with one element.
2261 self.expect(&token::CloseDelim(token::Bracket))?;
2262 ex = ExprKind::Array(vec![first_expr]);
2265 hi = self.prev_span;
2269 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2271 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2273 if self.eat_keyword(keywords::Move) {
2274 let lo = self.prev_span;
2275 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2277 if self.eat_keyword(keywords::If) {
2278 return self.parse_if_expr(attrs);
2280 if self.eat_keyword(keywords::For) {
2281 let lo = self.prev_span;
2282 return self.parse_for_expr(None, lo, attrs);
2284 if self.eat_keyword(keywords::While) {
2285 let lo = self.prev_span;
2286 return self.parse_while_expr(None, lo, attrs);
2288 if self.token.is_lifetime() {
2289 let label = Spanned { node: self.get_label(),
2293 self.expect(&token::Colon)?;
2294 if self.eat_keyword(keywords::While) {
2295 return self.parse_while_expr(Some(label), lo, attrs)
2297 if self.eat_keyword(keywords::For) {
2298 return self.parse_for_expr(Some(label), lo, attrs)
2300 if self.eat_keyword(keywords::Loop) {
2301 return self.parse_loop_expr(Some(label), lo, attrs)
2303 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2305 if self.eat_keyword(keywords::Loop) {
2306 let lo = self.prev_span;
2307 return self.parse_loop_expr(None, lo, attrs);
2309 if self.eat_keyword(keywords::Continue) {
2310 let ex = if self.token.is_lifetime() {
2311 let ex = ExprKind::Continue(Some(Spanned{
2312 node: self.get_label(),
2318 ExprKind::Continue(None)
2320 let hi = self.prev_span;
2321 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2323 if self.eat_keyword(keywords::Match) {
2324 return self.parse_match_expr(attrs);
2326 if self.eat_keyword(keywords::Unsafe) {
2327 return self.parse_block_expr(
2329 BlockCheckMode::Unsafe(ast::UserProvided),
2332 if self.is_catch_expr() {
2334 assert!(self.eat_keyword(keywords::Do));
2335 assert!(self.eat_keyword(keywords::Catch));
2336 return self.parse_catch_expr(lo, attrs);
2338 if self.eat_keyword(keywords::Return) {
2339 if self.token.can_begin_expr() {
2340 let e = self.parse_expr()?;
2342 ex = ExprKind::Ret(Some(e));
2344 ex = ExprKind::Ret(None);
2346 } else if self.eat_keyword(keywords::Break) {
2347 let lt = if self.token.is_lifetime() {
2348 let spanned_lt = Spanned {
2349 node: self.get_label(),
2357 let e = if self.token.can_begin_expr()
2358 && !(self.token == token::OpenDelim(token::Brace)
2359 && self.restrictions.contains(
2360 Restrictions::NO_STRUCT_LITERAL)) {
2361 Some(self.parse_expr()?)
2365 ex = ExprKind::Break(lt, e);
2366 hi = self.prev_span;
2367 } else if self.eat_keyword(keywords::Yield) {
2368 if self.token.can_begin_expr() {
2369 let e = self.parse_expr()?;
2371 ex = ExprKind::Yield(Some(e));
2373 ex = ExprKind::Yield(None);
2375 } else if self.token.is_keyword(keywords::Let) {
2376 // Catch this syntax error here, instead of in `parse_ident`, so
2377 // that we can explicitly mention that let is not to be used as an expression
2378 let mut db = self.fatal("expected expression, found statement (`let`)");
2379 db.note("variable declaration using `let` is a statement");
2381 } else if self.token.is_path_start() {
2382 let pth = self.parse_path(PathStyle::Expr)?;
2384 // `!`, as an operator, is prefix, so we know this isn't that
2385 if self.eat(&token::Not) {
2386 // MACRO INVOCATION expression
2387 let (_, tts) = self.expect_delimited_token_tree()?;
2388 let hi = self.prev_span;
2389 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2391 if self.check(&token::OpenDelim(token::Brace)) {
2392 // This is a struct literal, unless we're prohibited
2393 // from parsing struct literals here.
2394 let prohibited = self.restrictions.contains(
2395 Restrictions::NO_STRUCT_LITERAL
2398 return self.parse_struct_expr(lo, pth, attrs);
2403 ex = ExprKind::Path(None, pth);
2405 match self.parse_lit() {
2408 ex = ExprKind::Lit(P(lit));
2411 self.cancel(&mut err);
2412 let msg = format!("expected expression, found {}",
2413 self.this_token_descr());
2414 return Err(self.fatal(&msg));
2421 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2422 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2427 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2428 -> PResult<'a, P<Expr>> {
2430 let mut fields = Vec::new();
2431 let mut base = None;
2433 attrs.extend(self.parse_inner_attributes()?);
2435 while self.token != token::CloseDelim(token::Brace) {
2436 if self.eat(&token::DotDot) {
2437 let exp_span = self.prev_span;
2438 match self.parse_expr() {
2444 self.recover_stmt();
2447 if self.token == token::Comma {
2448 let mut err = self.sess.span_diagnostic.mut_span_err(
2449 exp_span.to(self.prev_span),
2450 "cannot use a comma after the base struct",
2452 err.span_suggestion_short(self.span, "remove this comma", "".to_owned());
2453 err.note("the base struct must always be the last field");
2455 self.recover_stmt();
2460 match self.parse_field() {
2461 Ok(f) => fields.push(f),
2464 self.recover_stmt();
2469 match self.expect_one_of(&[token::Comma],
2470 &[token::CloseDelim(token::Brace)]) {
2474 self.recover_stmt();
2480 let span = lo.to(self.span);
2481 self.expect(&token::CloseDelim(token::Brace))?;
2482 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2485 fn parse_or_use_outer_attributes(&mut self,
2486 already_parsed_attrs: Option<ThinVec<Attribute>>)
2487 -> PResult<'a, ThinVec<Attribute>> {
2488 if let Some(attrs) = already_parsed_attrs {
2491 self.parse_outer_attributes().map(|a| a.into())
2495 /// Parse a block or unsafe block
2496 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2497 outer_attrs: ThinVec<Attribute>)
2498 -> PResult<'a, P<Expr>> {
2499 self.expect(&token::OpenDelim(token::Brace))?;
2501 let mut attrs = outer_attrs;
2502 attrs.extend(self.parse_inner_attributes()?);
2504 let blk = self.parse_block_tail(lo, blk_mode)?;
2505 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2508 /// parse a.b or a(13) or a[4] or just a
2509 pub fn parse_dot_or_call_expr(&mut self,
2510 already_parsed_attrs: Option<ThinVec<Attribute>>)
2511 -> PResult<'a, P<Expr>> {
2512 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2514 let b = self.parse_bottom_expr();
2515 let (span, b) = self.interpolated_or_expr_span(b)?;
2516 self.parse_dot_or_call_expr_with(b, span, attrs)
2519 pub fn parse_dot_or_call_expr_with(&mut self,
2522 mut attrs: ThinVec<Attribute>)
2523 -> PResult<'a, P<Expr>> {
2524 // Stitch the list of outer attributes onto the return value.
2525 // A little bit ugly, but the best way given the current code
2527 self.parse_dot_or_call_expr_with_(e0, lo)
2529 expr.map(|mut expr| {
2530 attrs.extend::<Vec<_>>(expr.attrs.into());
2533 ExprKind::If(..) | ExprKind::IfLet(..) => {
2534 if !expr.attrs.is_empty() {
2535 // Just point to the first attribute in there...
2536 let span = expr.attrs[0].span;
2539 "attributes are not yet allowed on `if` \
2550 // Assuming we have just parsed `.`, continue parsing into an expression.
2551 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2552 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2553 Ok(match self.token {
2554 token::OpenDelim(token::Paren) => {
2555 // Method call `expr.f()`
2556 let mut args = self.parse_unspanned_seq(
2557 &token::OpenDelim(token::Paren),
2558 &token::CloseDelim(token::Paren),
2559 SeqSep::trailing_allowed(token::Comma),
2560 |p| Ok(p.parse_expr()?)
2562 args.insert(0, self_arg);
2564 let span = lo.to(self.prev_span);
2565 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2568 // Field access `expr.f`
2569 if let Some(parameters) = segment.parameters {
2570 self.span_err(parameters.span(),
2571 "field expressions may not have generic arguments");
2574 let span = lo.to(self.prev_span);
2575 let ident = respan(segment.span, segment.identifier);
2576 self.mk_expr(span, ExprKind::Field(self_arg, ident), ThinVec::new())
2581 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2586 while self.eat(&token::Question) {
2587 let hi = self.prev_span;
2588 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2592 if self.eat(&token::Dot) {
2594 token::Ident(..) => {
2595 e = self.parse_dot_suffix(e, lo)?;
2597 token::Literal(token::Integer(index_ident), suf) => {
2600 // A tuple index may not have a suffix
2601 self.expect_no_suffix(sp, "tuple index", suf);
2603 let dot_span = self.prev_span;
2607 let invalid_msg = "invalid tuple or struct index";
2609 let index = index_ident.as_str().parse::<usize>().ok();
2612 if n.to_string() != index_ident.as_str() {
2613 let mut err = self.struct_span_err(self.prev_span, invalid_msg);
2614 err.span_suggestion(self.prev_span,
2615 "try simplifying the index",
2619 let id = respan(dot_span.to(hi), n);
2620 let field = self.mk_tup_field(e, id);
2621 e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2624 let prev_span = self.prev_span;
2625 self.span_err(prev_span, invalid_msg);
2629 token::Literal(token::Float(n), _suf) => {
2631 let fstr = n.as_str();
2632 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2633 &format!("unexpected token: `{}`", n));
2634 err.span_label(self.prev_span, "unexpected token");
2635 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2636 let float = match fstr.parse::<f64>().ok() {
2640 let sugg = pprust::to_string(|s| {
2641 use print::pprust::PrintState;
2645 s.print_usize(float.trunc() as usize)?;
2648 s.s.word(fstr.splitn(2, ".").last().unwrap())
2650 err.span_suggestion(
2651 lo.to(self.prev_span),
2652 "try parenthesizing the first index",
2659 // FIXME Could factor this out into non_fatal_unexpected or something.
2660 let actual = self.this_token_to_string();
2661 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2666 if self.expr_is_complete(&e) { break; }
2669 token::OpenDelim(token::Paren) => {
2670 let es = self.parse_unspanned_seq(
2671 &token::OpenDelim(token::Paren),
2672 &token::CloseDelim(token::Paren),
2673 SeqSep::trailing_allowed(token::Comma),
2674 |p| Ok(p.parse_expr()?)
2676 hi = self.prev_span;
2678 let nd = self.mk_call(e, es);
2679 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2683 // Could be either an index expression or a slicing expression.
2684 token::OpenDelim(token::Bracket) => {
2686 let ix = self.parse_expr()?;
2688 self.expect(&token::CloseDelim(token::Bracket))?;
2689 let index = self.mk_index(e, ix);
2690 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2698 pub fn process_potential_macro_variable(&mut self) {
2699 let ident = match self.token {
2700 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2701 self.look_ahead(1, |t| t.is_ident()) => {
2703 let name = match self.token { token::Ident(ident) => ident, _ => unreachable!() };
2704 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2707 token::Interpolated(ref nt) => {
2708 self.meta_var_span = Some(self.span);
2710 token::NtIdent(ident) => ident,
2716 self.token = token::Ident(ident.node);
2717 self.span = ident.span;
2720 /// parse a single token tree from the input.
2721 pub fn parse_token_tree(&mut self) -> TokenTree {
2723 token::OpenDelim(..) => {
2724 let frame = mem::replace(&mut self.token_cursor.frame,
2725 self.token_cursor.stack.pop().unwrap());
2726 self.span = frame.span;
2728 TokenTree::Delimited(frame.span, Delimited {
2730 tts: frame.tree_cursor.original_stream().into(),
2733 token::CloseDelim(_) | token::Eof => unreachable!(),
2735 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2737 TokenTree::Token(span, token)
2742 // parse a stream of tokens into a list of TokenTree's,
2744 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2745 let mut tts = Vec::new();
2746 while self.token != token::Eof {
2747 tts.push(self.parse_token_tree());
2752 pub fn parse_tokens(&mut self) -> TokenStream {
2753 let mut result = Vec::new();
2756 token::Eof | token::CloseDelim(..) => break,
2757 _ => result.push(self.parse_token_tree().into()),
2760 TokenStream::concat(result)
2763 /// Parse a prefix-unary-operator expr
2764 pub fn parse_prefix_expr(&mut self,
2765 already_parsed_attrs: Option<ThinVec<Attribute>>)
2766 -> PResult<'a, P<Expr>> {
2767 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2769 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2770 let (hi, ex) = match self.token {
2773 let e = self.parse_prefix_expr(None);
2774 let (span, e) = self.interpolated_or_expr_span(e)?;
2775 (lo.to(span), self.mk_unary(UnOp::Not, e))
2777 // Suggest `!` for bitwise negation when encountering a `~`
2780 let e = self.parse_prefix_expr(None);
2781 let (span, e) = self.interpolated_or_expr_span(e)?;
2782 let span_of_tilde = lo;
2783 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2784 "`~` can not be used as a unary operator");
2785 err.span_label(span_of_tilde, "did you mean `!`?");
2786 err.help("use `!` instead of `~` if you meant to perform bitwise negation");
2788 (lo.to(span), self.mk_unary(UnOp::Not, e))
2790 token::BinOp(token::Minus) => {
2792 let e = self.parse_prefix_expr(None);
2793 let (span, e) = self.interpolated_or_expr_span(e)?;
2794 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2796 token::BinOp(token::Star) => {
2798 let e = self.parse_prefix_expr(None);
2799 let (span, e) = self.interpolated_or_expr_span(e)?;
2800 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2802 token::BinOp(token::And) | token::AndAnd => {
2804 let m = self.parse_mutability();
2805 let e = self.parse_prefix_expr(None);
2806 let (span, e) = self.interpolated_or_expr_span(e)?;
2807 (lo.to(span), ExprKind::AddrOf(m, e))
2809 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2811 let place = self.parse_expr_res(
2812 Restrictions::NO_STRUCT_LITERAL,
2815 let blk = self.parse_block()?;
2816 let span = blk.span;
2817 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2818 (lo.to(span), ExprKind::InPlace(place, blk_expr))
2820 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2822 let e = self.parse_prefix_expr(None);
2823 let (span, e) = self.interpolated_or_expr_span(e)?;
2824 (lo.to(span), ExprKind::Box(e))
2826 _ => return self.parse_dot_or_call_expr(Some(attrs))
2828 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2831 /// Parse an associative expression
2833 /// This parses an expression accounting for associativity and precedence of the operators in
2835 pub fn parse_assoc_expr(&mut self,
2836 already_parsed_attrs: Option<ThinVec<Attribute>>)
2837 -> PResult<'a, P<Expr>> {
2838 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2841 /// Parse an associative expression with operators of at least `min_prec` precedence
2842 pub fn parse_assoc_expr_with(&mut self,
2845 -> PResult<'a, P<Expr>> {
2846 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2849 let attrs = match lhs {
2850 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2853 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2854 return self.parse_prefix_range_expr(attrs);
2856 self.parse_prefix_expr(attrs)?
2860 if self.expr_is_complete(&lhs) {
2861 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2864 self.expected_tokens.push(TokenType::Operator);
2865 while let Some(op) = AssocOp::from_token(&self.token) {
2867 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2868 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2869 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2870 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2871 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2872 (PrevTokenKind::Interpolated, _) => self.prev_span,
2873 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2874 if path.segments.len() == 1 => self.prev_span,
2878 let cur_op_span = self.span;
2879 let restrictions = if op.is_assign_like() {
2880 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2884 if op.precedence() < min_prec {
2887 // Check for deprecated `...` syntax
2888 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2889 self.err_dotdotdot_syntax(self.span);
2893 if op.is_comparison() {
2894 self.check_no_chained_comparison(&lhs, &op);
2897 if op == AssocOp::As {
2898 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2900 } else if op == AssocOp::Colon {
2901 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2904 err.span_label(self.span,
2905 "expecting a type here because of type ascription");
2906 let cm = self.sess.codemap();
2907 let cur_pos = cm.lookup_char_pos(self.span.lo());
2908 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
2909 if cur_pos.line != op_pos.line {
2910 err.span_suggestion_short(cur_op_span,
2911 "did you mean to use `;` here?",
2918 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2919 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2920 // generalise it to the Fixity::None code.
2922 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2923 // two variants are handled with `parse_prefix_range_expr` call above.
2924 let rhs = if self.is_at_start_of_range_notation_rhs() {
2925 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2926 LhsExpr::NotYetParsed)?)
2930 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2935 let limits = if op == AssocOp::DotDot {
2936 RangeLimits::HalfOpen
2941 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2942 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2946 let rhs = match op.fixity() {
2947 Fixity::Right => self.with_res(
2948 restrictions - Restrictions::STMT_EXPR,
2950 this.parse_assoc_expr_with(op.precedence(),
2951 LhsExpr::NotYetParsed)
2953 Fixity::Left => self.with_res(
2954 restrictions - Restrictions::STMT_EXPR,
2956 this.parse_assoc_expr_with(op.precedence() + 1,
2957 LhsExpr::NotYetParsed)
2959 // We currently have no non-associative operators that are not handled above by
2960 // the special cases. The code is here only for future convenience.
2961 Fixity::None => self.with_res(
2962 restrictions - Restrictions::STMT_EXPR,
2964 this.parse_assoc_expr_with(op.precedence() + 1,
2965 LhsExpr::NotYetParsed)
2969 let span = lhs_span.to(rhs.span);
2971 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2972 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2973 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2974 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2975 AssocOp::Greater | AssocOp::GreaterEqual => {
2976 let ast_op = op.to_ast_binop().unwrap();
2977 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2978 self.mk_expr(span, binary, ThinVec::new())
2981 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2983 self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
2984 AssocOp::AssignOp(k) => {
2986 token::Plus => BinOpKind::Add,
2987 token::Minus => BinOpKind::Sub,
2988 token::Star => BinOpKind::Mul,
2989 token::Slash => BinOpKind::Div,
2990 token::Percent => BinOpKind::Rem,
2991 token::Caret => BinOpKind::BitXor,
2992 token::And => BinOpKind::BitAnd,
2993 token::Or => BinOpKind::BitOr,
2994 token::Shl => BinOpKind::Shl,
2995 token::Shr => BinOpKind::Shr,
2997 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2998 self.mk_expr(span, aopexpr, ThinVec::new())
3000 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3001 self.bug("AssocOp should have been handled by special case")
3005 if op.fixity() == Fixity::None { break }
3010 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3011 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3012 -> PResult<'a, P<Expr>> {
3013 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3014 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3017 // Save the state of the parser before parsing type normally, in case there is a
3018 // LessThan comparison after this cast.
3019 let parser_snapshot_before_type = self.clone();
3020 match self.parse_ty_no_plus() {
3022 Ok(mk_expr(self, rhs))
3024 Err(mut type_err) => {
3025 // Rewind to before attempting to parse the type with generics, to recover
3026 // from situations like `x as usize < y` in which we first tried to parse
3027 // `usize < y` as a type with generic arguments.
3028 let parser_snapshot_after_type = self.clone();
3029 mem::replace(self, parser_snapshot_before_type);
3031 match self.parse_path(PathStyle::Expr) {
3033 let (op_noun, op_verb) = match self.token {
3034 token::Lt => ("comparison", "comparing"),
3035 token::BinOp(token::Shl) => ("shift", "shifting"),
3037 // We can end up here even without `<` being the next token, for
3038 // example because `parse_ty_no_plus` returns `Err` on keywords,
3039 // but `parse_path` returns `Ok` on them due to error recovery.
3040 // Return original error and parser state.
3041 mem::replace(self, parser_snapshot_after_type);
3042 return Err(type_err);
3046 // Successfully parsed the type path leaving a `<` yet to parse.
3049 // Report non-fatal diagnostics, keep `x as usize` as an expression
3050 // in AST and continue parsing.
3051 let msg = format!("`<` is interpreted as a start of generic \
3052 arguments for `{}`, not a {}", path, op_noun);
3053 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3054 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3055 "interpreted as generic arguments");
3056 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3058 let expr = mk_expr(self, P(Ty {
3060 node: TyKind::Path(None, path),
3061 id: ast::DUMMY_NODE_ID
3064 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
3065 .unwrap_or(pprust::expr_to_string(&expr));
3066 err.span_suggestion(expr.span,
3067 &format!("try {} the casted value", op_verb),
3068 format!("({})", expr_str));
3073 Err(mut path_err) => {
3074 // Couldn't parse as a path, return original error and parser state.
3076 mem::replace(self, parser_snapshot_after_type);
3084 /// Produce an error if comparison operators are chained (RFC #558).
3085 /// We only need to check lhs, not rhs, because all comparison ops
3086 /// have same precedence and are left-associative
3087 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3088 debug_assert!(outer_op.is_comparison(),
3089 "check_no_chained_comparison: {:?} is not comparison",
3092 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3093 // respan to include both operators
3094 let op_span = op.span.to(self.span);
3095 let mut err = self.diagnostic().struct_span_err(op_span,
3096 "chained comparison operators require parentheses");
3097 if op.node == BinOpKind::Lt &&
3098 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3099 *outer_op == AssocOp::Greater // even in a case like the following:
3100 { // Foo<Bar<Baz<Qux, ()>>>
3102 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3103 err.help("or use `(...)` if you meant to specify fn arguments");
3111 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3112 fn parse_prefix_range_expr(&mut self,
3113 already_parsed_attrs: Option<ThinVec<Attribute>>)
3114 -> PResult<'a, P<Expr>> {
3115 // Check for deprecated `...` syntax
3116 if self.token == token::DotDotDot {
3117 self.err_dotdotdot_syntax(self.span);
3120 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3121 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3123 let tok = self.token.clone();
3124 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3126 let mut hi = self.span;
3128 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3129 // RHS must be parsed with more associativity than the dots.
3130 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3131 Some(self.parse_assoc_expr_with(next_prec,
3132 LhsExpr::NotYetParsed)
3140 let limits = if tok == token::DotDot {
3141 RangeLimits::HalfOpen
3146 let r = try!(self.mk_range(None,
3149 Ok(self.mk_expr(lo.to(hi), r, attrs))
3152 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3153 if self.token.can_begin_expr() {
3154 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3155 if self.token == token::OpenDelim(token::Brace) {
3156 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3164 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3165 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3166 if self.check_keyword(keywords::Let) {
3167 return self.parse_if_let_expr(attrs);
3169 let lo = self.prev_span;
3170 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3172 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3173 // verify that the last statement is either an implicit return (no `;`) or an explicit
3174 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3175 // the dead code lint.
3176 if self.eat_keyword(keywords::Else) || !cond.returns() {
3177 let sp = lo.next_point();
3178 let mut err = self.diagnostic()
3179 .struct_span_err(sp, "missing condition for `if` statemement");
3180 err.span_label(sp, "expected if condition here");
3183 let thn = self.parse_block()?;
3184 let mut els: Option<P<Expr>> = None;
3185 let mut hi = thn.span;
3186 if self.eat_keyword(keywords::Else) {
3187 let elexpr = self.parse_else_expr()?;
3191 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3194 /// Parse an 'if let' expression ('if' token already eaten)
3195 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3196 -> PResult<'a, P<Expr>> {
3197 let lo = self.prev_span;
3198 self.expect_keyword(keywords::Let)?;
3199 let pat = self.parse_pat()?;
3200 self.expect(&token::Eq)?;
3201 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3202 let thn = self.parse_block()?;
3203 let (hi, els) = if self.eat_keyword(keywords::Else) {
3204 let expr = self.parse_else_expr()?;
3205 (expr.span, Some(expr))
3209 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
3212 // `move |args| expr`
3213 pub fn parse_lambda_expr(&mut self,
3215 capture_clause: CaptureBy,
3216 attrs: ThinVec<Attribute>)
3217 -> PResult<'a, P<Expr>>
3219 let decl = self.parse_fn_block_decl()?;
3220 let decl_hi = self.prev_span;
3221 let body = match decl.output {
3222 FunctionRetTy::Default(_) => {
3223 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3224 self.parse_expr_res(restrictions, None)?
3227 // If an explicit return type is given, require a
3228 // block to appear (RFC 968).
3229 let body_lo = self.span;
3230 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3236 ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3240 // `else` token already eaten
3241 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3242 if self.eat_keyword(keywords::If) {
3243 return self.parse_if_expr(ThinVec::new());
3245 let blk = self.parse_block()?;
3246 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3250 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3251 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3253 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3254 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3256 let pat = self.parse_pat()?;
3257 if !self.eat_keyword(keywords::In) {
3258 let in_span = self.prev_span.between(self.span);
3259 let mut err = self.sess.span_diagnostic
3260 .struct_span_err(in_span, "missing `in` in `for` loop");
3261 err.span_suggestion_short(in_span, "try adding `in` here", " in ".into());
3264 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3265 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3266 attrs.extend(iattrs);
3268 let hi = self.prev_span;
3269 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3272 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3273 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3275 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3276 if self.token.is_keyword(keywords::Let) {
3277 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3279 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3280 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3281 attrs.extend(iattrs);
3282 let span = span_lo.to(body.span);
3283 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3286 /// Parse a 'while let' expression ('while' token already eaten)
3287 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3289 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3290 self.expect_keyword(keywords::Let)?;
3291 let pat = self.parse_pat()?;
3292 self.expect(&token::Eq)?;
3293 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3294 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3295 attrs.extend(iattrs);
3296 let span = span_lo.to(body.span);
3297 return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3300 // parse `loop {...}`, `loop` token already eaten
3301 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3303 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3304 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3305 attrs.extend(iattrs);
3306 let span = span_lo.to(body.span);
3307 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3310 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3311 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3312 -> PResult<'a, P<Expr>>
3314 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3315 attrs.extend(iattrs);
3316 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3319 // `match` token already eaten
3320 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3321 let match_span = self.prev_span;
3322 let lo = self.prev_span;
3323 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3325 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3326 if self.token == token::Token::Semi {
3327 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3331 attrs.extend(self.parse_inner_attributes()?);
3333 let mut arms: Vec<Arm> = Vec::new();
3334 while self.token != token::CloseDelim(token::Brace) {
3335 match self.parse_arm() {
3336 Ok(arm) => arms.push(arm),
3338 // Recover by skipping to the end of the block.
3340 self.recover_stmt();
3341 let span = lo.to(self.span);
3342 if self.token == token::CloseDelim(token::Brace) {
3345 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3351 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3354 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3355 maybe_whole!(self, NtArm, |x| x);
3357 let attrs = self.parse_outer_attributes()?;
3358 // Allow a '|' before the pats (RFC 1925)
3359 let beginning_vert = if self.eat(&token::BinOp(token::Or)) {
3360 Some(self.prev_span)
3364 let pats = self.parse_pats()?;
3365 let guard = if self.eat_keyword(keywords::If) {
3366 Some(self.parse_expr()?)
3370 self.expect(&token::FatArrow)?;
3371 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)?;
3373 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3374 && self.token != token::CloseDelim(token::Brace);
3377 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3379 self.eat(&token::Comma);
3391 /// Parse an expression
3392 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3393 self.parse_expr_res(Restrictions::empty(), None)
3396 /// Evaluate the closure with restrictions in place.
3398 /// After the closure is evaluated, restrictions are reset.
3399 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3400 where F: FnOnce(&mut Self) -> T
3402 let old = self.restrictions;
3403 self.restrictions = r;
3405 self.restrictions = old;
3410 /// Parse an expression, subject to the given restrictions
3411 pub fn parse_expr_res(&mut self, r: Restrictions,
3412 already_parsed_attrs: Option<ThinVec<Attribute>>)
3413 -> PResult<'a, P<Expr>> {
3414 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3417 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3418 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3419 if self.check(&token::Eq) {
3421 Ok(Some(self.parse_expr()?))
3423 Ok(Some(self.parse_expr()?))
3429 /// Parse patterns, separated by '|' s
3430 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3431 let mut pats = Vec::new();
3433 pats.push(self.parse_pat()?);
3435 if self.token == token::OrOr {
3436 let mut err = self.struct_span_err(self.span,
3437 "unexpected token `||` after pattern");
3438 err.span_suggestion(self.span,
3439 "use a single `|` to specify multiple patterns",
3443 } else if self.check(&token::BinOp(token::Or)) {
3451 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3452 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3453 let mut fields = vec![];
3454 let mut ddpos = None;
3456 while !self.check(&token::CloseDelim(token::Paren)) {
3457 if ddpos.is_none() && self.eat(&token::DotDot) {
3458 ddpos = Some(fields.len());
3459 if self.eat(&token::Comma) {
3460 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3461 fields.push(self.parse_pat()?);
3463 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3464 // Emit a friendly error, ignore `..` and continue parsing
3465 self.span_err(self.prev_span, "`..` can only be used once per \
3466 tuple or tuple struct pattern");
3468 fields.push(self.parse_pat()?);
3471 if !self.check(&token::CloseDelim(token::Paren)) ||
3472 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3473 self.expect(&token::Comma)?;
3480 fn parse_pat_vec_elements(
3482 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3483 let mut before = Vec::new();
3484 let mut slice = None;
3485 let mut after = Vec::new();
3486 let mut first = true;
3487 let mut before_slice = true;
3489 while self.token != token::CloseDelim(token::Bracket) {
3493 self.expect(&token::Comma)?;
3495 if self.token == token::CloseDelim(token::Bracket)
3496 && (before_slice || !after.is_empty()) {
3502 if self.eat(&token::DotDot) {
3504 if self.check(&token::Comma) ||
3505 self.check(&token::CloseDelim(token::Bracket)) {
3506 slice = Some(P(Pat {
3507 id: ast::DUMMY_NODE_ID,
3508 node: PatKind::Wild,
3511 before_slice = false;
3517 let subpat = self.parse_pat()?;
3518 if before_slice && self.eat(&token::DotDot) {
3519 slice = Some(subpat);
3520 before_slice = false;
3521 } else if before_slice {
3522 before.push(subpat);
3528 Ok((before, slice, after))
3531 /// Parse the fields of a struct-like pattern
3532 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3533 let mut fields = Vec::new();
3534 let mut etc = false;
3535 let mut first = true;
3536 while self.token != token::CloseDelim(token::Brace) {
3540 self.expect(&token::Comma)?;
3541 // accept trailing commas
3542 if self.check(&token::CloseDelim(token::Brace)) { break }
3545 let attrs = self.parse_outer_attributes()?;
3549 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3550 if self.token == token::DotDotDot { // Issue #46718
3551 let mut err = self.struct_span_err(self.span,
3552 "expected field pattern, found `...`");
3553 err.span_suggestion(self.span,
3554 "to omit remaining fields, use one fewer `.`",
3560 if self.token != token::CloseDelim(token::Brace) {
3561 let token_str = self.this_token_to_string();
3562 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3569 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3570 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3571 // Parsing a pattern of the form "fieldname: pat"
3572 let fieldname = self.parse_field_name()?;
3574 let pat = self.parse_pat()?;
3576 (pat, fieldname, false)
3578 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3579 let is_box = self.eat_keyword(keywords::Box);
3580 let boxed_span = self.span;
3581 let is_ref = self.eat_keyword(keywords::Ref);
3582 let is_mut = self.eat_keyword(keywords::Mut);
3583 let fieldname = self.parse_ident()?;
3584 hi = self.prev_span;
3586 let bind_type = match (is_ref, is_mut) {
3587 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3588 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3589 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3590 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3592 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3593 let fieldpat = P(Pat {
3594 id: ast::DUMMY_NODE_ID,
3595 node: PatKind::Ident(bind_type, fieldpath, None),
3596 span: boxed_span.to(hi),
3599 let subpat = if is_box {
3601 id: ast::DUMMY_NODE_ID,
3602 node: PatKind::Box(fieldpat),
3608 (subpat, fieldname, true)
3611 fields.push(codemap::Spanned { span: lo.to(hi),
3612 node: ast::FieldPat {
3616 attrs: attrs.into(),
3620 return Ok((fields, etc));
3623 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3624 if self.token.is_path_start() {
3626 let (qself, path) = if self.eat_lt() {
3627 // Parse a qualified path
3628 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3631 // Parse an unqualified path
3632 (None, self.parse_path(PathStyle::Expr)?)
3634 let hi = self.prev_span;
3635 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3637 self.parse_pat_literal_maybe_minus()
3641 // helper function to decide whether to parse as ident binding or to try to do
3642 // something more complex like range patterns
3643 fn parse_as_ident(&mut self) -> bool {
3644 self.look_ahead(1, |t| match *t {
3645 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3646 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3647 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3648 // range pattern branch
3649 token::DotDot => None,
3651 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3652 token::Comma | token::CloseDelim(token::Bracket) => true,
3657 /// Parse a pattern.
3658 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3659 maybe_whole!(self, NtPat, |x| x);
3664 token::Underscore => {
3667 pat = PatKind::Wild;
3669 token::BinOp(token::And) | token::AndAnd => {
3670 // Parse &pat / &mut pat
3672 let mutbl = self.parse_mutability();
3673 if let token::Lifetime(ident) = self.token {
3674 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3676 let subpat = self.parse_pat()?;
3677 pat = PatKind::Ref(subpat, mutbl);
3679 token::OpenDelim(token::Paren) => {
3680 // Parse (pat,pat,pat,...) as tuple pattern
3682 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3683 self.expect(&token::CloseDelim(token::Paren))?;
3684 pat = PatKind::Tuple(fields, ddpos);
3686 token::OpenDelim(token::Bracket) => {
3687 // Parse [pat,pat,...] as slice pattern
3689 let (before, slice, after) = self.parse_pat_vec_elements()?;
3690 self.expect(&token::CloseDelim(token::Bracket))?;
3691 pat = PatKind::Slice(before, slice, after);
3693 // At this point, token != _, &, &&, (, [
3694 _ => if self.eat_keyword(keywords::Mut) {
3695 // Parse mut ident @ pat / mut ref ident @ pat
3696 let mutref_span = self.prev_span.to(self.span);
3697 let binding_mode = if self.eat_keyword(keywords::Ref) {
3699 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3700 .span_suggestion(mutref_span, "try switching the order", "ref mut".into())
3702 BindingMode::ByRef(Mutability::Mutable)
3704 BindingMode::ByValue(Mutability::Mutable)
3706 pat = self.parse_pat_ident(binding_mode)?;
3707 } else if self.eat_keyword(keywords::Ref) {
3708 // Parse ref ident @ pat / ref mut ident @ pat
3709 let mutbl = self.parse_mutability();
3710 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3711 } else if self.eat_keyword(keywords::Box) {
3713 let subpat = self.parse_pat()?;
3714 pat = PatKind::Box(subpat);
3715 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3716 self.parse_as_ident() {
3717 // Parse ident @ pat
3718 // This can give false positives and parse nullary enums,
3719 // they are dealt with later in resolve
3720 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3721 pat = self.parse_pat_ident(binding_mode)?;
3722 } else if self.token.is_path_start() {
3723 // Parse pattern starting with a path
3724 let (qself, path) = if self.eat_lt() {
3725 // Parse a qualified path
3726 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3729 // Parse an unqualified path
3730 (None, self.parse_path(PathStyle::Expr)?)
3733 token::Not if qself.is_none() => {
3734 // Parse macro invocation
3736 let (_, tts) = self.expect_delimited_token_tree()?;
3737 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3738 pat = PatKind::Mac(mac);
3740 token::DotDotDot | token::DotDotEq | token::DotDot => {
3741 let end_kind = match self.token {
3742 token::DotDot => RangeEnd::Excluded,
3743 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
3744 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
3745 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
3749 let span = lo.to(self.prev_span);
3750 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3752 let end = self.parse_pat_range_end()?;
3753 pat = PatKind::Range(begin, end, end_kind);
3755 token::OpenDelim(token::Brace) => {
3756 if qself.is_some() {
3757 return Err(self.fatal("unexpected `{` after qualified path"));
3759 // Parse struct pattern
3761 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3763 self.recover_stmt();
3767 pat = PatKind::Struct(path, fields, etc);
3769 token::OpenDelim(token::Paren) => {
3770 if qself.is_some() {
3771 return Err(self.fatal("unexpected `(` after qualified path"));
3773 // Parse tuple struct or enum pattern
3775 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3776 self.expect(&token::CloseDelim(token::Paren))?;
3777 pat = PatKind::TupleStruct(path, fields, ddpos)
3779 _ => pat = PatKind::Path(qself, path),
3782 // Try to parse everything else as literal with optional minus
3783 match self.parse_pat_literal_maybe_minus() {
3785 if self.eat(&token::DotDotDot) {
3786 let end = self.parse_pat_range_end()?;
3787 pat = PatKind::Range(begin, end,
3788 RangeEnd::Included(RangeSyntax::DotDotDot));
3789 } else if self.eat(&token::DotDotEq) {
3790 let end = self.parse_pat_range_end()?;
3791 pat = PatKind::Range(begin, end,
3792 RangeEnd::Included(RangeSyntax::DotDotEq));
3793 } else if self.eat(&token::DotDot) {
3794 let end = self.parse_pat_range_end()?;
3795 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3797 pat = PatKind::Lit(begin);
3801 self.cancel(&mut err);
3802 let msg = format!("expected pattern, found {}", self.this_token_descr());
3803 return Err(self.fatal(&msg));
3809 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
3810 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
3815 /// Parse ident or ident @ pat
3816 /// used by the copy foo and ref foo patterns to give a good
3817 /// error message when parsing mistakes like ref foo(a,b)
3818 fn parse_pat_ident(&mut self,
3819 binding_mode: ast::BindingMode)
3820 -> PResult<'a, PatKind> {
3821 let ident_span = self.span;
3822 let ident = self.parse_ident()?;
3823 let name = codemap::Spanned{span: ident_span, node: ident};
3824 let sub = if self.eat(&token::At) {
3825 Some(self.parse_pat()?)
3830 // just to be friendly, if they write something like
3832 // we end up here with ( as the current token. This shortly
3833 // leads to a parse error. Note that if there is no explicit
3834 // binding mode then we do not end up here, because the lookahead
3835 // will direct us over to parse_enum_variant()
3836 if self.token == token::OpenDelim(token::Paren) {
3837 return Err(self.span_fatal(
3839 "expected identifier, found enum pattern"))
3842 Ok(PatKind::Ident(binding_mode, name, sub))
3845 /// Parse a local variable declaration
3846 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3847 let lo = self.prev_span;
3848 let pat = self.parse_pat()?;
3850 let (err, ty) = if self.eat(&token::Colon) {
3851 // Save the state of the parser before parsing type normally, in case there is a `:`
3852 // instead of an `=` typo.
3853 let parser_snapshot_before_type = self.clone();
3854 let colon_sp = self.prev_span;
3855 match self.parse_ty() {
3856 Ok(ty) => (None, Some(ty)),
3858 // Rewind to before attempting to parse the type and continue parsing
3859 let parser_snapshot_after_type = self.clone();
3860 mem::replace(self, parser_snapshot_before_type);
3862 let snippet = self.sess.codemap().span_to_snippet(pat.span).unwrap();
3863 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
3864 (Some((parser_snapshot_after_type, colon_sp, err)), None)
3870 let init = match (self.parse_initializer(err.is_some()), err) {
3871 (Ok(init), None) => { // init parsed, ty parsed
3874 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
3875 // Could parse the type as if it were the initializer, it is likely there was a
3876 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
3877 err.span_suggestion_short(colon_sp,
3878 "use `=` if you meant to assign",
3881 // As this was parsed successfuly, continue as if the code has been fixed for the
3882 // rest of the file. It will still fail due to the emitted error, but we avoid
3886 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
3888 // Couldn't parse the type nor the initializer, only raise the type error and
3889 // return to the parser state before parsing the type as the initializer.
3890 // let x: <parse_error>;
3891 mem::replace(self, snapshot);
3894 (Err(err), None) => { // init error, ty parsed
3895 // Couldn't parse the initializer and we're not attempting to recover a failed
3896 // parse of the type, return the error.
3900 let hi = if self.token == token::Semi {
3909 id: ast::DUMMY_NODE_ID,
3915 /// Parse a structure field
3916 fn parse_name_and_ty(&mut self,
3919 attrs: Vec<Attribute>)
3920 -> PResult<'a, StructField> {
3921 let name = self.parse_ident()?;
3922 self.expect(&token::Colon)?;
3923 let ty = self.parse_ty()?;
3925 span: lo.to(self.prev_span),
3928 id: ast::DUMMY_NODE_ID,
3934 /// Emit an expected item after attributes error.
3935 fn expected_item_err(&self, attrs: &[Attribute]) {
3936 let message = match attrs.last() {
3937 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3938 _ => "expected item after attributes",
3941 self.span_err(self.prev_span, message);
3944 /// Parse a statement. This stops just before trailing semicolons on everything but items.
3945 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3946 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3947 Ok(self.parse_stmt_(true))
3950 // Eat tokens until we can be relatively sure we reached the end of the
3951 // statement. This is something of a best-effort heuristic.
3953 // We terminate when we find an unmatched `}` (without consuming it).
3954 fn recover_stmt(&mut self) {
3955 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
3958 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3959 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3960 // approximate - it can mean we break too early due to macros, but that
3961 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3963 // If `break_on_block` is `Break`, then we will stop consuming tokens
3964 // after finding (and consuming) a brace-delimited block.
3965 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
3966 let mut brace_depth = 0;
3967 let mut bracket_depth = 0;
3968 let mut in_block = false;
3969 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
3970 break_on_semi, break_on_block);
3972 debug!("recover_stmt_ loop {:?}", self.token);
3974 token::OpenDelim(token::DelimToken::Brace) => {
3977 if break_on_block == BlockMode::Break &&
3979 bracket_depth == 0 {
3983 token::OpenDelim(token::DelimToken::Bracket) => {
3987 token::CloseDelim(token::DelimToken::Brace) => {
3988 if brace_depth == 0 {
3989 debug!("recover_stmt_ return - close delim {:?}", self.token);
3994 if in_block && bracket_depth == 0 && brace_depth == 0 {
3995 debug!("recover_stmt_ return - block end {:?}", self.token);
3999 token::CloseDelim(token::DelimToken::Bracket) => {
4001 if bracket_depth < 0 {
4007 debug!("recover_stmt_ return - Eof");
4012 if break_on_semi == SemiColonMode::Break &&
4014 bracket_depth == 0 {
4015 debug!("recover_stmt_ return - Semi");
4026 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4027 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4029 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4034 fn is_catch_expr(&mut self) -> bool {
4035 self.token.is_keyword(keywords::Do) &&
4036 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4037 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4039 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
4040 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4043 fn is_union_item(&self) -> bool {
4044 self.token.is_keyword(keywords::Union) &&
4045 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4048 fn is_crate_vis(&self) -> bool {
4049 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4052 fn is_extern_non_path(&self) -> bool {
4053 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4056 fn eat_auto_trait(&mut self) -> bool {
4057 if self.token.is_keyword(keywords::Auto)
4058 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
4060 self.eat_keyword(keywords::Auto) && self.eat_keyword(keywords::Trait)
4066 fn is_defaultness(&self) -> bool {
4067 // `pub` is included for better error messages
4068 self.token.is_keyword(keywords::Default) &&
4069 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
4070 t.is_keyword(keywords::Const) ||
4071 t.is_keyword(keywords::Fn) ||
4072 t.is_keyword(keywords::Unsafe) ||
4073 t.is_keyword(keywords::Extern) ||
4074 t.is_keyword(keywords::Type) ||
4075 t.is_keyword(keywords::Pub))
4078 fn eat_defaultness(&mut self) -> bool {
4079 let is_defaultness = self.is_defaultness();
4083 self.expected_tokens.push(TokenType::Keyword(keywords::Default));
4088 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4089 -> PResult<'a, Option<P<Item>>> {
4090 let token_lo = self.span;
4091 let (ident, def) = match self.token {
4092 token::Ident(ident) if ident.name == keywords::Macro.name() => {
4094 let ident = self.parse_ident()?;
4095 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4096 match self.parse_token_tree() {
4097 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4098 _ => unreachable!(),
4100 } else if self.check(&token::OpenDelim(token::Paren)) {
4101 let args = self.parse_token_tree();
4102 let body = if self.check(&token::OpenDelim(token::Brace)) {
4103 self.parse_token_tree()
4108 TokenStream::concat(vec![
4110 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4118 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4120 token::Ident(ident) if ident.name == "macro_rules" &&
4121 self.look_ahead(1, |t| *t == token::Not) => {
4122 let prev_span = self.prev_span;
4123 self.complain_if_pub_macro(vis, prev_span);
4127 let ident = self.parse_ident()?;
4128 let (delim, tokens) = self.expect_delimited_token_tree()?;
4129 if delim != token::Brace {
4130 if !self.eat(&token::Semi) {
4131 let msg = "macros that expand to items must either \
4132 be surrounded with braces or followed by a semicolon";
4133 self.span_err(self.prev_span, msg);
4137 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4139 _ => return Ok(None),
4142 let span = lo.to(self.prev_span);
4143 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4146 fn parse_stmt_without_recovery(&mut self,
4147 macro_legacy_warnings: bool)
4148 -> PResult<'a, Option<Stmt>> {
4149 maybe_whole!(self, NtStmt, |x| Some(x));
4151 let attrs = self.parse_outer_attributes()?;
4154 Ok(Some(if self.eat_keyword(keywords::Let) {
4156 id: ast::DUMMY_NODE_ID,
4157 node: StmtKind::Local(self.parse_local(attrs.into())?),
4158 span: lo.to(self.prev_span),
4160 } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited, lo)? {
4162 id: ast::DUMMY_NODE_ID,
4163 node: StmtKind::Item(macro_def),
4164 span: lo.to(self.prev_span),
4166 // Starts like a simple path, but not a union item or item with `crate` visibility.
4167 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4168 // like a path (1 token), but it fact not a path.
4169 // `union::b::c` - path, `union U { ... }` - not a path.
4170 // `crate::b::c` - path, `crate struct S;` - not a path.
4171 // `extern::b::c` - path, `extern crate c;` - not a path.
4172 } else if self.token.is_path_start() &&
4173 !self.token.is_qpath_start() &&
4174 !self.is_union_item() &&
4175 !self.is_crate_vis() &&
4176 !self.is_extern_non_path() {
4177 let pth = self.parse_path(PathStyle::Expr)?;
4179 if !self.eat(&token::Not) {
4180 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4181 self.parse_struct_expr(lo, pth, ThinVec::new())?
4183 let hi = self.prev_span;
4184 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4187 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4188 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4189 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4192 return Ok(Some(Stmt {
4193 id: ast::DUMMY_NODE_ID,
4194 node: StmtKind::Expr(expr),
4195 span: lo.to(self.prev_span),
4199 // it's a macro invocation
4200 let id = match self.token {
4201 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4202 _ => self.parse_ident()?,
4205 // check that we're pointing at delimiters (need to check
4206 // again after the `if`, because of `parse_ident`
4207 // consuming more tokens).
4208 let delim = match self.token {
4209 token::OpenDelim(delim) => delim,
4211 // we only expect an ident if we didn't parse one
4213 let ident_str = if id.name == keywords::Invalid.name() {
4218 let tok_str = self.this_token_to_string();
4219 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4225 let (_, tts) = self.expect_delimited_token_tree()?;
4226 let hi = self.prev_span;
4228 let style = if delim == token::Brace {
4229 MacStmtStyle::Braces
4231 MacStmtStyle::NoBraces
4234 if id.name == keywords::Invalid.name() {
4235 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
4236 let node = if delim == token::Brace ||
4237 self.token == token::Semi || self.token == token::Eof {
4238 StmtKind::Mac(P((mac, style, attrs.into())))
4240 // We used to incorrectly stop parsing macro-expanded statements here.
4241 // If the next token will be an error anyway but could have parsed with the
4242 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4243 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4244 // These can continue an expression, so we can't stop parsing and warn.
4245 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4246 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4247 token::BinOp(token::And) | token::BinOp(token::Or) |
4248 token::AndAnd | token::OrOr |
4249 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4252 self.warn_missing_semicolon();
4253 StmtKind::Mac(P((mac, style, attrs.into())))
4255 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4256 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4257 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4261 id: ast::DUMMY_NODE_ID,
4266 // if it has a special ident, it's definitely an item
4268 // Require a semicolon or braces.
4269 if style != MacStmtStyle::Braces {
4270 if !self.eat(&token::Semi) {
4271 self.span_err(self.prev_span,
4272 "macros that expand to items must \
4273 either be surrounded with braces or \
4274 followed by a semicolon");
4277 let span = lo.to(hi);
4279 id: ast::DUMMY_NODE_ID,
4281 node: StmtKind::Item({
4283 span, id /*id is good here*/,
4284 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
4285 Visibility::Inherited,
4291 // FIXME: Bad copy of attrs
4292 let old_directory_ownership =
4293 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4294 let item = self.parse_item_(attrs.clone(), false, true)?;
4295 self.directory.ownership = old_directory_ownership;
4299 id: ast::DUMMY_NODE_ID,
4300 span: lo.to(i.span),
4301 node: StmtKind::Item(i),
4304 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4305 if !attrs.is_empty() {
4306 if s.prev_token_kind == PrevTokenKind::DocComment {
4307 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4308 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4309 s.span_err(s.span, "expected statement after outer attribute");
4314 // Do not attempt to parse an expression if we're done here.
4315 if self.token == token::Semi {
4316 unused_attrs(&attrs, self);
4321 if self.token == token::CloseDelim(token::Brace) {
4322 unused_attrs(&attrs, self);
4326 // Remainder are line-expr stmts.
4327 let e = self.parse_expr_res(
4328 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4330 id: ast::DUMMY_NODE_ID,
4331 span: lo.to(e.span),
4332 node: StmtKind::Expr(e),
4339 /// Is this expression a successfully-parsed statement?
4340 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4341 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4342 !classify::expr_requires_semi_to_be_stmt(e)
4345 /// Parse a block. No inner attrs are allowed.
4346 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4347 maybe_whole!(self, NtBlock, |x| x);
4351 if !self.eat(&token::OpenDelim(token::Brace)) {
4353 let tok = self.this_token_to_string();
4354 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4356 // Check to see if the user has written something like
4361 // Which is valid in other languages, but not Rust.
4362 match self.parse_stmt_without_recovery(false) {
4364 let mut stmt_span = stmt.span;
4365 // expand the span to include the semicolon, if it exists
4366 if self.eat(&token::Semi) {
4367 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4369 let sugg = pprust::to_string(|s| {
4370 use print::pprust::{PrintState, INDENT_UNIT};
4371 s.ibox(INDENT_UNIT)?;
4373 s.print_stmt(&stmt)?;
4374 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4376 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4379 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4380 self.cancel(&mut e);
4387 self.parse_block_tail(lo, BlockCheckMode::Default)
4390 /// Parse a block. Inner attrs are allowed.
4391 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4392 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4395 self.expect(&token::OpenDelim(token::Brace))?;
4396 Ok((self.parse_inner_attributes()?,
4397 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4400 /// Parse the rest of a block expression or function body
4401 /// Precondition: already parsed the '{'.
4402 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4403 let mut stmts = vec![];
4404 let mut recovered = false;
4406 while !self.eat(&token::CloseDelim(token::Brace)) {
4407 let stmt = match self.parse_full_stmt(false) {
4410 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4411 self.eat(&token::CloseDelim(token::Brace));
4417 if let Some(stmt) = stmt {
4419 } else if self.token == token::Eof {
4422 // Found only `;` or `}`.
4428 id: ast::DUMMY_NODE_ID,
4430 span: lo.to(self.prev_span),
4435 /// Parse a statement, including the trailing semicolon.
4436 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4437 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4439 None => return Ok(None),
4443 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4444 // expression without semicolon
4445 if classify::expr_requires_semi_to_be_stmt(expr) {
4446 // Just check for errors and recover; do not eat semicolon yet.
4448 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4451 self.recover_stmt();
4455 StmtKind::Local(..) => {
4456 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4457 if macro_legacy_warnings && self.token != token::Semi {
4458 self.warn_missing_semicolon();
4460 self.expect_one_of(&[token::Semi], &[])?;
4466 if self.eat(&token::Semi) {
4467 stmt = stmt.add_trailing_semicolon();
4470 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4474 fn warn_missing_semicolon(&self) {
4475 self.diagnostic().struct_span_warn(self.span, {
4476 &format!("expected `;`, found `{}`", self.this_token_to_string())
4478 "This was erroneously allowed and will become a hard error in a future release"
4482 fn err_dotdotdot_syntax(&self, span: Span) {
4483 self.diagnostic().struct_span_err(span, {
4484 "`...` syntax cannot be used in expressions"
4486 "Use `..` if you need an exclusive range (a < b)"
4488 "or `..=` if you need an inclusive range (a <= b)"
4492 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4493 // BOUND = TY_BOUND | LT_BOUND
4494 // LT_BOUND = LIFETIME (e.g. `'a`)
4495 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4496 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4497 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4498 let mut bounds = Vec::new();
4500 // This needs to be syncronized with `Token::can_begin_bound`.
4501 let is_bound_start = self.check_path() || self.check_lifetime() ||
4502 self.check(&token::Question) ||
4503 self.check_keyword(keywords::For) ||
4504 self.check(&token::OpenDelim(token::Paren));
4506 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4507 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4508 if self.token.is_lifetime() {
4509 if let Some(question_span) = question {
4510 self.span_err(question_span,
4511 "`?` may only modify trait bounds, not lifetime bounds");
4513 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4516 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4517 let path = self.parse_path(PathStyle::Type)?;
4518 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4519 let modifier = if question.is_some() {
4520 TraitBoundModifier::Maybe
4522 TraitBoundModifier::None
4524 bounds.push(TraitTyParamBound(poly_trait, modifier));
4527 self.expect(&token::CloseDelim(token::Paren))?;
4528 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4529 self.span_err(self.prev_span,
4530 "parenthesized lifetime bounds are not supported");
4537 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4545 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4546 self.parse_ty_param_bounds_common(true)
4549 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4550 // BOUND = LT_BOUND (e.g. `'a`)
4551 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4552 let mut lifetimes = Vec::new();
4553 while self.check_lifetime() {
4554 lifetimes.push(self.expect_lifetime());
4556 if !self.eat(&token::BinOp(token::Plus)) {
4563 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4564 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4565 let span = self.span;
4566 let ident = self.parse_ident()?;
4568 // Parse optional colon and param bounds.
4569 let bounds = if self.eat(&token::Colon) {
4570 self.parse_ty_param_bounds()?
4575 let default = if self.eat(&token::Eq) {
4576 Some(self.parse_ty()?)
4582 attrs: preceding_attrs.into(),
4584 id: ast::DUMMY_NODE_ID,
4591 /// Parses the following grammar:
4592 /// TraitItemAssocTy = Ident ["<"...">"] [":" [TyParamBounds]] ["where" ...] ["=" Ty]
4593 fn parse_trait_item_assoc_ty(&mut self, preceding_attrs: Vec<Attribute>)
4594 -> PResult<'a, (ast::Generics, TyParam)> {
4595 let span = self.span;
4596 let ident = self.parse_ident()?;
4597 let mut generics = self.parse_generics()?;
4599 // Parse optional colon and param bounds.
4600 let bounds = if self.eat(&token::Colon) {
4601 self.parse_ty_param_bounds()?
4605 generics.where_clause = self.parse_where_clause()?;
4607 let default = if self.eat(&token::Eq) {
4608 Some(self.parse_ty()?)
4612 self.expect(&token::Semi)?;
4614 Ok((generics, TyParam {
4615 attrs: preceding_attrs.into(),
4617 id: ast::DUMMY_NODE_ID,
4624 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4625 /// trailing comma and erroneous trailing attributes.
4626 pub fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4627 let mut params = Vec::new();
4628 let mut seen_ty_param = false;
4630 let attrs = self.parse_outer_attributes()?;
4631 if self.check_lifetime() {
4632 let lifetime = self.expect_lifetime();
4633 // Parse lifetime parameter.
4634 let bounds = if self.eat(&token::Colon) {
4635 self.parse_lt_param_bounds()
4639 params.push(ast::GenericParam::Lifetime(LifetimeDef {
4640 attrs: attrs.into(),
4645 self.span_err(self.prev_span,
4646 "lifetime parameters must be declared prior to type parameters");
4648 } else if self.check_ident() {
4649 // Parse type parameter.
4650 params.push(ast::GenericParam::Type(self.parse_ty_param(attrs)?));
4651 seen_ty_param = true;
4653 // Check for trailing attributes and stop parsing.
4654 if !attrs.is_empty() {
4655 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4656 self.span_err(attrs[0].span,
4657 &format!("trailing attribute after {} parameters", param_kind));
4662 if !self.eat(&token::Comma) {
4669 /// Parse a set of optional generic type parameter declarations. Where
4670 /// clauses are not parsed here, and must be added later via
4671 /// `parse_where_clause()`.
4673 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4674 /// | ( < lifetimes , typaramseq ( , )? > )
4675 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4676 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4677 maybe_whole!(self, NtGenerics, |x| x);
4679 let span_lo = self.span;
4681 let params = self.parse_generic_params()?;
4685 where_clause: WhereClause {
4686 id: ast::DUMMY_NODE_ID,
4687 predicates: Vec::new(),
4688 span: syntax_pos::DUMMY_SP,
4690 span: span_lo.to(self.prev_span),
4693 Ok(ast::Generics::default())
4697 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4698 /// possibly including trailing comma.
4699 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4700 let mut lifetimes = Vec::new();
4701 let mut types = Vec::new();
4702 let mut bindings = Vec::new();
4703 let mut seen_type = false;
4704 let mut seen_binding = false;
4706 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4707 // Parse lifetime argument.
4708 lifetimes.push(self.expect_lifetime());
4709 if seen_type || seen_binding {
4710 self.span_err(self.prev_span,
4711 "lifetime parameters must be declared prior to type parameters");
4713 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4714 // Parse associated type binding.
4716 let ident = self.parse_ident()?;
4718 let ty = self.parse_ty()?;
4719 bindings.push(TypeBinding {
4720 id: ast::DUMMY_NODE_ID,
4723 span: lo.to(self.prev_span),
4725 seen_binding = true;
4726 } else if self.check_type() {
4727 // Parse type argument.
4728 types.push(self.parse_ty()?);
4730 self.span_err(types[types.len() - 1].span,
4731 "type parameters must be declared prior to associated type bindings");
4738 if !self.eat(&token::Comma) {
4742 Ok((lifetimes, types, bindings))
4745 /// Parses an optional `where` clause and places it in `generics`.
4747 /// ```ignore (only-for-syntax-highlight)
4748 /// where T : Trait<U, V> + 'b, 'a : 'b
4750 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4751 maybe_whole!(self, NtWhereClause, |x| x);
4753 let mut where_clause = WhereClause {
4754 id: ast::DUMMY_NODE_ID,
4755 predicates: Vec::new(),
4756 span: syntax_pos::DUMMY_SP,
4759 if !self.eat_keyword(keywords::Where) {
4760 return Ok(where_clause);
4762 let lo = self.prev_span;
4764 // This is a temporary future proofing.
4766 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4767 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4768 // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4769 if token::Lt == self.token {
4770 let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4771 if ident_or_lifetime {
4772 let gt_comma_or_colon = self.look_ahead(2, |t| {
4773 *t == token::Gt || *t == token::Comma || *t == token::Colon
4775 if gt_comma_or_colon {
4776 self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4783 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4784 let lifetime = self.expect_lifetime();
4785 // Bounds starting with a colon are mandatory, but possibly empty.
4786 self.expect(&token::Colon)?;
4787 let bounds = self.parse_lt_param_bounds();
4788 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4789 ast::WhereRegionPredicate {
4790 span: lo.to(self.prev_span),
4795 } else if self.check_type() {
4796 // Parse optional `for<'a, 'b>`.
4797 // This `for` is parsed greedily and applies to the whole predicate,
4798 // the bounded type can have its own `for` applying only to it.
4799 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4800 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4801 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4802 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4804 // Parse type with mandatory colon and (possibly empty) bounds,
4805 // or with mandatory equality sign and the second type.
4806 let ty = self.parse_ty()?;
4807 if self.eat(&token::Colon) {
4808 let bounds = self.parse_ty_param_bounds()?;
4809 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4810 ast::WhereBoundPredicate {
4811 span: lo.to(self.prev_span),
4812 bound_generic_params: lifetime_defs,
4817 // FIXME: Decide what should be used here, `=` or `==`.
4818 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4819 let rhs_ty = self.parse_ty()?;
4820 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4821 ast::WhereEqPredicate {
4822 span: lo.to(self.prev_span),
4825 id: ast::DUMMY_NODE_ID,
4829 return self.unexpected();
4835 if !self.eat(&token::Comma) {
4840 where_clause.span = lo.to(self.prev_span);
4844 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4845 -> PResult<'a, (Vec<Arg> , bool)> {
4847 let mut variadic = false;
4848 let args: Vec<Option<Arg>> =
4849 self.parse_unspanned_seq(
4850 &token::OpenDelim(token::Paren),
4851 &token::CloseDelim(token::Paren),
4852 SeqSep::trailing_allowed(token::Comma),
4854 if p.token == token::DotDotDot {
4857 if p.token != token::CloseDelim(token::Paren) {
4860 "`...` must be last in argument list for variadic function");
4865 "only foreign functions are allowed to be variadic");
4870 match p.parse_arg_general(named_args) {
4871 Ok(arg) => Ok(Some(arg)),
4874 let lo = p.prev_span;
4875 // Skip every token until next possible arg or end.
4876 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4877 // Create a placeholder argument for proper arg count (#34264).
4878 let span = lo.to(p.prev_span);
4879 Ok(Some(dummy_arg(span)))
4886 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4888 if variadic && args.is_empty() {
4890 "variadic function must be declared with at least one named argument");
4893 Ok((args, variadic))
4896 /// Parse the argument list and result type of a function declaration
4897 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4899 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4900 let ret_ty = self.parse_ret_ty()?;
4909 /// Returns the parsed optional self argument and whether a self shortcut was used.
4910 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4911 let expect_ident = |this: &mut Self| match this.token {
4912 // Preserve hygienic context.
4913 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4916 let isolated_self = |this: &mut Self, n| {
4917 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4918 this.look_ahead(n + 1, |t| t != &token::ModSep)
4921 // Parse optional self parameter of a method.
4922 // Only a limited set of initial token sequences is considered self parameters, anything
4923 // else is parsed as a normal function parameter list, so some lookahead is required.
4924 let eself_lo = self.span;
4925 let (eself, eself_ident) = match self.token {
4926 token::BinOp(token::And) => {
4932 if isolated_self(self, 1) {
4934 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4935 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4936 isolated_self(self, 2) {
4939 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4940 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4941 isolated_self(self, 2) {
4943 let lt = self.expect_lifetime();
4944 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4945 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4946 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4947 isolated_self(self, 3) {
4949 let lt = self.expect_lifetime();
4951 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4956 token::BinOp(token::Star) => {
4961 // Emit special error for `self` cases.
4962 if isolated_self(self, 1) {
4964 self.span_err(self.span, "cannot pass `self` by raw pointer");
4965 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4966 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4967 isolated_self(self, 2) {
4970 self.span_err(self.span, "cannot pass `self` by raw pointer");
4971 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4976 token::Ident(..) => {
4977 if isolated_self(self, 0) {
4980 let eself_ident = expect_ident(self);
4981 if self.eat(&token::Colon) {
4982 let ty = self.parse_ty()?;
4983 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4985 (SelfKind::Value(Mutability::Immutable), eself_ident)
4987 } else if self.token.is_keyword(keywords::Mut) &&
4988 isolated_self(self, 1) {
4992 let eself_ident = expect_ident(self);
4993 if self.eat(&token::Colon) {
4994 let ty = self.parse_ty()?;
4995 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4997 (SelfKind::Value(Mutability::Mutable), eself_ident)
5003 _ => return Ok(None),
5006 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
5007 Ok(Some(Arg::from_self(eself, eself_ident)))
5010 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5011 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5012 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5014 self.expect(&token::OpenDelim(token::Paren))?;
5016 // Parse optional self argument
5017 let self_arg = self.parse_self_arg()?;
5019 // Parse the rest of the function parameter list.
5020 let sep = SeqSep::trailing_allowed(token::Comma);
5021 let fn_inputs = if let Some(self_arg) = self_arg {
5022 if self.check(&token::CloseDelim(token::Paren)) {
5024 } else if self.eat(&token::Comma) {
5025 let mut fn_inputs = vec![self_arg];
5026 fn_inputs.append(&mut self.parse_seq_to_before_end(
5027 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5031 return self.unexpected();
5034 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5037 // Parse closing paren and return type.
5038 self.expect(&token::CloseDelim(token::Paren))?;
5041 output: self.parse_ret_ty()?,
5046 // parse the |arg, arg| header on a lambda
5047 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5048 let inputs_captures = {
5049 if self.eat(&token::OrOr) {
5052 self.expect(&token::BinOp(token::Or))?;
5053 let args = self.parse_seq_to_before_tokens(
5054 &[&token::BinOp(token::Or), &token::OrOr],
5055 SeqSep::trailing_allowed(token::Comma),
5056 TokenExpectType::NoExpect,
5057 |p| p.parse_fn_block_arg()
5063 let output = self.parse_ret_ty()?;
5066 inputs: inputs_captures,
5072 /// Parse the name and optional generic types of a function header.
5073 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5074 let id = self.parse_ident()?;
5075 let generics = self.parse_generics()?;
5079 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5080 attrs: Vec<Attribute>) -> P<Item> {
5084 id: ast::DUMMY_NODE_ID,
5092 /// Parse an item-position function declaration.
5093 fn parse_item_fn(&mut self,
5095 constness: Spanned<Constness>,
5097 -> PResult<'a, ItemInfo> {
5098 let (ident, mut generics) = self.parse_fn_header()?;
5099 let decl = self.parse_fn_decl(false)?;
5100 generics.where_clause = self.parse_where_clause()?;
5101 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5102 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
5105 /// true if we are looking at `const ID`, false for things like `const fn` etc
5106 pub fn is_const_item(&mut self) -> bool {
5107 self.token.is_keyword(keywords::Const) &&
5108 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5109 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5112 /// parses all the "front matter" for a `fn` declaration, up to
5113 /// and including the `fn` keyword:
5117 /// - `const unsafe fn`
5120 pub fn parse_fn_front_matter(&mut self)
5121 -> PResult<'a, (Spanned<ast::Constness>,
5124 let is_const_fn = self.eat_keyword(keywords::Const);
5125 let const_span = self.prev_span;
5126 let unsafety = self.parse_unsafety()?;
5127 let (constness, unsafety, abi) = if is_const_fn {
5128 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5130 let abi = if self.eat_keyword(keywords::Extern) {
5131 self.parse_opt_abi()?.unwrap_or(Abi::C)
5135 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5137 self.expect_keyword(keywords::Fn)?;
5138 Ok((constness, unsafety, abi))
5141 /// Parse an impl item.
5142 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5143 maybe_whole!(self, NtImplItem, |x| x);
5144 let attrs = self.parse_outer_attributes()?;
5145 let (mut item, tokens) = self.collect_tokens(|this| {
5146 this.parse_impl_item_(at_end, attrs)
5149 // See `parse_item` for why this clause is here.
5150 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5151 item.tokens = Some(tokens);
5156 fn parse_impl_item_(&mut self,
5158 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5160 let vis = self.parse_visibility(false)?;
5161 let defaultness = self.parse_defaultness()?;
5162 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
5163 // This parses the grammar:
5164 // ImplItemAssocTy = Ident ["<"...">"] ["where" ...] "=" Ty ";"
5165 let name = self.parse_ident()?;
5166 let mut generics = self.parse_generics()?;
5167 generics.where_clause = self.parse_where_clause()?;
5168 self.expect(&token::Eq)?;
5169 let typ = self.parse_ty()?;
5170 self.expect(&token::Semi)?;
5171 (name, ast::ImplItemKind::Type(typ), generics)
5172 } else if self.is_const_item() {
5173 // This parses the grammar:
5174 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5175 self.expect_keyword(keywords::Const)?;
5176 let name = self.parse_ident()?;
5177 self.expect(&token::Colon)?;
5178 let typ = self.parse_ty()?;
5179 self.expect(&token::Eq)?;
5180 let expr = self.parse_expr()?;
5181 self.expect(&token::Semi)?;
5182 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5184 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5185 attrs.extend(inner_attrs);
5186 (name, node, generics)
5190 id: ast::DUMMY_NODE_ID,
5191 span: lo.to(self.prev_span),
5202 fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
5203 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5208 fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
5210 Visibility::Inherited => Ok(()),
5212 let is_macro_rules: bool = match self.token {
5213 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
5217 let mut err = self.diagnostic()
5218 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5219 err.help("did you mean #[macro_export]?");
5222 let mut err = self.diagnostic()
5223 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5224 err.help("try adjusting the macro to put `pub` inside the invocation");
5231 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5232 -> DiagnosticBuilder<'a>
5234 // Given this code `path(`, it seems like this is not
5235 // setting the visibility of a macro invocation, but rather
5236 // a mistyped method declaration.
5237 // Create a diagnostic pointing out that `fn` is missing.
5239 // x | pub path(&self) {
5240 // | ^ missing `fn`, `type`, or `const`
5242 // ^^ `sp` below will point to this
5243 let sp = prev_span.between(self.prev_span);
5244 let mut err = self.diagnostic().struct_span_err(
5246 &format!("missing `fn`, `type`, or `const` for {}-item declaration",
5248 err.span_label(sp, "missing `fn`, `type`, or `const`");
5252 /// Parse a method or a macro invocation in a trait impl.
5253 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5254 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::Generics,
5255 ast::ImplItemKind)> {
5256 // code copied from parse_macro_use_or_failure... abstraction!
5257 if self.token.is_path_start() && !self.is_extern_non_path() {
5260 let prev_span = self.prev_span;
5263 let pth = self.parse_path(PathStyle::Mod)?;
5264 if pth.segments.len() == 1 {
5265 if !self.eat(&token::Not) {
5266 return Err(self.missing_assoc_item_kind_err("impl", prev_span));
5269 self.expect(&token::Not)?;
5272 self.complain_if_pub_macro(vis, prev_span);
5274 // eat a matched-delimiter token tree:
5276 let (delim, tts) = self.expect_delimited_token_tree()?;
5277 if delim != token::Brace {
5278 self.expect(&token::Semi)?
5281 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
5282 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5283 ast::ImplItemKind::Macro(mac)))
5285 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
5286 let ident = self.parse_ident()?;
5287 let mut generics = self.parse_generics()?;
5288 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5289 generics.where_clause = self.parse_where_clause()?;
5291 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5292 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(ast::MethodSig {
5301 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5302 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5303 let ident = self.parse_ident()?;
5304 let mut tps = self.parse_generics()?;
5306 // Parse optional colon and supertrait bounds.
5307 let bounds = if self.eat(&token::Colon) {
5308 self.parse_ty_param_bounds()?
5313 if self.eat(&token::Eq) {
5314 // it's a trait alias
5315 let bounds = self.parse_ty_param_bounds()?;
5316 tps.where_clause = self.parse_where_clause()?;
5317 self.expect(&token::Semi)?;
5318 if unsafety != Unsafety::Normal {
5319 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5321 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5323 // it's a normal trait
5324 tps.where_clause = self.parse_where_clause()?;
5325 self.expect(&token::OpenDelim(token::Brace))?;
5326 let mut trait_items = vec![];
5327 while !self.eat(&token::CloseDelim(token::Brace)) {
5328 let mut at_end = false;
5329 match self.parse_trait_item(&mut at_end) {
5330 Ok(item) => trait_items.push(item),
5334 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5339 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5343 /// Parses items implementations variants
5344 /// impl<T> Foo { ... }
5345 /// impl<T> ToString for &'static T { ... }
5346 /// impl Send for .. {}
5347 fn parse_item_impl(&mut self,
5348 unsafety: ast::Unsafety,
5349 defaultness: Defaultness) -> PResult<'a, ItemInfo> {
5350 let impl_span = self.span;
5352 // First, parse type parameters if necessary.
5353 let mut generics = self.parse_generics()?;
5355 // Special case: if the next identifier that follows is '(', don't
5356 // allow this to be parsed as a trait.
5357 let could_be_trait = self.token != token::OpenDelim(token::Paren);
5359 let neg_span = self.span;
5360 let polarity = if self.eat(&token::Not) {
5361 ast::ImplPolarity::Negative
5363 ast::ImplPolarity::Positive
5367 let mut ty = self.parse_ty()?;
5369 // Parse traits, if necessary.
5370 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
5371 // New-style trait. Reinterpret the type as a trait.
5373 TyKind::Path(None, ref path) => {
5375 path: (*path).clone(),
5380 self.span_err(ty.span, "not a trait");
5385 if polarity == ast::ImplPolarity::Negative {
5386 // This is a negated type implementation
5387 // `impl !MyType {}`, which is not allowed.
5388 self.span_err(neg_span, "inherent implementation can't be negated");
5393 if opt_trait.is_some() && self.eat(&token::DotDot) {
5394 if generics.is_parameterized() {
5395 self.span_err(impl_span, "auto trait implementations are not \
5396 allowed to have generics");
5399 if let ast::Defaultness::Default = defaultness {
5400 self.span_err(impl_span, "`default impl` is not allowed for \
5401 auto trait implementations");
5404 self.expect(&token::OpenDelim(token::Brace))?;
5405 self.expect(&token::CloseDelim(token::Brace))?;
5406 Ok((keywords::Invalid.ident(),
5407 ItemKind::AutoImpl(unsafety, opt_trait.unwrap()), None))
5409 if opt_trait.is_some() {
5410 ty = self.parse_ty()?;
5412 generics.where_clause = self.parse_where_clause()?;
5414 self.expect(&token::OpenDelim(token::Brace))?;
5415 let attrs = self.parse_inner_attributes()?;
5417 let mut impl_items = vec![];
5418 while !self.eat(&token::CloseDelim(token::Brace)) {
5419 let mut at_end = false;
5420 match self.parse_impl_item(&mut at_end) {
5421 Ok(item) => impl_items.push(item),
5425 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5431 Ok((keywords::Invalid.ident(),
5432 ItemKind::Impl(unsafety, polarity, defaultness, generics, opt_trait, ty, impl_items),
5437 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5438 if self.eat_keyword(keywords::For) {
5440 let params = self.parse_generic_params()?;
5443 let first_non_lifetime_param_span = params.iter()
5444 .filter_map(|param| match *param {
5445 ast::GenericParam::Lifetime(_) => None,
5446 ast::GenericParam::Type(ref t) => Some(t.span),
5450 if let Some(span) = first_non_lifetime_param_span {
5451 self.span_err(span, "only lifetime parameters can be used in this context");
5460 /// Parse struct Foo { ... }
5461 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5462 let class_name = self.parse_ident()?;
5464 let mut generics = self.parse_generics()?;
5466 // There is a special case worth noting here, as reported in issue #17904.
5467 // If we are parsing a tuple struct it is the case that the where clause
5468 // should follow the field list. Like so:
5470 // struct Foo<T>(T) where T: Copy;
5472 // If we are parsing a normal record-style struct it is the case
5473 // that the where clause comes before the body, and after the generics.
5474 // So if we look ahead and see a brace or a where-clause we begin
5475 // parsing a record style struct.
5477 // Otherwise if we look ahead and see a paren we parse a tuple-style
5480 let vdata = if self.token.is_keyword(keywords::Where) {
5481 generics.where_clause = self.parse_where_clause()?;
5482 if self.eat(&token::Semi) {
5483 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5484 VariantData::Unit(ast::DUMMY_NODE_ID)
5486 // If we see: `struct Foo<T> where T: Copy { ... }`
5487 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5489 // No `where` so: `struct Foo<T>;`
5490 } else if self.eat(&token::Semi) {
5491 VariantData::Unit(ast::DUMMY_NODE_ID)
5492 // Record-style struct definition
5493 } else if self.token == token::OpenDelim(token::Brace) {
5494 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5495 // Tuple-style struct definition with optional where-clause.
5496 } else if self.token == token::OpenDelim(token::Paren) {
5497 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5498 generics.where_clause = self.parse_where_clause()?;
5499 self.expect(&token::Semi)?;
5502 let token_str = self.this_token_to_string();
5503 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5504 name, found `{}`", token_str)))
5507 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5510 /// Parse union Foo { ... }
5511 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5512 let class_name = self.parse_ident()?;
5514 let mut generics = self.parse_generics()?;
5516 let vdata = if self.token.is_keyword(keywords::Where) {
5517 generics.where_clause = self.parse_where_clause()?;
5518 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5519 } else if self.token == token::OpenDelim(token::Brace) {
5520 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5522 let token_str = self.this_token_to_string();
5523 return Err(self.fatal(&format!("expected `where` or `{{` after union \
5524 name, found `{}`", token_str)))
5527 Ok((class_name, ItemKind::Union(vdata, generics), None))
5530 fn consume_block(&mut self, delim: token::DelimToken) {
5531 let mut brace_depth = 0;
5532 if !self.eat(&token::OpenDelim(delim)) {
5536 if self.eat(&token::OpenDelim(delim)) {
5538 } else if self.eat(&token::CloseDelim(delim)) {
5539 if brace_depth == 0 {
5545 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5553 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5554 let mut fields = Vec::new();
5555 if self.eat(&token::OpenDelim(token::Brace)) {
5556 while self.token != token::CloseDelim(token::Brace) {
5557 let field = self.parse_struct_decl_field().map_err(|e| {
5558 self.recover_stmt();
5562 Ok(field) => fields.push(field),
5568 self.eat(&token::CloseDelim(token::Brace));
5570 let token_str = self.this_token_to_string();
5571 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5579 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5580 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5581 // Unit like structs are handled in parse_item_struct function
5582 let fields = self.parse_unspanned_seq(
5583 &token::OpenDelim(token::Paren),
5584 &token::CloseDelim(token::Paren),
5585 SeqSep::trailing_allowed(token::Comma),
5587 let attrs = p.parse_outer_attributes()?;
5589 let vis = p.parse_visibility(true)?;
5590 let ty = p.parse_ty()?;
5592 span: lo.to(p.span),
5595 id: ast::DUMMY_NODE_ID,
5604 /// Parse a structure field declaration
5605 pub fn parse_single_struct_field(&mut self,
5608 attrs: Vec<Attribute> )
5609 -> PResult<'a, StructField> {
5610 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5615 token::CloseDelim(token::Brace) => {}
5616 token::DocComment(_) => {
5617 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
5618 self.bump(); // consume the doc comment
5619 if self.eat(&token::Comma) || self.token == token::CloseDelim(token::Brace) {
5625 _ => return Err(self.span_fatal_help(self.span,
5626 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5627 "struct fields should be separated by commas")),
5632 /// Parse an element of a struct definition
5633 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5634 let attrs = self.parse_outer_attributes()?;
5636 let vis = self.parse_visibility(false)?;
5637 self.parse_single_struct_field(lo, vis, attrs)
5640 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5641 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5642 /// a function definition, it's not a tuple struct field) and the contents within the parens
5643 /// isn't valid, emit a proper diagnostic.
5644 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5645 maybe_whole!(self, NtVis, |x| x);
5647 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
5648 if self.is_crate_vis() {
5649 self.bump(); // `crate`
5650 return Ok(Visibility::Crate(self.prev_span, CrateSugar::JustCrate));
5653 if !self.eat_keyword(keywords::Pub) {
5654 return Ok(Visibility::Inherited)
5657 if self.check(&token::OpenDelim(token::Paren)) {
5658 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5659 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5660 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5661 // by the following tokens.
5662 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5665 self.bump(); // `crate`
5666 let vis = Visibility::Crate(self.prev_span, CrateSugar::PubCrate);
5667 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5669 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5672 self.bump(); // `in`
5673 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5674 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5675 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5677 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5678 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5679 t.is_keyword(keywords::SelfValue)) {
5680 // `pub(self)` or `pub(super)`
5682 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5683 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5684 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5686 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5687 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5689 let msg = "incorrect visibility restriction";
5690 let suggestion = r##"some possible visibility restrictions are:
5691 `pub(crate)`: visible only on the current crate
5692 `pub(super)`: visible only in the current module's parent
5693 `pub(in path::to::module)`: visible only on the specified path"##;
5694 let path = self.parse_path(PathStyle::Mod)?;
5695 let path_span = self.prev_span;
5696 let help_msg = format!("make this visible only to module `{}` with `in`", path);
5697 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5698 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5699 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5700 err.emit(); // emit diagnostic, but continue with public visibility
5704 Ok(Visibility::Public)
5707 /// Parse defaultness: DEFAULT or nothing
5708 fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5709 if self.eat_defaultness() {
5710 Ok(Defaultness::Default)
5712 Ok(Defaultness::Final)
5716 /// Given a termination token, parse all of the items in a module
5717 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5718 let mut items = vec![];
5719 while let Some(item) = self.parse_item()? {
5723 if !self.eat(term) {
5724 let token_str = self.this_token_to_string();
5725 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
5726 let msg = "consider removing this semicolon";
5727 if token_str == ";" {
5728 err.span_suggestion_short(self.span, msg, "".to_string());
5733 let hi = if self.span == syntax_pos::DUMMY_SP {
5740 inner: inner_lo.to(hi),
5745 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5746 let id = self.parse_ident()?;
5747 self.expect(&token::Colon)?;
5748 let ty = self.parse_ty()?;
5749 self.expect(&token::Eq)?;
5750 let e = self.parse_expr()?;
5751 self.expect(&token::Semi)?;
5752 let item = match m {
5753 Some(m) => ItemKind::Static(ty, m, e),
5754 None => ItemKind::Const(ty, e),
5756 Ok((id, item, None))
5759 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5760 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5761 let (in_cfg, outer_attrs) = {
5762 let mut strip_unconfigured = ::config::StripUnconfigured {
5764 should_test: false, // irrelevant
5765 features: None, // don't perform gated feature checking
5767 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5768 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5771 let id_span = self.span;
5772 let id = self.parse_ident()?;
5773 if self.check(&token::Semi) {
5775 if in_cfg && self.recurse_into_file_modules {
5776 // This mod is in an external file. Let's go get it!
5777 let ModulePathSuccess { path, directory_ownership, warn } =
5778 self.submod_path(id, &outer_attrs, id_span)?;
5779 let (module, mut attrs) =
5780 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5782 let attr = ast::Attribute {
5783 id: attr::mk_attr_id(),
5784 style: ast::AttrStyle::Outer,
5785 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5786 Ident::from_str("warn_directory_ownership")),
5787 tokens: TokenStream::empty(),
5788 is_sugared_doc: false,
5789 span: syntax_pos::DUMMY_SP,
5791 attr::mark_known(&attr);
5794 Ok((id, module, Some(attrs)))
5796 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5797 Ok((id, ItemKind::Mod(placeholder), None))
5800 let old_directory = self.directory.clone();
5801 self.push_directory(id, &outer_attrs);
5803 self.expect(&token::OpenDelim(token::Brace))?;
5804 let mod_inner_lo = self.span;
5805 let attrs = self.parse_inner_attributes()?;
5806 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5808 self.directory = old_directory;
5809 Ok((id, ItemKind::Mod(module), Some(attrs)))
5813 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5814 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5815 self.directory.path.push(&path.as_str());
5816 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
5818 self.directory.path.push(&id.name.as_str());
5822 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5823 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5826 /// Returns either a path to a module, or .
5827 pub fn default_submod_path(
5829 relative: Option<ast::Ident>,
5831 codemap: &CodeMap) -> ModulePath
5833 // If we're in a foo.rs file instead of a mod.rs file,
5834 // we need to look for submodules in
5835 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
5836 // `./<id>.rs` and `./<id>/mod.rs`.
5837 let relative_prefix_string;
5838 let relative_prefix = if let Some(ident) = relative {
5839 relative_prefix_string = format!("{}{}", ident.name.as_str(), path::MAIN_SEPARATOR);
5840 &relative_prefix_string
5845 let mod_name = id.to_string();
5846 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
5847 let secondary_path_str = format!("{}{}{}mod.rs",
5848 relative_prefix, mod_name, path::MAIN_SEPARATOR);
5849 let default_path = dir_path.join(&default_path_str);
5850 let secondary_path = dir_path.join(&secondary_path_str);
5851 let default_exists = codemap.file_exists(&default_path);
5852 let secondary_exists = codemap.file_exists(&secondary_path);
5854 let result = match (default_exists, secondary_exists) {
5855 (true, false) => Ok(ModulePathSuccess {
5857 directory_ownership: DirectoryOwnership::Owned {
5862 (false, true) => Ok(ModulePathSuccess {
5863 path: secondary_path,
5864 directory_ownership: DirectoryOwnership::Owned {
5869 (false, false) => Err(Error::FileNotFoundForModule {
5870 mod_name: mod_name.clone(),
5871 default_path: default_path_str,
5872 secondary_path: secondary_path_str,
5873 dir_path: format!("{}", dir_path.display()),
5875 (true, true) => Err(Error::DuplicatePaths {
5876 mod_name: mod_name.clone(),
5877 default_path: default_path_str,
5878 secondary_path: secondary_path_str,
5884 path_exists: default_exists || secondary_exists,
5889 fn submod_path(&mut self,
5891 outer_attrs: &[ast::Attribute],
5893 -> PResult<'a, ModulePathSuccess> {
5894 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5895 return Ok(ModulePathSuccess {
5896 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5897 Some("mod.rs") => DirectoryOwnership::Owned { relative: None },
5899 DirectoryOwnership::Owned { relative: Some(id) }
5901 _ => DirectoryOwnership::UnownedViaMod(true),
5908 let relative = match self.directory.ownership {
5909 DirectoryOwnership::Owned { relative } => {
5910 // Push the usage onto the list of non-mod.rs mod uses.
5911 // This is used later for feature-gate error reporting.
5912 if let Some(cur_file_ident) = relative {
5914 .non_modrs_mods.borrow_mut()
5915 .push((cur_file_ident, id_sp));
5919 DirectoryOwnership::UnownedViaBlock |
5920 DirectoryOwnership::UnownedViaMod(_) => None,
5922 let paths = Parser::default_submod_path(
5923 id, relative, &self.directory.path, self.sess.codemap());
5925 match self.directory.ownership {
5926 DirectoryOwnership::Owned { .. } => {
5927 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5929 DirectoryOwnership::UnownedViaBlock => {
5931 "Cannot declare a non-inline module inside a block \
5932 unless it has a path attribute";
5933 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5934 if paths.path_exists {
5935 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5937 err.span_note(id_sp, &msg);
5941 DirectoryOwnership::UnownedViaMod(warn) => {
5943 if let Ok(result) = paths.result {
5944 return Ok(ModulePathSuccess { warn: true, ..result });
5947 let mut err = self.diagnostic().struct_span_err(id_sp,
5948 "cannot declare a new module at this location");
5949 if id_sp != syntax_pos::DUMMY_SP {
5950 let src_path = self.sess.codemap().span_to_filename(id_sp);
5951 if let FileName::Real(src_path) = src_path {
5952 if let Some(stem) = src_path.file_stem() {
5953 let mut dest_path = src_path.clone();
5954 dest_path.set_file_name(stem);
5955 dest_path.push("mod.rs");
5956 err.span_note(id_sp,
5957 &format!("maybe move this module `{}` to its own \
5958 directory via `{}`", src_path.display(),
5959 dest_path.display()));
5963 if paths.path_exists {
5964 err.span_note(id_sp,
5965 &format!("... or maybe `use` the module `{}` instead \
5966 of possibly redeclaring it",
5974 /// Read a module from a source file.
5975 fn eval_src_mod(&mut self,
5977 directory_ownership: DirectoryOwnership,
5980 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5981 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5982 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5983 let mut err = String::from("circular modules: ");
5984 let len = included_mod_stack.len();
5985 for p in &included_mod_stack[i.. len] {
5986 err.push_str(&p.to_string_lossy());
5987 err.push_str(" -> ");
5989 err.push_str(&path.to_string_lossy());
5990 return Err(self.span_fatal(id_sp, &err[..]));
5992 included_mod_stack.push(path.clone());
5993 drop(included_mod_stack);
5996 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5997 p0.cfg_mods = self.cfg_mods;
5998 let mod_inner_lo = p0.span;
5999 let mod_attrs = p0.parse_inner_attributes()?;
6000 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6001 self.sess.included_mod_stack.borrow_mut().pop();
6002 Ok((ast::ItemKind::Mod(m0), mod_attrs))
6005 /// Parse a function declaration from a foreign module
6006 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6007 -> PResult<'a, ForeignItem> {
6008 self.expect_keyword(keywords::Fn)?;
6010 let (ident, mut generics) = self.parse_fn_header()?;
6011 let decl = self.parse_fn_decl(true)?;
6012 generics.where_clause = self.parse_where_clause()?;
6014 self.expect(&token::Semi)?;
6015 Ok(ast::ForeignItem {
6018 node: ForeignItemKind::Fn(decl, generics),
6019 id: ast::DUMMY_NODE_ID,
6025 /// Parse a static item from a foreign module.
6026 /// Assumes that the `static` keyword is already parsed.
6027 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6028 -> PResult<'a, ForeignItem> {
6029 let mutbl = self.eat_keyword(keywords::Mut);
6030 let ident = self.parse_ident()?;
6031 self.expect(&token::Colon)?;
6032 let ty = self.parse_ty()?;
6034 self.expect(&token::Semi)?;
6038 node: ForeignItemKind::Static(ty, mutbl),
6039 id: ast::DUMMY_NODE_ID,
6045 /// Parse a type from a foreign module
6046 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6047 -> PResult<'a, ForeignItem> {
6048 self.expect_keyword(keywords::Type)?;
6050 let ident = self.parse_ident()?;
6052 self.expect(&token::Semi)?;
6053 Ok(ast::ForeignItem {
6056 node: ForeignItemKind::Ty,
6057 id: ast::DUMMY_NODE_ID,
6063 /// Parse extern crate links
6067 /// extern crate foo;
6068 /// extern crate bar as foo;
6069 fn parse_item_extern_crate(&mut self,
6071 visibility: Visibility,
6072 attrs: Vec<Attribute>)
6073 -> PResult<'a, P<Item>> {
6075 let crate_name = self.parse_ident()?;
6076 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
6077 (Some(crate_name.name), ident)
6081 self.expect(&token::Semi)?;
6083 let prev_span = self.prev_span;
6084 Ok(self.mk_item(lo.to(prev_span),
6086 ItemKind::ExternCrate(maybe_path),
6091 /// Parse `extern` for foreign ABIs
6094 /// `extern` is expected to have been
6095 /// consumed before calling this method
6101 fn parse_item_foreign_mod(&mut self,
6103 opt_abi: Option<abi::Abi>,
6104 visibility: Visibility,
6105 mut attrs: Vec<Attribute>)
6106 -> PResult<'a, P<Item>> {
6107 self.expect(&token::OpenDelim(token::Brace))?;
6109 let abi = opt_abi.unwrap_or(Abi::C);
6111 attrs.extend(self.parse_inner_attributes()?);
6113 let mut foreign_items = vec![];
6114 while let Some(item) = self.parse_foreign_item()? {
6115 foreign_items.push(item);
6117 self.expect(&token::CloseDelim(token::Brace))?;
6119 let prev_span = self.prev_span;
6120 let m = ast::ForeignMod {
6122 items: foreign_items
6124 let invalid = keywords::Invalid.ident();
6125 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6128 /// Parse type Foo = Bar;
6129 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
6130 let ident = self.parse_ident()?;
6131 let mut tps = self.parse_generics()?;
6132 tps.where_clause = self.parse_where_clause()?;
6133 self.expect(&token::Eq)?;
6134 let ty = self.parse_ty()?;
6135 self.expect(&token::Semi)?;
6136 Ok((ident, ItemKind::Ty(ty, tps), None))
6139 /// Parse the part of an "enum" decl following the '{'
6140 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6141 let mut variants = Vec::new();
6142 let mut all_nullary = true;
6143 let mut any_disr = None;
6144 while self.token != token::CloseDelim(token::Brace) {
6145 let variant_attrs = self.parse_outer_attributes()?;
6146 let vlo = self.span;
6149 let mut disr_expr = None;
6150 let ident = self.parse_ident()?;
6151 if self.check(&token::OpenDelim(token::Brace)) {
6152 // Parse a struct variant.
6153 all_nullary = false;
6154 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6155 ast::DUMMY_NODE_ID);
6156 } else if self.check(&token::OpenDelim(token::Paren)) {
6157 all_nullary = false;
6158 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6159 ast::DUMMY_NODE_ID);
6160 } else if self.eat(&token::Eq) {
6161 disr_expr = Some(self.parse_expr()?);
6162 any_disr = disr_expr.as_ref().map(|expr| expr.span);
6163 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6165 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6168 let vr = ast::Variant_ {
6170 attrs: variant_attrs,
6174 variants.push(respan(vlo.to(self.prev_span), vr));
6176 if !self.eat(&token::Comma) { break; }
6178 self.expect(&token::CloseDelim(token::Brace))?;
6180 Some(disr_span) if !all_nullary =>
6181 self.span_err(disr_span,
6182 "discriminator values can only be used with a field-less enum"),
6186 Ok(ast::EnumDef { variants: variants })
6189 /// Parse an "enum" declaration
6190 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6191 let id = self.parse_ident()?;
6192 let mut generics = self.parse_generics()?;
6193 generics.where_clause = self.parse_where_clause()?;
6194 self.expect(&token::OpenDelim(token::Brace))?;
6196 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6197 self.recover_stmt();
6198 self.eat(&token::CloseDelim(token::Brace));
6201 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6204 /// Parses a string as an ABI spec on an extern type or module. Consumes
6205 /// the `extern` keyword, if one is found.
6206 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
6208 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6210 self.expect_no_suffix(sp, "ABI spec", suf);
6212 match abi::lookup(&s.as_str()) {
6213 Some(abi) => Ok(Some(abi)),
6215 let prev_span = self.prev_span;
6218 &format!("invalid ABI: expected one of [{}], \
6220 abi::all_names().join(", "),
6231 /// Parse one of the items allowed by the flags.
6232 /// NB: this function no longer parses the items inside an
6234 fn parse_item_(&mut self, attrs: Vec<Attribute>,
6235 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
6236 maybe_whole!(self, NtItem, |item| {
6237 let mut item = item.into_inner();
6238 let mut attrs = attrs;
6239 mem::swap(&mut item.attrs, &mut attrs);
6240 item.attrs.extend(attrs);
6246 let visibility = self.parse_visibility(false)?;
6248 if self.eat_keyword(keywords::Use) {
6250 let item_ = ItemKind::Use(P(self.parse_use_tree(false)?));
6251 self.expect(&token::Semi)?;
6253 let prev_span = self.prev_span;
6254 let invalid = keywords::Invalid.ident();
6255 let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
6256 return Ok(Some(item));
6259 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6260 self.bump(); // `extern`
6261 if self.eat_keyword(keywords::Crate) {
6262 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6265 let opt_abi = self.parse_opt_abi()?;
6267 if self.eat_keyword(keywords::Fn) {
6268 // EXTERN FUNCTION ITEM
6269 let fn_span = self.prev_span;
6270 let abi = opt_abi.unwrap_or(Abi::C);
6271 let (ident, item_, extra_attrs) =
6272 self.parse_item_fn(Unsafety::Normal,
6273 respan(fn_span, Constness::NotConst),
6275 let prev_span = self.prev_span;
6276 let item = self.mk_item(lo.to(prev_span),
6280 maybe_append(attrs, extra_attrs));
6281 return Ok(Some(item));
6282 } else if self.check(&token::OpenDelim(token::Brace)) {
6283 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6289 if self.eat_keyword(keywords::Static) {
6291 let m = if self.eat_keyword(keywords::Mut) {
6294 Mutability::Immutable
6296 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6297 let prev_span = self.prev_span;
6298 let item = self.mk_item(lo.to(prev_span),
6302 maybe_append(attrs, extra_attrs));
6303 return Ok(Some(item));
6305 if self.eat_keyword(keywords::Const) {
6306 let const_span = self.prev_span;
6307 if self.check_keyword(keywords::Fn)
6308 || (self.check_keyword(keywords::Unsafe)
6309 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6310 // CONST FUNCTION ITEM
6311 let unsafety = if self.eat_keyword(keywords::Unsafe) {
6317 let (ident, item_, extra_attrs) =
6318 self.parse_item_fn(unsafety,
6319 respan(const_span, Constness::Const),
6321 let prev_span = self.prev_span;
6322 let item = self.mk_item(lo.to(prev_span),
6326 maybe_append(attrs, extra_attrs));
6327 return Ok(Some(item));
6331 if self.eat_keyword(keywords::Mut) {
6332 let prev_span = self.prev_span;
6333 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6334 .help("did you mean to declare a static?")
6337 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6338 let prev_span = self.prev_span;
6339 let item = self.mk_item(lo.to(prev_span),
6343 maybe_append(attrs, extra_attrs));
6344 return Ok(Some(item));
6346 if self.check_keyword(keywords::Unsafe) &&
6347 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
6348 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
6350 // UNSAFE TRAIT ITEM
6351 self.expect_keyword(keywords::Unsafe)?;
6352 let is_auto = if self.eat_keyword(keywords::Trait) {
6355 self.eat_auto_trait();
6358 let (ident, item_, extra_attrs) =
6359 self.parse_item_trait(is_auto, ast::Unsafety::Unsafe)?;
6360 let prev_span = self.prev_span;
6361 let item = self.mk_item(lo.to(prev_span),
6365 maybe_append(attrs, extra_attrs));
6366 return Ok(Some(item));
6368 if (self.check_keyword(keywords::Unsafe) &&
6369 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))) ||
6370 (self.check_keyword(keywords::Default) &&
6371 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) &&
6372 self.look_ahead(2, |t| t.is_keyword(keywords::Impl)))
6375 let defaultness = self.parse_defaultness()?;
6376 self.expect_keyword(keywords::Unsafe)?;
6377 self.expect_keyword(keywords::Impl)?;
6380 extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe, defaultness)?;
6381 let prev_span = self.prev_span;
6382 let item = self.mk_item(lo.to(prev_span),
6386 maybe_append(attrs, extra_attrs));
6387 return Ok(Some(item));
6389 if self.check_keyword(keywords::Fn) {
6392 let fn_span = self.prev_span;
6393 let (ident, item_, extra_attrs) =
6394 self.parse_item_fn(Unsafety::Normal,
6395 respan(fn_span, Constness::NotConst),
6397 let prev_span = self.prev_span;
6398 let item = self.mk_item(lo.to(prev_span),
6402 maybe_append(attrs, extra_attrs));
6403 return Ok(Some(item));
6405 if self.check_keyword(keywords::Unsafe)
6406 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
6407 // UNSAFE FUNCTION ITEM
6409 let abi = if self.eat_keyword(keywords::Extern) {
6410 self.parse_opt_abi()?.unwrap_or(Abi::C)
6414 self.expect_keyword(keywords::Fn)?;
6415 let fn_span = self.prev_span;
6416 let (ident, item_, extra_attrs) =
6417 self.parse_item_fn(Unsafety::Unsafe,
6418 respan(fn_span, Constness::NotConst),
6420 let prev_span = self.prev_span;
6421 let item = self.mk_item(lo.to(prev_span),
6425 maybe_append(attrs, extra_attrs));
6426 return Ok(Some(item));
6428 if self.eat_keyword(keywords::Mod) {
6430 let (ident, item_, extra_attrs) =
6431 self.parse_item_mod(&attrs[..])?;
6432 let prev_span = self.prev_span;
6433 let item = self.mk_item(lo.to(prev_span),
6437 maybe_append(attrs, extra_attrs));
6438 return Ok(Some(item));
6440 if self.eat_keyword(keywords::Type) {
6442 let (ident, item_, extra_attrs) = self.parse_item_type()?;
6443 let prev_span = self.prev_span;
6444 let item = self.mk_item(lo.to(prev_span),
6448 maybe_append(attrs, extra_attrs));
6449 return Ok(Some(item));
6451 if self.eat_keyword(keywords::Enum) {
6453 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
6454 let prev_span = self.prev_span;
6455 let item = self.mk_item(lo.to(prev_span),
6459 maybe_append(attrs, extra_attrs));
6460 return Ok(Some(item));
6462 if self.check_keyword(keywords::Trait)
6463 || (self.check_keyword(keywords::Auto)
6464 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
6466 let is_auto = if self.eat_keyword(keywords::Trait) {
6469 self.eat_auto_trait();
6473 let (ident, item_, extra_attrs) =
6474 self.parse_item_trait(is_auto, ast::Unsafety::Normal)?;
6475 let prev_span = self.prev_span;
6476 let item = self.mk_item(lo.to(prev_span),
6480 maybe_append(attrs, extra_attrs));
6481 return Ok(Some(item));
6483 if (self.check_keyword(keywords::Impl)) ||
6484 (self.check_keyword(keywords::Default) &&
6485 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)))
6488 let defaultness = self.parse_defaultness()?;
6489 self.expect_keyword(keywords::Impl)?;
6492 extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal, defaultness)?;
6493 let prev_span = self.prev_span;
6494 let item = self.mk_item(lo.to(prev_span),
6498 maybe_append(attrs, extra_attrs));
6499 return Ok(Some(item));
6501 if self.eat_keyword(keywords::Struct) {
6503 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6504 let prev_span = self.prev_span;
6505 let item = self.mk_item(lo.to(prev_span),
6509 maybe_append(attrs, extra_attrs));
6510 return Ok(Some(item));
6512 if self.is_union_item() {
6515 let (ident, item_, extra_attrs) = self.parse_item_union()?;
6516 let prev_span = self.prev_span;
6517 let item = self.mk_item(lo.to(prev_span),
6521 maybe_append(attrs, extra_attrs));
6522 return Ok(Some(item));
6524 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
6525 return Ok(Some(macro_def));
6528 // Verify wether we have encountered a struct or method definition where the user forgot to
6529 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
6530 if visibility == Visibility::Public &&
6531 self.check_ident() &&
6532 self.look_ahead(1, |t| *t != token::Not)
6534 // Space between `pub` keyword and the identifier
6537 // ^^^ `sp` points here
6538 let sp = self.prev_span.between(self.span);
6539 let full_sp = self.prev_span.to(self.span);
6540 let ident_sp = self.span;
6541 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
6542 // possible public struct definition where `struct` was forgotten
6543 let ident = self.parse_ident().unwrap();
6544 let msg = format!("add `struct` here to parse `{}` as a public struct",
6546 let mut err = self.diagnostic()
6547 .struct_span_err(sp, "missing `struct` for struct definition");
6548 err.span_suggestion_short(sp, &msg, " struct ".into());
6550 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
6551 let ident = self.parse_ident().unwrap();
6552 self.consume_block(token::Paren);
6553 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
6554 self.check(&token::OpenDelim(token::Brace))
6556 ("fn", "method", false)
6557 } else if self.check(&token::Colon) {
6561 ("fn` or `struct", "method or struct", true)
6564 let msg = format!("missing `{}` for {} definition", kw, kw_name);
6565 let mut err = self.diagnostic().struct_span_err(sp, &msg);
6567 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
6571 err.span_suggestion_short(sp, &suggestion, format!(" {} ", kw));
6573 if let Ok(snippet) = self.sess.codemap().span_to_snippet(ident_sp) {
6574 err.span_suggestion(
6576 "if you meant to call a macro, write instead",
6577 format!("{}!", snippet));
6579 err.help("if you meant to call a macro, remove the `pub` \
6580 and add a trailing `!` after the identifier");
6586 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
6589 /// Parse a foreign item.
6590 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
6591 let attrs = self.parse_outer_attributes()?;
6593 let visibility = self.parse_visibility(false)?;
6595 // FOREIGN STATIC ITEM
6596 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
6597 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
6598 if self.token.is_keyword(keywords::Const) {
6600 .struct_span_err(self.span, "extern items cannot be `const`")
6601 .span_suggestion(self.span, "instead try using", "static".to_owned())
6604 self.bump(); // `static` or `const`
6605 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6607 // FOREIGN FUNCTION ITEM
6608 if self.check_keyword(keywords::Fn) {
6609 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6611 // FOREIGN TYPE ITEM
6612 if self.check_keyword(keywords::Type) {
6613 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
6616 // FIXME #5668: this will occur for a macro invocation:
6617 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
6619 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
6625 /// This is the fall-through for parsing items.
6626 fn parse_macro_use_or_failure(
6628 attrs: Vec<Attribute> ,
6629 macros_allowed: bool,
6630 attributes_allowed: bool,
6632 visibility: Visibility
6633 ) -> PResult<'a, Option<P<Item>>> {
6634 if macros_allowed && self.token.is_path_start() {
6635 // MACRO INVOCATION ITEM
6637 let prev_span = self.prev_span;
6638 self.complain_if_pub_macro(&visibility, prev_span);
6640 let mac_lo = self.span;
6643 let pth = self.parse_path(PathStyle::Mod)?;
6644 self.expect(&token::Not)?;
6646 // a 'special' identifier (like what `macro_rules!` uses)
6647 // is optional. We should eventually unify invoc syntax
6649 let id = if self.token.is_ident() {
6652 keywords::Invalid.ident() // no special identifier
6654 // eat a matched-delimiter token tree:
6655 let (delim, tts) = self.expect_delimited_token_tree()?;
6656 if delim != token::Brace {
6657 if !self.eat(&token::Semi) {
6658 self.span_err(self.prev_span,
6659 "macros that expand to items must either \
6660 be surrounded with braces or followed by \
6665 let hi = self.prev_span;
6666 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6667 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6668 return Ok(Some(item));
6671 // FAILURE TO PARSE ITEM
6673 Visibility::Inherited => {}
6675 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
6679 if !attributes_allowed && !attrs.is_empty() {
6680 self.expected_item_err(&attrs);
6685 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
6686 where F: FnOnce(&mut Self) -> PResult<'a, R>
6688 // Record all tokens we parse when parsing this item.
6689 let mut tokens = Vec::new();
6690 match self.token_cursor.frame.last_token {
6691 LastToken::Collecting(_) => {
6692 panic!("cannot collect tokens recursively yet")
6694 LastToken::Was(ref mut last) => tokens.extend(last.take()),
6696 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
6697 let prev = self.token_cursor.stack.len();
6699 let last_token = if self.token_cursor.stack.len() == prev {
6700 &mut self.token_cursor.frame.last_token
6702 &mut self.token_cursor.stack[prev].last_token
6704 let mut tokens = match *last_token {
6705 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
6706 LastToken::Was(_) => panic!("our vector went away?"),
6709 // If we're not at EOF our current token wasn't actually consumed by
6710 // `f`, but it'll still be in our list that we pulled out. In that case
6712 if self.token == token::Eof {
6713 *last_token = LastToken::Was(None);
6715 *last_token = LastToken::Was(tokens.pop());
6718 Ok((ret?, tokens.into_iter().collect()))
6721 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6722 let attrs = self.parse_outer_attributes()?;
6724 let (ret, tokens) = self.collect_tokens(|this| {
6725 this.parse_item_(attrs, true, false)
6728 // Once we've parsed an item and recorded the tokens we got while
6729 // parsing we may want to store `tokens` into the item we're about to
6730 // return. Note, though, that we specifically didn't capture tokens
6731 // related to outer attributes. The `tokens` field here may later be
6732 // used with procedural macros to convert this item back into a token
6733 // stream, but during expansion we may be removing attributes as we go
6736 // If we've got inner attributes then the `tokens` we've got above holds
6737 // these inner attributes. If an inner attribute is expanded we won't
6738 // actually remove it from the token stream, so we'll just keep yielding
6739 // it (bad!). To work around this case for now we just avoid recording
6740 // `tokens` if we detect any inner attributes. This should help keep
6741 // expansion correct, but we should fix this bug one day!
6744 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6745 i.tokens = Some(tokens);
6752 /// `{` or `::{` or `*` or `::*`
6753 /// `::{` or `::*` (also `{` or `*` if unprefixed is true)
6754 fn is_import_coupler(&mut self, unprefixed: bool) -> bool {
6755 self.is_import_coupler_inner(&token::OpenDelim(token::Brace), unprefixed) ||
6756 self.is_import_coupler_inner(&token::BinOp(token::Star), unprefixed)
6759 fn is_import_coupler_inner(&mut self, token: &token::Token, unprefixed: bool) -> bool {
6760 if self.check(&token::ModSep) {
6761 self.look_ahead(1, |t| t == token)
6762 } else if unprefixed {
6771 /// USE_TREE = `*` |
6772 /// `{` USE_TREE_LIST `}` |
6774 /// PATH `::` `{` USE_TREE_LIST `}` |
6775 /// PATH [`as` IDENT]
6776 fn parse_use_tree(&mut self, nested: bool) -> PResult<'a, UseTree> {
6779 let mut prefix = ast::Path {
6781 span: lo.to(self.span),
6784 let kind = if self.is_import_coupler(true) {
6785 // `use *;` or `use ::*;` or `use {...};` `use ::{...};`
6787 // Remove the first `::`
6788 if self.eat(&token::ModSep) {
6789 prefix.segments.push(PathSegment::crate_root(self.prev_span));
6791 prefix.segments.push(PathSegment::crate_root(self.span));
6794 if self.eat(&token::BinOp(token::Star)) {
6797 } else if self.check(&token::OpenDelim(token::Brace)) {
6799 UseTreeKind::Nested(self.parse_use_tree_list()?)
6801 return self.unexpected();
6805 let mut parsed = self.parse_path(PathStyle::Mod)?;
6807 parsed = parsed.default_to_global();
6810 prefix.segments.append(&mut parsed.segments);
6811 prefix.span = prefix.span.to(parsed.span);
6813 if self.eat(&token::ModSep) {
6814 if self.eat(&token::BinOp(token::Star)) {
6817 } else if self.check(&token::OpenDelim(token::Brace)) {
6818 // `use path::{...};`
6819 UseTreeKind::Nested(self.parse_use_tree_list()?)
6821 return self.unexpected();
6824 // `use path::foo;` or `use path::foo as bar;`
6825 let rename = self.parse_rename()?.
6826 unwrap_or(prefix.segments.last().unwrap().identifier);
6827 UseTreeKind::Simple(rename)
6832 span: lo.to(self.prev_span),
6838 /// Parse UseTreeKind::Nested(list)
6840 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
6841 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
6842 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
6843 &token::CloseDelim(token::Brace),
6844 SeqSep::trailing_allowed(token::Comma), |this| {
6845 Ok((this.parse_use_tree(true)?, ast::DUMMY_NODE_ID))
6849 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6850 if self.eat_keyword(keywords::As) {
6851 self.parse_ident().map(Some)
6857 /// Parses a source module as a crate. This is the main
6858 /// entry point for the parser.
6859 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6862 attrs: self.parse_inner_attributes()?,
6863 module: self.parse_mod_items(&token::Eof, lo)?,
6864 span: lo.to(self.span),
6868 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6869 let ret = match self.token {
6870 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6871 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6878 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6879 match self.parse_optional_str() {
6880 Some((s, style, suf)) => {
6881 let sp = self.prev_span;
6882 self.expect_no_suffix(sp, "string literal", suf);
6885 _ => Err(self.fatal("expected string literal"))