1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use ast::{AngleBracketedParameterData, ParenthesizedParameterData, AttrStyle, BareFnTy};
13 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
15 use ast::{Mod, Arg, Arm, Attribute, BindingMode, TraitItemKind};
17 use ast::{BlockCheckMode, CaptureBy, Movability};
18 use ast::{Constness, Crate};
21 use ast::{Expr, ExprKind, RangeLimits};
22 use ast::{Field, FnDecl};
23 use ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
24 use ast::GenericParam;
25 use ast::{Ident, ImplItem, IsAuto, Item, ItemKind};
26 use ast::{Label, Lifetime, LifetimeDef, Lit, LitKind, UintTy};
28 use ast::MacStmtStyle;
30 use ast::{MutTy, Mutability};
31 use ast::{Pat, PatKind, PathSegment};
32 use ast::{PolyTraitRef, QSelf};
33 use ast::{Stmt, StmtKind};
34 use ast::{VariantData, StructField};
37 use ast::{TraitItem, TraitRef, TraitObjectSyntax};
38 use ast::{Ty, TyKind, TypeBinding, TyParam, TyParamBounds};
39 use ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
40 use ast::{UseTree, UseTreeKind};
41 use ast::{BinOpKind, UnOp};
42 use ast::{RangeEnd, RangeSyntax};
44 use codemap::{self, CodeMap, Spanned, respan};
45 use syntax_pos::{self, Span, MultiSpan, BytePos, FileName, DUMMY_SP};
46 use errors::{self, DiagnosticBuilder};
47 use parse::{self, classify, token};
48 use parse::common::SeqSep;
49 use parse::lexer::TokenAndSpan;
50 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
51 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
52 use util::parser::{AssocOp, Fixity};
56 use tokenstream::{self, Delimited, ThinTokenStream, TokenTree, TokenStream};
57 use symbol::{Symbol, keywords};
62 use std::path::{self, Path, PathBuf};
66 pub struct Restrictions: u8 {
67 const STMT_EXPR = 1 << 0;
68 const NO_STRUCT_LITERAL = 1 << 1;
72 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
74 /// How to parse a path.
75 #[derive(Copy, Clone, PartialEq)]
77 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
78 /// with something else. For example, in expressions `segment < ....` can be interpreted
79 /// as a comparison and `segment ( ....` can be interpreted as a function call.
80 /// In all such contexts the non-path interpretation is preferred by default for practical
81 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
82 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
84 /// In other contexts, notably in types, no ambiguity exists and paths can be written
85 /// without the disambiguator, e.g. `x<y>` - unambiguously a path.
86 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
88 /// A path with generic arguments disallowed, e.g. `foo::bar::Baz`, used in imports,
89 /// visibilities or attributes.
90 /// Technically, this variant is unnecessary and e.g. `Expr` can be used instead
91 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
92 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
93 /// tokens when something goes wrong.
97 #[derive(Clone, Copy, Debug, PartialEq)]
98 pub enum SemiColonMode {
103 #[derive(Clone, Copy, Debug, PartialEq)]
109 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
110 /// dropped into the token stream, which happens while parsing the result of
111 /// macro expansion). Placement of these is not as complex as I feared it would
112 /// be. The important thing is to make sure that lookahead doesn't balk at
113 /// `token::Interpolated` tokens.
114 macro_rules! maybe_whole_expr {
116 if let token::Interpolated(nt) = $p.token.clone() {
118 token::NtExpr(ref e) => {
120 return Ok((*e).clone());
122 token::NtPath(ref path) => {
125 let kind = ExprKind::Path(None, (*path).clone());
126 return Ok($p.mk_expr(span, kind, ThinVec::new()));
128 token::NtBlock(ref block) => {
131 let kind = ExprKind::Block((*block).clone());
132 return Ok($p.mk_expr(span, kind, ThinVec::new()));
140 /// As maybe_whole_expr, but for things other than expressions
141 macro_rules! maybe_whole {
142 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
143 if let token::Interpolated(nt) = $p.token.clone() {
144 if let token::$constructor($x) = nt.0.clone() {
152 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
153 if let Some(ref mut rhs) = rhs {
159 #[derive(Debug, Clone, Copy, PartialEq)]
170 trait RecoverQPath: Sized {
171 const PATH_STYLE: PathStyle = PathStyle::Expr;
172 fn to_ty(&self) -> Option<P<Ty>>;
173 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self;
174 fn to_string(&self) -> String;
177 impl RecoverQPath for Ty {
178 const PATH_STYLE: PathStyle = PathStyle::Type;
179 fn to_ty(&self) -> Option<P<Ty>> {
180 Some(P(self.clone()))
182 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
183 Self { span: path.span, node: TyKind::Path(qself, path), id: self.id }
185 fn to_string(&self) -> String {
186 pprust::ty_to_string(self)
190 impl RecoverQPath for Pat {
191 fn to_ty(&self) -> Option<P<Ty>> {
194 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
195 Self { span: path.span, node: PatKind::Path(qself, path), id: self.id }
197 fn to_string(&self) -> String {
198 pprust::pat_to_string(self)
202 impl RecoverQPath for Expr {
203 fn to_ty(&self) -> Option<P<Ty>> {
206 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
207 Self { span: path.span, node: ExprKind::Path(qself, path),
208 id: self.id, attrs: self.attrs.clone() }
210 fn to_string(&self) -> String {
211 pprust::expr_to_string(self)
215 /* ident is handled by common.rs */
218 pub struct Parser<'a> {
219 pub sess: &'a ParseSess,
220 /// the current token:
221 pub token: token::Token,
222 /// the span of the current token:
224 /// the span of the previous token:
225 pub meta_var_span: Option<Span>,
227 /// the previous token kind
228 prev_token_kind: PrevTokenKind,
229 pub restrictions: Restrictions,
230 /// Used to determine the path to externally loaded source files
231 pub directory: Directory,
232 /// Whether to parse sub-modules in other files.
233 pub recurse_into_file_modules: bool,
234 /// Name of the root module this parser originated from. If `None`, then the
235 /// name is not known. This does not change while the parser is descending
236 /// into modules, and sub-parsers have new values for this name.
237 pub root_module_name: Option<String>,
238 pub expected_tokens: Vec<TokenType>,
239 token_cursor: TokenCursor,
240 pub desugar_doc_comments: bool,
241 /// Whether we should configure out of line modules as we parse.
248 frame: TokenCursorFrame,
249 stack: Vec<TokenCursorFrame>,
253 struct TokenCursorFrame {
254 delim: token::DelimToken,
257 tree_cursor: tokenstream::Cursor,
259 last_token: LastToken,
262 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
263 /// by the parser, and then that's transitively used to record the tokens that
264 /// each parse AST item is created with.
266 /// Right now this has two states, either collecting tokens or not collecting
267 /// tokens. If we're collecting tokens we just save everything off into a local
268 /// `Vec`. This should eventually though likely save tokens from the original
269 /// token stream and just use slicing of token streams to avoid creation of a
270 /// whole new vector.
272 /// The second state is where we're passively not recording tokens, but the last
273 /// token is still tracked for when we want to start recording tokens. This
274 /// "last token" means that when we start recording tokens we'll want to ensure
275 /// that this, the first token, is included in the output.
277 /// You can find some more example usage of this in the `collect_tokens` method
281 Collecting(Vec<TokenTree>),
282 Was(Option<TokenTree>),
285 impl TokenCursorFrame {
286 fn new(sp: Span, delimited: &Delimited) -> Self {
288 delim: delimited.delim,
290 open_delim: delimited.delim == token::NoDelim,
291 tree_cursor: delimited.stream().into_trees(),
292 close_delim: delimited.delim == token::NoDelim,
293 last_token: LastToken::Was(None),
299 fn next(&mut self) -> TokenAndSpan {
301 let tree = if !self.frame.open_delim {
302 self.frame.open_delim = true;
303 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
304 .open_tt(self.frame.span)
305 } else if let Some(tree) = self.frame.tree_cursor.next() {
307 } else if !self.frame.close_delim {
308 self.frame.close_delim = true;
309 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
310 .close_tt(self.frame.span)
311 } else if let Some(frame) = self.stack.pop() {
315 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
318 match self.frame.last_token {
319 LastToken::Collecting(ref mut v) => v.push(tree.clone()),
320 LastToken::Was(ref mut t) => *t = Some(tree.clone()),
324 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
325 TokenTree::Delimited(sp, ref delimited) => {
326 let frame = TokenCursorFrame::new(sp, delimited);
327 self.stack.push(mem::replace(&mut self.frame, frame));
333 fn next_desugared(&mut self) -> TokenAndSpan {
334 let (sp, name) = match self.next() {
335 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
339 let stripped = strip_doc_comment_decoration(&name.as_str());
341 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
342 // required to wrap the text.
343 let mut num_of_hashes = 0;
345 for ch in stripped.chars() {
348 '#' if count > 0 => count + 1,
351 num_of_hashes = cmp::max(num_of_hashes, count);
354 let body = TokenTree::Delimited(sp, Delimited {
355 delim: token::Bracket,
356 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
357 TokenTree::Token(sp, token::Eq),
358 TokenTree::Token(sp, token::Literal(
359 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
360 .iter().cloned().collect::<TokenStream>().into(),
363 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
364 delim: token::NoDelim,
365 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
366 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
367 .iter().cloned().collect::<TokenStream>().into()
369 [TokenTree::Token(sp, token::Pound), body]
370 .iter().cloned().collect::<TokenStream>().into()
378 #[derive(PartialEq, Eq, Clone)]
381 Keyword(keywords::Keyword),
390 fn to_string(&self) -> String {
392 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
393 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
394 TokenType::Operator => "an operator".to_string(),
395 TokenType::Lifetime => "lifetime".to_string(),
396 TokenType::Ident => "identifier".to_string(),
397 TokenType::Path => "path".to_string(),
398 TokenType::Type => "type".to_string(),
403 /// Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
404 /// `IDENT<<u8 as Trait>::AssocTy>`.
406 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
407 /// that IDENT is not the ident of a fn trait
408 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
409 t == &token::ModSep || t == &token::Lt ||
410 t == &token::BinOp(token::Shl)
413 /// Information about the path to a module.
414 pub struct ModulePath {
416 pub path_exists: bool,
417 pub result: Result<ModulePathSuccess, Error>,
420 pub struct ModulePathSuccess {
422 pub directory_ownership: DirectoryOwnership,
426 pub struct ModulePathError {
428 pub help_msg: String,
432 FileNotFoundForModule {
434 default_path: String,
435 secondary_path: String,
440 default_path: String,
441 secondary_path: String,
444 InclusiveRangeWithNoEnd,
448 pub fn span_err<S: Into<MultiSpan>>(self,
450 handler: &errors::Handler) -> DiagnosticBuilder {
452 Error::FileNotFoundForModule { ref mod_name,
456 let mut err = struct_span_err!(handler, sp, E0583,
457 "file not found for module `{}`", mod_name);
458 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
464 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
465 let mut err = struct_span_err!(handler, sp, E0584,
466 "file for module `{}` found at both {} and {}",
470 err.help("delete or rename one of them to remove the ambiguity");
473 Error::UselessDocComment => {
474 let mut err = struct_span_err!(handler, sp, E0585,
475 "found a documentation comment that doesn't document anything");
476 err.help("doc comments must come before what they document, maybe a comment was \
477 intended with `//`?");
480 Error::InclusiveRangeWithNoEnd => {
481 let mut err = struct_span_err!(handler, sp, E0586,
482 "inclusive range with no end");
483 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
493 AttributesParsed(ThinVec<Attribute>),
494 AlreadyParsed(P<Expr>),
497 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
498 fn from(o: Option<ThinVec<Attribute>>) -> Self {
499 if let Some(attrs) = o {
500 LhsExpr::AttributesParsed(attrs)
502 LhsExpr::NotYetParsed
507 impl From<P<Expr>> for LhsExpr {
508 fn from(expr: P<Expr>) -> Self {
509 LhsExpr::AlreadyParsed(expr)
513 /// Create a placeholder argument.
514 fn dummy_arg(span: Span) -> Arg {
515 let ident = Ident::new(keywords::Invalid.name(), span);
517 id: ast::DUMMY_NODE_ID,
518 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
524 id: ast::DUMMY_NODE_ID
526 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
529 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
530 enum TokenExpectType {
535 impl<'a> Parser<'a> {
536 pub fn new(sess: &'a ParseSess,
538 directory: Option<Directory>,
539 recurse_into_file_modules: bool,
540 desugar_doc_comments: bool)
542 let mut parser = Parser {
544 token: token::Whitespace,
545 span: syntax_pos::DUMMY_SP,
546 prev_span: syntax_pos::DUMMY_SP,
548 prev_token_kind: PrevTokenKind::Other,
549 restrictions: Restrictions::empty(),
550 recurse_into_file_modules,
551 directory: Directory {
552 path: PathBuf::new(),
553 ownership: DirectoryOwnership::Owned { relative: None }
555 root_module_name: None,
556 expected_tokens: Vec::new(),
557 token_cursor: TokenCursor {
558 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
559 delim: token::NoDelim,
564 desugar_doc_comments,
568 let tok = parser.next_tok();
569 parser.token = tok.tok;
570 parser.span = tok.sp;
572 if let Some(directory) = directory {
573 parser.directory = directory;
574 } else if !parser.span.source_equal(&DUMMY_SP) {
575 if let FileName::Real(path) = sess.codemap().span_to_unmapped_path(parser.span) {
576 parser.directory.path = path;
577 parser.directory.path.pop();
581 parser.process_potential_macro_variable();
585 fn next_tok(&mut self) -> TokenAndSpan {
586 let mut next = if self.desugar_doc_comments {
587 self.token_cursor.next_desugared()
589 self.token_cursor.next()
591 if next.sp == syntax_pos::DUMMY_SP {
592 next.sp = self.prev_span;
597 /// Convert a token to a string using self's reader
598 pub fn token_to_string(token: &token::Token) -> String {
599 pprust::token_to_string(token)
602 /// Convert the current token to a string using self's reader
603 pub fn this_token_to_string(&self) -> String {
604 Parser::token_to_string(&self.token)
607 pub fn token_descr(&self) -> Option<&'static str> {
608 Some(match &self.token {
609 t if t.is_special_ident() => "reserved identifier",
610 t if t.is_used_keyword() => "keyword",
611 t if t.is_unused_keyword() => "reserved keyword",
616 pub fn this_token_descr(&self) -> String {
617 if let Some(prefix) = self.token_descr() {
618 format!("{} `{}`", prefix, self.this_token_to_string())
620 format!("`{}`", self.this_token_to_string())
624 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
625 let token_str = Parser::token_to_string(t);
626 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
629 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
630 match self.expect_one_of(&[], &[]) {
632 Ok(_) => unreachable!(),
636 /// Expect and consume the token t. Signal an error if
637 /// the next token is not t.
638 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
639 if self.expected_tokens.is_empty() {
640 if self.token == *t {
644 let token_str = Parser::token_to_string(t);
645 let this_token_str = self.this_token_to_string();
646 let mut err = self.fatal(&format!("expected `{}`, found `{}`",
649 err.span_label(self.span, format!("expected `{}`", token_str));
653 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
657 /// Expect next token to be edible or inedible token. If edible,
658 /// then consume it; if inedible, then return without consuming
659 /// anything. Signal a fatal error if next token is unexpected.
660 pub fn expect_one_of(&mut self,
661 edible: &[token::Token],
662 inedible: &[token::Token]) -> PResult<'a, ()>{
663 fn tokens_to_string(tokens: &[TokenType]) -> String {
664 let mut i = tokens.iter();
665 // This might be a sign we need a connect method on Iterator.
667 .map_or("".to_string(), |t| t.to_string());
668 i.enumerate().fold(b, |mut b, (i, a)| {
669 if tokens.len() > 2 && i == tokens.len() - 2 {
671 } else if tokens.len() == 2 && i == tokens.len() - 2 {
676 b.push_str(&a.to_string());
680 if edible.contains(&self.token) {
683 } else if inedible.contains(&self.token) {
684 // leave it in the input
687 let mut expected = edible.iter()
688 .map(|x| TokenType::Token(x.clone()))
689 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
690 .chain(self.expected_tokens.iter().cloned())
691 .collect::<Vec<_>>();
692 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
694 let expect = tokens_to_string(&expected[..]);
695 let actual = self.this_token_to_string();
696 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
697 let short_expect = if expected.len() > 6 {
698 format!("{} possible tokens", expected.len())
702 (format!("expected one of {}, found `{}`", expect, actual),
703 (self.sess.codemap().next_point(self.prev_span),
704 format!("expected one of {} here", short_expect)))
705 } else if expected.is_empty() {
706 (format!("unexpected token: `{}`", actual),
707 (self.prev_span, "unexpected token after this".to_string()))
709 (format!("expected {}, found `{}`", expect, actual),
710 (self.sess.codemap().next_point(self.prev_span),
711 format!("expected {} here", expect)))
713 let mut err = self.fatal(&msg_exp);
714 let sp = if self.token == token::Token::Eof {
715 // This is EOF, don't want to point at the following char, but rather the last token
721 let cm = self.sess.codemap();
722 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
723 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
724 // When the spans are in the same line, it means that the only content between
725 // them is whitespace, point at the found token in that case:
727 // X | () => { syntax error };
728 // | ^^^^^ expected one of 8 possible tokens here
730 // instead of having:
732 // X | () => { syntax error };
733 // | -^^^^^ unexpected token
735 // | expected one of 8 possible tokens here
736 err.span_label(self.span, label_exp);
739 err.span_label(sp, label_exp);
740 err.span_label(self.span, "unexpected token");
747 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
748 fn interpolated_or_expr_span(&self,
749 expr: PResult<'a, P<Expr>>)
750 -> PResult<'a, (Span, P<Expr>)> {
752 if self.prev_token_kind == PrevTokenKind::Interpolated {
760 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
761 let mut err = self.struct_span_err(self.span,
762 &format!("expected identifier, found {}",
763 self.this_token_descr()));
764 if let Some(token_descr) = self.token_descr() {
765 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
767 err.span_label(self.span, "expected identifier");
772 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
773 self.parse_ident_common(true)
776 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
778 token::Ident(ident, _) => {
779 if self.token.is_reserved_ident() {
780 let mut err = self.expected_ident_found();
787 let span = self.span;
789 Ok(Ident::new(ident.name, span))
792 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
793 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
795 self.expected_ident_found()
801 /// Check if the next token is `tok`, and return `true` if so.
803 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
805 pub fn check(&mut self, tok: &token::Token) -> bool {
806 let is_present = self.token == *tok;
807 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
811 /// Consume token 'tok' if it exists. Returns true if the given
812 /// token was present, false otherwise.
813 pub fn eat(&mut self, tok: &token::Token) -> bool {
814 let is_present = self.check(tok);
815 if is_present { self.bump() }
819 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
820 self.expected_tokens.push(TokenType::Keyword(kw));
821 self.token.is_keyword(kw)
824 /// If the next token is the given keyword, eat it and return
825 /// true. Otherwise, return false.
826 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
827 if self.check_keyword(kw) {
835 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
836 if self.token.is_keyword(kw) {
844 /// If the given word is not a keyword, signal an error.
845 /// If the next token is not the given word, signal an error.
846 /// Otherwise, eat it.
847 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
848 if !self.eat_keyword(kw) {
855 fn check_ident(&mut self) -> bool {
856 if self.token.is_ident() {
859 self.expected_tokens.push(TokenType::Ident);
864 fn check_path(&mut self) -> bool {
865 if self.token.is_path_start() {
868 self.expected_tokens.push(TokenType::Path);
873 fn check_type(&mut self) -> bool {
874 if self.token.can_begin_type() {
877 self.expected_tokens.push(TokenType::Type);
882 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
883 /// `&` and continue. If an `&` is not seen, signal an error.
884 fn expect_and(&mut self) -> PResult<'a, ()> {
885 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
887 token::BinOp(token::And) => {
892 let span = self.span.with_lo(self.span.lo() + BytePos(1));
893 Ok(self.bump_with(token::BinOp(token::And), span))
895 _ => self.unexpected()
899 /// Expect and consume an `|`. If `||` is seen, replace it with a single
900 /// `|` and continue. If an `|` is not seen, signal an error.
901 fn expect_or(&mut self) -> PResult<'a, ()> {
902 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
904 token::BinOp(token::Or) => {
909 let span = self.span.with_lo(self.span.lo() + BytePos(1));
910 Ok(self.bump_with(token::BinOp(token::Or), span))
912 _ => self.unexpected()
916 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
918 None => {/* everything ok */}
920 let text = suf.as_str();
922 self.span_bug(sp, "found empty literal suffix in Some")
924 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
929 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
930 /// `<` and continue. If a `<` is not seen, return false.
932 /// This is meant to be used when parsing generics on a path to get the
934 fn eat_lt(&mut self) -> bool {
935 self.expected_tokens.push(TokenType::Token(token::Lt));
941 token::BinOp(token::Shl) => {
942 let span = self.span.with_lo(self.span.lo() + BytePos(1));
943 self.bump_with(token::Lt, span);
950 fn expect_lt(&mut self) -> PResult<'a, ()> {
958 /// Expect and consume a GT. if a >> is seen, replace it
959 /// with a single > and continue. If a GT is not seen,
961 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
962 self.expected_tokens.push(TokenType::Token(token::Gt));
968 token::BinOp(token::Shr) => {
969 let span = self.span.with_lo(self.span.lo() + BytePos(1));
970 Ok(self.bump_with(token::Gt, span))
972 token::BinOpEq(token::Shr) => {
973 let span = self.span.with_lo(self.span.lo() + BytePos(1));
974 Ok(self.bump_with(token::Ge, span))
977 let span = self.span.with_lo(self.span.lo() + BytePos(1));
978 Ok(self.bump_with(token::Eq, span))
980 _ => self.unexpected()
984 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
985 sep: Option<token::Token>,
987 -> PResult<'a, (Vec<T>, bool)>
988 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
990 let mut v = Vec::new();
991 // This loop works by alternating back and forth between parsing types
992 // and commas. For example, given a string `A, B,>`, the parser would
993 // first parse `A`, then a comma, then `B`, then a comma. After that it
994 // would encounter a `>` and stop. This lets the parser handle trailing
995 // commas in generic parameters, because it can stop either after
996 // parsing a type or after parsing a comma.
998 if self.check(&token::Gt)
999 || self.token == token::BinOp(token::Shr)
1000 || self.token == token::Ge
1001 || self.token == token::BinOpEq(token::Shr) {
1007 Some(result) => v.push(result),
1008 None => return Ok((v, true))
1011 if let Some(t) = sep.as_ref() {
1017 return Ok((v, false));
1020 /// Parse a sequence bracketed by '<' and '>', stopping
1022 pub fn parse_seq_to_before_gt<T, F>(&mut self,
1023 sep: Option<token::Token>,
1025 -> PResult<'a, Vec<T>> where
1026 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1028 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
1029 |p| Ok(Some(f(p)?)))?;
1034 pub fn parse_seq_to_gt<T, F>(&mut self,
1035 sep: Option<token::Token>,
1037 -> PResult<'a, Vec<T>> where
1038 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1040 let v = self.parse_seq_to_before_gt(sep, f)?;
1045 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
1046 sep: Option<token::Token>,
1048 -> PResult<'a, (Vec<T>, bool)> where
1049 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
1051 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
1055 return Ok((v, returned));
1058 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1059 /// passes through any errors encountered. Used for error recovery.
1060 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1061 let handler = self.diagnostic();
1063 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1065 TokenExpectType::Expect,
1066 |p| Ok(p.parse_token_tree())) {
1067 handler.cancel(err);
1071 /// Parse a sequence, including the closing delimiter. The function
1072 /// f must consume tokens until reaching the next separator or
1073 /// closing bracket.
1074 pub fn parse_seq_to_end<T, F>(&mut self,
1078 -> PResult<'a, Vec<T>> where
1079 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1081 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1086 /// Parse a sequence, not including the closing delimiter. The function
1087 /// f must consume tokens until reaching the next separator or
1088 /// closing bracket.
1089 pub fn parse_seq_to_before_end<T, F>(&mut self,
1093 -> PResult<'a, Vec<T>>
1094 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1096 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1099 fn parse_seq_to_before_tokens<T, F>(&mut self,
1100 kets: &[&token::Token],
1102 expect: TokenExpectType,
1104 -> PResult<'a, Vec<T>>
1105 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1107 let mut first: bool = true;
1109 while !kets.contains(&&self.token) {
1111 token::CloseDelim(..) | token::Eof => break,
1114 if let Some(ref t) = sep.sep {
1118 if let Err(mut e) = self.expect(t) {
1119 // Attempt to keep parsing if it was a similar separator
1120 if let Some(ref tokens) = t.similar_tokens() {
1121 if tokens.contains(&self.token) {
1126 // Attempt to keep parsing if it was an omitted separator
1140 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1142 TokenExpectType::Expect => self.check(k),
1143 TokenExpectType::NoExpect => self.token == **k,
1156 /// Parse a sequence, including the closing delimiter. The function
1157 /// f must consume tokens until reaching the next separator or
1158 /// closing bracket.
1159 pub fn parse_unspanned_seq<T, F>(&mut self,
1164 -> PResult<'a, Vec<T>> where
1165 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1168 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1169 if self.token == *ket {
1175 // NB: Do not use this function unless you actually plan to place the
1176 // spanned list in the AST.
1177 pub fn parse_seq<T, F>(&mut self,
1182 -> PResult<'a, Spanned<Vec<T>>> where
1183 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1187 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1190 Ok(respan(lo.to(hi), result))
1193 /// Advance the parser by one token
1194 pub fn bump(&mut self) {
1195 if self.prev_token_kind == PrevTokenKind::Eof {
1196 // Bumping after EOF is a bad sign, usually an infinite loop.
1197 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1200 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1202 // Record last token kind for possible error recovery.
1203 self.prev_token_kind = match self.token {
1204 token::DocComment(..) => PrevTokenKind::DocComment,
1205 token::Comma => PrevTokenKind::Comma,
1206 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1207 token::Interpolated(..) => PrevTokenKind::Interpolated,
1208 token::Eof => PrevTokenKind::Eof,
1209 token::Ident(..) => PrevTokenKind::Ident,
1210 _ => PrevTokenKind::Other,
1213 let next = self.next_tok();
1214 self.span = next.sp;
1215 self.token = next.tok;
1216 self.expected_tokens.clear();
1217 // check after each token
1218 self.process_potential_macro_variable();
1221 /// Advance the parser using provided token as a next one. Use this when
1222 /// consuming a part of a token. For example a single `<` from `<<`.
1223 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1224 self.prev_span = self.span.with_hi(span.lo());
1225 // It would be incorrect to record the kind of the current token, but
1226 // fortunately for tokens currently using `bump_with`, the
1227 // prev_token_kind will be of no use anyway.
1228 self.prev_token_kind = PrevTokenKind::Other;
1231 self.expected_tokens.clear();
1234 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1235 F: FnOnce(&token::Token) -> R,
1238 return f(&self.token)
1241 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1242 Some(tree) => match tree {
1243 TokenTree::Token(_, tok) => tok,
1244 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1246 None => token::CloseDelim(self.token_cursor.frame.delim),
1250 fn look_ahead_span(&self, dist: usize) -> Span {
1255 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1256 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1257 None => self.look_ahead_span(dist - 1),
1260 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1261 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1263 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1264 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1266 pub fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1267 err.span_err(sp, self.diagnostic())
1269 pub fn span_fatal_help<S: Into<MultiSpan>>(&self,
1272 help: &str) -> DiagnosticBuilder<'a> {
1273 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1277 pub fn bug(&self, m: &str) -> ! {
1278 self.sess.span_diagnostic.span_bug(self.span, m)
1280 pub fn warn(&self, m: &str) {
1281 self.sess.span_diagnostic.span_warn(self.span, m)
1283 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1284 self.sess.span_diagnostic.span_warn(sp, m)
1286 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1287 self.sess.span_diagnostic.span_err(sp, m)
1289 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1290 self.sess.span_diagnostic.struct_span_err(sp, m)
1292 pub fn span_err_help<S: Into<MultiSpan>>(&self, sp: S, m: &str, h: &str) {
1293 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1297 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1298 self.sess.span_diagnostic.span_bug(sp, m)
1300 pub fn abort_if_errors(&self) {
1301 self.sess.span_diagnostic.abort_if_errors();
1304 fn cancel(&self, err: &mut DiagnosticBuilder) {
1305 self.sess.span_diagnostic.cancel(err)
1308 pub fn diagnostic(&self) -> &'a errors::Handler {
1309 &self.sess.span_diagnostic
1312 /// Is the current token one of the keywords that signals a bare function
1314 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1315 self.check_keyword(keywords::Fn) ||
1316 self.check_keyword(keywords::Unsafe) ||
1317 self.check_keyword(keywords::Extern) && self.is_extern_non_path()
1320 /// parse a TyKind::BareFn type:
1321 pub fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>)
1322 -> PResult<'a, TyKind> {
1325 [unsafe] [extern "ABI"] fn (S) -> T
1335 let unsafety = self.parse_unsafety();
1336 let abi = if self.eat_keyword(keywords::Extern) {
1337 self.parse_opt_abi()?.unwrap_or(Abi::C)
1342 self.expect_keyword(keywords::Fn)?;
1343 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1344 let ret_ty = self.parse_ret_ty(false)?;
1345 let decl = P(FnDecl {
1350 Ok(TyKind::BareFn(P(BareFnTy {
1358 /// Parse unsafety: `unsafe` or nothing.
1359 fn parse_unsafety(&mut self) -> Unsafety {
1360 if self.eat_keyword(keywords::Unsafe) {
1367 /// Parse the items in a trait declaration
1368 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1369 maybe_whole!(self, NtTraitItem, |x| x);
1370 let attrs = self.parse_outer_attributes()?;
1371 let (mut item, tokens) = self.collect_tokens(|this| {
1372 this.parse_trait_item_(at_end, attrs)
1374 // See `parse_item` for why this clause is here.
1375 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1376 item.tokens = Some(tokens);
1381 fn parse_trait_item_(&mut self,
1383 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1386 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1387 let (generics, TyParam {ident, bounds, default, ..}) =
1388 self.parse_trait_item_assoc_ty(vec![])?;
1389 (ident, TraitItemKind::Type(bounds, default), generics)
1390 } else if self.is_const_item() {
1391 self.expect_keyword(keywords::Const)?;
1392 let ident = self.parse_ident()?;
1393 self.expect(&token::Colon)?;
1394 let ty = self.parse_ty()?;
1395 let default = if self.check(&token::Eq) {
1397 let expr = self.parse_expr()?;
1398 self.expect(&token::Semi)?;
1401 self.expect(&token::Semi)?;
1404 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1405 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1406 // trait item macro.
1407 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1409 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
1411 let ident = self.parse_ident()?;
1412 let mut generics = self.parse_generics()?;
1414 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1415 // This is somewhat dubious; We don't want to allow
1416 // argument names to be left off if there is a
1418 p.parse_arg_general(false)
1420 generics.where_clause = self.parse_where_clause()?;
1422 let sig = ast::MethodSig {
1429 let body = match self.token {
1433 debug!("parse_trait_methods(): parsing required method");
1436 token::OpenDelim(token::Brace) => {
1437 debug!("parse_trait_methods(): parsing provided method");
1439 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1440 attrs.extend(inner_attrs.iter().cloned());
1444 let token_str = self.this_token_to_string();
1445 let mut err = self.fatal(&format!("expected `;` or `{{`, found `{}`",
1447 err.span_label(self.span, "expected `;` or `{`");
1451 (ident, ast::TraitItemKind::Method(sig, body), generics)
1455 id: ast::DUMMY_NODE_ID,
1460 span: lo.to(self.prev_span),
1465 /// Parse optional return type [ -> TY ] in function decl
1466 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1467 if self.eat(&token::RArrow) {
1468 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1470 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1475 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1476 self.parse_ty_common(true, true)
1479 /// Parse a type in restricted contexts where `+` is not permitted.
1480 /// Example 1: `&'a TYPE`
1481 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1482 /// Example 2: `value1 as TYPE + value2`
1483 /// `+` is prohibited to avoid interactions with expression grammar.
1484 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1485 self.parse_ty_common(false, true)
1488 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1489 -> PResult<'a, P<Ty>> {
1490 maybe_whole!(self, NtTy, |x| x);
1493 let mut impl_dyn_multi = false;
1494 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1495 // `(TYPE)` is a parenthesized type.
1496 // `(TYPE,)` is a tuple with a single field of type TYPE.
1497 let mut ts = vec![];
1498 let mut last_comma = false;
1499 while self.token != token::CloseDelim(token::Paren) {
1500 ts.push(self.parse_ty()?);
1501 if self.eat(&token::Comma) {
1508 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1509 self.expect(&token::CloseDelim(token::Paren))?;
1511 if ts.len() == 1 && !last_comma {
1512 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1513 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1515 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1516 TyKind::Path(None, ref path) if maybe_bounds => {
1517 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1519 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1520 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1521 let path = match bounds[0] {
1522 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1523 _ => self.bug("unexpected lifetime bound"),
1525 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1528 _ => TyKind::Paren(P(ty))
1533 } else if self.eat(&token::Not) {
1536 } else if self.eat(&token::BinOp(token::Star)) {
1538 TyKind::Ptr(self.parse_ptr()?)
1539 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1541 let t = self.parse_ty()?;
1542 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1543 let t = match self.maybe_parse_fixed_length_of_vec()? {
1544 None => TyKind::Slice(t),
1545 Some(suffix) => TyKind::Array(t, suffix),
1547 self.expect(&token::CloseDelim(token::Bracket))?;
1549 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1552 self.parse_borrowed_pointee()?
1553 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1555 // In order to not be ambiguous, the type must be surrounded by parens.
1556 self.expect(&token::OpenDelim(token::Paren))?;
1557 let e = self.parse_expr()?;
1558 self.expect(&token::CloseDelim(token::Paren))?;
1560 } else if self.eat_keyword(keywords::Underscore) {
1561 // A type to be inferred `_`
1563 } else if self.token_is_bare_fn_keyword() {
1564 // Function pointer type
1565 self.parse_ty_bare_fn(Vec::new())?
1566 } else if self.check_keyword(keywords::For) {
1567 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1568 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1569 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1571 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1572 if self.token_is_bare_fn_keyword() {
1573 self.parse_ty_bare_fn(lifetime_defs)?
1575 let path = self.parse_path(PathStyle::Type)?;
1576 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1577 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1579 } else if self.eat_keyword(keywords::Impl) {
1580 // Always parse bounds greedily for better error recovery.
1581 let bounds = self.parse_ty_param_bounds()?;
1582 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1583 TyKind::ImplTrait(bounds)
1584 } else if self.check_keyword(keywords::Dyn) &&
1585 self.look_ahead(1, |t| t.can_begin_bound() &&
1586 !can_continue_type_after_non_fn_ident(t)) {
1587 self.bump(); // `dyn`
1588 // Always parse bounds greedily for better error recovery.
1589 let bounds = self.parse_ty_param_bounds()?;
1590 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1591 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1592 } else if self.check(&token::Question) ||
1593 self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)) {
1594 // Bound list (trait object type)
1595 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?,
1596 TraitObjectSyntax::None)
1597 } else if self.eat_lt() {
1599 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1600 TyKind::Path(Some(qself), path)
1601 } else if self.token.is_path_start() {
1603 let path = self.parse_path(PathStyle::Type)?;
1604 if self.eat(&token::Not) {
1605 // Macro invocation in type position
1606 let (_, tts) = self.expect_delimited_token_tree()?;
1607 TyKind::Mac(respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts }))
1609 // Just a type path or bound list (trait object type) starting with a trait.
1611 // `Trait1 + Trait2 + 'a`
1612 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1613 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1615 TyKind::Path(None, path)
1619 let msg = format!("expected type, found {}", self.this_token_descr());
1620 return Err(self.fatal(&msg));
1623 let span = lo.to(self.prev_span);
1624 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1626 // Try to recover from use of `+` with incorrect priority.
1627 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1628 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1629 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1634 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1635 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1636 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1637 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1640 bounds.append(&mut self.parse_ty_param_bounds()?);
1642 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1645 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1646 if !allow_plus && impl_dyn_multi {
1647 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1648 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1649 .span_suggestion(ty.span, "use parentheses to disambiguate", sum_with_parens)
1654 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1655 // Do not add `+` to expected tokens.
1656 if !allow_plus || self.token != token::BinOp(token::Plus) {
1661 let bounds = self.parse_ty_param_bounds()?;
1662 let sum_span = ty.span.to(self.prev_span);
1664 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1665 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1668 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1669 let sum_with_parens = pprust::to_string(|s| {
1670 use print::pprust::PrintState;
1673 s.print_opt_lifetime(lifetime)?;
1674 s.print_mutability(mut_ty.mutbl)?;
1676 s.print_type(&mut_ty.ty)?;
1677 s.print_bounds(" +", &bounds)?;
1680 err.span_suggestion(sum_span, "try adding parentheses", sum_with_parens);
1682 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1683 err.span_label(sum_span, "perhaps you forgot parentheses?");
1686 err.span_label(sum_span, "expected a path");
1693 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1694 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1696 // Do not add `::` to expected tokens.
1697 if !allow_recovery || self.token != token::ModSep {
1700 let ty = match base.to_ty() {
1702 None => return Ok(base),
1705 self.bump(); // `::`
1706 let mut segments = Vec::new();
1707 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1709 let span = ty.span.to(self.prev_span);
1711 base.to_recovered(Some(QSelf { ty, position: 0 }), ast::Path { segments, span });
1714 .struct_span_err(span, "missing angle brackets in associated item path")
1715 .span_suggestion(span, "try", recovered.to_string()).emit();
1720 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1721 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1722 let mutbl = self.parse_mutability();
1723 let ty = self.parse_ty_no_plus()?;
1724 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1727 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1728 let mutbl = if self.eat_keyword(keywords::Mut) {
1730 } else if self.eat_keyword(keywords::Const) {
1731 Mutability::Immutable
1733 let span = self.prev_span;
1735 "expected mut or const in raw pointer type (use \
1736 `*mut T` or `*const T` as appropriate)");
1737 Mutability::Immutable
1739 let t = self.parse_ty_no_plus()?;
1740 Ok(MutTy { ty: t, mutbl: mutbl })
1743 fn is_named_argument(&mut self) -> bool {
1744 let offset = match self.token {
1745 token::Interpolated(ref nt) => match nt.0 {
1746 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1749 token::BinOp(token::And) | token::AndAnd => 1,
1750 _ if self.token.is_keyword(keywords::Mut) => 1,
1754 self.look_ahead(offset, |t| t.is_ident()) &&
1755 self.look_ahead(offset + 1, |t| t == &token::Colon)
1758 /// This version of parse arg doesn't necessarily require
1759 /// identifier names.
1760 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1761 maybe_whole!(self, NtArg, |x| x);
1763 let pat = if require_name || self.is_named_argument() {
1764 debug!("parse_arg_general parse_pat (require_name:{})",
1766 let pat = self.parse_pat()?;
1768 self.expect(&token::Colon)?;
1771 debug!("parse_arg_general ident_to_pat");
1772 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1774 id: ast::DUMMY_NODE_ID,
1775 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
1780 let t = self.parse_ty()?;
1785 id: ast::DUMMY_NODE_ID,
1789 /// Parse a single function argument
1790 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1791 self.parse_arg_general(true)
1794 /// Parse an argument in a lambda header e.g. |arg, arg|
1795 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1796 let pat = self.parse_pat()?;
1797 let t = if self.eat(&token::Colon) {
1801 id: ast::DUMMY_NODE_ID,
1802 node: TyKind::Infer,
1809 id: ast::DUMMY_NODE_ID
1813 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1814 if self.eat(&token::Semi) {
1815 Ok(Some(self.parse_expr()?))
1821 /// Matches token_lit = LIT_INTEGER | ...
1822 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1823 let out = match self.token {
1824 token::Interpolated(ref nt) => match nt.0 {
1825 token::NtExpr(ref v) => match v.node {
1826 ExprKind::Lit(ref lit) => { lit.node.clone() }
1827 _ => { return self.unexpected_last(&self.token); }
1829 _ => { return self.unexpected_last(&self.token); }
1831 token::Literal(lit, suf) => {
1832 let diag = Some((self.span, &self.sess.span_diagnostic));
1833 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1837 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1842 _ => { return self.unexpected_last(&self.token); }
1849 /// Matches lit = true | false | token_lit
1850 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1852 let lit = if self.eat_keyword(keywords::True) {
1854 } else if self.eat_keyword(keywords::False) {
1855 LitKind::Bool(false)
1857 let lit = self.parse_lit_token()?;
1860 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1863 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1864 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1865 maybe_whole_expr!(self);
1867 let minus_lo = self.span;
1868 let minus_present = self.eat(&token::BinOp(token::Minus));
1870 let literal = P(self.parse_lit()?);
1871 let hi = self.prev_span;
1872 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1875 let minus_hi = self.prev_span;
1876 let unary = self.mk_unary(UnOp::Neg, expr);
1877 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1883 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1885 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
1886 let span = self.span;
1888 Ok(Ident::new(ident.name, span))
1890 _ => self.parse_ident(),
1894 /// Parses qualified path.
1895 /// Assumes that the leading `<` has been parsed already.
1897 /// `qualified_path = <type [as trait_ref]>::path`
1901 /// `<T as U>::F::a<S>` (without disambiguator)
1902 /// `<T as U>::F::a::<S>` (with disambiguator)
1903 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1904 let lo = self.prev_span;
1905 let ty = self.parse_ty()?;
1906 let mut path = if self.eat_keyword(keywords::As) {
1907 self.parse_path(PathStyle::Type)?
1909 ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP }
1911 self.expect(&token::Gt)?;
1912 self.expect(&token::ModSep)?;
1914 let qself = QSelf { ty, position: path.segments.len() };
1915 self.parse_path_segments(&mut path.segments, style, true)?;
1917 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1920 /// Parses simple paths.
1922 /// `path = [::] segment+`
1923 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1926 /// `a::b::C<D>` (without disambiguator)
1927 /// `a::b::C::<D>` (with disambiguator)
1928 /// `Fn(Args)` (without disambiguator)
1929 /// `Fn::(Args)` (with disambiguator)
1930 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1931 self.parse_path_common(style, true)
1934 pub fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1935 -> PResult<'a, ast::Path> {
1936 maybe_whole!(self, NtPath, |path| {
1937 if style == PathStyle::Mod &&
1938 path.segments.iter().any(|segment| segment.parameters.is_some()) {
1939 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1944 let lo = self.meta_var_span.unwrap_or(self.span);
1945 let mut segments = Vec::new();
1946 if self.eat(&token::ModSep) {
1947 segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
1949 self.parse_path_segments(&mut segments, style, enable_warning)?;
1951 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1954 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1955 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1956 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1957 let meta_ident = match self.token {
1958 token::Interpolated(ref nt) => match nt.0 {
1959 token::NtMeta(ref meta) => match meta.node {
1960 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
1967 if let Some(ident) = meta_ident {
1969 return Ok(ast::Path::from_ident(ident.with_span_pos(self.prev_span)));
1971 self.parse_path(style)
1974 fn parse_path_segments(&mut self,
1975 segments: &mut Vec<PathSegment>,
1977 enable_warning: bool)
1978 -> PResult<'a, ()> {
1980 segments.push(self.parse_path_segment(style, enable_warning)?);
1982 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1988 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
1989 -> PResult<'a, PathSegment> {
1990 let ident = self.parse_path_segment_ident()?;
1992 let is_args_start = |token: &token::Token| match *token {
1993 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
1996 let check_args_start = |this: &mut Self| {
1997 this.expected_tokens.extend_from_slice(
1998 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2000 is_args_start(&this.token)
2003 Ok(if style == PathStyle::Type && check_args_start(self) ||
2004 style != PathStyle::Mod && self.check(&token::ModSep)
2005 && self.look_ahead(1, |t| is_args_start(t)) {
2006 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2008 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2009 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2010 .span_label(self.prev_span, "try removing `::`").emit();
2013 let parameters = if self.eat_lt() {
2015 let (lifetimes, types, bindings) = self.parse_generic_args()?;
2017 let span = lo.to(self.prev_span);
2018 AngleBracketedParameterData { lifetimes, types, bindings, span }.into()
2022 let inputs = self.parse_seq_to_before_tokens(
2023 &[&token::CloseDelim(token::Paren)],
2024 SeqSep::trailing_allowed(token::Comma),
2025 TokenExpectType::Expect,
2028 let output = if self.eat(&token::RArrow) {
2029 Some(self.parse_ty_common(false, false)?)
2033 let span = lo.to(self.prev_span);
2034 ParenthesizedParameterData { inputs, output, span }.into()
2037 PathSegment { ident, parameters }
2039 // Generic arguments are not found.
2040 PathSegment::from_ident(ident)
2044 fn check_lifetime(&mut self) -> bool {
2045 self.expected_tokens.push(TokenType::Lifetime);
2046 self.token.is_lifetime()
2049 /// Parse single lifetime 'a or panic.
2050 pub fn expect_lifetime(&mut self) -> Lifetime {
2051 if let Some(ident) = self.token.lifetime() {
2052 let span = self.span;
2054 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2056 self.span_bug(self.span, "not a lifetime")
2060 fn eat_label(&mut self) -> Option<Label> {
2061 if let Some(ident) = self.token.lifetime() {
2062 let span = self.span;
2064 Some(Label { ident: Ident::new(ident.name, span) })
2070 /// Parse mutability (`mut` or nothing).
2071 fn parse_mutability(&mut self) -> Mutability {
2072 if self.eat_keyword(keywords::Mut) {
2075 Mutability::Immutable
2079 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2080 if let token::Literal(token::Integer(name), None) = self.token {
2082 Ok(Ident::new(name, self.prev_span))
2084 self.parse_ident_common(false)
2088 /// Parse ident (COLON expr)?
2089 pub fn parse_field(&mut self) -> PResult<'a, Field> {
2090 let attrs = self.parse_outer_attributes()?;
2093 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2094 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2095 let fieldname = self.parse_field_name()?;
2097 (fieldname, self.parse_expr()?, false)
2099 let fieldname = self.parse_ident_common(false)?;
2101 // Mimic `x: x` for the `x` field shorthand.
2102 let path = ast::Path::from_ident(fieldname);
2103 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2104 (fieldname, expr, true)
2108 span: lo.to(expr.span),
2111 attrs: attrs.into(),
2115 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2116 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2119 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2120 ExprKind::Unary(unop, expr)
2123 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2124 ExprKind::Binary(binop, lhs, rhs)
2127 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2128 ExprKind::Call(f, args)
2131 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2132 ExprKind::Index(expr, idx)
2135 pub fn mk_range(&mut self,
2136 start: Option<P<Expr>>,
2137 end: Option<P<Expr>>,
2138 limits: RangeLimits)
2139 -> PResult<'a, ast::ExprKind> {
2140 if end.is_none() && limits == RangeLimits::Closed {
2141 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2143 Ok(ExprKind::Range(start, end, limits))
2147 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2148 ExprKind::TupField(expr, idx)
2151 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2152 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2153 ExprKind::AssignOp(binop, lhs, rhs)
2156 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2158 id: ast::DUMMY_NODE_ID,
2159 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2165 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2166 let span = &self.span;
2167 let lv_lit = P(codemap::Spanned {
2168 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2173 id: ast::DUMMY_NODE_ID,
2174 node: ExprKind::Lit(lv_lit),
2180 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2182 token::OpenDelim(delim) => match self.parse_token_tree() {
2183 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2184 _ => unreachable!(),
2187 let msg = "expected open delimiter";
2188 let mut err = self.fatal(msg);
2189 err.span_label(self.span, msg);
2195 /// At the bottom (top?) of the precedence hierarchy,
2196 /// parse things like parenthesized exprs,
2197 /// macros, return, etc.
2199 /// NB: This does not parse outer attributes,
2200 /// and is private because it only works
2201 /// correctly if called from parse_dot_or_call_expr().
2202 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2203 maybe_whole_expr!(self);
2205 // Outer attributes are already parsed and will be
2206 // added to the return value after the fact.
2208 // Therefore, prevent sub-parser from parsing
2209 // attributes by giving them a empty "already parsed" list.
2210 let mut attrs = ThinVec::new();
2213 let mut hi = self.span;
2217 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2219 token::OpenDelim(token::Paren) => {
2222 attrs.extend(self.parse_inner_attributes()?);
2224 // (e) is parenthesized e
2225 // (e,) is a tuple with only one field, e
2226 let mut es = vec![];
2227 let mut trailing_comma = false;
2228 while self.token != token::CloseDelim(token::Paren) {
2229 es.push(self.parse_expr()?);
2230 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2231 if self.check(&token::Comma) {
2232 trailing_comma = true;
2236 trailing_comma = false;
2242 hi = self.prev_span;
2243 ex = if es.len() == 1 && !trailing_comma {
2244 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2249 token::OpenDelim(token::Brace) => {
2250 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2252 token::BinOp(token::Or) | token::OrOr => {
2253 return self.parse_lambda_expr(attrs);
2255 token::OpenDelim(token::Bracket) => {
2258 attrs.extend(self.parse_inner_attributes()?);
2260 if self.check(&token::CloseDelim(token::Bracket)) {
2263 ex = ExprKind::Array(Vec::new());
2266 let first_expr = self.parse_expr()?;
2267 if self.check(&token::Semi) {
2268 // Repeating array syntax: [ 0; 512 ]
2270 let count = self.parse_expr()?;
2271 self.expect(&token::CloseDelim(token::Bracket))?;
2272 ex = ExprKind::Repeat(first_expr, count);
2273 } else if self.check(&token::Comma) {
2274 // Vector with two or more elements.
2276 let remaining_exprs = self.parse_seq_to_end(
2277 &token::CloseDelim(token::Bracket),
2278 SeqSep::trailing_allowed(token::Comma),
2279 |p| Ok(p.parse_expr()?)
2281 let mut exprs = vec![first_expr];
2282 exprs.extend(remaining_exprs);
2283 ex = ExprKind::Array(exprs);
2285 // Vector with one element.
2286 self.expect(&token::CloseDelim(token::Bracket))?;
2287 ex = ExprKind::Array(vec![first_expr]);
2290 hi = self.prev_span;
2294 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2296 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2298 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2299 return self.parse_lambda_expr(attrs);
2301 if self.eat_keyword(keywords::If) {
2302 return self.parse_if_expr(attrs);
2304 if self.eat_keyword(keywords::For) {
2305 let lo = self.prev_span;
2306 return self.parse_for_expr(None, lo, attrs);
2308 if self.eat_keyword(keywords::While) {
2309 let lo = self.prev_span;
2310 return self.parse_while_expr(None, lo, attrs);
2312 if let Some(label) = self.eat_label() {
2313 let lo = label.ident.span;
2314 self.expect(&token::Colon)?;
2315 if self.eat_keyword(keywords::While) {
2316 return self.parse_while_expr(Some(label), lo, attrs)
2318 if self.eat_keyword(keywords::For) {
2319 return self.parse_for_expr(Some(label), lo, attrs)
2321 if self.eat_keyword(keywords::Loop) {
2322 return self.parse_loop_expr(Some(label), lo, attrs)
2324 let msg = "expected `while`, `for`, or `loop` after a label";
2325 let mut err = self.fatal(msg);
2326 err.span_label(self.span, msg);
2329 if self.eat_keyword(keywords::Loop) {
2330 let lo = self.prev_span;
2331 return self.parse_loop_expr(None, lo, attrs);
2333 if self.eat_keyword(keywords::Continue) {
2334 let label = self.eat_label();
2335 let ex = ExprKind::Continue(label);
2336 let hi = self.prev_span;
2337 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2339 if self.eat_keyword(keywords::Match) {
2340 return self.parse_match_expr(attrs);
2342 if self.eat_keyword(keywords::Unsafe) {
2343 return self.parse_block_expr(
2345 BlockCheckMode::Unsafe(ast::UserProvided),
2348 if self.is_catch_expr() {
2350 assert!(self.eat_keyword(keywords::Do));
2351 assert!(self.eat_keyword(keywords::Catch));
2352 return self.parse_catch_expr(lo, attrs);
2354 if self.eat_keyword(keywords::Return) {
2355 if self.token.can_begin_expr() {
2356 let e = self.parse_expr()?;
2358 ex = ExprKind::Ret(Some(e));
2360 ex = ExprKind::Ret(None);
2362 } else if self.eat_keyword(keywords::Break) {
2363 let label = self.eat_label();
2364 let e = if self.token.can_begin_expr()
2365 && !(self.token == token::OpenDelim(token::Brace)
2366 && self.restrictions.contains(
2367 Restrictions::NO_STRUCT_LITERAL)) {
2368 Some(self.parse_expr()?)
2372 ex = ExprKind::Break(label, e);
2373 hi = self.prev_span;
2374 } else if self.eat_keyword(keywords::Yield) {
2375 if self.token.can_begin_expr() {
2376 let e = self.parse_expr()?;
2378 ex = ExprKind::Yield(Some(e));
2380 ex = ExprKind::Yield(None);
2382 } else if self.token.is_keyword(keywords::Let) {
2383 // Catch this syntax error here, instead of in `parse_ident`, so
2384 // that we can explicitly mention that let is not to be used as an expression
2385 let mut db = self.fatal("expected expression, found statement (`let`)");
2386 db.span_label(self.span, "expected expression");
2387 db.note("variable declaration using `let` is a statement");
2389 } else if self.token.is_path_start() {
2390 let pth = self.parse_path(PathStyle::Expr)?;
2392 // `!`, as an operator, is prefix, so we know this isn't that
2393 if self.eat(&token::Not) {
2394 // MACRO INVOCATION expression
2395 let (_, tts) = self.expect_delimited_token_tree()?;
2396 let hi = self.prev_span;
2397 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2399 if self.check(&token::OpenDelim(token::Brace)) {
2400 // This is a struct literal, unless we're prohibited
2401 // from parsing struct literals here.
2402 let prohibited = self.restrictions.contains(
2403 Restrictions::NO_STRUCT_LITERAL
2406 return self.parse_struct_expr(lo, pth, attrs);
2411 ex = ExprKind::Path(None, pth);
2413 match self.parse_lit() {
2416 ex = ExprKind::Lit(P(lit));
2419 self.cancel(&mut err);
2420 let msg = format!("expected expression, found {}",
2421 self.this_token_descr());
2422 let mut err = self.fatal(&msg);
2423 err.span_label(self.span, "expected expression");
2431 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2432 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2437 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2438 -> PResult<'a, P<Expr>> {
2439 let struct_sp = lo.to(self.prev_span);
2441 let mut fields = Vec::new();
2442 let mut base = None;
2444 attrs.extend(self.parse_inner_attributes()?);
2446 while self.token != token::CloseDelim(token::Brace) {
2447 if self.eat(&token::DotDot) {
2448 let exp_span = self.prev_span;
2449 match self.parse_expr() {
2455 self.recover_stmt();
2458 if self.token == token::Comma {
2459 let mut err = self.sess.span_diagnostic.mut_span_err(
2460 exp_span.to(self.prev_span),
2461 "cannot use a comma after the base struct",
2463 err.span_suggestion_short(self.span, "remove this comma", "".to_owned());
2464 err.note("the base struct must always be the last field");
2466 self.recover_stmt();
2471 match self.parse_field() {
2472 Ok(f) => fields.push(f),
2474 e.span_label(struct_sp, "while parsing this struct");
2476 self.recover_stmt();
2481 match self.expect_one_of(&[token::Comma],
2482 &[token::CloseDelim(token::Brace)]) {
2486 self.recover_stmt();
2492 let span = lo.to(self.span);
2493 self.expect(&token::CloseDelim(token::Brace))?;
2494 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2497 fn parse_or_use_outer_attributes(&mut self,
2498 already_parsed_attrs: Option<ThinVec<Attribute>>)
2499 -> PResult<'a, ThinVec<Attribute>> {
2500 if let Some(attrs) = already_parsed_attrs {
2503 self.parse_outer_attributes().map(|a| a.into())
2507 /// Parse a block or unsafe block
2508 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2509 outer_attrs: ThinVec<Attribute>)
2510 -> PResult<'a, P<Expr>> {
2511 self.expect(&token::OpenDelim(token::Brace))?;
2513 let mut attrs = outer_attrs;
2514 attrs.extend(self.parse_inner_attributes()?);
2516 let blk = self.parse_block_tail(lo, blk_mode)?;
2517 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2520 /// parse a.b or a(13) or a[4] or just a
2521 pub fn parse_dot_or_call_expr(&mut self,
2522 already_parsed_attrs: Option<ThinVec<Attribute>>)
2523 -> PResult<'a, P<Expr>> {
2524 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2526 let b = self.parse_bottom_expr();
2527 let (span, b) = self.interpolated_or_expr_span(b)?;
2528 self.parse_dot_or_call_expr_with(b, span, attrs)
2531 pub fn parse_dot_or_call_expr_with(&mut self,
2534 mut attrs: ThinVec<Attribute>)
2535 -> PResult<'a, P<Expr>> {
2536 // Stitch the list of outer attributes onto the return value.
2537 // A little bit ugly, but the best way given the current code
2539 self.parse_dot_or_call_expr_with_(e0, lo)
2541 expr.map(|mut expr| {
2542 attrs.extend::<Vec<_>>(expr.attrs.into());
2545 ExprKind::If(..) | ExprKind::IfLet(..) => {
2546 if !expr.attrs.is_empty() {
2547 // Just point to the first attribute in there...
2548 let span = expr.attrs[0].span;
2551 "attributes are not yet allowed on `if` \
2562 // Assuming we have just parsed `.`, continue parsing into an expression.
2563 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2564 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2565 Ok(match self.token {
2566 token::OpenDelim(token::Paren) => {
2567 // Method call `expr.f()`
2568 let mut args = self.parse_unspanned_seq(
2569 &token::OpenDelim(token::Paren),
2570 &token::CloseDelim(token::Paren),
2571 SeqSep::trailing_allowed(token::Comma),
2572 |p| Ok(p.parse_expr()?)
2574 args.insert(0, self_arg);
2576 let span = lo.to(self.prev_span);
2577 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2580 // Field access `expr.f`
2581 if let Some(parameters) = segment.parameters {
2582 self.span_err(parameters.span(),
2583 "field expressions may not have generic arguments");
2586 let span = lo.to(self.prev_span);
2587 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2592 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2597 while self.eat(&token::Question) {
2598 let hi = self.prev_span;
2599 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2603 if self.eat(&token::Dot) {
2605 token::Ident(..) => {
2606 e = self.parse_dot_suffix(e, lo)?;
2608 token::Literal(token::Integer(index_ident), suf) => {
2611 // A tuple index may not have a suffix
2612 self.expect_no_suffix(sp, "tuple index", suf);
2614 let idx_span = self.span;
2617 let invalid_msg = "invalid tuple or struct index";
2619 let index = index_ident.as_str().parse::<usize>().ok();
2622 if n.to_string() != index_ident.as_str() {
2623 let mut err = self.struct_span_err(self.prev_span, invalid_msg);
2624 err.span_suggestion(self.prev_span,
2625 "try simplifying the index",
2629 let field = self.mk_tup_field(e, respan(idx_span, n));
2630 e = self.mk_expr(lo.to(idx_span), field, ThinVec::new());
2633 let prev_span = self.prev_span;
2634 self.span_err(prev_span, invalid_msg);
2638 token::Literal(token::Float(n), _suf) => {
2640 let fstr = n.as_str();
2641 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2642 &format!("unexpected token: `{}`", n));
2643 err.span_label(self.prev_span, "unexpected token");
2644 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2645 let float = match fstr.parse::<f64>().ok() {
2649 let sugg = pprust::to_string(|s| {
2650 use print::pprust::PrintState;
2654 s.print_usize(float.trunc() as usize)?;
2657 s.s.word(fstr.splitn(2, ".").last().unwrap())
2659 err.span_suggestion(
2660 lo.to(self.prev_span),
2661 "try parenthesizing the first index",
2668 // FIXME Could factor this out into non_fatal_unexpected or something.
2669 let actual = self.this_token_to_string();
2670 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2675 if self.expr_is_complete(&e) { break; }
2678 token::OpenDelim(token::Paren) => {
2679 let es = self.parse_unspanned_seq(
2680 &token::OpenDelim(token::Paren),
2681 &token::CloseDelim(token::Paren),
2682 SeqSep::trailing_allowed(token::Comma),
2683 |p| Ok(p.parse_expr()?)
2685 hi = self.prev_span;
2687 let nd = self.mk_call(e, es);
2688 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2692 // Could be either an index expression or a slicing expression.
2693 token::OpenDelim(token::Bracket) => {
2695 let ix = self.parse_expr()?;
2697 self.expect(&token::CloseDelim(token::Bracket))?;
2698 let index = self.mk_index(e, ix);
2699 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2707 pub fn process_potential_macro_variable(&mut self) {
2708 let (token, span) = match self.token {
2709 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2710 self.look_ahead(1, |t| t.is_ident()) => {
2712 let name = match self.token {
2713 token::Ident(ident, _) => ident,
2716 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2717 err.span_label(self.span, "unknown macro variable");
2721 token::Interpolated(ref nt) => {
2722 self.meta_var_span = Some(self.span);
2723 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2724 // and lifetime tokens, so the former are never encountered during normal parsing.
2726 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2727 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2737 /// parse a single token tree from the input.
2738 pub fn parse_token_tree(&mut self) -> TokenTree {
2740 token::OpenDelim(..) => {
2741 let frame = mem::replace(&mut self.token_cursor.frame,
2742 self.token_cursor.stack.pop().unwrap());
2743 self.span = frame.span;
2745 TokenTree::Delimited(frame.span, Delimited {
2747 tts: frame.tree_cursor.original_stream().into(),
2750 token::CloseDelim(_) | token::Eof => unreachable!(),
2752 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2754 TokenTree::Token(span, token)
2759 // parse a stream of tokens into a list of TokenTree's,
2761 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2762 let mut tts = Vec::new();
2763 while self.token != token::Eof {
2764 tts.push(self.parse_token_tree());
2769 pub fn parse_tokens(&mut self) -> TokenStream {
2770 let mut result = Vec::new();
2773 token::Eof | token::CloseDelim(..) => break,
2774 _ => result.push(self.parse_token_tree().into()),
2777 TokenStream::concat(result)
2780 /// Parse a prefix-unary-operator expr
2781 pub fn parse_prefix_expr(&mut self,
2782 already_parsed_attrs: Option<ThinVec<Attribute>>)
2783 -> PResult<'a, P<Expr>> {
2784 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2786 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2787 let (hi, ex) = match self.token {
2790 let e = self.parse_prefix_expr(None);
2791 let (span, e) = self.interpolated_or_expr_span(e)?;
2792 (lo.to(span), self.mk_unary(UnOp::Not, e))
2794 // Suggest `!` for bitwise negation when encountering a `~`
2797 let e = self.parse_prefix_expr(None);
2798 let (span, e) = self.interpolated_or_expr_span(e)?;
2799 let span_of_tilde = lo;
2800 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2801 "`~` cannot be used as a unary operator");
2802 err.span_suggestion_short(span_of_tilde,
2803 "use `!` to perform bitwise negation",
2806 (lo.to(span), self.mk_unary(UnOp::Not, e))
2808 token::BinOp(token::Minus) => {
2810 let e = self.parse_prefix_expr(None);
2811 let (span, e) = self.interpolated_or_expr_span(e)?;
2812 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2814 token::BinOp(token::Star) => {
2816 let e = self.parse_prefix_expr(None);
2817 let (span, e) = self.interpolated_or_expr_span(e)?;
2818 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2820 token::BinOp(token::And) | token::AndAnd => {
2822 let m = self.parse_mutability();
2823 let e = self.parse_prefix_expr(None);
2824 let (span, e) = self.interpolated_or_expr_span(e)?;
2825 (lo.to(span), ExprKind::AddrOf(m, e))
2827 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2829 let e = self.parse_prefix_expr(None);
2830 let (span, e) = self.interpolated_or_expr_span(e)?;
2831 (lo.to(span), ExprKind::Box(e))
2833 _ => return self.parse_dot_or_call_expr(Some(attrs))
2835 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2838 /// Parse an associative expression
2840 /// This parses an expression accounting for associativity and precedence of the operators in
2842 pub fn parse_assoc_expr(&mut self,
2843 already_parsed_attrs: Option<ThinVec<Attribute>>)
2844 -> PResult<'a, P<Expr>> {
2845 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2848 /// Parse an associative expression with operators of at least `min_prec` precedence
2849 pub fn parse_assoc_expr_with(&mut self,
2852 -> PResult<'a, P<Expr>> {
2853 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2856 let attrs = match lhs {
2857 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2860 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2861 return self.parse_prefix_range_expr(attrs);
2863 self.parse_prefix_expr(attrs)?
2867 if self.expr_is_complete(&lhs) {
2868 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2871 self.expected_tokens.push(TokenType::Operator);
2872 while let Some(op) = AssocOp::from_token(&self.token) {
2874 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2875 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2876 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2877 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2878 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2879 (PrevTokenKind::Interpolated, _) => self.prev_span,
2880 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2881 if path.segments.len() == 1 => self.prev_span,
2885 let cur_op_span = self.span;
2886 let restrictions = if op.is_assign_like() {
2887 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2891 if op.precedence() < min_prec {
2894 // Check for deprecated `...` syntax
2895 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2896 self.err_dotdotdot_syntax(self.span);
2900 if op.is_comparison() {
2901 self.check_no_chained_comparison(&lhs, &op);
2904 if op == AssocOp::As {
2905 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2907 } else if op == AssocOp::Colon {
2908 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2911 err.span_label(self.span,
2912 "expecting a type here because of type ascription");
2913 let cm = self.sess.codemap();
2914 let cur_pos = cm.lookup_char_pos(self.span.lo());
2915 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
2916 if cur_pos.line != op_pos.line {
2917 err.span_suggestion_short(cur_op_span,
2918 "did you mean to use `;` here?",
2925 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2926 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2927 // generalise it to the Fixity::None code.
2929 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2930 // two variants are handled with `parse_prefix_range_expr` call above.
2931 let rhs = if self.is_at_start_of_range_notation_rhs() {
2932 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2933 LhsExpr::NotYetParsed)?)
2937 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2942 let limits = if op == AssocOp::DotDot {
2943 RangeLimits::HalfOpen
2948 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2949 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2953 let rhs = match op.fixity() {
2954 Fixity::Right => self.with_res(
2955 restrictions - Restrictions::STMT_EXPR,
2957 this.parse_assoc_expr_with(op.precedence(),
2958 LhsExpr::NotYetParsed)
2960 Fixity::Left => self.with_res(
2961 restrictions - Restrictions::STMT_EXPR,
2963 this.parse_assoc_expr_with(op.precedence() + 1,
2964 LhsExpr::NotYetParsed)
2966 // We currently have no non-associative operators that are not handled above by
2967 // the special cases. The code is here only for future convenience.
2968 Fixity::None => self.with_res(
2969 restrictions - Restrictions::STMT_EXPR,
2971 this.parse_assoc_expr_with(op.precedence() + 1,
2972 LhsExpr::NotYetParsed)
2976 let span = lhs_span.to(rhs.span);
2978 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2979 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2980 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2981 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2982 AssocOp::Greater | AssocOp::GreaterEqual => {
2983 let ast_op = op.to_ast_binop().unwrap();
2984 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2985 self.mk_expr(span, binary, ThinVec::new())
2988 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2989 AssocOp::AssignOp(k) => {
2991 token::Plus => BinOpKind::Add,
2992 token::Minus => BinOpKind::Sub,
2993 token::Star => BinOpKind::Mul,
2994 token::Slash => BinOpKind::Div,
2995 token::Percent => BinOpKind::Rem,
2996 token::Caret => BinOpKind::BitXor,
2997 token::And => BinOpKind::BitAnd,
2998 token::Or => BinOpKind::BitOr,
2999 token::Shl => BinOpKind::Shl,
3000 token::Shr => BinOpKind::Shr,
3002 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
3003 self.mk_expr(span, aopexpr, ThinVec::new())
3005 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3006 self.bug("AssocOp should have been handled by special case")
3010 if op.fixity() == Fixity::None { break }
3015 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3016 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3017 -> PResult<'a, P<Expr>> {
3018 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3019 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3022 // Save the state of the parser before parsing type normally, in case there is a
3023 // LessThan comparison after this cast.
3024 let parser_snapshot_before_type = self.clone();
3025 match self.parse_ty_no_plus() {
3027 Ok(mk_expr(self, rhs))
3029 Err(mut type_err) => {
3030 // Rewind to before attempting to parse the type with generics, to recover
3031 // from situations like `x as usize < y` in which we first tried to parse
3032 // `usize < y` as a type with generic arguments.
3033 let parser_snapshot_after_type = self.clone();
3034 mem::replace(self, parser_snapshot_before_type);
3036 match self.parse_path(PathStyle::Expr) {
3038 let (op_noun, op_verb) = match self.token {
3039 token::Lt => ("comparison", "comparing"),
3040 token::BinOp(token::Shl) => ("shift", "shifting"),
3042 // We can end up here even without `<` being the next token, for
3043 // example because `parse_ty_no_plus` returns `Err` on keywords,
3044 // but `parse_path` returns `Ok` on them due to error recovery.
3045 // Return original error and parser state.
3046 mem::replace(self, parser_snapshot_after_type);
3047 return Err(type_err);
3051 // Successfully parsed the type path leaving a `<` yet to parse.
3054 // Report non-fatal diagnostics, keep `x as usize` as an expression
3055 // in AST and continue parsing.
3056 let msg = format!("`<` is interpreted as a start of generic \
3057 arguments for `{}`, not a {}", path, op_noun);
3058 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3059 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3060 "interpreted as generic arguments");
3061 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3063 let expr = mk_expr(self, P(Ty {
3065 node: TyKind::Path(None, path),
3066 id: ast::DUMMY_NODE_ID
3069 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
3070 .unwrap_or(pprust::expr_to_string(&expr));
3071 err.span_suggestion(expr.span,
3072 &format!("try {} the cast value", op_verb),
3073 format!("({})", expr_str));
3078 Err(mut path_err) => {
3079 // Couldn't parse as a path, return original error and parser state.
3081 mem::replace(self, parser_snapshot_after_type);
3089 /// Produce an error if comparison operators are chained (RFC #558).
3090 /// We only need to check lhs, not rhs, because all comparison ops
3091 /// have same precedence and are left-associative
3092 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3093 debug_assert!(outer_op.is_comparison(),
3094 "check_no_chained_comparison: {:?} is not comparison",
3097 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3098 // respan to include both operators
3099 let op_span = op.span.to(self.span);
3100 let mut err = self.diagnostic().struct_span_err(op_span,
3101 "chained comparison operators require parentheses");
3102 if op.node == BinOpKind::Lt &&
3103 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3104 *outer_op == AssocOp::Greater // even in a case like the following:
3105 { // Foo<Bar<Baz<Qux, ()>>>
3107 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3108 err.help("or use `(...)` if you meant to specify fn arguments");
3116 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3117 fn parse_prefix_range_expr(&mut self,
3118 already_parsed_attrs: Option<ThinVec<Attribute>>)
3119 -> PResult<'a, P<Expr>> {
3120 // Check for deprecated `...` syntax
3121 if self.token == token::DotDotDot {
3122 self.err_dotdotdot_syntax(self.span);
3125 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3126 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3128 let tok = self.token.clone();
3129 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3131 let mut hi = self.span;
3133 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3134 // RHS must be parsed with more associativity than the dots.
3135 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3136 Some(self.parse_assoc_expr_with(next_prec,
3137 LhsExpr::NotYetParsed)
3145 let limits = if tok == token::DotDot {
3146 RangeLimits::HalfOpen
3151 let r = try!(self.mk_range(None,
3154 Ok(self.mk_expr(lo.to(hi), r, attrs))
3157 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3158 if self.token.can_begin_expr() {
3159 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3160 if self.token == token::OpenDelim(token::Brace) {
3161 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3169 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3170 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3171 if self.check_keyword(keywords::Let) {
3172 return self.parse_if_let_expr(attrs);
3174 let lo = self.prev_span;
3175 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3177 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3178 // verify that the last statement is either an implicit return (no `;`) or an explicit
3179 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3180 // the dead code lint.
3181 if self.eat_keyword(keywords::Else) || !cond.returns() {
3182 let sp = self.sess.codemap().next_point(lo);
3183 let mut err = self.diagnostic()
3184 .struct_span_err(sp, "missing condition for `if` statemement");
3185 err.span_label(sp, "expected if condition here");
3188 let not_block = self.token != token::OpenDelim(token::Brace);
3189 let thn = self.parse_block().map_err(|mut err| {
3191 err.span_label(lo, "this `if` statement has a condition, but no block");
3195 let mut els: Option<P<Expr>> = None;
3196 let mut hi = thn.span;
3197 if self.eat_keyword(keywords::Else) {
3198 let elexpr = self.parse_else_expr()?;
3202 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3205 /// Parse an 'if let' expression ('if' token already eaten)
3206 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3207 -> PResult<'a, P<Expr>> {
3208 let lo = self.prev_span;
3209 self.expect_keyword(keywords::Let)?;
3210 let pats = self.parse_pats()?;
3211 self.expect(&token::Eq)?;
3212 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3213 let thn = self.parse_block()?;
3214 let (hi, els) = if self.eat_keyword(keywords::Else) {
3215 let expr = self.parse_else_expr()?;
3216 (expr.span, Some(expr))
3220 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3223 // `move |args| expr`
3224 pub fn parse_lambda_expr(&mut self,
3225 attrs: ThinVec<Attribute>)
3226 -> PResult<'a, P<Expr>>
3229 let movability = if self.eat_keyword(keywords::Static) {
3234 let capture_clause = if self.eat_keyword(keywords::Move) {
3239 let decl = self.parse_fn_block_decl()?;
3240 let decl_hi = self.prev_span;
3241 let body = match decl.output {
3242 FunctionRetTy::Default(_) => {
3243 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3244 self.parse_expr_res(restrictions, None)?
3247 // If an explicit return type is given, require a
3248 // block to appear (RFC 968).
3249 let body_lo = self.span;
3250 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3256 ExprKind::Closure(capture_clause, movability, decl, body, lo.to(decl_hi)),
3260 // `else` token already eaten
3261 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3262 if self.eat_keyword(keywords::If) {
3263 return self.parse_if_expr(ThinVec::new());
3265 let blk = self.parse_block()?;
3266 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3270 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3271 pub fn parse_for_expr(&mut self, opt_label: Option<Label>,
3273 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3274 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3276 let pat = self.parse_top_level_pat()?;
3277 if !self.eat_keyword(keywords::In) {
3278 let in_span = self.prev_span.between(self.span);
3279 let mut err = self.sess.span_diagnostic
3280 .struct_span_err(in_span, "missing `in` in `for` loop");
3281 err.span_suggestion_short(in_span, "try adding `in` here", " in ".into());
3284 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3285 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3286 attrs.extend(iattrs);
3288 let hi = self.prev_span;
3289 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3292 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3293 pub fn parse_while_expr(&mut self, opt_label: Option<Label>,
3295 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3296 if self.token.is_keyword(keywords::Let) {
3297 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3299 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3300 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3301 attrs.extend(iattrs);
3302 let span = span_lo.to(body.span);
3303 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3306 /// Parse a 'while let' expression ('while' token already eaten)
3307 pub fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3309 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3310 self.expect_keyword(keywords::Let)?;
3311 let pats = self.parse_pats()?;
3312 self.expect(&token::Eq)?;
3313 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3314 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3315 attrs.extend(iattrs);
3316 let span = span_lo.to(body.span);
3317 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3320 // parse `loop {...}`, `loop` token already eaten
3321 pub fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3323 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3324 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3325 attrs.extend(iattrs);
3326 let span = span_lo.to(body.span);
3327 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3330 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3331 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3332 -> PResult<'a, P<Expr>>
3334 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3335 attrs.extend(iattrs);
3336 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3339 // `match` token already eaten
3340 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3341 let match_span = self.prev_span;
3342 let lo = self.prev_span;
3343 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3345 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3346 if self.token == token::Token::Semi {
3347 e.span_suggestion_short(match_span, "try removing this `match`", "".to_owned());
3351 attrs.extend(self.parse_inner_attributes()?);
3353 let mut arms: Vec<Arm> = Vec::new();
3354 while self.token != token::CloseDelim(token::Brace) {
3355 match self.parse_arm() {
3356 Ok(arm) => arms.push(arm),
3358 // Recover by skipping to the end of the block.
3360 self.recover_stmt();
3361 let span = lo.to(self.span);
3362 if self.token == token::CloseDelim(token::Brace) {
3365 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3371 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3374 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3375 maybe_whole!(self, NtArm, |x| x);
3377 let attrs = self.parse_outer_attributes()?;
3378 // Allow a '|' before the pats (RFC 1925)
3379 self.eat(&token::BinOp(token::Or));
3380 let pats = self.parse_pats()?;
3381 let guard = if self.eat_keyword(keywords::If) {
3382 Some(self.parse_expr()?)
3386 let arrow_span = self.span;
3387 self.expect(&token::FatArrow)?;
3388 let arm_start_span = self.span;
3390 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3391 .map_err(|mut err| {
3392 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3396 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3397 && self.token != token::CloseDelim(token::Brace);
3400 let cm = self.sess.codemap();
3401 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3402 .map_err(|mut err| {
3403 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3404 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3405 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3406 && expr_lines.lines.len() == 2
3407 && self.token == token::FatArrow => {
3408 // We check wether there's any trailing code in the parse span, if there
3409 // isn't, we very likely have the following:
3412 // | -- - missing comma
3418 // | parsed until here as `"y" & X`
3419 err.span_suggestion_short(
3420 cm.next_point(arm_start_span),
3421 "missing a comma here to end this `match` arm",
3426 err.span_label(arrow_span,
3427 "while parsing the `match` arm starting here");
3433 self.eat(&token::Comma);
3444 /// Parse an expression
3445 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3446 self.parse_expr_res(Restrictions::empty(), None)
3449 /// Evaluate the closure with restrictions in place.
3451 /// After the closure is evaluated, restrictions are reset.
3452 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3453 where F: FnOnce(&mut Self) -> T
3455 let old = self.restrictions;
3456 self.restrictions = r;
3458 self.restrictions = old;
3463 /// Parse an expression, subject to the given restrictions
3464 pub fn parse_expr_res(&mut self, r: Restrictions,
3465 already_parsed_attrs: Option<ThinVec<Attribute>>)
3466 -> PResult<'a, P<Expr>> {
3467 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3470 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3471 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3472 if self.check(&token::Eq) {
3474 Ok(Some(self.parse_expr()?))
3476 Ok(Some(self.parse_expr()?))
3482 /// Parse patterns, separated by '|' s
3483 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3484 let mut pats = Vec::new();
3486 pats.push(self.parse_top_level_pat()?);
3488 if self.token == token::OrOr {
3489 let mut err = self.struct_span_err(self.span,
3490 "unexpected token `||` after pattern");
3491 err.span_suggestion(self.span,
3492 "use a single `|` to specify multiple patterns",
3496 } else if self.check(&token::BinOp(token::Or)) {
3504 // Parses a parenthesized list of patterns like
3505 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3506 // - a vector of the patterns that were parsed
3507 // - an option indicating the index of the `..` element
3508 // - a boolean indicating whether a trailing comma was present.
3509 // Trailing commas are significant because (p) and (p,) are different patterns.
3510 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3511 self.expect(&token::OpenDelim(token::Paren))?;
3512 let result = self.parse_pat_list()?;
3513 self.expect(&token::CloseDelim(token::Paren))?;
3517 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3518 let mut fields = Vec::new();
3519 let mut ddpos = None;
3520 let mut trailing_comma = false;
3522 if self.eat(&token::DotDot) {
3523 if ddpos.is_none() {
3524 ddpos = Some(fields.len());
3526 // Emit a friendly error, ignore `..` and continue parsing
3527 self.span_err(self.prev_span,
3528 "`..` can only be used once per tuple or tuple struct pattern");
3530 } else if !self.check(&token::CloseDelim(token::Paren)) {
3531 fields.push(self.parse_pat()?);
3536 trailing_comma = self.eat(&token::Comma);
3537 if !trailing_comma {
3542 if ddpos == Some(fields.len()) && trailing_comma {
3543 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3544 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3547 Ok((fields, ddpos, trailing_comma))
3550 fn parse_pat_vec_elements(
3552 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3553 let mut before = Vec::new();
3554 let mut slice = None;
3555 let mut after = Vec::new();
3556 let mut first = true;
3557 let mut before_slice = true;
3559 while self.token != token::CloseDelim(token::Bracket) {
3563 self.expect(&token::Comma)?;
3565 if self.token == token::CloseDelim(token::Bracket)
3566 && (before_slice || !after.is_empty()) {
3572 if self.eat(&token::DotDot) {
3574 if self.check(&token::Comma) ||
3575 self.check(&token::CloseDelim(token::Bracket)) {
3576 slice = Some(P(Pat {
3577 id: ast::DUMMY_NODE_ID,
3578 node: PatKind::Wild,
3579 span: self.prev_span,
3581 before_slice = false;
3587 let subpat = self.parse_pat()?;
3588 if before_slice && self.eat(&token::DotDot) {
3589 slice = Some(subpat);
3590 before_slice = false;
3591 } else if before_slice {
3592 before.push(subpat);
3598 Ok((before, slice, after))
3601 /// Parse the fields of a struct-like pattern
3602 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3603 let mut fields = Vec::new();
3604 let mut etc = false;
3605 let mut first = true;
3606 while self.token != token::CloseDelim(token::Brace) {
3610 self.expect(&token::Comma)?;
3611 // accept trailing commas
3612 if self.check(&token::CloseDelim(token::Brace)) { break }
3615 let attrs = self.parse_outer_attributes()?;
3619 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3620 if self.token == token::DotDotDot { // Issue #46718
3621 let mut err = self.struct_span_err(self.span,
3622 "expected field pattern, found `...`");
3623 err.span_suggestion(self.span,
3624 "to omit remaining fields, use one fewer `.`",
3630 if self.token != token::CloseDelim(token::Brace) {
3631 let token_str = self.this_token_to_string();
3632 let mut err = self.fatal(&format!("expected `{}`, found `{}`", "}", token_str));
3633 if self.token == token::Comma { // Issue #49257
3634 err.span_label(self.span,
3635 "`..` must be in the last position, \
3636 and cannot have a trailing comma");
3638 err.span_label(self.span, "expected `}`");
3646 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3647 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3648 // Parsing a pattern of the form "fieldname: pat"
3649 let fieldname = self.parse_field_name()?;
3651 let pat = self.parse_pat()?;
3653 (pat, fieldname, false)
3655 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3656 let is_box = self.eat_keyword(keywords::Box);
3657 let boxed_span = self.span;
3658 let is_ref = self.eat_keyword(keywords::Ref);
3659 let is_mut = self.eat_keyword(keywords::Mut);
3660 let fieldname = self.parse_ident()?;
3661 hi = self.prev_span;
3663 let bind_type = match (is_ref, is_mut) {
3664 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3665 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3666 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3667 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3669 let fieldpat = P(Pat {
3670 id: ast::DUMMY_NODE_ID,
3671 node: PatKind::Ident(bind_type, fieldname, None),
3672 span: boxed_span.to(hi),
3675 let subpat = if is_box {
3677 id: ast::DUMMY_NODE_ID,
3678 node: PatKind::Box(fieldpat),
3684 (subpat, fieldname, true)
3687 fields.push(codemap::Spanned { span: lo.to(hi),
3688 node: ast::FieldPat {
3692 attrs: attrs.into(),
3696 return Ok((fields, etc));
3699 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3700 if self.token.is_path_start() {
3702 let (qself, path) = if self.eat_lt() {
3703 // Parse a qualified path
3704 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3707 // Parse an unqualified path
3708 (None, self.parse_path(PathStyle::Expr)?)
3710 let hi = self.prev_span;
3711 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3713 self.parse_pat_literal_maybe_minus()
3717 // helper function to decide whether to parse as ident binding or to try to do
3718 // something more complex like range patterns
3719 fn parse_as_ident(&mut self) -> bool {
3720 self.look_ahead(1, |t| match *t {
3721 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3722 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3723 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3724 // range pattern branch
3725 token::DotDot => None,
3727 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3728 token::Comma | token::CloseDelim(token::Bracket) => true,
3733 /// A wrapper around `parse_pat` with some special error handling for the
3734 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contast
3735 /// to subpatterns within such).
3736 pub fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3737 let pat = self.parse_pat()?;
3738 if self.token == token::Comma {
3739 // An unexpected comma after a top-level pattern is a clue that the
3740 // user (perhaps more accustomed to some other language) forgot the
3741 // parentheses in what should have been a tuple pattern; return a
3742 // suggestion-enhanced error here rather than choking on the comma
3744 let comma_span = self.span;
3746 if let Err(mut err) = self.parse_pat_list() {
3747 // We didn't expect this to work anyway; we just wanted
3748 // to advance to the end of the comma-sequence so we know
3749 // the span to suggest parenthesizing
3752 let seq_span = pat.span.to(self.prev_span);
3753 let mut err = self.struct_span_err(comma_span,
3754 "unexpected `,` in pattern");
3755 if let Ok(seq_snippet) = self.sess.codemap().span_to_snippet(seq_span) {
3756 err.span_suggestion(seq_span, "try adding parentheses",
3757 format!("({})", seq_snippet));
3764 /// Parse a pattern.
3765 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3766 self.parse_pat_with_range_pat(true)
3769 /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
3771 fn parse_pat_with_range_pat(&mut self, allow_range_pat: bool) -> PResult<'a, P<Pat>> {
3772 maybe_whole!(self, NtPat, |x| x);
3777 token::BinOp(token::And) | token::AndAnd => {
3778 // Parse &pat / &mut pat
3780 let mutbl = self.parse_mutability();
3781 if let token::Lifetime(ident) = self.token {
3782 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
3784 err.span_label(self.span, "unexpected lifetime");
3787 let subpat = self.parse_pat_with_range_pat(false)?;
3788 pat = PatKind::Ref(subpat, mutbl);
3790 token::OpenDelim(token::Paren) => {
3791 // Parse (pat,pat,pat,...) as tuple pattern
3792 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
3793 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
3794 PatKind::Paren(fields.into_iter().nth(0).unwrap())
3796 PatKind::Tuple(fields, ddpos)
3799 token::OpenDelim(token::Bracket) => {
3800 // Parse [pat,pat,...] as slice pattern
3802 let (before, slice, after) = self.parse_pat_vec_elements()?;
3803 self.expect(&token::CloseDelim(token::Bracket))?;
3804 pat = PatKind::Slice(before, slice, after);
3806 // At this point, token != &, &&, (, [
3807 _ => if self.eat_keyword(keywords::Underscore) {
3809 pat = PatKind::Wild;
3810 } else if self.eat_keyword(keywords::Mut) {
3811 // Parse mut ident @ pat / mut ref ident @ pat
3812 let mutref_span = self.prev_span.to(self.span);
3813 let binding_mode = if self.eat_keyword(keywords::Ref) {
3815 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3816 .span_suggestion(mutref_span, "try switching the order", "ref mut".into())
3818 BindingMode::ByRef(Mutability::Mutable)
3820 BindingMode::ByValue(Mutability::Mutable)
3822 pat = self.parse_pat_ident(binding_mode)?;
3823 } else if self.eat_keyword(keywords::Ref) {
3824 // Parse ref ident @ pat / ref mut ident @ pat
3825 let mutbl = self.parse_mutability();
3826 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3827 } else if self.eat_keyword(keywords::Box) {
3829 let subpat = self.parse_pat_with_range_pat(false)?;
3830 pat = PatKind::Box(subpat);
3831 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3832 self.parse_as_ident() {
3833 // Parse ident @ pat
3834 // This can give false positives and parse nullary enums,
3835 // they are dealt with later in resolve
3836 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3837 pat = self.parse_pat_ident(binding_mode)?;
3838 } else if self.token.is_path_start() {
3839 // Parse pattern starting with a path
3840 let (qself, path) = if self.eat_lt() {
3841 // Parse a qualified path
3842 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3845 // Parse an unqualified path
3846 (None, self.parse_path(PathStyle::Expr)?)
3849 token::Not if qself.is_none() => {
3850 // Parse macro invocation
3852 let (_, tts) = self.expect_delimited_token_tree()?;
3853 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3854 pat = PatKind::Mac(mac);
3856 token::DotDotDot | token::DotDotEq | token::DotDot => {
3857 let end_kind = match self.token {
3858 token::DotDot => RangeEnd::Excluded,
3859 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
3860 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
3861 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
3865 let span = lo.to(self.prev_span);
3866 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3868 let end = self.parse_pat_range_end()?;
3869 pat = PatKind::Range(begin, end, end_kind);
3871 token::OpenDelim(token::Brace) => {
3872 if qself.is_some() {
3873 let msg = "unexpected `{` after qualified path";
3874 let mut err = self.fatal(msg);
3875 err.span_label(self.span, msg);
3878 // Parse struct pattern
3880 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3882 self.recover_stmt();
3886 pat = PatKind::Struct(path, fields, etc);
3888 token::OpenDelim(token::Paren) => {
3889 if qself.is_some() {
3890 let msg = "unexpected `(` after qualified path";
3891 let mut err = self.fatal(msg);
3892 err.span_label(self.span, msg);
3895 // Parse tuple struct or enum pattern
3896 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
3897 pat = PatKind::TupleStruct(path, fields, ddpos)
3899 _ => pat = PatKind::Path(qself, path),
3902 // Try to parse everything else as literal with optional minus
3903 match self.parse_pat_literal_maybe_minus() {
3905 if self.eat(&token::DotDotDot) {
3906 let end = self.parse_pat_range_end()?;
3907 pat = PatKind::Range(begin, end,
3908 RangeEnd::Included(RangeSyntax::DotDotDot));
3909 } else if self.eat(&token::DotDotEq) {
3910 let end = self.parse_pat_range_end()?;
3911 pat = PatKind::Range(begin, end,
3912 RangeEnd::Included(RangeSyntax::DotDotEq));
3913 } else if self.eat(&token::DotDot) {
3914 let end = self.parse_pat_range_end()?;
3915 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3917 pat = PatKind::Lit(begin);
3921 self.cancel(&mut err);
3922 let msg = format!("expected pattern, found {}", self.this_token_descr());
3923 let mut err = self.fatal(&msg);
3924 err.span_label(self.span, "expected pattern");
3931 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
3932 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
3934 if !allow_range_pat {
3936 PatKind::Range(_, _, RangeEnd::Included(RangeSyntax::DotDotDot)) => {}
3937 PatKind::Range(..) => {
3938 let mut err = self.struct_span_err(
3940 "the range pattern here has ambiguous interpretation",
3942 err.span_suggestion(
3944 "add parentheses to clarify the precedence",
3945 format!("({})", pprust::pat_to_string(&pat)),
3956 /// Parse ident or ident @ pat
3957 /// used by the copy foo and ref foo patterns to give a good
3958 /// error message when parsing mistakes like ref foo(a,b)
3959 fn parse_pat_ident(&mut self,
3960 binding_mode: ast::BindingMode)
3961 -> PResult<'a, PatKind> {
3962 let ident = self.parse_ident()?;
3963 let sub = if self.eat(&token::At) {
3964 Some(self.parse_pat()?)
3969 // just to be friendly, if they write something like
3971 // we end up here with ( as the current token. This shortly
3972 // leads to a parse error. Note that if there is no explicit
3973 // binding mode then we do not end up here, because the lookahead
3974 // will direct us over to parse_enum_variant()
3975 if self.token == token::OpenDelim(token::Paren) {
3976 return Err(self.span_fatal(
3978 "expected identifier, found enum pattern"))
3981 Ok(PatKind::Ident(binding_mode, ident, sub))
3984 /// Parse a local variable declaration
3985 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3986 let lo = self.prev_span;
3987 let pat = self.parse_top_level_pat()?;
3989 let (err, ty) = if self.eat(&token::Colon) {
3990 // Save the state of the parser before parsing type normally, in case there is a `:`
3991 // instead of an `=` typo.
3992 let parser_snapshot_before_type = self.clone();
3993 let colon_sp = self.prev_span;
3994 match self.parse_ty() {
3995 Ok(ty) => (None, Some(ty)),
3997 // Rewind to before attempting to parse the type and continue parsing
3998 let parser_snapshot_after_type = self.clone();
3999 mem::replace(self, parser_snapshot_before_type);
4001 let snippet = self.sess.codemap().span_to_snippet(pat.span).unwrap();
4002 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4003 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4009 let init = match (self.parse_initializer(err.is_some()), err) {
4010 (Ok(init), None) => { // init parsed, ty parsed
4013 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4014 // Could parse the type as if it were the initializer, it is likely there was a
4015 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4016 err.span_suggestion_short(colon_sp,
4017 "use `=` if you meant to assign",
4020 // As this was parsed successfully, continue as if the code has been fixed for the
4021 // rest of the file. It will still fail due to the emitted error, but we avoid
4025 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4027 // Couldn't parse the type nor the initializer, only raise the type error and
4028 // return to the parser state before parsing the type as the initializer.
4029 // let x: <parse_error>;
4030 mem::replace(self, snapshot);
4033 (Err(err), None) => { // init error, ty parsed
4034 // Couldn't parse the initializer and we're not attempting to recover a failed
4035 // parse of the type, return the error.
4039 let hi = if self.token == token::Semi {
4048 id: ast::DUMMY_NODE_ID,
4054 /// Parse a structure field
4055 fn parse_name_and_ty(&mut self,
4058 attrs: Vec<Attribute>)
4059 -> PResult<'a, StructField> {
4060 let name = self.parse_ident()?;
4061 self.expect(&token::Colon)?;
4062 let ty = self.parse_ty()?;
4064 span: lo.to(self.prev_span),
4067 id: ast::DUMMY_NODE_ID,
4073 /// Emit an expected item after attributes error.
4074 fn expected_item_err(&self, attrs: &[Attribute]) {
4075 let message = match attrs.last() {
4076 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4077 _ => "expected item after attributes",
4080 self.span_err(self.prev_span, message);
4083 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4084 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4085 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4086 Ok(self.parse_stmt_(true))
4089 // Eat tokens until we can be relatively sure we reached the end of the
4090 // statement. This is something of a best-effort heuristic.
4092 // We terminate when we find an unmatched `}` (without consuming it).
4093 fn recover_stmt(&mut self) {
4094 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4097 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4098 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4099 // approximate - it can mean we break too early due to macros, but that
4100 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
4102 // If `break_on_block` is `Break`, then we will stop consuming tokens
4103 // after finding (and consuming) a brace-delimited block.
4104 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4105 let mut brace_depth = 0;
4106 let mut bracket_depth = 0;
4107 let mut in_block = false;
4108 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4109 break_on_semi, break_on_block);
4111 debug!("recover_stmt_ loop {:?}", self.token);
4113 token::OpenDelim(token::DelimToken::Brace) => {
4116 if break_on_block == BlockMode::Break &&
4118 bracket_depth == 0 {
4122 token::OpenDelim(token::DelimToken::Bracket) => {
4126 token::CloseDelim(token::DelimToken::Brace) => {
4127 if brace_depth == 0 {
4128 debug!("recover_stmt_ return - close delim {:?}", self.token);
4133 if in_block && bracket_depth == 0 && brace_depth == 0 {
4134 debug!("recover_stmt_ return - block end {:?}", self.token);
4138 token::CloseDelim(token::DelimToken::Bracket) => {
4140 if bracket_depth < 0 {
4146 debug!("recover_stmt_ return - Eof");
4151 if break_on_semi == SemiColonMode::Break &&
4153 bracket_depth == 0 {
4154 debug!("recover_stmt_ return - Semi");
4165 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4166 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4168 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4173 fn is_catch_expr(&mut self) -> bool {
4174 self.token.is_keyword(keywords::Do) &&
4175 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4176 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4178 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
4179 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4182 fn is_union_item(&self) -> bool {
4183 self.token.is_keyword(keywords::Union) &&
4184 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4187 fn is_crate_vis(&self) -> bool {
4188 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4191 fn is_extern_non_path(&self) -> bool {
4192 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4195 fn is_auto_trait_item(&mut self) -> bool {
4197 (self.token.is_keyword(keywords::Auto)
4198 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4199 || // unsafe auto trait
4200 (self.token.is_keyword(keywords::Unsafe) &&
4201 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4202 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4205 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4206 -> PResult<'a, Option<P<Item>>> {
4207 let token_lo = self.span;
4208 let (ident, def) = match self.token {
4209 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4211 let ident = self.parse_ident()?;
4212 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4213 match self.parse_token_tree() {
4214 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4215 _ => unreachable!(),
4217 } else if self.check(&token::OpenDelim(token::Paren)) {
4218 let args = self.parse_token_tree();
4219 let body = if self.check(&token::OpenDelim(token::Brace)) {
4220 self.parse_token_tree()
4225 TokenStream::concat(vec![
4227 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4235 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4237 token::Ident(ident, _) if ident.name == "macro_rules" &&
4238 self.look_ahead(1, |t| *t == token::Not) => {
4239 let prev_span = self.prev_span;
4240 self.complain_if_pub_macro(&vis.node, prev_span);
4244 let ident = self.parse_ident()?;
4245 let (delim, tokens) = self.expect_delimited_token_tree()?;
4246 if delim != token::Brace {
4247 if !self.eat(&token::Semi) {
4248 let msg = "macros that expand to items must either \
4249 be surrounded with braces or followed by a semicolon";
4250 self.span_err(self.prev_span, msg);
4254 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4256 _ => return Ok(None),
4259 let span = lo.to(self.prev_span);
4260 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4263 fn parse_stmt_without_recovery(&mut self,
4264 macro_legacy_warnings: bool)
4265 -> PResult<'a, Option<Stmt>> {
4266 maybe_whole!(self, NtStmt, |x| Some(x));
4268 let attrs = self.parse_outer_attributes()?;
4271 Ok(Some(if self.eat_keyword(keywords::Let) {
4273 id: ast::DUMMY_NODE_ID,
4274 node: StmtKind::Local(self.parse_local(attrs.into())?),
4275 span: lo.to(self.prev_span),
4277 } else if let Some(macro_def) = self.eat_macro_def(
4279 &codemap::respan(lo, VisibilityKind::Inherited),
4283 id: ast::DUMMY_NODE_ID,
4284 node: StmtKind::Item(macro_def),
4285 span: lo.to(self.prev_span),
4287 // Starts like a simple path, being careful to avoid contextual keywords
4288 // such as a union items, item with `crate` visibility or auto trait items.
4289 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4290 // like a path (1 token), but it fact not a path.
4291 // `union::b::c` - path, `union U { ... }` - not a path.
4292 // `crate::b::c` - path, `crate struct S;` - not a path.
4293 // `extern::b::c` - path, `extern crate c;` - not a path.
4294 } else if self.token.is_path_start() &&
4295 !self.token.is_qpath_start() &&
4296 !self.is_union_item() &&
4297 !self.is_crate_vis() &&
4298 !self.is_extern_non_path() &&
4299 !self.is_auto_trait_item() {
4300 let pth = self.parse_path(PathStyle::Expr)?;
4302 if !self.eat(&token::Not) {
4303 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4304 self.parse_struct_expr(lo, pth, ThinVec::new())?
4306 let hi = self.prev_span;
4307 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4310 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4311 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4312 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4315 return Ok(Some(Stmt {
4316 id: ast::DUMMY_NODE_ID,
4317 node: StmtKind::Expr(expr),
4318 span: lo.to(self.prev_span),
4322 // it's a macro invocation
4323 let id = match self.token {
4324 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4325 _ => self.parse_ident()?,
4328 // check that we're pointing at delimiters (need to check
4329 // again after the `if`, because of `parse_ident`
4330 // consuming more tokens).
4331 let delim = match self.token {
4332 token::OpenDelim(delim) => delim,
4334 // we only expect an ident if we didn't parse one
4336 let ident_str = if id.name == keywords::Invalid.name() {
4341 let tok_str = self.this_token_to_string();
4342 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4345 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4350 let (_, tts) = self.expect_delimited_token_tree()?;
4351 let hi = self.prev_span;
4353 let style = if delim == token::Brace {
4354 MacStmtStyle::Braces
4356 MacStmtStyle::NoBraces
4359 if id.name == keywords::Invalid.name() {
4360 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
4361 let node = if delim == token::Brace ||
4362 self.token == token::Semi || self.token == token::Eof {
4363 StmtKind::Mac(P((mac, style, attrs.into())))
4365 // We used to incorrectly stop parsing macro-expanded statements here.
4366 // If the next token will be an error anyway but could have parsed with the
4367 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4368 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4369 // These can continue an expression, so we can't stop parsing and warn.
4370 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4371 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4372 token::BinOp(token::And) | token::BinOp(token::Or) |
4373 token::AndAnd | token::OrOr |
4374 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4377 self.warn_missing_semicolon();
4378 StmtKind::Mac(P((mac, style, attrs.into())))
4380 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4381 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4382 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4386 id: ast::DUMMY_NODE_ID,
4391 // if it has a special ident, it's definitely an item
4393 // Require a semicolon or braces.
4394 if style != MacStmtStyle::Braces {
4395 if !self.eat(&token::Semi) {
4396 self.span_err(self.prev_span,
4397 "macros that expand to items must \
4398 either be surrounded with braces or \
4399 followed by a semicolon");
4402 let span = lo.to(hi);
4404 id: ast::DUMMY_NODE_ID,
4406 node: StmtKind::Item({
4408 span, id /*id is good here*/,
4409 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
4410 respan(lo, VisibilityKind::Inherited),
4416 // FIXME: Bad copy of attrs
4417 let old_directory_ownership =
4418 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4419 let item = self.parse_item_(attrs.clone(), false, true)?;
4420 self.directory.ownership = old_directory_ownership;
4424 id: ast::DUMMY_NODE_ID,
4425 span: lo.to(i.span),
4426 node: StmtKind::Item(i),
4429 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4430 if !attrs.is_empty() {
4431 if s.prev_token_kind == PrevTokenKind::DocComment {
4432 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4433 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4434 s.span_err(s.span, "expected statement after outer attribute");
4439 // Do not attempt to parse an expression if we're done here.
4440 if self.token == token::Semi {
4441 unused_attrs(&attrs, self);
4446 if self.token == token::CloseDelim(token::Brace) {
4447 unused_attrs(&attrs, self);
4451 // Remainder are line-expr stmts.
4452 let e = self.parse_expr_res(
4453 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4455 id: ast::DUMMY_NODE_ID,
4456 span: lo.to(e.span),
4457 node: StmtKind::Expr(e),
4464 /// Is this expression a successfully-parsed statement?
4465 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4466 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4467 !classify::expr_requires_semi_to_be_stmt(e)
4470 /// Parse a block. No inner attrs are allowed.
4471 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4472 maybe_whole!(self, NtBlock, |x| x);
4476 if !self.eat(&token::OpenDelim(token::Brace)) {
4478 let tok = self.this_token_to_string();
4479 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4481 // Check to see if the user has written something like
4486 // Which is valid in other languages, but not Rust.
4487 match self.parse_stmt_without_recovery(false) {
4489 let mut stmt_span = stmt.span;
4490 // expand the span to include the semicolon, if it exists
4491 if self.eat(&token::Semi) {
4492 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4494 let sugg = pprust::to_string(|s| {
4495 use print::pprust::{PrintState, INDENT_UNIT};
4496 s.ibox(INDENT_UNIT)?;
4498 s.print_stmt(&stmt)?;
4499 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4501 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4504 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4505 self.cancel(&mut e);
4512 self.parse_block_tail(lo, BlockCheckMode::Default)
4515 /// Parse a block. Inner attrs are allowed.
4516 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4517 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4520 self.expect(&token::OpenDelim(token::Brace))?;
4521 Ok((self.parse_inner_attributes()?,
4522 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4525 /// Parse the rest of a block expression or function body
4526 /// Precondition: already parsed the '{'.
4527 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4528 let mut stmts = vec![];
4529 let mut recovered = false;
4531 while !self.eat(&token::CloseDelim(token::Brace)) {
4532 let stmt = match self.parse_full_stmt(false) {
4535 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4536 self.eat(&token::CloseDelim(token::Brace));
4542 if let Some(stmt) = stmt {
4544 } else if self.token == token::Eof {
4547 // Found only `;` or `}`.
4553 id: ast::DUMMY_NODE_ID,
4555 span: lo.to(self.prev_span),
4560 /// Parse a statement, including the trailing semicolon.
4561 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4562 // skip looking for a trailing semicolon when we have an interpolated statement
4563 maybe_whole!(self, NtStmt, |x| Some(x));
4565 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4567 None => return Ok(None),
4571 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4572 // expression without semicolon
4573 if classify::expr_requires_semi_to_be_stmt(expr) {
4574 // Just check for errors and recover; do not eat semicolon yet.
4576 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4579 self.recover_stmt();
4583 StmtKind::Local(..) => {
4584 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4585 if macro_legacy_warnings && self.token != token::Semi {
4586 self.warn_missing_semicolon();
4588 self.expect_one_of(&[token::Semi], &[])?;
4594 if self.eat(&token::Semi) {
4595 stmt = stmt.add_trailing_semicolon();
4598 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4602 fn warn_missing_semicolon(&self) {
4603 self.diagnostic().struct_span_warn(self.span, {
4604 &format!("expected `;`, found `{}`", self.this_token_to_string())
4606 "This was erroneously allowed and will become a hard error in a future release"
4610 fn err_dotdotdot_syntax(&self, span: Span) {
4611 self.diagnostic().struct_span_err(span, {
4612 "`...` syntax cannot be used in expressions"
4614 "Use `..` if you need an exclusive range (a < b)"
4616 "or `..=` if you need an inclusive range (a <= b)"
4620 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4621 // BOUND = TY_BOUND | LT_BOUND
4622 // LT_BOUND = LIFETIME (e.g. `'a`)
4623 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4624 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4625 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4626 let mut bounds = Vec::new();
4628 // This needs to be syncronized with `Token::can_begin_bound`.
4629 let is_bound_start = self.check_path() || self.check_lifetime() ||
4630 self.check(&token::Question) ||
4631 self.check_keyword(keywords::For) ||
4632 self.check(&token::OpenDelim(token::Paren));
4634 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4635 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4636 if self.token.is_lifetime() {
4637 if let Some(question_span) = question {
4638 self.span_err(question_span,
4639 "`?` may only modify trait bounds, not lifetime bounds");
4641 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4644 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4645 let path = self.parse_path(PathStyle::Type)?;
4646 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4647 let modifier = if question.is_some() {
4648 TraitBoundModifier::Maybe
4650 TraitBoundModifier::None
4652 bounds.push(TraitTyParamBound(poly_trait, modifier));
4655 self.expect(&token::CloseDelim(token::Paren))?;
4656 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4657 self.span_err(self.prev_span,
4658 "parenthesized lifetime bounds are not supported");
4665 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4673 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4674 self.parse_ty_param_bounds_common(true)
4677 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4678 // BOUND = LT_BOUND (e.g. `'a`)
4679 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4680 let mut lifetimes = Vec::new();
4681 while self.check_lifetime() {
4682 lifetimes.push(self.expect_lifetime());
4684 if !self.eat(&token::BinOp(token::Plus)) {
4691 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4692 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4693 let ident = self.parse_ident()?;
4695 // Parse optional colon and param bounds.
4696 let bounds = if self.eat(&token::Colon) {
4697 self.parse_ty_param_bounds()?
4702 let default = if self.eat(&token::Eq) {
4703 Some(self.parse_ty()?)
4709 attrs: preceding_attrs.into(),
4711 id: ast::DUMMY_NODE_ID,
4717 /// Parses the following grammar:
4718 /// TraitItemAssocTy = Ident ["<"...">"] [":" [TyParamBounds]] ["where" ...] ["=" Ty]
4719 fn parse_trait_item_assoc_ty(&mut self, preceding_attrs: Vec<Attribute>)
4720 -> PResult<'a, (ast::Generics, TyParam)> {
4721 let ident = self.parse_ident()?;
4722 let mut generics = self.parse_generics()?;
4724 // Parse optional colon and param bounds.
4725 let bounds = if self.eat(&token::Colon) {
4726 self.parse_ty_param_bounds()?
4730 generics.where_clause = self.parse_where_clause()?;
4732 let default = if self.eat(&token::Eq) {
4733 Some(self.parse_ty()?)
4737 self.expect(&token::Semi)?;
4739 Ok((generics, TyParam {
4740 attrs: preceding_attrs.into(),
4742 id: ast::DUMMY_NODE_ID,
4748 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4749 /// trailing comma and erroneous trailing attributes.
4750 pub fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4751 let mut params = Vec::new();
4752 let mut seen_ty_param = false;
4754 let attrs = self.parse_outer_attributes()?;
4755 if self.check_lifetime() {
4756 let lifetime = self.expect_lifetime();
4757 // Parse lifetime parameter.
4758 let bounds = if self.eat(&token::Colon) {
4759 self.parse_lt_param_bounds()
4763 params.push(ast::GenericParam::Lifetime(LifetimeDef {
4764 attrs: attrs.into(),
4769 self.span_err(self.prev_span,
4770 "lifetime parameters must be declared prior to type parameters");
4772 } else if self.check_ident() {
4773 // Parse type parameter.
4774 params.push(ast::GenericParam::Type(self.parse_ty_param(attrs)?));
4775 seen_ty_param = true;
4777 // Check for trailing attributes and stop parsing.
4778 if !attrs.is_empty() {
4779 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4780 self.span_err(attrs[0].span,
4781 &format!("trailing attribute after {} parameters", param_kind));
4786 if !self.eat(&token::Comma) {
4793 /// Parse a set of optional generic type parameter declarations. Where
4794 /// clauses are not parsed here, and must be added later via
4795 /// `parse_where_clause()`.
4797 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4798 /// | ( < lifetimes , typaramseq ( , )? > )
4799 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4800 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4801 maybe_whole!(self, NtGenerics, |x| x);
4803 let span_lo = self.span;
4805 let params = self.parse_generic_params()?;
4809 where_clause: WhereClause {
4810 id: ast::DUMMY_NODE_ID,
4811 predicates: Vec::new(),
4812 span: syntax_pos::DUMMY_SP,
4814 span: span_lo.to(self.prev_span),
4817 Ok(ast::Generics::default())
4821 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4822 /// possibly including trailing comma.
4823 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4824 let mut lifetimes = Vec::new();
4825 let mut types = Vec::new();
4826 let mut bindings = Vec::new();
4827 let mut seen_type = false;
4828 let mut seen_binding = false;
4830 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4831 // Parse lifetime argument.
4832 lifetimes.push(self.expect_lifetime());
4833 if seen_type || seen_binding {
4834 self.span_err(self.prev_span,
4835 "lifetime parameters must be declared prior to type parameters");
4837 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4838 // Parse associated type binding.
4840 let ident = self.parse_ident()?;
4842 let ty = self.parse_ty()?;
4843 bindings.push(TypeBinding {
4844 id: ast::DUMMY_NODE_ID,
4847 span: lo.to(self.prev_span),
4849 seen_binding = true;
4850 } else if self.check_type() {
4851 // Parse type argument.
4852 types.push(self.parse_ty()?);
4854 self.span_err(types[types.len() - 1].span,
4855 "type parameters must be declared prior to associated type bindings");
4862 if !self.eat(&token::Comma) {
4866 Ok((lifetimes, types, bindings))
4869 /// Parses an optional `where` clause and places it in `generics`.
4871 /// ```ignore (only-for-syntax-highlight)
4872 /// where T : Trait<U, V> + 'b, 'a : 'b
4874 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4875 maybe_whole!(self, NtWhereClause, |x| x);
4877 let mut where_clause = WhereClause {
4878 id: ast::DUMMY_NODE_ID,
4879 predicates: Vec::new(),
4880 span: syntax_pos::DUMMY_SP,
4883 if !self.eat_keyword(keywords::Where) {
4884 return Ok(where_clause);
4886 let lo = self.prev_span;
4888 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4889 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4890 // change we parse those generics now, but report an error.
4891 if self.choose_generics_over_qpath() {
4892 let generics = self.parse_generics()?;
4893 self.span_err(generics.span,
4894 "generic parameters on `where` clauses are reserved for future use");
4899 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4900 let lifetime = self.expect_lifetime();
4901 // Bounds starting with a colon are mandatory, but possibly empty.
4902 self.expect(&token::Colon)?;
4903 let bounds = self.parse_lt_param_bounds();
4904 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4905 ast::WhereRegionPredicate {
4906 span: lo.to(self.prev_span),
4911 } else if self.check_type() {
4912 // Parse optional `for<'a, 'b>`.
4913 // This `for` is parsed greedily and applies to the whole predicate,
4914 // the bounded type can have its own `for` applying only to it.
4915 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4916 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4917 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4918 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4920 // Parse type with mandatory colon and (possibly empty) bounds,
4921 // or with mandatory equality sign and the second type.
4922 let ty = self.parse_ty()?;
4923 if self.eat(&token::Colon) {
4924 let bounds = self.parse_ty_param_bounds()?;
4925 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4926 ast::WhereBoundPredicate {
4927 span: lo.to(self.prev_span),
4928 bound_generic_params: lifetime_defs,
4933 // FIXME: Decide what should be used here, `=` or `==`.
4934 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
4935 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4936 let rhs_ty = self.parse_ty()?;
4937 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4938 ast::WhereEqPredicate {
4939 span: lo.to(self.prev_span),
4942 id: ast::DUMMY_NODE_ID,
4946 return self.unexpected();
4952 if !self.eat(&token::Comma) {
4957 where_clause.span = lo.to(self.prev_span);
4961 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4962 -> PResult<'a, (Vec<Arg> , bool)> {
4964 let mut variadic = false;
4965 let args: Vec<Option<Arg>> =
4966 self.parse_unspanned_seq(
4967 &token::OpenDelim(token::Paren),
4968 &token::CloseDelim(token::Paren),
4969 SeqSep::trailing_allowed(token::Comma),
4971 if p.token == token::DotDotDot {
4975 if p.token != token::CloseDelim(token::Paren) {
4978 "`...` must be last in argument list for variadic function");
4982 let span = p.prev_span;
4983 if p.token == token::CloseDelim(token::Paren) {
4984 // continue parsing to present any further errors
4987 "only foreign functions are allowed to be variadic"
4989 Ok(Some(dummy_arg(span)))
4991 // this function definition looks beyond recovery, stop parsing
4993 "only foreign functions are allowed to be variadic");
4998 match p.parse_arg_general(named_args) {
4999 Ok(arg) => Ok(Some(arg)),
5002 let lo = p.prev_span;
5003 // Skip every token until next possible arg or end.
5004 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5005 // Create a placeholder argument for proper arg count (#34264).
5006 let span = lo.to(p.prev_span);
5007 Ok(Some(dummy_arg(span)))
5014 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5016 if variadic && args.is_empty() {
5018 "variadic function must be declared with at least one named argument");
5021 Ok((args, variadic))
5024 /// Parse the argument list and result type of a function declaration
5025 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5027 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5028 let ret_ty = self.parse_ret_ty(true)?;
5037 /// Returns the parsed optional self argument and whether a self shortcut was used.
5038 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5039 let expect_ident = |this: &mut Self| match this.token {
5040 // Preserve hygienic context.
5041 token::Ident(ident, _) =>
5042 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5045 let isolated_self = |this: &mut Self, n| {
5046 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5047 this.look_ahead(n + 1, |t| t != &token::ModSep)
5050 // Parse optional self parameter of a method.
5051 // Only a limited set of initial token sequences is considered self parameters, anything
5052 // else is parsed as a normal function parameter list, so some lookahead is required.
5053 let eself_lo = self.span;
5054 let (eself, eself_ident) = match self.token {
5055 token::BinOp(token::And) => {
5061 if isolated_self(self, 1) {
5063 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
5064 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5065 isolated_self(self, 2) {
5068 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
5069 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5070 isolated_self(self, 2) {
5072 let lt = self.expect_lifetime();
5073 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
5074 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5075 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5076 isolated_self(self, 3) {
5078 let lt = self.expect_lifetime();
5080 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
5085 token::BinOp(token::Star) => {
5090 // Emit special error for `self` cases.
5091 if isolated_self(self, 1) {
5093 self.span_err(self.span, "cannot pass `self` by raw pointer");
5094 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
5095 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5096 isolated_self(self, 2) {
5099 self.span_err(self.span, "cannot pass `self` by raw pointer");
5100 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
5105 token::Ident(..) => {
5106 if isolated_self(self, 0) {
5109 let eself_ident = expect_ident(self);
5110 if self.eat(&token::Colon) {
5111 let ty = self.parse_ty()?;
5112 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
5114 (SelfKind::Value(Mutability::Immutable), eself_ident)
5116 } else if self.token.is_keyword(keywords::Mut) &&
5117 isolated_self(self, 1) {
5121 let eself_ident = expect_ident(self);
5122 if self.eat(&token::Colon) {
5123 let ty = self.parse_ty()?;
5124 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
5126 (SelfKind::Value(Mutability::Mutable), eself_ident)
5132 _ => return Ok(None),
5135 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
5136 Ok(Some(Arg::from_self(eself, eself_ident)))
5139 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5140 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5141 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5143 self.expect(&token::OpenDelim(token::Paren))?;
5145 // Parse optional self argument
5146 let self_arg = self.parse_self_arg()?;
5148 // Parse the rest of the function parameter list.
5149 let sep = SeqSep::trailing_allowed(token::Comma);
5150 let fn_inputs = if let Some(self_arg) = self_arg {
5151 if self.check(&token::CloseDelim(token::Paren)) {
5153 } else if self.eat(&token::Comma) {
5154 let mut fn_inputs = vec![self_arg];
5155 fn_inputs.append(&mut self.parse_seq_to_before_end(
5156 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5160 return self.unexpected();
5163 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5166 // Parse closing paren and return type.
5167 self.expect(&token::CloseDelim(token::Paren))?;
5170 output: self.parse_ret_ty(true)?,
5175 // parse the |arg, arg| header on a lambda
5176 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5177 let inputs_captures = {
5178 if self.eat(&token::OrOr) {
5181 self.expect(&token::BinOp(token::Or))?;
5182 let args = self.parse_seq_to_before_tokens(
5183 &[&token::BinOp(token::Or), &token::OrOr],
5184 SeqSep::trailing_allowed(token::Comma),
5185 TokenExpectType::NoExpect,
5186 |p| p.parse_fn_block_arg()
5192 let output = self.parse_ret_ty(true)?;
5195 inputs: inputs_captures,
5201 /// Parse the name and optional generic types of a function header.
5202 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5203 let id = self.parse_ident()?;
5204 let generics = self.parse_generics()?;
5208 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5209 attrs: Vec<Attribute>) -> P<Item> {
5213 id: ast::DUMMY_NODE_ID,
5221 /// Parse an item-position function declaration.
5222 fn parse_item_fn(&mut self,
5224 constness: Spanned<Constness>,
5226 -> PResult<'a, ItemInfo> {
5227 let (ident, mut generics) = self.parse_fn_header()?;
5228 let decl = self.parse_fn_decl(false)?;
5229 generics.where_clause = self.parse_where_clause()?;
5230 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5231 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
5234 /// true if we are looking at `const ID`, false for things like `const fn` etc
5235 pub fn is_const_item(&mut self) -> bool {
5236 self.token.is_keyword(keywords::Const) &&
5237 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5238 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5241 /// parses all the "front matter" for a `fn` declaration, up to
5242 /// and including the `fn` keyword:
5246 /// - `const unsafe fn`
5249 pub fn parse_fn_front_matter(&mut self) -> PResult<'a, (Spanned<Constness>, Unsafety, Abi)> {
5250 let is_const_fn = self.eat_keyword(keywords::Const);
5251 let const_span = self.prev_span;
5252 let unsafety = self.parse_unsafety();
5253 let (constness, unsafety, abi) = if is_const_fn {
5254 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5256 let abi = if self.eat_keyword(keywords::Extern) {
5257 self.parse_opt_abi()?.unwrap_or(Abi::C)
5261 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5263 self.expect_keyword(keywords::Fn)?;
5264 Ok((constness, unsafety, abi))
5267 /// Parse an impl item.
5268 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5269 maybe_whole!(self, NtImplItem, |x| x);
5270 let attrs = self.parse_outer_attributes()?;
5271 let (mut item, tokens) = self.collect_tokens(|this| {
5272 this.parse_impl_item_(at_end, attrs)
5275 // See `parse_item` for why this clause is here.
5276 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5277 item.tokens = Some(tokens);
5282 fn parse_impl_item_(&mut self,
5284 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5286 let vis = self.parse_visibility(false)?;
5287 let defaultness = self.parse_defaultness();
5288 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
5289 // This parses the grammar:
5290 // ImplItemAssocTy = Ident ["<"...">"] ["where" ...] "=" Ty ";"
5291 let name = self.parse_ident()?;
5292 let mut generics = self.parse_generics()?;
5293 generics.where_clause = self.parse_where_clause()?;
5294 self.expect(&token::Eq)?;
5295 let typ = self.parse_ty()?;
5296 self.expect(&token::Semi)?;
5297 (name, ast::ImplItemKind::Type(typ), generics)
5298 } else if self.is_const_item() {
5299 // This parses the grammar:
5300 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5301 self.expect_keyword(keywords::Const)?;
5302 let name = self.parse_ident()?;
5303 self.expect(&token::Colon)?;
5304 let typ = self.parse_ty()?;
5305 self.expect(&token::Eq)?;
5306 let expr = self.parse_expr()?;
5307 self.expect(&token::Semi)?;
5308 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5310 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5311 attrs.extend(inner_attrs);
5312 (name, node, generics)
5316 id: ast::DUMMY_NODE_ID,
5317 span: lo.to(self.prev_span),
5328 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5329 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5334 fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5336 VisibilityKind::Inherited => Ok(()),
5338 let is_macro_rules: bool = match self.token {
5339 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5343 let mut err = self.diagnostic()
5344 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5345 err.span_suggestion(sp,
5346 "try exporting the macro",
5347 "#[macro_export]".to_owned());
5350 let mut err = self.diagnostic()
5351 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5352 err.help("try adjusting the macro to put `pub` inside the invocation");
5359 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5360 -> DiagnosticBuilder<'a>
5362 let expected_kinds = if item_type == "extern" {
5363 "missing `fn`, `type`, or `static`"
5365 "missing `fn`, `type`, or `const`"
5368 // Given this code `path(`, it seems like this is not
5369 // setting the visibility of a macro invocation, but rather
5370 // a mistyped method declaration.
5371 // Create a diagnostic pointing out that `fn` is missing.
5373 // x | pub path(&self) {
5374 // | ^ missing `fn`, `type`, or `const`
5376 // ^^ `sp` below will point to this
5377 let sp = prev_span.between(self.prev_span);
5378 let mut err = self.diagnostic().struct_span_err(
5380 &format!("{} for {}-item declaration",
5381 expected_kinds, item_type));
5382 err.span_label(sp, expected_kinds);
5386 /// Parse a method or a macro invocation in a trait impl.
5387 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5388 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5389 ast::ImplItemKind)> {
5390 // code copied from parse_macro_use_or_failure... abstraction!
5391 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5393 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5394 ast::ImplItemKind::Macro(mac)))
5396 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
5397 let ident = self.parse_ident()?;
5398 let mut generics = self.parse_generics()?;
5399 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5400 generics.where_clause = self.parse_where_clause()?;
5402 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5403 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(ast::MethodSig {
5412 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5413 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5414 let ident = self.parse_ident()?;
5415 let mut tps = self.parse_generics()?;
5417 // Parse optional colon and supertrait bounds.
5418 let bounds = if self.eat(&token::Colon) {
5419 self.parse_ty_param_bounds()?
5424 if self.eat(&token::Eq) {
5425 // it's a trait alias
5426 let bounds = self.parse_ty_param_bounds()?;
5427 tps.where_clause = self.parse_where_clause()?;
5428 self.expect(&token::Semi)?;
5429 if unsafety != Unsafety::Normal {
5430 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5432 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5434 // it's a normal trait
5435 tps.where_clause = self.parse_where_clause()?;
5436 self.expect(&token::OpenDelim(token::Brace))?;
5437 let mut trait_items = vec![];
5438 while !self.eat(&token::CloseDelim(token::Brace)) {
5439 let mut at_end = false;
5440 match self.parse_trait_item(&mut at_end) {
5441 Ok(item) => trait_items.push(item),
5445 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5450 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5454 fn choose_generics_over_qpath(&self) -> bool {
5455 // There's an ambiguity between generic parameters and qualified paths in impls.
5456 // If we see `<` it may start both, so we have to inspect some following tokens.
5457 // The following combinations can only start generics,
5458 // but not qualified paths (with one exception):
5459 // `<` `>` - empty generic parameters
5460 // `<` `#` - generic parameters with attributes
5461 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5462 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5463 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5464 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5465 // The only truly ambiguous case is
5466 // `<` IDENT `>` `::` IDENT ...
5467 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5468 // because this is what almost always expected in practice, qualified paths in impls
5469 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5470 self.token == token::Lt &&
5471 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5472 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5473 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5474 t == &token::Colon || t == &token::Eq))
5477 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5478 self.expect(&token::OpenDelim(token::Brace))?;
5479 let attrs = self.parse_inner_attributes()?;
5481 let mut impl_items = Vec::new();
5482 while !self.eat(&token::CloseDelim(token::Brace)) {
5483 let mut at_end = false;
5484 match self.parse_impl_item(&mut at_end) {
5485 Ok(impl_item) => impl_items.push(impl_item),
5489 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5494 Ok((impl_items, attrs))
5497 /// Parses an implementation item, `impl` keyword is already parsed.
5498 /// impl<'a, T> TYPE { /* impl items */ }
5499 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5500 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5501 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5502 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5503 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5504 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5505 -> PResult<'a, ItemInfo> {
5506 // First, parse generic parameters if necessary.
5507 let mut generics = if self.choose_generics_over_qpath() {
5508 self.parse_generics()?
5510 ast::Generics::default()
5513 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5514 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5516 ast::ImplPolarity::Negative
5518 ast::ImplPolarity::Positive
5521 // Parse both types and traits as a type, then reinterpret if necessary.
5522 let ty_first = self.parse_ty()?;
5524 // If `for` is missing we try to recover.
5525 let has_for = self.eat_keyword(keywords::For);
5526 let missing_for_span = self.prev_span.between(self.span);
5528 let ty_second = if self.token == token::DotDot {
5529 // We need to report this error after `cfg` expansion for compatibility reasons
5530 self.bump(); // `..`, do not add it to expected tokens
5531 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5532 } else if has_for || self.token.can_begin_type() {
5533 Some(self.parse_ty()?)
5538 generics.where_clause = self.parse_where_clause()?;
5540 let (impl_items, attrs) = self.parse_impl_body()?;
5542 let item_kind = match ty_second {
5543 Some(ty_second) => {
5544 // impl Trait for Type
5546 self.span_err(missing_for_span, "missing `for` in a trait impl");
5549 let ty_first = ty_first.into_inner();
5550 let path = match ty_first.node {
5551 // This notably includes paths passed through `ty` macro fragments (#46438).
5552 TyKind::Path(None, path) => path,
5554 self.span_err(ty_first.span, "expected a trait, found type");
5555 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
5558 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5560 ItemKind::Impl(unsafety, polarity, defaultness,
5561 generics, Some(trait_ref), ty_second, impl_items)
5565 ItemKind::Impl(unsafety, polarity, defaultness,
5566 generics, None, ty_first, impl_items)
5570 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5573 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5574 if self.eat_keyword(keywords::For) {
5576 let params = self.parse_generic_params()?;
5578 // We rely on AST validation to rule out invalid cases: There must not be type
5579 // parameters, and the lifetime parameters must not have bounds.
5586 /// Parse struct Foo { ... }
5587 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5588 let class_name = self.parse_ident()?;
5590 let mut generics = self.parse_generics()?;
5592 // There is a special case worth noting here, as reported in issue #17904.
5593 // If we are parsing a tuple struct it is the case that the where clause
5594 // should follow the field list. Like so:
5596 // struct Foo<T>(T) where T: Copy;
5598 // If we are parsing a normal record-style struct it is the case
5599 // that the where clause comes before the body, and after the generics.
5600 // So if we look ahead and see a brace or a where-clause we begin
5601 // parsing a record style struct.
5603 // Otherwise if we look ahead and see a paren we parse a tuple-style
5606 let vdata = if self.token.is_keyword(keywords::Where) {
5607 generics.where_clause = self.parse_where_clause()?;
5608 if self.eat(&token::Semi) {
5609 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5610 VariantData::Unit(ast::DUMMY_NODE_ID)
5612 // If we see: `struct Foo<T> where T: Copy { ... }`
5613 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5615 // No `where` so: `struct Foo<T>;`
5616 } else if self.eat(&token::Semi) {
5617 VariantData::Unit(ast::DUMMY_NODE_ID)
5618 // Record-style struct definition
5619 } else if self.token == token::OpenDelim(token::Brace) {
5620 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5621 // Tuple-style struct definition with optional where-clause.
5622 } else if self.token == token::OpenDelim(token::Paren) {
5623 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5624 generics.where_clause = self.parse_where_clause()?;
5625 self.expect(&token::Semi)?;
5628 let token_str = self.this_token_to_string();
5629 let mut err = self.fatal(&format!(
5630 "expected `where`, `{{`, `(`, or `;` after struct name, found `{}`",
5633 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
5637 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5640 /// Parse union Foo { ... }
5641 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5642 let class_name = self.parse_ident()?;
5644 let mut generics = self.parse_generics()?;
5646 let vdata = if self.token.is_keyword(keywords::Where) {
5647 generics.where_clause = self.parse_where_clause()?;
5648 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5649 } else if self.token == token::OpenDelim(token::Brace) {
5650 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5652 let token_str = self.this_token_to_string();
5653 let mut err = self.fatal(&format!(
5654 "expected `where` or `{{` after union name, found `{}`", token_str));
5655 err.span_label(self.span, "expected `where` or `{` after union name");
5659 Ok((class_name, ItemKind::Union(vdata, generics), None))
5662 fn consume_block(&mut self, delim: token::DelimToken) {
5663 let mut brace_depth = 0;
5664 if !self.eat(&token::OpenDelim(delim)) {
5668 if self.eat(&token::OpenDelim(delim)) {
5670 } else if self.eat(&token::CloseDelim(delim)) {
5671 if brace_depth == 0 {
5677 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5685 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5686 let mut fields = Vec::new();
5687 if self.eat(&token::OpenDelim(token::Brace)) {
5688 while self.token != token::CloseDelim(token::Brace) {
5689 let field = self.parse_struct_decl_field().map_err(|e| {
5690 self.recover_stmt();
5694 Ok(field) => fields.push(field),
5700 self.eat(&token::CloseDelim(token::Brace));
5702 let token_str = self.this_token_to_string();
5703 let mut err = self.fatal(&format!(
5704 "expected `where`, or `{{` after struct name, found `{}`", token_str));
5705 err.span_label(self.span, "expected `where`, or `{` after struct name");
5712 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5713 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5714 // Unit like structs are handled in parse_item_struct function
5715 let fields = self.parse_unspanned_seq(
5716 &token::OpenDelim(token::Paren),
5717 &token::CloseDelim(token::Paren),
5718 SeqSep::trailing_allowed(token::Comma),
5720 let attrs = p.parse_outer_attributes()?;
5722 let vis = p.parse_visibility(true)?;
5723 let ty = p.parse_ty()?;
5725 span: lo.to(p.span),
5728 id: ast::DUMMY_NODE_ID,
5737 /// Parse a structure field declaration
5738 pub fn parse_single_struct_field(&mut self,
5741 attrs: Vec<Attribute> )
5742 -> PResult<'a, StructField> {
5743 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5748 token::CloseDelim(token::Brace) => {}
5749 token::DocComment(_) => {
5750 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
5751 self.bump(); // consume the doc comment
5752 if self.eat(&token::Comma) || self.token == token::CloseDelim(token::Brace) {
5758 _ => return Err(self.span_fatal_help(self.span,
5759 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5760 "struct fields should be separated by commas")),
5765 /// Parse an element of a struct definition
5766 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5767 let attrs = self.parse_outer_attributes()?;
5769 let vis = self.parse_visibility(false)?;
5770 self.parse_single_struct_field(lo, vis, attrs)
5773 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5774 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5775 /// a function definition, it's not a tuple struct field) and the contents within the parens
5776 /// isn't valid, emit a proper diagnostic.
5777 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5778 maybe_whole!(self, NtVis, |x| x);
5780 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
5781 if self.is_crate_vis() {
5782 self.bump(); // `crate`
5783 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
5786 if !self.eat_keyword(keywords::Pub) {
5787 return Ok(respan(self.prev_span, VisibilityKind::Inherited))
5789 let lo = self.prev_span;
5791 if self.check(&token::OpenDelim(token::Paren)) {
5792 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5793 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5794 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5795 // by the following tokens.
5796 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5799 self.bump(); // `crate`
5800 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5802 lo.to(self.prev_span),
5803 VisibilityKind::Crate(CrateSugar::PubCrate),
5806 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5809 self.bump(); // `in`
5810 let path = self.parse_path(PathStyle::Mod)?; // `path`
5811 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5812 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
5814 id: ast::DUMMY_NODE_ID,
5817 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5818 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5819 t.is_keyword(keywords::SelfValue))
5821 // `pub(self)` or `pub(super)`
5823 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
5824 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5825 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
5827 id: ast::DUMMY_NODE_ID,
5830 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5831 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5833 let msg = "incorrect visibility restriction";
5834 let suggestion = r##"some possible visibility restrictions are:
5835 `pub(crate)`: visible only on the current crate
5836 `pub(super)`: visible only in the current module's parent
5837 `pub(in path::to::module)`: visible only on the specified path"##;
5838 let path = self.parse_path(PathStyle::Mod)?;
5839 let path_span = self.prev_span;
5840 let help_msg = format!("make this visible only to module `{}` with `in`", path);
5841 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5842 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5843 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5844 err.emit(); // emit diagnostic, but continue with public visibility
5848 Ok(respan(lo, VisibilityKind::Public))
5851 /// Parse defaultness: `default` or nothing.
5852 fn parse_defaultness(&mut self) -> Defaultness {
5853 // `pub` is included for better error messages
5854 if self.check_keyword(keywords::Default) &&
5855 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
5856 t.is_keyword(keywords::Const) ||
5857 t.is_keyword(keywords::Fn) ||
5858 t.is_keyword(keywords::Unsafe) ||
5859 t.is_keyword(keywords::Extern) ||
5860 t.is_keyword(keywords::Type) ||
5861 t.is_keyword(keywords::Pub)) {
5862 self.bump(); // `default`
5863 Defaultness::Default
5869 /// Given a termination token, parse all of the items in a module
5870 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5871 let mut items = vec![];
5872 while let Some(item) = self.parse_item()? {
5876 if !self.eat(term) {
5877 let token_str = self.this_token_to_string();
5878 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
5879 if token_str == ";" {
5880 let msg = "consider removing this semicolon";
5881 err.span_suggestion_short(self.span, msg, "".to_string());
5883 err.span_label(self.span, "expected item");
5888 let hi = if self.span == syntax_pos::DUMMY_SP {
5895 inner: inner_lo.to(hi),
5900 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5901 let id = self.parse_ident()?;
5902 self.expect(&token::Colon)?;
5903 let ty = self.parse_ty()?;
5904 self.expect(&token::Eq)?;
5905 let e = self.parse_expr()?;
5906 self.expect(&token::Semi)?;
5907 let item = match m {
5908 Some(m) => ItemKind::Static(ty, m, e),
5909 None => ItemKind::Const(ty, e),
5911 Ok((id, item, None))
5914 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5915 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5916 let (in_cfg, outer_attrs) = {
5917 let mut strip_unconfigured = ::config::StripUnconfigured {
5919 should_test: false, // irrelevant
5920 features: None, // don't perform gated feature checking
5922 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5923 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5926 let id_span = self.span;
5927 let id = self.parse_ident()?;
5928 if self.check(&token::Semi) {
5930 if in_cfg && self.recurse_into_file_modules {
5931 // This mod is in an external file. Let's go get it!
5932 let ModulePathSuccess { path, directory_ownership, warn } =
5933 self.submod_path(id, &outer_attrs, id_span)?;
5934 let (module, mut attrs) =
5935 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5937 let attr = Attribute {
5938 id: attr::mk_attr_id(),
5939 style: ast::AttrStyle::Outer,
5940 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
5941 tokens: TokenStream::empty(),
5942 is_sugared_doc: false,
5943 span: syntax_pos::DUMMY_SP,
5945 attr::mark_known(&attr);
5948 Ok((id, module, Some(attrs)))
5950 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5951 Ok((id, ItemKind::Mod(placeholder), None))
5954 let old_directory = self.directory.clone();
5955 self.push_directory(id, &outer_attrs);
5957 self.expect(&token::OpenDelim(token::Brace))?;
5958 let mod_inner_lo = self.span;
5959 let attrs = self.parse_inner_attributes()?;
5960 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5962 self.directory = old_directory;
5963 Ok((id, ItemKind::Mod(module), Some(attrs)))
5967 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5968 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5969 self.directory.path.push(&path.as_str());
5970 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
5972 self.directory.path.push(&id.name.as_str());
5976 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
5977 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5980 /// Returns either a path to a module, or .
5981 pub fn default_submod_path(
5983 relative: Option<ast::Ident>,
5985 codemap: &CodeMap) -> ModulePath
5987 // If we're in a foo.rs file instead of a mod.rs file,
5988 // we need to look for submodules in
5989 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
5990 // `./<id>.rs` and `./<id>/mod.rs`.
5991 let relative_prefix_string;
5992 let relative_prefix = if let Some(ident) = relative {
5993 relative_prefix_string = format!("{}{}", ident.name.as_str(), path::MAIN_SEPARATOR);
5994 &relative_prefix_string
5999 let mod_name = id.to_string();
6000 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6001 let secondary_path_str = format!("{}{}{}mod.rs",
6002 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6003 let default_path = dir_path.join(&default_path_str);
6004 let secondary_path = dir_path.join(&secondary_path_str);
6005 let default_exists = codemap.file_exists(&default_path);
6006 let secondary_exists = codemap.file_exists(&secondary_path);
6008 let result = match (default_exists, secondary_exists) {
6009 (true, false) => Ok(ModulePathSuccess {
6011 directory_ownership: DirectoryOwnership::Owned {
6016 (false, true) => Ok(ModulePathSuccess {
6017 path: secondary_path,
6018 directory_ownership: DirectoryOwnership::Owned {
6023 (false, false) => Err(Error::FileNotFoundForModule {
6024 mod_name: mod_name.clone(),
6025 default_path: default_path_str,
6026 secondary_path: secondary_path_str,
6027 dir_path: format!("{}", dir_path.display()),
6029 (true, true) => Err(Error::DuplicatePaths {
6030 mod_name: mod_name.clone(),
6031 default_path: default_path_str,
6032 secondary_path: secondary_path_str,
6038 path_exists: default_exists || secondary_exists,
6043 fn submod_path(&mut self,
6045 outer_attrs: &[Attribute],
6047 -> PResult<'a, ModulePathSuccess> {
6048 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6049 return Ok(ModulePathSuccess {
6050 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6051 // All `#[path]` files are treated as though they are a `mod.rs` file.
6052 // This means that `mod foo;` declarations inside `#[path]`-included
6053 // files are siblings,
6055 // Note that this will produce weirdness when a file named `foo.rs` is
6056 // `#[path]` included and contains a `mod foo;` declaration.
6057 // If you encounter this, it's your own darn fault :P
6058 Some(_) => DirectoryOwnership::Owned { relative: None },
6059 _ => DirectoryOwnership::UnownedViaMod(true),
6066 let relative = match self.directory.ownership {
6067 DirectoryOwnership::Owned { relative } => {
6068 // Push the usage onto the list of non-mod.rs mod uses.
6069 // This is used later for feature-gate error reporting.
6070 if let Some(cur_file_ident) = relative {
6072 .non_modrs_mods.borrow_mut()
6073 .push((cur_file_ident, id_sp));
6077 DirectoryOwnership::UnownedViaBlock |
6078 DirectoryOwnership::UnownedViaMod(_) => None,
6080 let paths = Parser::default_submod_path(
6081 id, relative, &self.directory.path, self.sess.codemap());
6083 match self.directory.ownership {
6084 DirectoryOwnership::Owned { .. } => {
6085 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6087 DirectoryOwnership::UnownedViaBlock => {
6089 "Cannot declare a non-inline module inside a block \
6090 unless it has a path attribute";
6091 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6092 if paths.path_exists {
6093 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6095 err.span_note(id_sp, &msg);
6099 DirectoryOwnership::UnownedViaMod(warn) => {
6101 if let Ok(result) = paths.result {
6102 return Ok(ModulePathSuccess { warn: true, ..result });
6105 let mut err = self.diagnostic().struct_span_err(id_sp,
6106 "cannot declare a new module at this location");
6107 if id_sp != syntax_pos::DUMMY_SP {
6108 let src_path = self.sess.codemap().span_to_filename(id_sp);
6109 if let FileName::Real(src_path) = src_path {
6110 if let Some(stem) = src_path.file_stem() {
6111 let mut dest_path = src_path.clone();
6112 dest_path.set_file_name(stem);
6113 dest_path.push("mod.rs");
6114 err.span_note(id_sp,
6115 &format!("maybe move this module `{}` to its own \
6116 directory via `{}`", src_path.display(),
6117 dest_path.display()));
6121 if paths.path_exists {
6122 err.span_note(id_sp,
6123 &format!("... or maybe `use` the module `{}` instead \
6124 of possibly redeclaring it",
6132 /// Read a module from a source file.
6133 fn eval_src_mod(&mut self,
6135 directory_ownership: DirectoryOwnership,
6138 -> PResult<'a, (ast::ItemKind, Vec<Attribute> )> {
6139 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6140 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6141 let mut err = String::from("circular modules: ");
6142 let len = included_mod_stack.len();
6143 for p in &included_mod_stack[i.. len] {
6144 err.push_str(&p.to_string_lossy());
6145 err.push_str(" -> ");
6147 err.push_str(&path.to_string_lossy());
6148 return Err(self.span_fatal(id_sp, &err[..]));
6150 included_mod_stack.push(path.clone());
6151 drop(included_mod_stack);
6154 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6155 p0.cfg_mods = self.cfg_mods;
6156 let mod_inner_lo = p0.span;
6157 let mod_attrs = p0.parse_inner_attributes()?;
6158 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6159 self.sess.included_mod_stack.borrow_mut().pop();
6160 Ok((ast::ItemKind::Mod(m0), mod_attrs))
6163 /// Parse a function declaration from a foreign module
6164 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6165 -> PResult<'a, ForeignItem> {
6166 self.expect_keyword(keywords::Fn)?;
6168 let (ident, mut generics) = self.parse_fn_header()?;
6169 let decl = self.parse_fn_decl(true)?;
6170 generics.where_clause = self.parse_where_clause()?;
6172 self.expect(&token::Semi)?;
6173 Ok(ast::ForeignItem {
6176 node: ForeignItemKind::Fn(decl, generics),
6177 id: ast::DUMMY_NODE_ID,
6183 /// Parse a static item from a foreign module.
6184 /// Assumes that the `static` keyword is already parsed.
6185 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6186 -> PResult<'a, ForeignItem> {
6187 let mutbl = self.eat_keyword(keywords::Mut);
6188 let ident = self.parse_ident()?;
6189 self.expect(&token::Colon)?;
6190 let ty = self.parse_ty()?;
6192 self.expect(&token::Semi)?;
6196 node: ForeignItemKind::Static(ty, mutbl),
6197 id: ast::DUMMY_NODE_ID,
6203 /// Parse a type from a foreign module
6204 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6205 -> PResult<'a, ForeignItem> {
6206 self.expect_keyword(keywords::Type)?;
6208 let ident = self.parse_ident()?;
6210 self.expect(&token::Semi)?;
6211 Ok(ast::ForeignItem {
6214 node: ForeignItemKind::Ty,
6215 id: ast::DUMMY_NODE_ID,
6221 /// Parse extern crate links
6225 /// extern crate foo;
6226 /// extern crate bar as foo;
6227 fn parse_item_extern_crate(&mut self,
6229 visibility: Visibility,
6230 attrs: Vec<Attribute>)
6231 -> PResult<'a, P<Item>> {
6232 let orig_name = self.parse_ident()?;
6233 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6234 (rename, Some(orig_name.name))
6238 self.expect(&token::Semi)?;
6240 let span = lo.to(self.prev_span);
6241 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6244 /// Parse `extern` for foreign ABIs
6247 /// `extern` is expected to have been
6248 /// consumed before calling this method
6254 fn parse_item_foreign_mod(&mut self,
6256 opt_abi: Option<Abi>,
6257 visibility: Visibility,
6258 mut attrs: Vec<Attribute>)
6259 -> PResult<'a, P<Item>> {
6260 self.expect(&token::OpenDelim(token::Brace))?;
6262 let abi = opt_abi.unwrap_or(Abi::C);
6264 attrs.extend(self.parse_inner_attributes()?);
6266 let mut foreign_items = vec![];
6267 while let Some(item) = self.parse_foreign_item()? {
6268 foreign_items.push(item);
6270 self.expect(&token::CloseDelim(token::Brace))?;
6272 let prev_span = self.prev_span;
6273 let m = ast::ForeignMod {
6275 items: foreign_items
6277 let invalid = keywords::Invalid.ident();
6278 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6281 /// Parse type Foo = Bar;
6282 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
6283 let ident = self.parse_ident()?;
6284 let mut tps = self.parse_generics()?;
6285 tps.where_clause = self.parse_where_clause()?;
6286 self.expect(&token::Eq)?;
6287 let ty = self.parse_ty()?;
6288 self.expect(&token::Semi)?;
6289 Ok((ident, ItemKind::Ty(ty, tps), None))
6292 /// Parse the part of an "enum" decl following the '{'
6293 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6294 let mut variants = Vec::new();
6295 let mut all_nullary = true;
6296 let mut any_disr = None;
6297 while self.token != token::CloseDelim(token::Brace) {
6298 let variant_attrs = self.parse_outer_attributes()?;
6299 let vlo = self.span;
6302 let mut disr_expr = None;
6303 let ident = self.parse_ident()?;
6304 if self.check(&token::OpenDelim(token::Brace)) {
6305 // Parse a struct variant.
6306 all_nullary = false;
6307 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6308 ast::DUMMY_NODE_ID);
6309 } else if self.check(&token::OpenDelim(token::Paren)) {
6310 all_nullary = false;
6311 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6312 ast::DUMMY_NODE_ID);
6313 } else if self.eat(&token::Eq) {
6314 disr_expr = Some(self.parse_expr()?);
6315 any_disr = disr_expr.as_ref().map(|expr| expr.span);
6316 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6318 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6321 let vr = ast::Variant_ {
6323 attrs: variant_attrs,
6327 variants.push(respan(vlo.to(self.prev_span), vr));
6329 if !self.eat(&token::Comma) { break; }
6331 self.expect(&token::CloseDelim(token::Brace))?;
6333 Some(disr_span) if !all_nullary =>
6334 self.span_err(disr_span,
6335 "discriminator values can only be used with a field-less enum"),
6339 Ok(ast::EnumDef { variants: variants })
6342 /// Parse an "enum" declaration
6343 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6344 let id = self.parse_ident()?;
6345 let mut generics = self.parse_generics()?;
6346 generics.where_clause = self.parse_where_clause()?;
6347 self.expect(&token::OpenDelim(token::Brace))?;
6349 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6350 self.recover_stmt();
6351 self.eat(&token::CloseDelim(token::Brace));
6354 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6357 /// Parses a string as an ABI spec on an extern type or module. Consumes
6358 /// the `extern` keyword, if one is found.
6359 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6361 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6363 self.expect_no_suffix(sp, "ABI spec", suf);
6365 match abi::lookup(&s.as_str()) {
6366 Some(abi) => Ok(Some(abi)),
6368 let prev_span = self.prev_span;
6371 &format!("invalid ABI: expected one of [{}], \
6373 abi::all_names().join(", "),
6384 fn is_static_global(&mut self) -> bool {
6385 if self.check_keyword(keywords::Static) {
6386 // Check if this could be a closure
6387 !self.look_ahead(1, |token| {
6388 if token.is_keyword(keywords::Move) {
6392 token::BinOp(token::Or) | token::OrOr => true,
6401 /// Parse one of the items allowed by the flags.
6402 /// NB: this function no longer parses the items inside an
6404 fn parse_item_(&mut self, attrs: Vec<Attribute>,
6405 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
6406 maybe_whole!(self, NtItem, |item| {
6407 let mut item = item.into_inner();
6408 let mut attrs = attrs;
6409 mem::swap(&mut item.attrs, &mut attrs);
6410 item.attrs.extend(attrs);
6416 let visibility = self.parse_visibility(false)?;
6418 if self.eat_keyword(keywords::Use) {
6420 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
6421 self.expect(&token::Semi)?;
6423 let span = lo.to(self.prev_span);
6424 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
6425 return Ok(Some(item));
6428 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6429 self.bump(); // `extern`
6430 if self.eat_keyword(keywords::Crate) {
6431 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6434 let opt_abi = self.parse_opt_abi()?;
6436 if self.eat_keyword(keywords::Fn) {
6437 // EXTERN FUNCTION ITEM
6438 let fn_span = self.prev_span;
6439 let abi = opt_abi.unwrap_or(Abi::C);
6440 let (ident, item_, extra_attrs) =
6441 self.parse_item_fn(Unsafety::Normal,
6442 respan(fn_span, Constness::NotConst),
6444 let prev_span = self.prev_span;
6445 let item = self.mk_item(lo.to(prev_span),
6449 maybe_append(attrs, extra_attrs));
6450 return Ok(Some(item));
6451 } else if self.check(&token::OpenDelim(token::Brace)) {
6452 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6458 if self.is_static_global() {
6461 let m = if self.eat_keyword(keywords::Mut) {
6464 Mutability::Immutable
6466 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6467 let prev_span = self.prev_span;
6468 let item = self.mk_item(lo.to(prev_span),
6472 maybe_append(attrs, extra_attrs));
6473 return Ok(Some(item));
6475 if self.eat_keyword(keywords::Const) {
6476 let const_span = self.prev_span;
6477 if self.check_keyword(keywords::Fn)
6478 || (self.check_keyword(keywords::Unsafe)
6479 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6480 // CONST FUNCTION ITEM
6481 let unsafety = self.parse_unsafety();
6483 let (ident, item_, extra_attrs) =
6484 self.parse_item_fn(unsafety,
6485 respan(const_span, Constness::Const),
6487 let prev_span = self.prev_span;
6488 let item = self.mk_item(lo.to(prev_span),
6492 maybe_append(attrs, extra_attrs));
6493 return Ok(Some(item));
6497 if self.eat_keyword(keywords::Mut) {
6498 let prev_span = self.prev_span;
6499 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6500 .help("did you mean to declare a static?")
6503 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
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.check_keyword(keywords::Unsafe) &&
6513 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
6514 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
6516 // UNSAFE TRAIT ITEM
6517 self.bump(); // `unsafe`
6518 let is_auto = if self.eat_keyword(keywords::Trait) {
6521 self.expect_keyword(keywords::Auto)?;
6522 self.expect_keyword(keywords::Trait)?;
6525 let (ident, item_, extra_attrs) =
6526 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
6527 let prev_span = self.prev_span;
6528 let item = self.mk_item(lo.to(prev_span),
6532 maybe_append(attrs, extra_attrs));
6533 return Ok(Some(item));
6535 if self.check_keyword(keywords::Impl) ||
6536 self.check_keyword(keywords::Unsafe) &&
6537 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6538 self.check_keyword(keywords::Default) &&
6539 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6540 self.check_keyword(keywords::Default) &&
6541 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
6543 let defaultness = self.parse_defaultness();
6544 let unsafety = self.parse_unsafety();
6545 self.expect_keyword(keywords::Impl)?;
6546 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
6547 let span = lo.to(self.prev_span);
6548 return Ok(Some(self.mk_item(span, ident, item, visibility,
6549 maybe_append(attrs, extra_attrs))));
6551 if self.check_keyword(keywords::Fn) {
6554 let fn_span = self.prev_span;
6555 let (ident, item_, extra_attrs) =
6556 self.parse_item_fn(Unsafety::Normal,
6557 respan(fn_span, Constness::NotConst),
6559 let prev_span = self.prev_span;
6560 let item = self.mk_item(lo.to(prev_span),
6564 maybe_append(attrs, extra_attrs));
6565 return Ok(Some(item));
6567 if self.check_keyword(keywords::Unsafe)
6568 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
6569 // UNSAFE FUNCTION ITEM
6570 self.bump(); // `unsafe`
6571 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
6572 self.check(&token::OpenDelim(token::Brace));
6573 let abi = if self.eat_keyword(keywords::Extern) {
6574 self.parse_opt_abi()?.unwrap_or(Abi::C)
6578 self.expect_keyword(keywords::Fn)?;
6579 let fn_span = self.prev_span;
6580 let (ident, item_, extra_attrs) =
6581 self.parse_item_fn(Unsafety::Unsafe,
6582 respan(fn_span, Constness::NotConst),
6584 let prev_span = self.prev_span;
6585 let item = self.mk_item(lo.to(prev_span),
6589 maybe_append(attrs, extra_attrs));
6590 return Ok(Some(item));
6592 if self.eat_keyword(keywords::Mod) {
6594 let (ident, item_, extra_attrs) =
6595 self.parse_item_mod(&attrs[..])?;
6596 let prev_span = self.prev_span;
6597 let item = self.mk_item(lo.to(prev_span),
6601 maybe_append(attrs, extra_attrs));
6602 return Ok(Some(item));
6604 if self.eat_keyword(keywords::Type) {
6606 let (ident, item_, extra_attrs) = self.parse_item_type()?;
6607 let prev_span = self.prev_span;
6608 let item = self.mk_item(lo.to(prev_span),
6612 maybe_append(attrs, extra_attrs));
6613 return Ok(Some(item));
6615 if self.eat_keyword(keywords::Enum) {
6617 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
6618 let prev_span = self.prev_span;
6619 let item = self.mk_item(lo.to(prev_span),
6623 maybe_append(attrs, extra_attrs));
6624 return Ok(Some(item));
6626 if self.check_keyword(keywords::Trait)
6627 || (self.check_keyword(keywords::Auto)
6628 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
6630 let is_auto = if self.eat_keyword(keywords::Trait) {
6633 self.expect_keyword(keywords::Auto)?;
6634 self.expect_keyword(keywords::Trait)?;
6638 let (ident, item_, extra_attrs) =
6639 self.parse_item_trait(is_auto, Unsafety::Normal)?;
6640 let prev_span = self.prev_span;
6641 let item = self.mk_item(lo.to(prev_span),
6645 maybe_append(attrs, extra_attrs));
6646 return Ok(Some(item));
6648 if self.eat_keyword(keywords::Struct) {
6650 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6651 let prev_span = self.prev_span;
6652 let item = self.mk_item(lo.to(prev_span),
6656 maybe_append(attrs, extra_attrs));
6657 return Ok(Some(item));
6659 if self.is_union_item() {
6662 let (ident, item_, extra_attrs) = self.parse_item_union()?;
6663 let prev_span = self.prev_span;
6664 let item = self.mk_item(lo.to(prev_span),
6668 maybe_append(attrs, extra_attrs));
6669 return Ok(Some(item));
6671 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
6672 return Ok(Some(macro_def));
6675 // Verify whether we have encountered a struct or method definition where the user forgot to
6676 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
6677 if visibility.node == VisibilityKind::Public &&
6678 self.check_ident() &&
6679 self.look_ahead(1, |t| *t != token::Not)
6681 // Space between `pub` keyword and the identifier
6684 // ^^^ `sp` points here
6685 let sp = self.prev_span.between(self.span);
6686 let full_sp = self.prev_span.to(self.span);
6687 let ident_sp = self.span;
6688 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
6689 // possible public struct definition where `struct` was forgotten
6690 let ident = self.parse_ident().unwrap();
6691 let msg = format!("add `struct` here to parse `{}` as a public struct",
6693 let mut err = self.diagnostic()
6694 .struct_span_err(sp, "missing `struct` for struct definition");
6695 err.span_suggestion_short(sp, &msg, " struct ".into());
6697 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
6698 let ident = self.parse_ident().unwrap();
6699 self.consume_block(token::Paren);
6700 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
6701 self.check(&token::OpenDelim(token::Brace))
6703 ("fn", "method", false)
6704 } else if self.check(&token::Colon) {
6708 ("fn` or `struct", "method or struct", true)
6711 let msg = format!("missing `{}` for {} definition", kw, kw_name);
6712 let mut err = self.diagnostic().struct_span_err(sp, &msg);
6714 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
6718 err.span_suggestion_short(sp, &suggestion, format!(" {} ", kw));
6720 if let Ok(snippet) = self.sess.codemap().span_to_snippet(ident_sp) {
6721 err.span_suggestion(
6723 "if you meant to call a macro, write instead",
6724 format!("{}!", snippet));
6726 err.help("if you meant to call a macro, remove the `pub` \
6727 and add a trailing `!` after the identifier");
6733 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
6736 /// Parse a foreign item.
6737 pub fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
6738 maybe_whole!(self, NtForeignItem, |ni| Some(ni));
6740 let attrs = self.parse_outer_attributes()?;
6742 let visibility = self.parse_visibility(false)?;
6744 // FOREIGN STATIC ITEM
6745 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
6746 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
6747 if self.token.is_keyword(keywords::Const) {
6749 .struct_span_err(self.span, "extern items cannot be `const`")
6750 .span_suggestion(self.span, "instead try using", "static".to_owned())
6753 self.bump(); // `static` or `const`
6754 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6756 // FOREIGN FUNCTION ITEM
6757 if self.check_keyword(keywords::Fn) {
6758 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6760 // FOREIGN TYPE ITEM
6761 if self.check_keyword(keywords::Type) {
6762 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
6765 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
6769 ident: keywords::Invalid.ident(),
6770 span: lo.to(self.prev_span),
6771 id: ast::DUMMY_NODE_ID,
6774 node: ForeignItemKind::Macro(mac),
6779 if !attrs.is_empty() {
6780 self.expected_item_err(&attrs);
6788 /// This is the fall-through for parsing items.
6789 fn parse_macro_use_or_failure(
6791 attrs: Vec<Attribute> ,
6792 macros_allowed: bool,
6793 attributes_allowed: bool,
6795 visibility: Visibility
6796 ) -> PResult<'a, Option<P<Item>>> {
6797 if macros_allowed && self.token.is_path_start() {
6798 // MACRO INVOCATION ITEM
6800 let prev_span = self.prev_span;
6801 self.complain_if_pub_macro(&visibility.node, prev_span);
6803 let mac_lo = self.span;
6806 let pth = self.parse_path(PathStyle::Mod)?;
6807 self.expect(&token::Not)?;
6809 // a 'special' identifier (like what `macro_rules!` uses)
6810 // is optional. We should eventually unify invoc syntax
6812 let id = if self.token.is_ident() {
6815 keywords::Invalid.ident() // no special identifier
6817 // eat a matched-delimiter token tree:
6818 let (delim, tts) = self.expect_delimited_token_tree()?;
6819 if delim != token::Brace {
6820 if !self.eat(&token::Semi) {
6821 self.span_err(self.prev_span,
6822 "macros that expand to items must either \
6823 be surrounded with braces or followed by \
6828 let hi = self.prev_span;
6829 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6830 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6831 return Ok(Some(item));
6834 // FAILURE TO PARSE ITEM
6835 match visibility.node {
6836 VisibilityKind::Inherited => {}
6838 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
6842 if !attributes_allowed && !attrs.is_empty() {
6843 self.expected_item_err(&attrs);
6848 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
6849 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
6850 at_end: &mut bool) -> PResult<'a, Option<Mac>>
6852 if self.token.is_path_start() && !self.is_extern_non_path() {
6853 let prev_span = self.prev_span;
6855 let pth = self.parse_path(PathStyle::Mod)?;
6857 if pth.segments.len() == 1 {
6858 if !self.eat(&token::Not) {
6859 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
6862 self.expect(&token::Not)?;
6865 if let Some(vis) = vis {
6866 self.complain_if_pub_macro(&vis.node, prev_span);
6871 // eat a matched-delimiter token tree:
6872 let (delim, tts) = self.expect_delimited_token_tree()?;
6873 if delim != token::Brace {
6874 self.expect(&token::Semi)?
6877 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts })))
6883 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
6884 where F: FnOnce(&mut Self) -> PResult<'a, R>
6886 // Record all tokens we parse when parsing this item.
6887 let mut tokens = Vec::new();
6888 match self.token_cursor.frame.last_token {
6889 LastToken::Collecting(_) => {
6890 panic!("cannot collect tokens recursively yet")
6892 LastToken::Was(ref mut last) => tokens.extend(last.take()),
6894 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
6895 let prev = self.token_cursor.stack.len();
6897 let last_token = if self.token_cursor.stack.len() == prev {
6898 &mut self.token_cursor.frame.last_token
6900 &mut self.token_cursor.stack[prev].last_token
6902 let mut tokens = match *last_token {
6903 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
6904 LastToken::Was(_) => panic!("our vector went away?"),
6907 // If we're not at EOF our current token wasn't actually consumed by
6908 // `f`, but it'll still be in our list that we pulled out. In that case
6910 if self.token == token::Eof {
6911 *last_token = LastToken::Was(None);
6913 *last_token = LastToken::Was(tokens.pop());
6916 Ok((ret?, tokens.into_iter().collect()))
6919 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6920 let attrs = self.parse_outer_attributes()?;
6922 let (ret, tokens) = self.collect_tokens(|this| {
6923 this.parse_item_(attrs, true, false)
6926 // Once we've parsed an item and recorded the tokens we got while
6927 // parsing we may want to store `tokens` into the item we're about to
6928 // return. Note, though, that we specifically didn't capture tokens
6929 // related to outer attributes. The `tokens` field here may later be
6930 // used with procedural macros to convert this item back into a token
6931 // stream, but during expansion we may be removing attributes as we go
6934 // If we've got inner attributes then the `tokens` we've got above holds
6935 // these inner attributes. If an inner attribute is expanded we won't
6936 // actually remove it from the token stream, so we'll just keep yielding
6937 // it (bad!). To work around this case for now we just avoid recording
6938 // `tokens` if we detect any inner attributes. This should help keep
6939 // expansion correct, but we should fix this bug one day!
6942 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6943 i.tokens = Some(tokens);
6951 fn is_import_coupler(&mut self) -> bool {
6952 self.check(&token::ModSep) &&
6953 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6954 *t == token::BinOp(token::Star))
6959 /// USE_TREE = [`::`] `*` |
6960 /// [`::`] `{` USE_TREE_LIST `}` |
6962 /// PATH `::` `{` USE_TREE_LIST `}` |
6963 /// PATH [`as` IDENT]
6964 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
6967 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
6968 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
6969 self.check(&token::BinOp(token::Star)) ||
6970 self.is_import_coupler() {
6971 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
6972 if self.eat(&token::ModSep) {
6973 prefix.segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
6976 if self.eat(&token::BinOp(token::Star)) {
6979 UseTreeKind::Nested(self.parse_use_tree_list()?)
6982 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
6983 prefix = self.parse_path(PathStyle::Mod)?;
6985 if self.eat(&token::ModSep) {
6986 if self.eat(&token::BinOp(token::Star)) {
6989 UseTreeKind::Nested(self.parse_use_tree_list()?)
6992 UseTreeKind::Simple(self.parse_rename()?)
6996 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
6999 /// Parse UseTreeKind::Nested(list)
7001 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7002 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7003 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7004 &token::CloseDelim(token::Brace),
7005 SeqSep::trailing_allowed(token::Comma), |this| {
7006 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7010 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7011 if self.eat_keyword(keywords::As) {
7013 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
7015 Ok(Some(Ident { name: ident.name.gensymed(), ..ident }))
7017 _ => self.parse_ident().map(Some),
7024 /// Parses a source module as a crate. This is the main
7025 /// entry point for the parser.
7026 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7029 attrs: self.parse_inner_attributes()?,
7030 module: self.parse_mod_items(&token::Eof, lo)?,
7031 span: lo.to(self.span),
7035 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7036 let ret = match self.token {
7037 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7038 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7045 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7046 match self.parse_optional_str() {
7047 Some((s, style, suf)) => {
7048 let sp = self.prev_span;
7049 self.expect_no_suffix(sp, "string literal", suf);
7053 let msg = "expected string literal";
7054 let mut err = self.fatal(msg);
7055 err.span_label(self.span, msg);