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::obsolete::ObsoleteSyntax;
52 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
53 use util::parser::{AssocOp, Fixity};
57 use tokenstream::{self, Delimited, ThinTokenStream, TokenTree, TokenStream};
58 use symbol::{Symbol, keywords};
62 use std::collections::HashSet;
64 use std::path::{self, Path, PathBuf};
68 pub struct Restrictions: u8 {
69 const STMT_EXPR = 1 << 0;
70 const NO_STRUCT_LITERAL = 1 << 1;
74 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
76 /// How to parse a path.
77 #[derive(Copy, Clone, PartialEq)]
79 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
80 /// with something else. For example, in expressions `segment < ....` can be interpreted
81 /// as a comparison and `segment ( ....` can be interpreted as a function call.
82 /// In all such contexts the non-path interpretation is preferred by default for practical
83 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
84 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
86 /// In other contexts, notably in types, no ambiguity exists and paths can be written
87 /// without the disambiguator, e.g. `x<y>` - unambiguously a path.
88 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
90 /// A path with generic arguments disallowed, e.g. `foo::bar::Baz`, used in imports,
91 /// visibilities or attributes.
92 /// Technically, this variant is unnecessary and e.g. `Expr` can be used instead
93 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
94 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
95 /// tokens when something goes wrong.
99 #[derive(Clone, Copy, Debug, PartialEq)]
100 pub enum SemiColonMode {
105 #[derive(Clone, Copy, Debug, PartialEq)]
111 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
112 /// dropped into the token stream, which happens while parsing the result of
113 /// macro expansion). Placement of these is not as complex as I feared it would
114 /// be. The important thing is to make sure that lookahead doesn't balk at
115 /// `token::Interpolated` tokens.
116 macro_rules! maybe_whole_expr {
118 if let token::Interpolated(nt) = $p.token.clone() {
120 token::NtExpr(ref e) => {
122 return Ok((*e).clone());
124 token::NtPath(ref path) => {
127 let kind = ExprKind::Path(None, (*path).clone());
128 return Ok($p.mk_expr(span, kind, ThinVec::new()));
130 token::NtBlock(ref block) => {
133 let kind = ExprKind::Block((*block).clone());
134 return Ok($p.mk_expr(span, kind, ThinVec::new()));
142 /// As maybe_whole_expr, but for things other than expressions
143 macro_rules! maybe_whole {
144 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
145 if let token::Interpolated(nt) = $p.token.clone() {
146 if let token::$constructor($x) = nt.0.clone() {
154 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
155 if let Some(ref mut rhs) = rhs {
161 #[derive(Debug, Clone, Copy, PartialEq)]
172 trait RecoverQPath: Sized {
173 const PATH_STYLE: PathStyle = PathStyle::Expr;
174 fn to_ty(&self) -> Option<P<Ty>>;
175 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self;
176 fn to_string(&self) -> String;
179 impl RecoverQPath for Ty {
180 const PATH_STYLE: PathStyle = PathStyle::Type;
181 fn to_ty(&self) -> Option<P<Ty>> {
182 Some(P(self.clone()))
184 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
185 Self { span: path.span, node: TyKind::Path(qself, path), id: self.id }
187 fn to_string(&self) -> String {
188 pprust::ty_to_string(self)
192 impl RecoverQPath for Pat {
193 fn to_ty(&self) -> Option<P<Ty>> {
196 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
197 Self { span: path.span, node: PatKind::Path(qself, path), id: self.id }
199 fn to_string(&self) -> String {
200 pprust::pat_to_string(self)
204 impl RecoverQPath for Expr {
205 fn to_ty(&self) -> Option<P<Ty>> {
208 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
209 Self { span: path.span, node: ExprKind::Path(qself, path),
210 id: self.id, attrs: self.attrs.clone() }
212 fn to_string(&self) -> String {
213 pprust::expr_to_string(self)
217 /* ident is handled by common.rs */
220 pub struct Parser<'a> {
221 pub sess: &'a ParseSess,
222 /// the current token:
223 pub token: token::Token,
224 /// the span of the current token:
226 /// the span of the previous token:
227 pub meta_var_span: Option<Span>,
229 /// the previous token kind
230 prev_token_kind: PrevTokenKind,
231 pub restrictions: Restrictions,
232 /// The set of seen errors about obsolete syntax. Used to suppress
233 /// extra detail when the same error is seen twice
234 pub obsolete_set: HashSet<ObsoleteSyntax>,
235 /// Used to determine the path to externally loaded source files
236 pub directory: Directory,
237 /// Whether to parse sub-modules in other files.
238 pub recurse_into_file_modules: bool,
239 /// Name of the root module this parser originated from. If `None`, then the
240 /// name is not known. This does not change while the parser is descending
241 /// into modules, and sub-parsers have new values for this name.
242 pub root_module_name: Option<String>,
243 pub expected_tokens: Vec<TokenType>,
244 token_cursor: TokenCursor,
245 pub desugar_doc_comments: bool,
246 /// Whether we should configure out of line modules as we parse.
253 frame: TokenCursorFrame,
254 stack: Vec<TokenCursorFrame>,
258 struct TokenCursorFrame {
259 delim: token::DelimToken,
262 tree_cursor: tokenstream::Cursor,
264 last_token: LastToken,
267 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
268 /// by the parser, and then that's transitively used to record the tokens that
269 /// each parse AST item is created with.
271 /// Right now this has two states, either collecting tokens or not collecting
272 /// tokens. If we're collecting tokens we just save everything off into a local
273 /// `Vec`. This should eventually though likely save tokens from the original
274 /// token stream and just use slicing of token streams to avoid creation of a
275 /// whole new vector.
277 /// The second state is where we're passively not recording tokens, but the last
278 /// token is still tracked for when we want to start recording tokens. This
279 /// "last token" means that when we start recording tokens we'll want to ensure
280 /// that this, the first token, is included in the output.
282 /// You can find some more example usage of this in the `collect_tokens` method
286 Collecting(Vec<TokenTree>),
287 Was(Option<TokenTree>),
290 impl TokenCursorFrame {
291 fn new(sp: Span, delimited: &Delimited) -> Self {
293 delim: delimited.delim,
295 open_delim: delimited.delim == token::NoDelim,
296 tree_cursor: delimited.stream().into_trees(),
297 close_delim: delimited.delim == token::NoDelim,
298 last_token: LastToken::Was(None),
304 fn next(&mut self) -> TokenAndSpan {
306 let tree = if !self.frame.open_delim {
307 self.frame.open_delim = true;
308 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
309 .open_tt(self.frame.span)
310 } else if let Some(tree) = self.frame.tree_cursor.next() {
312 } else if !self.frame.close_delim {
313 self.frame.close_delim = true;
314 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
315 .close_tt(self.frame.span)
316 } else if let Some(frame) = self.stack.pop() {
320 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
323 match self.frame.last_token {
324 LastToken::Collecting(ref mut v) => v.push(tree.clone()),
325 LastToken::Was(ref mut t) => *t = Some(tree.clone()),
329 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
330 TokenTree::Delimited(sp, ref delimited) => {
331 let frame = TokenCursorFrame::new(sp, delimited);
332 self.stack.push(mem::replace(&mut self.frame, frame));
338 fn next_desugared(&mut self) -> TokenAndSpan {
339 let (sp, name) = match self.next() {
340 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
344 let stripped = strip_doc_comment_decoration(&name.as_str());
346 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
347 // required to wrap the text.
348 let mut num_of_hashes = 0;
350 for ch in stripped.chars() {
353 '#' if count > 0 => count + 1,
356 num_of_hashes = cmp::max(num_of_hashes, count);
359 let body = TokenTree::Delimited(sp, Delimited {
360 delim: token::Bracket,
361 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"))),
362 TokenTree::Token(sp, token::Eq),
363 TokenTree::Token(sp, token::Literal(
364 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
365 .iter().cloned().collect::<TokenStream>().into(),
368 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
369 delim: token::NoDelim,
370 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
371 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
372 .iter().cloned().collect::<TokenStream>().into()
374 [TokenTree::Token(sp, token::Pound), body]
375 .iter().cloned().collect::<TokenStream>().into()
383 #[derive(PartialEq, Eq, Clone)]
386 Keyword(keywords::Keyword),
395 fn to_string(&self) -> String {
397 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
398 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
399 TokenType::Operator => "an operator".to_string(),
400 TokenType::Lifetime => "lifetime".to_string(),
401 TokenType::Ident => "identifier".to_string(),
402 TokenType::Path => "path".to_string(),
403 TokenType::Type => "type".to_string(),
408 /// Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
409 /// `IDENT<<u8 as Trait>::AssocTy>`.
411 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
412 /// that IDENT is not the ident of a fn trait
413 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
414 t == &token::ModSep || t == &token::Lt ||
415 t == &token::BinOp(token::Shl)
418 /// Information about the path to a module.
419 pub struct ModulePath {
421 pub path_exists: bool,
422 pub result: Result<ModulePathSuccess, Error>,
425 pub struct ModulePathSuccess {
427 pub directory_ownership: DirectoryOwnership,
431 pub struct ModulePathError {
433 pub help_msg: String,
437 FileNotFoundForModule {
439 default_path: String,
440 secondary_path: String,
445 default_path: String,
446 secondary_path: String,
449 InclusiveRangeWithNoEnd,
453 pub fn span_err<S: Into<MultiSpan>>(self,
455 handler: &errors::Handler) -> DiagnosticBuilder {
457 Error::FileNotFoundForModule { ref mod_name,
461 let mut err = struct_span_err!(handler, sp, E0583,
462 "file not found for module `{}`", mod_name);
463 err.help(&format!("name the file either {} or {} inside the directory {:?}",
469 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
470 let mut err = struct_span_err!(handler, sp, E0584,
471 "file for module `{}` found at both {} and {}",
475 err.help("delete or rename one of them to remove the ambiguity");
478 Error::UselessDocComment => {
479 let mut err = struct_span_err!(handler, sp, E0585,
480 "found a documentation comment that doesn't document anything");
481 err.help("doc comments must come before what they document, maybe a comment was \
482 intended with `//`?");
485 Error::InclusiveRangeWithNoEnd => {
486 let mut err = struct_span_err!(handler, sp, E0586,
487 "inclusive range with no end");
488 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
498 AttributesParsed(ThinVec<Attribute>),
499 AlreadyParsed(P<Expr>),
502 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
503 fn from(o: Option<ThinVec<Attribute>>) -> Self {
504 if let Some(attrs) = o {
505 LhsExpr::AttributesParsed(attrs)
507 LhsExpr::NotYetParsed
512 impl From<P<Expr>> for LhsExpr {
513 fn from(expr: P<Expr>) -> Self {
514 LhsExpr::AlreadyParsed(expr)
518 /// Create a placeholder argument.
519 fn dummy_arg(span: Span) -> Arg {
520 let spanned = Spanned {
522 node: keywords::Invalid.ident()
525 id: ast::DUMMY_NODE_ID,
526 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), spanned, None),
532 id: ast::DUMMY_NODE_ID
534 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
537 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
538 enum TokenExpectType {
543 impl<'a> Parser<'a> {
544 pub fn new(sess: &'a ParseSess,
546 directory: Option<Directory>,
547 recurse_into_file_modules: bool,
548 desugar_doc_comments: bool)
550 let mut parser = Parser {
552 token: token::Whitespace,
553 span: syntax_pos::DUMMY_SP,
554 prev_span: syntax_pos::DUMMY_SP,
556 prev_token_kind: PrevTokenKind::Other,
557 restrictions: Restrictions::empty(),
558 obsolete_set: HashSet::new(),
559 recurse_into_file_modules,
560 directory: Directory {
561 path: PathBuf::new(),
562 ownership: DirectoryOwnership::Owned { relative: None }
564 root_module_name: None,
565 expected_tokens: Vec::new(),
566 token_cursor: TokenCursor {
567 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
568 delim: token::NoDelim,
573 desugar_doc_comments,
577 let tok = parser.next_tok();
578 parser.token = tok.tok;
579 parser.span = tok.sp;
581 if let Some(directory) = directory {
582 parser.directory = directory;
583 } else if !parser.span.source_equal(&DUMMY_SP) {
584 if let FileName::Real(path) = sess.codemap().span_to_unmapped_path(parser.span) {
585 parser.directory.path = path;
586 parser.directory.path.pop();
590 parser.process_potential_macro_variable();
594 fn next_tok(&mut self) -> TokenAndSpan {
595 let mut next = if self.desugar_doc_comments {
596 self.token_cursor.next_desugared()
598 self.token_cursor.next()
600 if next.sp == syntax_pos::DUMMY_SP {
601 next.sp = self.prev_span;
606 /// Convert a token to a string using self's reader
607 pub fn token_to_string(token: &token::Token) -> String {
608 pprust::token_to_string(token)
611 /// Convert the current token to a string using self's reader
612 pub fn this_token_to_string(&self) -> String {
613 Parser::token_to_string(&self.token)
616 pub fn token_descr(&self) -> Option<&'static str> {
617 Some(match &self.token {
618 t if t.is_special_ident() => "reserved identifier",
619 t if t.is_used_keyword() => "keyword",
620 t if t.is_unused_keyword() => "reserved keyword",
625 pub fn this_token_descr(&self) -> String {
626 if let Some(prefix) = self.token_descr() {
627 format!("{} `{}`", prefix, self.this_token_to_string())
629 format!("`{}`", self.this_token_to_string())
633 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
634 let token_str = Parser::token_to_string(t);
635 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
638 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
639 match self.expect_one_of(&[], &[]) {
641 Ok(_) => unreachable!(),
645 /// Expect and consume the token t. Signal an error if
646 /// the next token is not t.
647 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
648 if self.expected_tokens.is_empty() {
649 if self.token == *t {
653 let token_str = Parser::token_to_string(t);
654 let this_token_str = self.this_token_to_string();
655 let mut err = self.fatal(&format!("expected `{}`, found `{}`",
658 err.span_label(self.span, format!("expected `{}`", token_str));
662 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
666 /// Expect next token to be edible or inedible token. If edible,
667 /// then consume it; if inedible, then return without consuming
668 /// anything. Signal a fatal error if next token is unexpected.
669 pub fn expect_one_of(&mut self,
670 edible: &[token::Token],
671 inedible: &[token::Token]) -> PResult<'a, ()>{
672 fn tokens_to_string(tokens: &[TokenType]) -> String {
673 let mut i = tokens.iter();
674 // This might be a sign we need a connect method on Iterator.
676 .map_or("".to_string(), |t| t.to_string());
677 i.enumerate().fold(b, |mut b, (i, a)| {
678 if tokens.len() > 2 && i == tokens.len() - 2 {
680 } else if tokens.len() == 2 && i == tokens.len() - 2 {
685 b.push_str(&a.to_string());
689 if edible.contains(&self.token) {
692 } else if inedible.contains(&self.token) {
693 // leave it in the input
696 let mut expected = edible.iter()
697 .map(|x| TokenType::Token(x.clone()))
698 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
699 .chain(self.expected_tokens.iter().cloned())
700 .collect::<Vec<_>>();
701 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
703 let expect = tokens_to_string(&expected[..]);
704 let actual = self.this_token_to_string();
705 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
706 let short_expect = if expected.len() > 6 {
707 format!("{} possible tokens", expected.len())
711 (format!("expected one of {}, found `{}`", expect, actual),
712 (self.sess.codemap().next_point(self.prev_span),
713 format!("expected one of {} here", short_expect)))
714 } else if expected.is_empty() {
715 (format!("unexpected token: `{}`", actual),
716 (self.prev_span, "unexpected token after this".to_string()))
718 (format!("expected {}, found `{}`", expect, actual),
719 (self.sess.codemap().next_point(self.prev_span),
720 format!("expected {} here", expect)))
722 let mut err = self.fatal(&msg_exp);
723 let sp = if self.token == token::Token::Eof {
724 // This is EOF, don't want to point at the following char, but rather the last token
730 let cm = self.sess.codemap();
731 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
732 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
733 // When the spans are in the same line, it means that the only content between
734 // them is whitespace, point at the found token in that case:
736 // X | () => { syntax error };
737 // | ^^^^^ expected one of 8 possible tokens here
739 // instead of having:
741 // X | () => { syntax error };
742 // | -^^^^^ unexpected token
744 // | expected one of 8 possible tokens here
745 err.span_label(self.span, label_exp);
748 err.span_label(sp, label_exp);
749 err.span_label(self.span, "unexpected token");
756 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
757 fn interpolated_or_expr_span(&self,
758 expr: PResult<'a, P<Expr>>)
759 -> PResult<'a, (Span, P<Expr>)> {
761 if self.prev_token_kind == PrevTokenKind::Interpolated {
769 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
770 let mut err = self.struct_span_err(self.span,
771 &format!("expected identifier, found {}",
772 self.this_token_descr()));
773 if let Some(token_descr) = self.token_descr() {
774 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
776 err.span_label(self.span, "expected identifier");
781 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
782 self.parse_ident_common(true)
785 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
788 if self.token.is_reserved_ident() {
789 let mut err = self.expected_ident_found();
800 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
801 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
803 self.expected_ident_found()
809 /// Check if the next token is `tok`, and return `true` if so.
811 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
813 pub fn check(&mut self, tok: &token::Token) -> bool {
814 let is_present = self.token == *tok;
815 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
819 /// Consume token 'tok' if it exists. Returns true if the given
820 /// token was present, false otherwise.
821 pub fn eat(&mut self, tok: &token::Token) -> bool {
822 let is_present = self.check(tok);
823 if is_present { self.bump() }
827 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
828 self.expected_tokens.push(TokenType::Keyword(kw));
829 self.token.is_keyword(kw)
832 /// If the next token is the given keyword, eat it and return
833 /// true. Otherwise, return false.
834 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
835 if self.check_keyword(kw) {
843 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
844 if self.token.is_keyword(kw) {
852 /// If the given word is not a keyword, signal an error.
853 /// If the next token is not the given word, signal an error.
854 /// Otherwise, eat it.
855 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
856 if !self.eat_keyword(kw) {
863 fn check_ident(&mut self) -> bool {
864 if self.token.is_ident() {
867 self.expected_tokens.push(TokenType::Ident);
872 fn check_path(&mut self) -> bool {
873 if self.token.is_path_start() {
876 self.expected_tokens.push(TokenType::Path);
881 fn check_type(&mut self) -> bool {
882 if self.token.can_begin_type() {
885 self.expected_tokens.push(TokenType::Type);
890 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
891 /// `&` and continue. If an `&` is not seen, signal an error.
892 fn expect_and(&mut self) -> PResult<'a, ()> {
893 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
895 token::BinOp(token::And) => {
900 let span = self.span.with_lo(self.span.lo() + BytePos(1));
901 Ok(self.bump_with(token::BinOp(token::And), span))
903 _ => self.unexpected()
907 /// Expect and consume an `|`. If `||` is seen, replace it with a single
908 /// `|` and continue. If an `|` is not seen, signal an error.
909 fn expect_or(&mut self) -> PResult<'a, ()> {
910 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
912 token::BinOp(token::Or) => {
917 let span = self.span.with_lo(self.span.lo() + BytePos(1));
918 Ok(self.bump_with(token::BinOp(token::Or), span))
920 _ => self.unexpected()
924 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
926 None => {/* everything ok */}
928 let text = suf.as_str();
930 self.span_bug(sp, "found empty literal suffix in Some")
932 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
937 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
938 /// `<` and continue. If a `<` is not seen, return false.
940 /// This is meant to be used when parsing generics on a path to get the
942 fn eat_lt(&mut self) -> bool {
943 self.expected_tokens.push(TokenType::Token(token::Lt));
949 token::BinOp(token::Shl) => {
950 let span = self.span.with_lo(self.span.lo() + BytePos(1));
951 self.bump_with(token::Lt, span);
958 fn expect_lt(&mut self) -> PResult<'a, ()> {
966 /// Expect and consume a GT. if a >> is seen, replace it
967 /// with a single > and continue. If a GT is not seen,
969 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
970 self.expected_tokens.push(TokenType::Token(token::Gt));
976 token::BinOp(token::Shr) => {
977 let span = self.span.with_lo(self.span.lo() + BytePos(1));
978 Ok(self.bump_with(token::Gt, span))
980 token::BinOpEq(token::Shr) => {
981 let span = self.span.with_lo(self.span.lo() + BytePos(1));
982 Ok(self.bump_with(token::Ge, span))
985 let span = self.span.with_lo(self.span.lo() + BytePos(1));
986 Ok(self.bump_with(token::Eq, span))
988 _ => self.unexpected()
992 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
993 sep: Option<token::Token>,
995 -> PResult<'a, (Vec<T>, bool)>
996 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
998 let mut v = Vec::new();
999 // This loop works by alternating back and forth between parsing types
1000 // and commas. For example, given a string `A, B,>`, the parser would
1001 // first parse `A`, then a comma, then `B`, then a comma. After that it
1002 // would encounter a `>` and stop. This lets the parser handle trailing
1003 // commas in generic parameters, because it can stop either after
1004 // parsing a type or after parsing a comma.
1006 if self.check(&token::Gt)
1007 || self.token == token::BinOp(token::Shr)
1008 || self.token == token::Ge
1009 || self.token == token::BinOpEq(token::Shr) {
1015 Some(result) => v.push(result),
1016 None => return Ok((v, true))
1019 if let Some(t) = sep.as_ref() {
1025 return Ok((v, false));
1028 /// Parse a sequence bracketed by '<' and '>', stopping
1030 pub fn parse_seq_to_before_gt<T, F>(&mut self,
1031 sep: Option<token::Token>,
1033 -> PResult<'a, Vec<T>> where
1034 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1036 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
1037 |p| Ok(Some(f(p)?)))?;
1042 pub fn parse_seq_to_gt<T, F>(&mut self,
1043 sep: Option<token::Token>,
1045 -> PResult<'a, Vec<T>> where
1046 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1048 let v = self.parse_seq_to_before_gt(sep, f)?;
1053 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
1054 sep: Option<token::Token>,
1056 -> PResult<'a, (Vec<T>, bool)> where
1057 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
1059 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
1063 return Ok((v, returned));
1066 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1067 /// passes through any errors encountered. Used for error recovery.
1068 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1069 let handler = self.diagnostic();
1071 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1073 TokenExpectType::Expect,
1074 |p| Ok(p.parse_token_tree())) {
1075 handler.cancel(err);
1079 /// Parse a sequence, including the closing delimiter. The function
1080 /// f must consume tokens until reaching the next separator or
1081 /// closing bracket.
1082 pub fn parse_seq_to_end<T, F>(&mut self,
1086 -> PResult<'a, Vec<T>> where
1087 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1089 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1094 /// Parse a sequence, not including the closing delimiter. The function
1095 /// f must consume tokens until reaching the next separator or
1096 /// closing bracket.
1097 pub fn parse_seq_to_before_end<T, F>(&mut self,
1101 -> PResult<'a, Vec<T>>
1102 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1104 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1107 fn parse_seq_to_before_tokens<T, F>(&mut self,
1108 kets: &[&token::Token],
1110 expect: TokenExpectType,
1112 -> PResult<'a, Vec<T>>
1113 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1115 let mut first: bool = true;
1117 while !kets.contains(&&self.token) {
1119 token::CloseDelim(..) | token::Eof => break,
1122 if let Some(ref t) = sep.sep {
1126 if let Err(mut e) = self.expect(t) {
1127 // Attempt to keep parsing if it was a similar separator
1128 if let Some(ref tokens) = t.similar_tokens() {
1129 if tokens.contains(&self.token) {
1134 // Attempt to keep parsing if it was an omitted separator
1148 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1150 TokenExpectType::Expect => self.check(k),
1151 TokenExpectType::NoExpect => self.token == **k,
1164 /// Parse a sequence, including the closing delimiter. The function
1165 /// f must consume tokens until reaching the next separator or
1166 /// closing bracket.
1167 pub fn parse_unspanned_seq<T, F>(&mut self,
1172 -> PResult<'a, Vec<T>> where
1173 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1176 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1177 if self.token == *ket {
1183 // NB: Do not use this function unless you actually plan to place the
1184 // spanned list in the AST.
1185 pub fn parse_seq<T, F>(&mut self,
1190 -> PResult<'a, Spanned<Vec<T>>> where
1191 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1195 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1198 Ok(respan(lo.to(hi), result))
1201 /// Advance the parser by one token
1202 pub fn bump(&mut self) {
1203 if self.prev_token_kind == PrevTokenKind::Eof {
1204 // Bumping after EOF is a bad sign, usually an infinite loop.
1205 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1208 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1210 // Record last token kind for possible error recovery.
1211 self.prev_token_kind = match self.token {
1212 token::DocComment(..) => PrevTokenKind::DocComment,
1213 token::Comma => PrevTokenKind::Comma,
1214 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1215 token::Interpolated(..) => PrevTokenKind::Interpolated,
1216 token::Eof => PrevTokenKind::Eof,
1217 token::Ident(..) => PrevTokenKind::Ident,
1218 _ => PrevTokenKind::Other,
1221 let next = self.next_tok();
1222 self.span = next.sp;
1223 self.token = next.tok;
1224 self.expected_tokens.clear();
1225 // check after each token
1226 self.process_potential_macro_variable();
1229 /// Advance the parser using provided token as a next one. Use this when
1230 /// consuming a part of a token. For example a single `<` from `<<`.
1231 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1232 self.prev_span = self.span.with_hi(span.lo());
1233 // It would be incorrect to record the kind of the current token, but
1234 // fortunately for tokens currently using `bump_with`, the
1235 // prev_token_kind will be of no use anyway.
1236 self.prev_token_kind = PrevTokenKind::Other;
1239 self.expected_tokens.clear();
1242 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1243 F: FnOnce(&token::Token) -> R,
1246 return f(&self.token)
1249 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1250 Some(tree) => match tree {
1251 TokenTree::Token(_, tok) => tok,
1252 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1254 None => token::CloseDelim(self.token_cursor.frame.delim),
1258 fn look_ahead_span(&self, dist: usize) -> Span {
1263 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1264 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1265 None => self.look_ahead_span(dist - 1),
1268 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1269 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1271 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1272 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1274 pub fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1275 err.span_err(sp, self.diagnostic())
1277 pub fn span_fatal_help<S: Into<MultiSpan>>(&self,
1280 help: &str) -> DiagnosticBuilder<'a> {
1281 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1285 pub fn bug(&self, m: &str) -> ! {
1286 self.sess.span_diagnostic.span_bug(self.span, m)
1288 pub fn warn(&self, m: &str) {
1289 self.sess.span_diagnostic.span_warn(self.span, m)
1291 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1292 self.sess.span_diagnostic.span_warn(sp, m)
1294 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1295 self.sess.span_diagnostic.span_err(sp, m)
1297 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1298 self.sess.span_diagnostic.struct_span_err(sp, m)
1300 pub fn span_err_help<S: Into<MultiSpan>>(&self, sp: S, m: &str, h: &str) {
1301 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1305 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1306 self.sess.span_diagnostic.span_bug(sp, m)
1308 pub fn abort_if_errors(&self) {
1309 self.sess.span_diagnostic.abort_if_errors();
1312 fn cancel(&self, err: &mut DiagnosticBuilder) {
1313 self.sess.span_diagnostic.cancel(err)
1316 pub fn diagnostic(&self) -> &'a errors::Handler {
1317 &self.sess.span_diagnostic
1320 /// Is the current token one of the keywords that signals a bare function
1322 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1323 self.check_keyword(keywords::Fn) ||
1324 self.check_keyword(keywords::Unsafe) ||
1325 self.check_keyword(keywords::Extern) && self.is_extern_non_path()
1328 fn eat_label(&mut self) -> Option<Label> {
1329 let ident = match self.token {
1330 token::Lifetime(ref ident) => *ident,
1331 token::Interpolated(ref nt) => match nt.0 {
1332 token::NtLifetime(lifetime) => lifetime.ident,
1338 Some(Label { ident, span: self.prev_span })
1341 /// parse a TyKind::BareFn type:
1342 pub fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>)
1343 -> PResult<'a, TyKind> {
1346 [unsafe] [extern "ABI"] fn (S) -> T
1356 let unsafety = self.parse_unsafety();
1357 let abi = if self.eat_keyword(keywords::Extern) {
1358 self.parse_opt_abi()?.unwrap_or(Abi::C)
1363 self.expect_keyword(keywords::Fn)?;
1364 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1365 let ret_ty = self.parse_ret_ty(false)?;
1366 let decl = P(FnDecl {
1371 Ok(TyKind::BareFn(P(BareFnTy {
1379 /// Parse unsafety: `unsafe` or nothing.
1380 fn parse_unsafety(&mut self) -> Unsafety {
1381 if self.eat_keyword(keywords::Unsafe) {
1388 /// Parse the items in a trait declaration
1389 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1390 maybe_whole!(self, NtTraitItem, |x| x);
1391 let attrs = self.parse_outer_attributes()?;
1392 let (mut item, tokens) = self.collect_tokens(|this| {
1393 this.parse_trait_item_(at_end, attrs)
1395 // See `parse_item` for why this clause is here.
1396 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1397 item.tokens = Some(tokens);
1402 fn parse_trait_item_(&mut self,
1404 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1407 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1408 let (generics, TyParam {ident, bounds, default, ..}) =
1409 self.parse_trait_item_assoc_ty(vec![])?;
1410 (ident, TraitItemKind::Type(bounds, default), generics)
1411 } else if self.is_const_item() {
1412 self.expect_keyword(keywords::Const)?;
1413 let ident = self.parse_ident()?;
1414 self.expect(&token::Colon)?;
1415 let ty = self.parse_ty()?;
1416 let default = if self.check(&token::Eq) {
1418 let expr = self.parse_expr()?;
1419 self.expect(&token::Semi)?;
1422 self.expect(&token::Semi)?;
1425 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1426 } else if self.token.is_path_start() && !self.is_extern_non_path() {
1427 // trait item macro.
1428 // code copied from parse_macro_use_or_failure... abstraction!
1429 let prev_span = self.prev_span;
1431 let pth = self.parse_path(PathStyle::Mod)?;
1433 if pth.segments.len() == 1 {
1434 if !self.eat(&token::Not) {
1435 return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1438 self.expect(&token::Not)?;
1441 // eat a matched-delimiter token tree:
1442 let (delim, tts) = self.expect_delimited_token_tree()?;
1443 if delim != token::Brace {
1444 self.expect(&token::Semi)?
1447 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1448 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1450 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
1452 let ident = self.parse_ident()?;
1453 let mut generics = self.parse_generics()?;
1455 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1456 // This is somewhat dubious; We don't want to allow
1457 // argument names to be left off if there is a
1459 p.parse_arg_general(false)
1461 generics.where_clause = self.parse_where_clause()?;
1463 let sig = ast::MethodSig {
1470 let body = match self.token {
1474 debug!("parse_trait_methods(): parsing required method");
1477 token::OpenDelim(token::Brace) => {
1478 debug!("parse_trait_methods(): parsing provided method");
1480 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1481 attrs.extend(inner_attrs.iter().cloned());
1485 let token_str = self.this_token_to_string();
1486 let mut err = self.fatal(&format!("expected `;` or `{{`, found `{}`",
1488 err.span_label(self.span, "expected `;` or `{`");
1492 (ident, ast::TraitItemKind::Method(sig, body), generics)
1496 id: ast::DUMMY_NODE_ID,
1501 span: lo.to(self.prev_span),
1506 /// Parse optional return type [ -> TY ] in function decl
1507 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1508 if self.eat(&token::RArrow) {
1509 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1511 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1516 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1517 self.parse_ty_common(true, true)
1520 /// Parse a type in restricted contexts where `+` is not permitted.
1521 /// Example 1: `&'a TYPE`
1522 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1523 /// Example 2: `value1 as TYPE + value2`
1524 /// `+` is prohibited to avoid interactions with expression grammar.
1525 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1526 self.parse_ty_common(false, true)
1529 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1530 -> PResult<'a, P<Ty>> {
1531 maybe_whole!(self, NtTy, |x| x);
1534 let mut impl_dyn_multi = false;
1535 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1536 // `(TYPE)` is a parenthesized type.
1537 // `(TYPE,)` is a tuple with a single field of type TYPE.
1538 let mut ts = vec![];
1539 let mut last_comma = false;
1540 while self.token != token::CloseDelim(token::Paren) {
1541 ts.push(self.parse_ty()?);
1542 if self.eat(&token::Comma) {
1549 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1550 self.expect(&token::CloseDelim(token::Paren))?;
1552 if ts.len() == 1 && !last_comma {
1553 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1554 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1556 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1557 TyKind::Path(None, ref path) if maybe_bounds => {
1558 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1560 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1561 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1562 let path = match bounds[0] {
1563 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1564 _ => self.bug("unexpected lifetime bound"),
1566 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1569 _ => TyKind::Paren(P(ty))
1574 } else if self.eat(&token::Not) {
1577 } else if self.eat(&token::BinOp(token::Star)) {
1579 TyKind::Ptr(self.parse_ptr()?)
1580 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1582 let t = self.parse_ty()?;
1583 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1584 let t = match self.maybe_parse_fixed_length_of_vec()? {
1585 None => TyKind::Slice(t),
1586 Some(suffix) => TyKind::Array(t, suffix),
1588 self.expect(&token::CloseDelim(token::Bracket))?;
1590 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1593 self.parse_borrowed_pointee()?
1594 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1596 // In order to not be ambiguous, the type must be surrounded by parens.
1597 self.expect(&token::OpenDelim(token::Paren))?;
1598 let e = self.parse_expr()?;
1599 self.expect(&token::CloseDelim(token::Paren))?;
1601 } else if self.eat_keyword(keywords::Underscore) {
1602 // A type to be inferred `_`
1604 } else if self.token_is_bare_fn_keyword() {
1605 // Function pointer type
1606 self.parse_ty_bare_fn(Vec::new())?
1607 } else if self.check_keyword(keywords::For) {
1608 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1609 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1610 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1612 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1613 if self.token_is_bare_fn_keyword() {
1614 self.parse_ty_bare_fn(lifetime_defs)?
1616 let path = self.parse_path(PathStyle::Type)?;
1617 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1618 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1620 } else if self.eat_keyword(keywords::Impl) {
1621 // Always parse bounds greedily for better error recovery.
1622 let bounds = self.parse_ty_param_bounds()?;
1623 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1624 TyKind::ImplTrait(bounds)
1625 } else if self.check_keyword(keywords::Dyn) &&
1626 self.look_ahead(1, |t| t.can_begin_bound() &&
1627 !can_continue_type_after_non_fn_ident(t)) {
1628 self.bump(); // `dyn`
1629 // Always parse bounds greedily for better error recovery.
1630 let bounds = self.parse_ty_param_bounds()?;
1631 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1632 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1633 } else if self.check(&token::Question) ||
1634 self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)) {
1635 // Bound list (trait object type)
1636 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?,
1637 TraitObjectSyntax::None)
1638 } else if self.eat_lt() {
1640 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1641 TyKind::Path(Some(qself), path)
1642 } else if self.token.is_path_start() {
1644 let path = self.parse_path(PathStyle::Type)?;
1645 if self.eat(&token::Not) {
1646 // Macro invocation in type position
1647 let (_, tts) = self.expect_delimited_token_tree()?;
1648 TyKind::Mac(respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts }))
1650 // Just a type path or bound list (trait object type) starting with a trait.
1652 // `Trait1 + Trait2 + 'a`
1653 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1654 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1656 TyKind::Path(None, path)
1660 let msg = format!("expected type, found {}", self.this_token_descr());
1661 return Err(self.fatal(&msg));
1664 let span = lo.to(self.prev_span);
1665 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1667 // Try to recover from use of `+` with incorrect priority.
1668 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1669 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1670 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1675 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1676 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1677 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1678 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1681 bounds.append(&mut self.parse_ty_param_bounds()?);
1683 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1686 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1687 if !allow_plus && impl_dyn_multi {
1688 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1689 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1690 .span_suggestion(ty.span, "use parentheses to disambiguate", sum_with_parens)
1695 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1696 // Do not add `+` to expected tokens.
1697 if !allow_plus || self.token != token::BinOp(token::Plus) {
1702 let bounds = self.parse_ty_param_bounds()?;
1703 let sum_span = ty.span.to(self.prev_span);
1705 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1706 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1709 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1710 let sum_with_parens = pprust::to_string(|s| {
1711 use print::pprust::PrintState;
1714 s.print_opt_lifetime(lifetime)?;
1715 s.print_mutability(mut_ty.mutbl)?;
1717 s.print_type(&mut_ty.ty)?;
1718 s.print_bounds(" +", &bounds)?;
1721 err.span_suggestion(sum_span, "try adding parentheses", sum_with_parens);
1723 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1724 err.span_label(sum_span, "perhaps you forgot parentheses?");
1727 err.span_label(sum_span, "expected a path");
1734 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1735 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1737 // Do not add `::` to expected tokens.
1738 if !allow_recovery || self.token != token::ModSep {
1741 let ty = match base.to_ty() {
1743 None => return Ok(base),
1746 self.bump(); // `::`
1747 let mut segments = Vec::new();
1748 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1750 let span = ty.span.to(self.prev_span);
1752 base.to_recovered(Some(QSelf { ty, position: 0 }), ast::Path { segments, span });
1755 .struct_span_err(span, "missing angle brackets in associated item path")
1756 .span_suggestion(span, "try", recovered.to_string()).emit();
1761 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1762 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1763 let mutbl = self.parse_mutability();
1764 let ty = self.parse_ty_no_plus()?;
1765 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1768 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1769 let mutbl = if self.eat_keyword(keywords::Mut) {
1771 } else if self.eat_keyword(keywords::Const) {
1772 Mutability::Immutable
1774 let span = self.prev_span;
1776 "expected mut or const in raw pointer type (use \
1777 `*mut T` or `*const T` as appropriate)");
1778 Mutability::Immutable
1780 let t = self.parse_ty_no_plus()?;
1781 Ok(MutTy { ty: t, mutbl: mutbl })
1784 fn is_named_argument(&mut self) -> bool {
1785 let offset = match self.token {
1786 token::Interpolated(ref nt) => match nt.0 {
1787 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1790 token::BinOp(token::And) | token::AndAnd => 1,
1791 _ if self.token.is_keyword(keywords::Mut) => 1,
1795 self.look_ahead(offset, |t| t.is_ident()) &&
1796 self.look_ahead(offset + 1, |t| t == &token::Colon)
1799 /// This version of parse arg doesn't necessarily require
1800 /// identifier names.
1801 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1802 maybe_whole!(self, NtArg, |x| x);
1804 let pat = if require_name || self.is_named_argument() {
1805 debug!("parse_arg_general parse_pat (require_name:{})",
1807 let pat = self.parse_pat()?;
1809 self.expect(&token::Colon)?;
1812 debug!("parse_arg_general ident_to_pat");
1813 let sp = self.prev_span;
1814 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1816 id: ast::DUMMY_NODE_ID,
1817 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1823 let t = self.parse_ty()?;
1828 id: ast::DUMMY_NODE_ID,
1832 /// Parse a single function argument
1833 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1834 self.parse_arg_general(true)
1837 /// Parse an argument in a lambda header e.g. |arg, arg|
1838 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1839 let pat = self.parse_pat()?;
1840 let t = if self.eat(&token::Colon) {
1844 id: ast::DUMMY_NODE_ID,
1845 node: TyKind::Infer,
1852 id: ast::DUMMY_NODE_ID
1856 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1857 if self.eat(&token::Semi) {
1858 Ok(Some(self.parse_expr()?))
1864 /// Matches token_lit = LIT_INTEGER | ...
1865 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1866 let out = match self.token {
1867 token::Interpolated(ref nt) => match nt.0 {
1868 token::NtExpr(ref v) => match v.node {
1869 ExprKind::Lit(ref lit) => { lit.node.clone() }
1870 _ => { return self.unexpected_last(&self.token); }
1872 _ => { return self.unexpected_last(&self.token); }
1874 token::Literal(lit, suf) => {
1875 let diag = Some((self.span, &self.sess.span_diagnostic));
1876 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1880 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1885 _ => { return self.unexpected_last(&self.token); }
1892 /// Matches lit = true | false | token_lit
1893 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1895 let lit = if self.eat_keyword(keywords::True) {
1897 } else if self.eat_keyword(keywords::False) {
1898 LitKind::Bool(false)
1900 let lit = self.parse_lit_token()?;
1903 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1906 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1907 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1908 maybe_whole_expr!(self);
1910 let minus_lo = self.span;
1911 let minus_present = self.eat(&token::BinOp(token::Minus));
1913 let literal = P(self.parse_lit()?);
1914 let hi = self.prev_span;
1915 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1918 let minus_hi = self.prev_span;
1919 let unary = self.mk_unary(UnOp::Neg, expr);
1920 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1926 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1928 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1932 _ => self.parse_ident(),
1936 /// Parses qualified path.
1937 /// Assumes that the leading `<` has been parsed already.
1939 /// `qualified_path = <type [as trait_ref]>::path`
1943 /// `<T as U>::F::a<S>` (without disambiguator)
1944 /// `<T as U>::F::a::<S>` (with disambiguator)
1945 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1946 let lo = self.prev_span;
1947 let ty = self.parse_ty()?;
1948 let mut path = if self.eat_keyword(keywords::As) {
1949 self.parse_path(PathStyle::Type)?
1951 ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP }
1953 self.expect(&token::Gt)?;
1954 self.expect(&token::ModSep)?;
1956 let qself = QSelf { ty, position: path.segments.len() };
1957 self.parse_path_segments(&mut path.segments, style, true)?;
1959 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1962 /// Parses simple paths.
1964 /// `path = [::] segment+`
1965 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1968 /// `a::b::C<D>` (without disambiguator)
1969 /// `a::b::C::<D>` (with disambiguator)
1970 /// `Fn(Args)` (without disambiguator)
1971 /// `Fn::(Args)` (with disambiguator)
1972 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1973 self.parse_path_common(style, true)
1976 pub fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1977 -> PResult<'a, ast::Path> {
1978 maybe_whole!(self, NtPath, |path| {
1979 if style == PathStyle::Mod &&
1980 path.segments.iter().any(|segment| segment.parameters.is_some()) {
1981 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1986 let lo = self.meta_var_span.unwrap_or(self.span);
1987 let mut segments = Vec::new();
1988 if self.eat(&token::ModSep) {
1989 segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
1991 self.parse_path_segments(&mut segments, style, enable_warning)?;
1993 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1996 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1997 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1998 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1999 let meta_ident = match self.token {
2000 token::Interpolated(ref nt) => match nt.0 {
2001 token::NtMeta(ref meta) => match meta.node {
2002 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
2009 if let Some(ident) = meta_ident {
2011 return Ok(ast::Path::from_ident(self.prev_span, ident));
2013 self.parse_path(style)
2016 fn parse_path_segments(&mut self,
2017 segments: &mut Vec<PathSegment>,
2019 enable_warning: bool)
2020 -> PResult<'a, ()> {
2022 segments.push(self.parse_path_segment(style, enable_warning)?);
2024 if self.is_import_coupler() || !self.eat(&token::ModSep) {
2030 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
2031 -> PResult<'a, PathSegment> {
2032 let ident_span = self.span;
2033 let ident = self.parse_path_segment_ident()?;
2035 let is_args_start = |token: &token::Token| match *token {
2036 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
2039 let check_args_start = |this: &mut Self| {
2040 this.expected_tokens.extend_from_slice(
2041 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2043 is_args_start(&this.token)
2046 Ok(if style == PathStyle::Type && check_args_start(self) ||
2047 style != PathStyle::Mod && self.check(&token::ModSep)
2048 && self.look_ahead(1, |t| is_args_start(t)) {
2049 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2051 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2052 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2053 .span_label(self.prev_span, "try removing `::`").emit();
2056 let parameters = if self.eat_lt() {
2058 let (lifetimes, types, bindings) = self.parse_generic_args()?;
2060 let span = lo.to(self.prev_span);
2061 AngleBracketedParameterData { lifetimes, types, bindings, span }.into()
2065 let inputs = self.parse_seq_to_before_tokens(
2066 &[&token::CloseDelim(token::Paren)],
2067 SeqSep::trailing_allowed(token::Comma),
2068 TokenExpectType::Expect,
2071 let output = if self.eat(&token::RArrow) {
2072 Some(self.parse_ty_common(false, false)?)
2076 let span = lo.to(self.prev_span);
2077 ParenthesizedParameterData { inputs, output, span }.into()
2080 PathSegment { identifier: ident, span: ident_span, parameters }
2082 // Generic arguments are not found.
2083 PathSegment::from_ident(ident, ident_span)
2087 fn check_lifetime(&mut self) -> bool {
2088 self.expected_tokens.push(TokenType::Lifetime);
2089 self.token.is_lifetime()
2092 /// Parse single lifetime 'a or panic.
2093 pub fn expect_lifetime(&mut self) -> Lifetime {
2094 if let Some(lifetime) = self.token.lifetime(self.span) {
2098 self.span_bug(self.span, "not a lifetime")
2102 /// Parse mutability (`mut` or nothing).
2103 fn parse_mutability(&mut self) -> Mutability {
2104 if self.eat_keyword(keywords::Mut) {
2107 Mutability::Immutable
2111 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2112 if let token::Literal(token::Integer(name), None) = self.token {
2114 Ok(Ident::with_empty_ctxt(name))
2116 self.parse_ident_common(false)
2120 /// Parse ident (COLON expr)?
2121 pub fn parse_field(&mut self) -> PResult<'a, Field> {
2122 let attrs = self.parse_outer_attributes()?;
2126 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2127 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2128 let fieldname = self.parse_field_name()?;
2129 hi = self.prev_span;
2131 (fieldname, self.parse_expr()?, false)
2133 let fieldname = self.parse_ident_common(false)?;
2134 hi = self.prev_span;
2136 // Mimic `x: x` for the `x` field shorthand.
2137 let path = ast::Path::from_ident(lo.to(hi), fieldname);
2138 (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
2141 ident: respan(lo.to(hi), fieldname),
2142 span: lo.to(expr.span),
2145 attrs: attrs.into(),
2149 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2150 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2153 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2154 ExprKind::Unary(unop, expr)
2157 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2158 ExprKind::Binary(binop, lhs, rhs)
2161 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2162 ExprKind::Call(f, args)
2165 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2166 ExprKind::Index(expr, idx)
2169 pub fn mk_range(&mut self,
2170 start: Option<P<Expr>>,
2171 end: Option<P<Expr>>,
2172 limits: RangeLimits)
2173 -> PResult<'a, ast::ExprKind> {
2174 if end.is_none() && limits == RangeLimits::Closed {
2175 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2177 Ok(ExprKind::Range(start, end, limits))
2181 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2182 ExprKind::TupField(expr, idx)
2185 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2186 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2187 ExprKind::AssignOp(binop, lhs, rhs)
2190 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2192 id: ast::DUMMY_NODE_ID,
2193 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2199 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2200 let span = &self.span;
2201 let lv_lit = P(codemap::Spanned {
2202 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2207 id: ast::DUMMY_NODE_ID,
2208 node: ExprKind::Lit(lv_lit),
2214 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2216 token::OpenDelim(delim) => match self.parse_token_tree() {
2217 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2218 _ => unreachable!(),
2221 let msg = "expected open delimiter";
2222 let mut err = self.fatal(msg);
2223 err.span_label(self.span, msg);
2229 /// At the bottom (top?) of the precedence hierarchy,
2230 /// parse things like parenthesized exprs,
2231 /// macros, return, etc.
2233 /// NB: This does not parse outer attributes,
2234 /// and is private because it only works
2235 /// correctly if called from parse_dot_or_call_expr().
2236 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2237 maybe_whole_expr!(self);
2239 // Outer attributes are already parsed and will be
2240 // added to the return value after the fact.
2242 // Therefore, prevent sub-parser from parsing
2243 // attributes by giving them a empty "already parsed" list.
2244 let mut attrs = ThinVec::new();
2247 let mut hi = self.span;
2251 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2253 token::OpenDelim(token::Paren) => {
2256 attrs.extend(self.parse_inner_attributes()?);
2258 // (e) is parenthesized e
2259 // (e,) is a tuple with only one field, e
2260 let mut es = vec![];
2261 let mut trailing_comma = false;
2262 while self.token != token::CloseDelim(token::Paren) {
2263 es.push(self.parse_expr()?);
2264 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2265 if self.check(&token::Comma) {
2266 trailing_comma = true;
2270 trailing_comma = false;
2276 hi = self.prev_span;
2277 ex = if es.len() == 1 && !trailing_comma {
2278 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2283 token::OpenDelim(token::Brace) => {
2284 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2286 token::BinOp(token::Or) | token::OrOr => {
2287 return self.parse_lambda_expr(attrs);
2289 token::OpenDelim(token::Bracket) => {
2292 attrs.extend(self.parse_inner_attributes()?);
2294 if self.check(&token::CloseDelim(token::Bracket)) {
2297 ex = ExprKind::Array(Vec::new());
2300 let first_expr = self.parse_expr()?;
2301 if self.check(&token::Semi) {
2302 // Repeating array syntax: [ 0; 512 ]
2304 let count = self.parse_expr()?;
2305 self.expect(&token::CloseDelim(token::Bracket))?;
2306 ex = ExprKind::Repeat(first_expr, count);
2307 } else if self.check(&token::Comma) {
2308 // Vector with two or more elements.
2310 let remaining_exprs = self.parse_seq_to_end(
2311 &token::CloseDelim(token::Bracket),
2312 SeqSep::trailing_allowed(token::Comma),
2313 |p| Ok(p.parse_expr()?)
2315 let mut exprs = vec![first_expr];
2316 exprs.extend(remaining_exprs);
2317 ex = ExprKind::Array(exprs);
2319 // Vector with one element.
2320 self.expect(&token::CloseDelim(token::Bracket))?;
2321 ex = ExprKind::Array(vec![first_expr]);
2324 hi = self.prev_span;
2328 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2330 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2332 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2333 return self.parse_lambda_expr(attrs);
2335 if self.eat_keyword(keywords::If) {
2336 return self.parse_if_expr(attrs);
2338 if self.eat_keyword(keywords::For) {
2339 let lo = self.prev_span;
2340 return self.parse_for_expr(None, lo, attrs);
2342 if self.eat_keyword(keywords::While) {
2343 let lo = self.prev_span;
2344 return self.parse_while_expr(None, lo, attrs);
2346 if let Some(label) = self.eat_label() {
2347 let lo = label.span;
2348 self.expect(&token::Colon)?;
2349 if self.eat_keyword(keywords::While) {
2350 return self.parse_while_expr(Some(label), lo, attrs)
2352 if self.eat_keyword(keywords::For) {
2353 return self.parse_for_expr(Some(label), lo, attrs)
2355 if self.eat_keyword(keywords::Loop) {
2356 return self.parse_loop_expr(Some(label), lo, attrs)
2358 let msg = "expected `while`, `for`, or `loop` after a label";
2359 let mut err = self.fatal(msg);
2360 err.span_label(self.span, msg);
2363 if self.eat_keyword(keywords::Loop) {
2364 let lo = self.prev_span;
2365 return self.parse_loop_expr(None, lo, attrs);
2367 if self.eat_keyword(keywords::Continue) {
2368 let label = self.eat_label();
2369 let ex = ExprKind::Continue(label);
2370 let hi = self.prev_span;
2371 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2373 if self.eat_keyword(keywords::Match) {
2374 return self.parse_match_expr(attrs);
2376 if self.eat_keyword(keywords::Unsafe) {
2377 return self.parse_block_expr(
2379 BlockCheckMode::Unsafe(ast::UserProvided),
2382 if self.is_catch_expr() {
2384 assert!(self.eat_keyword(keywords::Do));
2385 assert!(self.eat_keyword(keywords::Catch));
2386 return self.parse_catch_expr(lo, attrs);
2388 if self.eat_keyword(keywords::Return) {
2389 if self.token.can_begin_expr() {
2390 let e = self.parse_expr()?;
2392 ex = ExprKind::Ret(Some(e));
2394 ex = ExprKind::Ret(None);
2396 } else if self.eat_keyword(keywords::Break) {
2397 let label = self.eat_label();
2398 let e = if self.token.can_begin_expr()
2399 && !(self.token == token::OpenDelim(token::Brace)
2400 && self.restrictions.contains(
2401 Restrictions::NO_STRUCT_LITERAL)) {
2402 Some(self.parse_expr()?)
2406 ex = ExprKind::Break(label, e);
2407 hi = self.prev_span;
2408 } else if self.eat_keyword(keywords::Yield) {
2409 if self.token.can_begin_expr() {
2410 let e = self.parse_expr()?;
2412 ex = ExprKind::Yield(Some(e));
2414 ex = ExprKind::Yield(None);
2416 } else if self.token.is_keyword(keywords::Let) {
2417 // Catch this syntax error here, instead of in `parse_ident`, so
2418 // that we can explicitly mention that let is not to be used as an expression
2419 let mut db = self.fatal("expected expression, found statement (`let`)");
2420 db.span_label(self.span, "expected expression");
2421 db.note("variable declaration using `let` is a statement");
2423 } else if self.token.is_path_start() {
2424 let pth = self.parse_path(PathStyle::Expr)?;
2426 // `!`, as an operator, is prefix, so we know this isn't that
2427 if self.eat(&token::Not) {
2428 // MACRO INVOCATION expression
2429 let (_, tts) = self.expect_delimited_token_tree()?;
2430 let hi = self.prev_span;
2431 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2433 if self.check(&token::OpenDelim(token::Brace)) {
2434 // This is a struct literal, unless we're prohibited
2435 // from parsing struct literals here.
2436 let prohibited = self.restrictions.contains(
2437 Restrictions::NO_STRUCT_LITERAL
2440 return self.parse_struct_expr(lo, pth, attrs);
2445 ex = ExprKind::Path(None, pth);
2447 match self.parse_lit() {
2450 ex = ExprKind::Lit(P(lit));
2453 self.cancel(&mut err);
2454 let msg = format!("expected expression, found {}",
2455 self.this_token_descr());
2456 let mut err = self.fatal(&msg);
2457 err.span_label(self.span, "expected expression");
2465 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2466 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2471 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2472 -> PResult<'a, P<Expr>> {
2473 let struct_sp = lo.to(self.prev_span);
2475 let mut fields = Vec::new();
2476 let mut base = None;
2478 attrs.extend(self.parse_inner_attributes()?);
2480 while self.token != token::CloseDelim(token::Brace) {
2481 if self.eat(&token::DotDot) {
2482 let exp_span = self.prev_span;
2483 match self.parse_expr() {
2489 self.recover_stmt();
2492 if self.token == token::Comma {
2493 let mut err = self.sess.span_diagnostic.mut_span_err(
2494 exp_span.to(self.prev_span),
2495 "cannot use a comma after the base struct",
2497 err.span_suggestion_short(self.span, "remove this comma", "".to_owned());
2498 err.note("the base struct must always be the last field");
2500 self.recover_stmt();
2505 match self.parse_field() {
2506 Ok(f) => fields.push(f),
2508 e.span_label(struct_sp, "while parsing this struct");
2510 self.recover_stmt();
2515 match self.expect_one_of(&[token::Comma],
2516 &[token::CloseDelim(token::Brace)]) {
2520 self.recover_stmt();
2526 let span = lo.to(self.span);
2527 self.expect(&token::CloseDelim(token::Brace))?;
2528 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2531 fn parse_or_use_outer_attributes(&mut self,
2532 already_parsed_attrs: Option<ThinVec<Attribute>>)
2533 -> PResult<'a, ThinVec<Attribute>> {
2534 if let Some(attrs) = already_parsed_attrs {
2537 self.parse_outer_attributes().map(|a| a.into())
2541 /// Parse a block or unsafe block
2542 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2543 outer_attrs: ThinVec<Attribute>)
2544 -> PResult<'a, P<Expr>> {
2545 self.expect(&token::OpenDelim(token::Brace))?;
2547 let mut attrs = outer_attrs;
2548 attrs.extend(self.parse_inner_attributes()?);
2550 let blk = self.parse_block_tail(lo, blk_mode)?;
2551 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2554 /// parse a.b or a(13) or a[4] or just a
2555 pub fn parse_dot_or_call_expr(&mut self,
2556 already_parsed_attrs: Option<ThinVec<Attribute>>)
2557 -> PResult<'a, P<Expr>> {
2558 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2560 let b = self.parse_bottom_expr();
2561 let (span, b) = self.interpolated_or_expr_span(b)?;
2562 self.parse_dot_or_call_expr_with(b, span, attrs)
2565 pub fn parse_dot_or_call_expr_with(&mut self,
2568 mut attrs: ThinVec<Attribute>)
2569 -> PResult<'a, P<Expr>> {
2570 // Stitch the list of outer attributes onto the return value.
2571 // A little bit ugly, but the best way given the current code
2573 self.parse_dot_or_call_expr_with_(e0, lo)
2575 expr.map(|mut expr| {
2576 attrs.extend::<Vec<_>>(expr.attrs.into());
2579 ExprKind::If(..) | ExprKind::IfLet(..) => {
2580 if !expr.attrs.is_empty() {
2581 // Just point to the first attribute in there...
2582 let span = expr.attrs[0].span;
2585 "attributes are not yet allowed on `if` \
2596 // Assuming we have just parsed `.`, continue parsing into an expression.
2597 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2598 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2599 Ok(match self.token {
2600 token::OpenDelim(token::Paren) => {
2601 // Method call `expr.f()`
2602 let mut args = self.parse_unspanned_seq(
2603 &token::OpenDelim(token::Paren),
2604 &token::CloseDelim(token::Paren),
2605 SeqSep::trailing_allowed(token::Comma),
2606 |p| Ok(p.parse_expr()?)
2608 args.insert(0, self_arg);
2610 let span = lo.to(self.prev_span);
2611 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2614 // Field access `expr.f`
2615 if let Some(parameters) = segment.parameters {
2616 self.span_err(parameters.span(),
2617 "field expressions may not have generic arguments");
2620 let span = lo.to(self.prev_span);
2621 let ident = respan(segment.span, segment.identifier);
2622 self.mk_expr(span, ExprKind::Field(self_arg, ident), ThinVec::new())
2627 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2632 while self.eat(&token::Question) {
2633 let hi = self.prev_span;
2634 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2638 if self.eat(&token::Dot) {
2640 token::Ident(..) => {
2641 e = self.parse_dot_suffix(e, lo)?;
2643 token::Literal(token::Integer(index_ident), suf) => {
2646 // A tuple index may not have a suffix
2647 self.expect_no_suffix(sp, "tuple index", suf);
2649 let idx_span = self.span;
2652 let invalid_msg = "invalid tuple or struct index";
2654 let index = index_ident.as_str().parse::<usize>().ok();
2657 if n.to_string() != index_ident.as_str() {
2658 let mut err = self.struct_span_err(self.prev_span, invalid_msg);
2659 err.span_suggestion(self.prev_span,
2660 "try simplifying the index",
2664 let field = self.mk_tup_field(e, respan(idx_span, n));
2665 e = self.mk_expr(lo.to(idx_span), field, ThinVec::new());
2668 let prev_span = self.prev_span;
2669 self.span_err(prev_span, invalid_msg);
2673 token::Literal(token::Float(n), _suf) => {
2675 let fstr = n.as_str();
2676 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2677 &format!("unexpected token: `{}`", n));
2678 err.span_label(self.prev_span, "unexpected token");
2679 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2680 let float = match fstr.parse::<f64>().ok() {
2684 let sugg = pprust::to_string(|s| {
2685 use print::pprust::PrintState;
2689 s.print_usize(float.trunc() as usize)?;
2692 s.s.word(fstr.splitn(2, ".").last().unwrap())
2694 err.span_suggestion(
2695 lo.to(self.prev_span),
2696 "try parenthesizing the first index",
2703 // FIXME Could factor this out into non_fatal_unexpected or something.
2704 let actual = self.this_token_to_string();
2705 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2710 if self.expr_is_complete(&e) { break; }
2713 token::OpenDelim(token::Paren) => {
2714 let es = self.parse_unspanned_seq(
2715 &token::OpenDelim(token::Paren),
2716 &token::CloseDelim(token::Paren),
2717 SeqSep::trailing_allowed(token::Comma),
2718 |p| Ok(p.parse_expr()?)
2720 hi = self.prev_span;
2722 let nd = self.mk_call(e, es);
2723 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2727 // Could be either an index expression or a slicing expression.
2728 token::OpenDelim(token::Bracket) => {
2730 let ix = self.parse_expr()?;
2732 self.expect(&token::CloseDelim(token::Bracket))?;
2733 let index = self.mk_index(e, ix);
2734 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2742 pub fn process_potential_macro_variable(&mut self) {
2743 let ident = match self.token {
2744 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2745 self.look_ahead(1, |t| t.is_ident()) => {
2747 let name = match self.token { token::Ident(ident) => ident, _ => unreachable!() };
2748 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2749 err.span_label(self.span, "unknown macro variable");
2753 token::Interpolated(ref nt) => {
2754 self.meta_var_span = Some(self.span);
2756 token::NtIdent(ident) => ident,
2762 self.token = token::Ident(ident.node);
2763 self.span = ident.span;
2766 /// parse a single token tree from the input.
2767 pub fn parse_token_tree(&mut self) -> TokenTree {
2769 token::OpenDelim(..) => {
2770 let frame = mem::replace(&mut self.token_cursor.frame,
2771 self.token_cursor.stack.pop().unwrap());
2772 self.span = frame.span;
2774 TokenTree::Delimited(frame.span, Delimited {
2776 tts: frame.tree_cursor.original_stream().into(),
2779 token::CloseDelim(_) | token::Eof => unreachable!(),
2781 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2783 TokenTree::Token(span, token)
2788 // parse a stream of tokens into a list of TokenTree's,
2790 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2791 let mut tts = Vec::new();
2792 while self.token != token::Eof {
2793 tts.push(self.parse_token_tree());
2798 pub fn parse_tokens(&mut self) -> TokenStream {
2799 let mut result = Vec::new();
2802 token::Eof | token::CloseDelim(..) => break,
2803 _ => result.push(self.parse_token_tree().into()),
2806 TokenStream::concat(result)
2809 /// Parse a prefix-unary-operator expr
2810 pub fn parse_prefix_expr(&mut self,
2811 already_parsed_attrs: Option<ThinVec<Attribute>>)
2812 -> PResult<'a, P<Expr>> {
2813 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2815 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2816 let (hi, ex) = match self.token {
2819 let e = self.parse_prefix_expr(None);
2820 let (span, e) = self.interpolated_or_expr_span(e)?;
2821 (lo.to(span), self.mk_unary(UnOp::Not, e))
2823 // Suggest `!` for bitwise negation when encountering a `~`
2826 let e = self.parse_prefix_expr(None);
2827 let (span, e) = self.interpolated_or_expr_span(e)?;
2828 let span_of_tilde = lo;
2829 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2830 "`~` cannot be used as a unary operator");
2831 err.span_suggestion_short(span_of_tilde,
2832 "use `!` to perform bitwise negation",
2835 (lo.to(span), self.mk_unary(UnOp::Not, e))
2837 token::BinOp(token::Minus) => {
2839 let e = self.parse_prefix_expr(None);
2840 let (span, e) = self.interpolated_or_expr_span(e)?;
2841 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2843 token::BinOp(token::Star) => {
2845 let e = self.parse_prefix_expr(None);
2846 let (span, e) = self.interpolated_or_expr_span(e)?;
2847 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2849 token::BinOp(token::And) | token::AndAnd => {
2851 let m = self.parse_mutability();
2852 let e = self.parse_prefix_expr(None);
2853 let (span, e) = self.interpolated_or_expr_span(e)?;
2854 (lo.to(span), ExprKind::AddrOf(m, e))
2856 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2858 let place = self.parse_expr_res(
2859 Restrictions::NO_STRUCT_LITERAL,
2862 let blk = self.parse_block()?;
2863 let span = blk.span;
2864 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2865 (lo.to(span), ExprKind::InPlace(place, blk_expr))
2867 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2869 let e = self.parse_prefix_expr(None);
2870 let (span, e) = self.interpolated_or_expr_span(e)?;
2871 (lo.to(span), ExprKind::Box(e))
2873 _ => return self.parse_dot_or_call_expr(Some(attrs))
2875 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2878 /// Parse an associative expression
2880 /// This parses an expression accounting for associativity and precedence of the operators in
2882 pub fn parse_assoc_expr(&mut self,
2883 already_parsed_attrs: Option<ThinVec<Attribute>>)
2884 -> PResult<'a, P<Expr>> {
2885 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2888 /// Parse an associative expression with operators of at least `min_prec` precedence
2889 pub fn parse_assoc_expr_with(&mut self,
2892 -> PResult<'a, P<Expr>> {
2893 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2896 let attrs = match lhs {
2897 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2900 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2901 return self.parse_prefix_range_expr(attrs);
2903 self.parse_prefix_expr(attrs)?
2907 if self.expr_is_complete(&lhs) {
2908 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2911 self.expected_tokens.push(TokenType::Operator);
2912 while let Some(op) = AssocOp::from_token(&self.token) {
2914 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2915 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2916 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2917 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2918 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2919 (PrevTokenKind::Interpolated, _) => self.prev_span,
2920 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2921 if path.segments.len() == 1 => self.prev_span,
2925 let cur_op_span = self.span;
2926 let restrictions = if op.is_assign_like() {
2927 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2931 if op.precedence() < min_prec {
2934 // Check for deprecated `...` syntax
2935 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2936 self.err_dotdotdot_syntax(self.span);
2940 if op.is_comparison() {
2941 self.check_no_chained_comparison(&lhs, &op);
2944 if op == AssocOp::As {
2945 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2947 } else if op == AssocOp::Colon {
2948 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2951 err.span_label(self.span,
2952 "expecting a type here because of type ascription");
2953 let cm = self.sess.codemap();
2954 let cur_pos = cm.lookup_char_pos(self.span.lo());
2955 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
2956 if cur_pos.line != op_pos.line {
2957 err.span_suggestion_short(cur_op_span,
2958 "did you mean to use `;` here?",
2965 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2966 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2967 // generalise it to the Fixity::None code.
2969 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2970 // two variants are handled with `parse_prefix_range_expr` call above.
2971 let rhs = if self.is_at_start_of_range_notation_rhs() {
2972 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2973 LhsExpr::NotYetParsed)?)
2977 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2982 let limits = if op == AssocOp::DotDot {
2983 RangeLimits::HalfOpen
2988 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2989 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2993 let rhs = match op.fixity() {
2994 Fixity::Right => self.with_res(
2995 restrictions - Restrictions::STMT_EXPR,
2997 this.parse_assoc_expr_with(op.precedence(),
2998 LhsExpr::NotYetParsed)
3000 Fixity::Left => self.with_res(
3001 restrictions - Restrictions::STMT_EXPR,
3003 this.parse_assoc_expr_with(op.precedence() + 1,
3004 LhsExpr::NotYetParsed)
3006 // We currently have no non-associative operators that are not handled above by
3007 // the special cases. The code is here only for future convenience.
3008 Fixity::None => self.with_res(
3009 restrictions - Restrictions::STMT_EXPR,
3011 this.parse_assoc_expr_with(op.precedence() + 1,
3012 LhsExpr::NotYetParsed)
3016 let span = lhs_span.to(rhs.span);
3018 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3019 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3020 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3021 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3022 AssocOp::Greater | AssocOp::GreaterEqual => {
3023 let ast_op = op.to_ast_binop().unwrap();
3024 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
3025 self.mk_expr(span, binary, ThinVec::new())
3028 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3030 self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
3031 AssocOp::AssignOp(k) => {
3033 token::Plus => BinOpKind::Add,
3034 token::Minus => BinOpKind::Sub,
3035 token::Star => BinOpKind::Mul,
3036 token::Slash => BinOpKind::Div,
3037 token::Percent => BinOpKind::Rem,
3038 token::Caret => BinOpKind::BitXor,
3039 token::And => BinOpKind::BitAnd,
3040 token::Or => BinOpKind::BitOr,
3041 token::Shl => BinOpKind::Shl,
3042 token::Shr => BinOpKind::Shr,
3044 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
3045 self.mk_expr(span, aopexpr, ThinVec::new())
3047 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3048 self.bug("AssocOp should have been handled by special case")
3052 if op.fixity() == Fixity::None { break }
3057 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3058 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3059 -> PResult<'a, P<Expr>> {
3060 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3061 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3064 // Save the state of the parser before parsing type normally, in case there is a
3065 // LessThan comparison after this cast.
3066 let parser_snapshot_before_type = self.clone();
3067 match self.parse_ty_no_plus() {
3069 Ok(mk_expr(self, rhs))
3071 Err(mut type_err) => {
3072 // Rewind to before attempting to parse the type with generics, to recover
3073 // from situations like `x as usize < y` in which we first tried to parse
3074 // `usize < y` as a type with generic arguments.
3075 let parser_snapshot_after_type = self.clone();
3076 mem::replace(self, parser_snapshot_before_type);
3078 match self.parse_path(PathStyle::Expr) {
3080 let (op_noun, op_verb) = match self.token {
3081 token::Lt => ("comparison", "comparing"),
3082 token::BinOp(token::Shl) => ("shift", "shifting"),
3084 // We can end up here even without `<` being the next token, for
3085 // example because `parse_ty_no_plus` returns `Err` on keywords,
3086 // but `parse_path` returns `Ok` on them due to error recovery.
3087 // Return original error and parser state.
3088 mem::replace(self, parser_snapshot_after_type);
3089 return Err(type_err);
3093 // Successfully parsed the type path leaving a `<` yet to parse.
3096 // Report non-fatal diagnostics, keep `x as usize` as an expression
3097 // in AST and continue parsing.
3098 let msg = format!("`<` is interpreted as a start of generic \
3099 arguments for `{}`, not a {}", path, op_noun);
3100 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3101 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3102 "interpreted as generic arguments");
3103 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3105 let expr = mk_expr(self, P(Ty {
3107 node: TyKind::Path(None, path),
3108 id: ast::DUMMY_NODE_ID
3111 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
3112 .unwrap_or(pprust::expr_to_string(&expr));
3113 err.span_suggestion(expr.span,
3114 &format!("try {} the cast value", op_verb),
3115 format!("({})", expr_str));
3120 Err(mut path_err) => {
3121 // Couldn't parse as a path, return original error and parser state.
3123 mem::replace(self, parser_snapshot_after_type);
3131 /// Produce an error if comparison operators are chained (RFC #558).
3132 /// We only need to check lhs, not rhs, because all comparison ops
3133 /// have same precedence and are left-associative
3134 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3135 debug_assert!(outer_op.is_comparison(),
3136 "check_no_chained_comparison: {:?} is not comparison",
3139 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3140 // respan to include both operators
3141 let op_span = op.span.to(self.span);
3142 let mut err = self.diagnostic().struct_span_err(op_span,
3143 "chained comparison operators require parentheses");
3144 if op.node == BinOpKind::Lt &&
3145 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3146 *outer_op == AssocOp::Greater // even in a case like the following:
3147 { // Foo<Bar<Baz<Qux, ()>>>
3149 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3150 err.help("or use `(...)` if you meant to specify fn arguments");
3158 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3159 fn parse_prefix_range_expr(&mut self,
3160 already_parsed_attrs: Option<ThinVec<Attribute>>)
3161 -> PResult<'a, P<Expr>> {
3162 // Check for deprecated `...` syntax
3163 if self.token == token::DotDotDot {
3164 self.err_dotdotdot_syntax(self.span);
3167 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3168 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3170 let tok = self.token.clone();
3171 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3173 let mut hi = self.span;
3175 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3176 // RHS must be parsed with more associativity than the dots.
3177 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3178 Some(self.parse_assoc_expr_with(next_prec,
3179 LhsExpr::NotYetParsed)
3187 let limits = if tok == token::DotDot {
3188 RangeLimits::HalfOpen
3193 let r = try!(self.mk_range(None,
3196 Ok(self.mk_expr(lo.to(hi), r, attrs))
3199 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3200 if self.token.can_begin_expr() {
3201 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3202 if self.token == token::OpenDelim(token::Brace) {
3203 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3211 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3212 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3213 if self.check_keyword(keywords::Let) {
3214 return self.parse_if_let_expr(attrs);
3216 let lo = self.prev_span;
3217 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3219 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3220 // verify that the last statement is either an implicit return (no `;`) or an explicit
3221 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3222 // the dead code lint.
3223 if self.eat_keyword(keywords::Else) || !cond.returns() {
3224 let sp = self.sess.codemap().next_point(lo);
3225 let mut err = self.diagnostic()
3226 .struct_span_err(sp, "missing condition for `if` statemement");
3227 err.span_label(sp, "expected if condition here");
3230 let not_block = self.token != token::OpenDelim(token::Brace);
3231 let thn = self.parse_block().map_err(|mut err| {
3233 err.span_label(lo, "this `if` statement has a condition, but no block");
3237 let mut els: Option<P<Expr>> = None;
3238 let mut hi = thn.span;
3239 if self.eat_keyword(keywords::Else) {
3240 let elexpr = self.parse_else_expr()?;
3244 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3247 /// Parse an 'if let' expression ('if' token already eaten)
3248 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3249 -> PResult<'a, P<Expr>> {
3250 let lo = self.prev_span;
3251 self.expect_keyword(keywords::Let)?;
3252 let pats = self.parse_pats()?;
3253 self.expect(&token::Eq)?;
3254 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3255 let thn = self.parse_block()?;
3256 let (hi, els) = if self.eat_keyword(keywords::Else) {
3257 let expr = self.parse_else_expr()?;
3258 (expr.span, Some(expr))
3262 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3265 // `move |args| expr`
3266 pub fn parse_lambda_expr(&mut self,
3267 attrs: ThinVec<Attribute>)
3268 -> PResult<'a, P<Expr>>
3271 let movability = if self.eat_keyword(keywords::Static) {
3276 let capture_clause = if self.eat_keyword(keywords::Move) {
3281 let decl = self.parse_fn_block_decl()?;
3282 let decl_hi = self.prev_span;
3283 let body = match decl.output {
3284 FunctionRetTy::Default(_) => {
3285 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3286 self.parse_expr_res(restrictions, None)?
3289 // If an explicit return type is given, require a
3290 // block to appear (RFC 968).
3291 let body_lo = self.span;
3292 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3298 ExprKind::Closure(capture_clause, movability, decl, body, lo.to(decl_hi)),
3302 // `else` token already eaten
3303 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3304 if self.eat_keyword(keywords::If) {
3305 return self.parse_if_expr(ThinVec::new());
3307 let blk = self.parse_block()?;
3308 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3312 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3313 pub fn parse_for_expr(&mut self, opt_label: Option<Label>,
3315 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3316 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3318 let pat = self.parse_top_level_pat()?;
3319 if !self.eat_keyword(keywords::In) {
3320 let in_span = self.prev_span.between(self.span);
3321 let mut err = self.sess.span_diagnostic
3322 .struct_span_err(in_span, "missing `in` in `for` loop");
3323 err.span_suggestion_short(in_span, "try adding `in` here", " in ".into());
3326 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3327 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3328 attrs.extend(iattrs);
3330 let hi = self.prev_span;
3331 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3334 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3335 pub fn parse_while_expr(&mut self, opt_label: Option<Label>,
3337 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3338 if self.token.is_keyword(keywords::Let) {
3339 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3341 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3342 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3343 attrs.extend(iattrs);
3344 let span = span_lo.to(body.span);
3345 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3348 /// Parse a 'while let' expression ('while' token already eaten)
3349 pub fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3351 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3352 self.expect_keyword(keywords::Let)?;
3353 let pats = self.parse_pats()?;
3354 self.expect(&token::Eq)?;
3355 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3356 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3357 attrs.extend(iattrs);
3358 let span = span_lo.to(body.span);
3359 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3362 // parse `loop {...}`, `loop` token already eaten
3363 pub fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3365 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3366 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3367 attrs.extend(iattrs);
3368 let span = span_lo.to(body.span);
3369 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3372 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3373 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3374 -> PResult<'a, P<Expr>>
3376 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3377 attrs.extend(iattrs);
3378 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3381 // `match` token already eaten
3382 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3383 let match_span = self.prev_span;
3384 let lo = self.prev_span;
3385 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3387 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3388 if self.token == token::Token::Semi {
3389 e.span_suggestion_short(match_span, "try removing this `match`", "".to_owned());
3393 attrs.extend(self.parse_inner_attributes()?);
3395 let mut arms: Vec<Arm> = Vec::new();
3396 while self.token != token::CloseDelim(token::Brace) {
3397 match self.parse_arm() {
3398 Ok(arm) => arms.push(arm),
3400 // Recover by skipping to the end of the block.
3402 self.recover_stmt();
3403 let span = lo.to(self.span);
3404 if self.token == token::CloseDelim(token::Brace) {
3407 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3413 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3416 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3417 maybe_whole!(self, NtArm, |x| x);
3419 let attrs = self.parse_outer_attributes()?;
3420 // Allow a '|' before the pats (RFC 1925)
3421 self.eat(&token::BinOp(token::Or));
3422 let pats = self.parse_pats()?;
3423 let guard = if self.eat_keyword(keywords::If) {
3424 Some(self.parse_expr()?)
3428 let arrow_span = self.span;
3429 self.expect(&token::FatArrow)?;
3430 let arm_start_span = self.span;
3432 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3433 .map_err(|mut err| {
3434 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3438 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3439 && self.token != token::CloseDelim(token::Brace);
3442 let cm = self.sess.codemap();
3443 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3444 .map_err(|mut err| {
3445 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3446 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3447 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3448 && expr_lines.lines.len() == 2
3449 && self.token == token::FatArrow => {
3450 // We check wether there's any trailing code in the parse span, if there
3451 // isn't, we very likely have the following:
3454 // | -- - missing comma
3460 // | parsed until here as `"y" & X`
3461 err.span_suggestion_short(
3462 cm.next_point(arm_start_span),
3463 "missing a comma here to end this `match` arm",
3468 err.span_label(arrow_span,
3469 "while parsing the `match` arm starting here");
3475 self.eat(&token::Comma);
3486 /// Parse an expression
3487 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3488 self.parse_expr_res(Restrictions::empty(), None)
3491 /// Evaluate the closure with restrictions in place.
3493 /// After the closure is evaluated, restrictions are reset.
3494 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3495 where F: FnOnce(&mut Self) -> T
3497 let old = self.restrictions;
3498 self.restrictions = r;
3500 self.restrictions = old;
3505 /// Parse an expression, subject to the given restrictions
3506 pub fn parse_expr_res(&mut self, r: Restrictions,
3507 already_parsed_attrs: Option<ThinVec<Attribute>>)
3508 -> PResult<'a, P<Expr>> {
3509 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3512 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3513 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3514 if self.check(&token::Eq) {
3516 Ok(Some(self.parse_expr()?))
3518 Ok(Some(self.parse_expr()?))
3524 /// Parse patterns, separated by '|' s
3525 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3526 let mut pats = Vec::new();
3528 pats.push(self.parse_top_level_pat()?);
3530 if self.token == token::OrOr {
3531 let mut err = self.struct_span_err(self.span,
3532 "unexpected token `||` after pattern");
3533 err.span_suggestion(self.span,
3534 "use a single `|` to specify multiple patterns",
3538 } else if self.check(&token::BinOp(token::Or)) {
3546 // Parses a parenthesized list of patterns like
3547 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3548 // - a vector of the patterns that were parsed
3549 // - an option indicating the index of the `..` element
3550 // - a boolean indicating whether a trailing comma was present.
3551 // Trailing commas are significant because (p) and (p,) are different patterns.
3552 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3553 self.expect(&token::OpenDelim(token::Paren))?;
3554 let result = self.parse_pat_list()?;
3555 self.expect(&token::CloseDelim(token::Paren))?;
3559 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3560 let mut fields = Vec::new();
3561 let mut ddpos = None;
3562 let mut trailing_comma = false;
3564 if self.eat(&token::DotDot) {
3565 if ddpos.is_none() {
3566 ddpos = Some(fields.len());
3568 // Emit a friendly error, ignore `..` and continue parsing
3569 self.span_err(self.prev_span,
3570 "`..` can only be used once per tuple or tuple struct pattern");
3572 } else if !self.check(&token::CloseDelim(token::Paren)) {
3573 fields.push(self.parse_pat()?);
3578 trailing_comma = self.eat(&token::Comma);
3579 if !trailing_comma {
3584 if ddpos == Some(fields.len()) && trailing_comma {
3585 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3586 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3589 Ok((fields, ddpos, trailing_comma))
3592 fn parse_pat_vec_elements(
3594 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3595 let mut before = Vec::new();
3596 let mut slice = None;
3597 let mut after = Vec::new();
3598 let mut first = true;
3599 let mut before_slice = true;
3601 while self.token != token::CloseDelim(token::Bracket) {
3605 self.expect(&token::Comma)?;
3607 if self.token == token::CloseDelim(token::Bracket)
3608 && (before_slice || !after.is_empty()) {
3614 if self.eat(&token::DotDot) {
3616 if self.check(&token::Comma) ||
3617 self.check(&token::CloseDelim(token::Bracket)) {
3618 slice = Some(P(Pat {
3619 id: ast::DUMMY_NODE_ID,
3620 node: PatKind::Wild,
3623 before_slice = false;
3629 let subpat = self.parse_pat()?;
3630 if before_slice && self.eat(&token::DotDot) {
3631 slice = Some(subpat);
3632 before_slice = false;
3633 } else if before_slice {
3634 before.push(subpat);
3640 Ok((before, slice, after))
3643 /// Parse the fields of a struct-like pattern
3644 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3645 let mut fields = Vec::new();
3646 let mut etc = false;
3647 let mut first = true;
3648 while self.token != token::CloseDelim(token::Brace) {
3652 self.expect(&token::Comma)?;
3653 // accept trailing commas
3654 if self.check(&token::CloseDelim(token::Brace)) { break }
3657 let attrs = self.parse_outer_attributes()?;
3661 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3662 if self.token == token::DotDotDot { // Issue #46718
3663 let mut err = self.struct_span_err(self.span,
3664 "expected field pattern, found `...`");
3665 err.span_suggestion(self.span,
3666 "to omit remaining fields, use one fewer `.`",
3672 if self.token != token::CloseDelim(token::Brace) {
3673 let token_str = self.this_token_to_string();
3674 let mut err = self.fatal(&format!("expected `{}`, found `{}`", "}", token_str));
3675 err.span_label(self.span, "expected `}`");
3682 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3683 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3684 // Parsing a pattern of the form "fieldname: pat"
3685 let fieldname = self.parse_field_name()?;
3687 let pat = self.parse_pat()?;
3689 (pat, fieldname, false)
3691 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3692 let is_box = self.eat_keyword(keywords::Box);
3693 let boxed_span = self.span;
3694 let is_ref = self.eat_keyword(keywords::Ref);
3695 let is_mut = self.eat_keyword(keywords::Mut);
3696 let fieldname = self.parse_ident()?;
3697 hi = self.prev_span;
3699 let bind_type = match (is_ref, is_mut) {
3700 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3701 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3702 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3703 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3705 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3706 let fieldpat = P(Pat {
3707 id: ast::DUMMY_NODE_ID,
3708 node: PatKind::Ident(bind_type, fieldpath, None),
3709 span: boxed_span.to(hi),
3712 let subpat = if is_box {
3714 id: ast::DUMMY_NODE_ID,
3715 node: PatKind::Box(fieldpat),
3721 (subpat, fieldname, true)
3724 fields.push(codemap::Spanned { span: lo.to(hi),
3725 node: ast::FieldPat {
3729 attrs: attrs.into(),
3733 return Ok((fields, etc));
3736 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3737 if self.token.is_path_start() {
3739 let (qself, path) = if self.eat_lt() {
3740 // Parse a qualified path
3741 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3744 // Parse an unqualified path
3745 (None, self.parse_path(PathStyle::Expr)?)
3747 let hi = self.prev_span;
3748 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3750 self.parse_pat_literal_maybe_minus()
3754 // helper function to decide whether to parse as ident binding or to try to do
3755 // something more complex like range patterns
3756 fn parse_as_ident(&mut self) -> bool {
3757 self.look_ahead(1, |t| match *t {
3758 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3759 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3760 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3761 // range pattern branch
3762 token::DotDot => None,
3764 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3765 token::Comma | token::CloseDelim(token::Bracket) => true,
3770 /// A wrapper around `parse_pat` with some special error handling for the
3771 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contast
3772 /// to subpatterns within such).
3773 pub fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3774 let pat = self.parse_pat()?;
3775 if self.token == token::Comma {
3776 // An unexpected comma after a top-level pattern is a clue that the
3777 // user (perhaps more accustomed to some other language) forgot the
3778 // parentheses in what should have been a tuple pattern; return a
3779 // suggestion-enhanced error here rather than choking on the comma
3781 let comma_span = self.span;
3783 if let Err(mut err) = self.parse_pat_list() {
3784 // We didn't expect this to work anyway; we just wanted
3785 // to advance to the end of the comma-sequence so we know
3786 // the span to suggest parenthesizing
3789 let seq_span = pat.span.to(self.prev_span);
3790 let mut err = self.struct_span_err(comma_span,
3791 "unexpected `,` in pattern");
3792 if let Ok(seq_snippet) = self.sess.codemap().span_to_snippet(seq_span) {
3793 err.span_suggestion(seq_span, "try adding parentheses",
3794 format!("({})", seq_snippet));
3801 /// Parse a pattern.
3802 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3803 self.parse_pat_with_range_pat(true)
3806 /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
3808 fn parse_pat_with_range_pat(&mut self, allow_range_pat: bool) -> PResult<'a, P<Pat>> {
3809 maybe_whole!(self, NtPat, |x| x);
3814 token::BinOp(token::And) | token::AndAnd => {
3815 // Parse &pat / &mut pat
3817 let mutbl = self.parse_mutability();
3818 if let token::Lifetime(ident) = self.token {
3819 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
3821 err.span_label(self.span, "unexpected lifetime");
3824 let subpat = self.parse_pat_with_range_pat(false)?;
3825 pat = PatKind::Ref(subpat, mutbl);
3827 token::OpenDelim(token::Paren) => {
3828 // Parse (pat,pat,pat,...) as tuple pattern
3829 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
3830 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
3831 PatKind::Paren(fields.into_iter().nth(0).unwrap())
3833 PatKind::Tuple(fields, ddpos)
3836 token::OpenDelim(token::Bracket) => {
3837 // Parse [pat,pat,...] as slice pattern
3839 let (before, slice, after) = self.parse_pat_vec_elements()?;
3840 self.expect(&token::CloseDelim(token::Bracket))?;
3841 pat = PatKind::Slice(before, slice, after);
3843 // At this point, token != &, &&, (, [
3844 _ => if self.eat_keyword(keywords::Underscore) {
3846 pat = PatKind::Wild;
3847 } else if self.eat_keyword(keywords::Mut) {
3848 // Parse mut ident @ pat / mut ref ident @ pat
3849 let mutref_span = self.prev_span.to(self.span);
3850 let binding_mode = if self.eat_keyword(keywords::Ref) {
3852 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3853 .span_suggestion(mutref_span, "try switching the order", "ref mut".into())
3855 BindingMode::ByRef(Mutability::Mutable)
3857 BindingMode::ByValue(Mutability::Mutable)
3859 pat = self.parse_pat_ident(binding_mode)?;
3860 } else if self.eat_keyword(keywords::Ref) {
3861 // Parse ref ident @ pat / ref mut ident @ pat
3862 let mutbl = self.parse_mutability();
3863 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3864 } else if self.eat_keyword(keywords::Box) {
3866 let subpat = self.parse_pat_with_range_pat(false)?;
3867 pat = PatKind::Box(subpat);
3868 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3869 self.parse_as_ident() {
3870 // Parse ident @ pat
3871 // This can give false positives and parse nullary enums,
3872 // they are dealt with later in resolve
3873 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3874 pat = self.parse_pat_ident(binding_mode)?;
3875 } else if self.token.is_path_start() {
3876 // Parse pattern starting with a path
3877 let (qself, path) = if self.eat_lt() {
3878 // Parse a qualified path
3879 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3882 // Parse an unqualified path
3883 (None, self.parse_path(PathStyle::Expr)?)
3886 token::Not if qself.is_none() => {
3887 // Parse macro invocation
3889 let (_, tts) = self.expect_delimited_token_tree()?;
3890 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3891 pat = PatKind::Mac(mac);
3893 token::DotDotDot | token::DotDotEq | token::DotDot => {
3894 let end_kind = match self.token {
3895 token::DotDot => RangeEnd::Excluded,
3896 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
3897 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
3898 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
3902 let span = lo.to(self.prev_span);
3903 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3905 let end = self.parse_pat_range_end()?;
3906 pat = PatKind::Range(begin, end, end_kind);
3908 token::OpenDelim(token::Brace) => {
3909 if qself.is_some() {
3910 let msg = "unexpected `{` after qualified path";
3911 let mut err = self.fatal(msg);
3912 err.span_label(self.span, msg);
3915 // Parse struct pattern
3917 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3919 self.recover_stmt();
3923 pat = PatKind::Struct(path, fields, etc);
3925 token::OpenDelim(token::Paren) => {
3926 if qself.is_some() {
3927 let msg = "unexpected `(` after qualified path";
3928 let mut err = self.fatal(msg);
3929 err.span_label(self.span, msg);
3932 // Parse tuple struct or enum pattern
3933 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
3934 pat = PatKind::TupleStruct(path, fields, ddpos)
3936 _ => pat = PatKind::Path(qself, path),
3939 // Try to parse everything else as literal with optional minus
3940 match self.parse_pat_literal_maybe_minus() {
3942 if self.eat(&token::DotDotDot) {
3943 let end = self.parse_pat_range_end()?;
3944 pat = PatKind::Range(begin, end,
3945 RangeEnd::Included(RangeSyntax::DotDotDot));
3946 } else if self.eat(&token::DotDotEq) {
3947 let end = self.parse_pat_range_end()?;
3948 pat = PatKind::Range(begin, end,
3949 RangeEnd::Included(RangeSyntax::DotDotEq));
3950 } else if self.eat(&token::DotDot) {
3951 let end = self.parse_pat_range_end()?;
3952 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3954 pat = PatKind::Lit(begin);
3958 self.cancel(&mut err);
3959 let msg = format!("expected pattern, found {}", self.this_token_descr());
3960 let mut err = self.fatal(&msg);
3961 err.span_label(self.span, "expected pattern");
3968 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
3969 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
3971 if !allow_range_pat {
3973 PatKind::Range(_, _, RangeEnd::Included(RangeSyntax::DotDotDot)) => {}
3974 PatKind::Range(..) => {
3975 let mut err = self.struct_span_err(
3977 "the range pattern here has ambiguous interpretation",
3979 err.span_suggestion(
3981 "add parentheses to clarify the precedence",
3982 format!("({})", pprust::pat_to_string(&pat)),
3993 /// Parse ident or ident @ pat
3994 /// used by the copy foo and ref foo patterns to give a good
3995 /// error message when parsing mistakes like ref foo(a,b)
3996 fn parse_pat_ident(&mut self,
3997 binding_mode: ast::BindingMode)
3998 -> PResult<'a, PatKind> {
3999 let ident_span = self.span;
4000 let ident = self.parse_ident()?;
4001 let name = codemap::Spanned{span: ident_span, node: ident};
4002 let sub = if self.eat(&token::At) {
4003 Some(self.parse_pat()?)
4008 // just to be friendly, if they write something like
4010 // we end up here with ( as the current token. This shortly
4011 // leads to a parse error. Note that if there is no explicit
4012 // binding mode then we do not end up here, because the lookahead
4013 // will direct us over to parse_enum_variant()
4014 if self.token == token::OpenDelim(token::Paren) {
4015 return Err(self.span_fatal(
4017 "expected identifier, found enum pattern"))
4020 Ok(PatKind::Ident(binding_mode, name, sub))
4023 /// Parse a local variable declaration
4024 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4025 let lo = self.prev_span;
4026 let pat = self.parse_top_level_pat()?;
4028 let (err, ty) = if self.eat(&token::Colon) {
4029 // Save the state of the parser before parsing type normally, in case there is a `:`
4030 // instead of an `=` typo.
4031 let parser_snapshot_before_type = self.clone();
4032 let colon_sp = self.prev_span;
4033 match self.parse_ty() {
4034 Ok(ty) => (None, Some(ty)),
4036 // Rewind to before attempting to parse the type and continue parsing
4037 let parser_snapshot_after_type = self.clone();
4038 mem::replace(self, parser_snapshot_before_type);
4040 let snippet = self.sess.codemap().span_to_snippet(pat.span).unwrap();
4041 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4042 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4048 let init = match (self.parse_initializer(err.is_some()), err) {
4049 (Ok(init), None) => { // init parsed, ty parsed
4052 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4053 // Could parse the type as if it were the initializer, it is likely there was a
4054 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4055 err.span_suggestion_short(colon_sp,
4056 "use `=` if you meant to assign",
4059 // As this was parsed successfully, continue as if the code has been fixed for the
4060 // rest of the file. It will still fail due to the emitted error, but we avoid
4064 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4066 // Couldn't parse the type nor the initializer, only raise the type error and
4067 // return to the parser state before parsing the type as the initializer.
4068 // let x: <parse_error>;
4069 mem::replace(self, snapshot);
4072 (Err(err), None) => { // init error, ty parsed
4073 // Couldn't parse the initializer and we're not attempting to recover a failed
4074 // parse of the type, return the error.
4078 let hi = if self.token == token::Semi {
4087 id: ast::DUMMY_NODE_ID,
4093 /// Parse a structure field
4094 fn parse_name_and_ty(&mut self,
4097 attrs: Vec<Attribute>)
4098 -> PResult<'a, StructField> {
4099 let name = self.parse_ident()?;
4100 self.expect(&token::Colon)?;
4101 let ty = self.parse_ty()?;
4103 span: lo.to(self.prev_span),
4106 id: ast::DUMMY_NODE_ID,
4112 /// Emit an expected item after attributes error.
4113 fn expected_item_err(&self, attrs: &[Attribute]) {
4114 let message = match attrs.last() {
4115 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4116 _ => "expected item after attributes",
4119 self.span_err(self.prev_span, message);
4122 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4123 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4124 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4125 Ok(self.parse_stmt_(true))
4128 // Eat tokens until we can be relatively sure we reached the end of the
4129 // statement. This is something of a best-effort heuristic.
4131 // We terminate when we find an unmatched `}` (without consuming it).
4132 fn recover_stmt(&mut self) {
4133 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4136 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4137 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4138 // approximate - it can mean we break too early due to macros, but that
4139 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
4141 // If `break_on_block` is `Break`, then we will stop consuming tokens
4142 // after finding (and consuming) a brace-delimited block.
4143 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4144 let mut brace_depth = 0;
4145 let mut bracket_depth = 0;
4146 let mut in_block = false;
4147 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4148 break_on_semi, break_on_block);
4150 debug!("recover_stmt_ loop {:?}", self.token);
4152 token::OpenDelim(token::DelimToken::Brace) => {
4155 if break_on_block == BlockMode::Break &&
4157 bracket_depth == 0 {
4161 token::OpenDelim(token::DelimToken::Bracket) => {
4165 token::CloseDelim(token::DelimToken::Brace) => {
4166 if brace_depth == 0 {
4167 debug!("recover_stmt_ return - close delim {:?}", self.token);
4172 if in_block && bracket_depth == 0 && brace_depth == 0 {
4173 debug!("recover_stmt_ return - block end {:?}", self.token);
4177 token::CloseDelim(token::DelimToken::Bracket) => {
4179 if bracket_depth < 0 {
4185 debug!("recover_stmt_ return - Eof");
4190 if break_on_semi == SemiColonMode::Break &&
4192 bracket_depth == 0 {
4193 debug!("recover_stmt_ return - Semi");
4204 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4205 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4207 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4212 fn is_catch_expr(&mut self) -> bool {
4213 self.token.is_keyword(keywords::Do) &&
4214 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4215 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4217 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
4218 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4221 fn is_union_item(&self) -> bool {
4222 self.token.is_keyword(keywords::Union) &&
4223 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4226 fn is_crate_vis(&self) -> bool {
4227 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4230 fn is_extern_non_path(&self) -> bool {
4231 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4234 fn is_auto_trait_item(&mut self) -> bool {
4236 (self.token.is_keyword(keywords::Auto)
4237 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4238 || // unsafe auto trait
4239 (self.token.is_keyword(keywords::Unsafe) &&
4240 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4241 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4244 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4245 -> PResult<'a, Option<P<Item>>> {
4246 let token_lo = self.span;
4247 let (ident, def) = match self.token {
4248 token::Ident(ident) if ident.name == keywords::Macro.name() => {
4250 let ident = self.parse_ident()?;
4251 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4252 match self.parse_token_tree() {
4253 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4254 _ => unreachable!(),
4256 } else if self.check(&token::OpenDelim(token::Paren)) {
4257 let args = self.parse_token_tree();
4258 let body = if self.check(&token::OpenDelim(token::Brace)) {
4259 self.parse_token_tree()
4264 TokenStream::concat(vec![
4266 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4274 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4276 token::Ident(ident) if ident.name == "macro_rules" &&
4277 self.look_ahead(1, |t| *t == token::Not) => {
4278 let prev_span = self.prev_span;
4279 self.complain_if_pub_macro(&vis.node, prev_span);
4283 let ident = self.parse_ident()?;
4284 let (delim, tokens) = self.expect_delimited_token_tree()?;
4285 if delim != token::Brace {
4286 if !self.eat(&token::Semi) {
4287 let msg = "macros that expand to items must either \
4288 be surrounded with braces or followed by a semicolon";
4289 self.span_err(self.prev_span, msg);
4293 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4295 _ => return Ok(None),
4298 let span = lo.to(self.prev_span);
4299 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4302 fn parse_stmt_without_recovery(&mut self,
4303 macro_legacy_warnings: bool)
4304 -> PResult<'a, Option<Stmt>> {
4305 maybe_whole!(self, NtStmt, |x| Some(x));
4307 let attrs = self.parse_outer_attributes()?;
4310 Ok(Some(if self.eat_keyword(keywords::Let) {
4312 id: ast::DUMMY_NODE_ID,
4313 node: StmtKind::Local(self.parse_local(attrs.into())?),
4314 span: lo.to(self.prev_span),
4316 } else if let Some(macro_def) = self.eat_macro_def(
4318 &codemap::respan(lo, VisibilityKind::Inherited),
4322 id: ast::DUMMY_NODE_ID,
4323 node: StmtKind::Item(macro_def),
4324 span: lo.to(self.prev_span),
4326 // Starts like a simple path, being careful to avoid contextual keywords
4327 // such as a union items, item with `crate` visibility or auto trait items.
4328 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4329 // like a path (1 token), but it fact not a path.
4330 // `union::b::c` - path, `union U { ... }` - not a path.
4331 // `crate::b::c` - path, `crate struct S;` - not a path.
4332 // `extern::b::c` - path, `extern crate c;` - not a path.
4333 } else if self.token.is_path_start() &&
4334 !self.token.is_qpath_start() &&
4335 !self.is_union_item() &&
4336 !self.is_crate_vis() &&
4337 !self.is_extern_non_path() &&
4338 !self.is_auto_trait_item() {
4339 let pth = self.parse_path(PathStyle::Expr)?;
4341 if !self.eat(&token::Not) {
4342 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4343 self.parse_struct_expr(lo, pth, ThinVec::new())?
4345 let hi = self.prev_span;
4346 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4349 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4350 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4351 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4354 return Ok(Some(Stmt {
4355 id: ast::DUMMY_NODE_ID,
4356 node: StmtKind::Expr(expr),
4357 span: lo.to(self.prev_span),
4361 // it's a macro invocation
4362 let id = match self.token {
4363 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4364 _ => self.parse_ident()?,
4367 // check that we're pointing at delimiters (need to check
4368 // again after the `if`, because of `parse_ident`
4369 // consuming more tokens).
4370 let delim = match self.token {
4371 token::OpenDelim(delim) => delim,
4373 // we only expect an ident if we didn't parse one
4375 let ident_str = if id.name == keywords::Invalid.name() {
4380 let tok_str = self.this_token_to_string();
4381 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4384 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4389 let (_, tts) = self.expect_delimited_token_tree()?;
4390 let hi = self.prev_span;
4392 let style = if delim == token::Brace {
4393 MacStmtStyle::Braces
4395 MacStmtStyle::NoBraces
4398 if id.name == keywords::Invalid.name() {
4399 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
4400 let node = if delim == token::Brace ||
4401 self.token == token::Semi || self.token == token::Eof {
4402 StmtKind::Mac(P((mac, style, attrs.into())))
4404 // We used to incorrectly stop parsing macro-expanded statements here.
4405 // If the next token will be an error anyway but could have parsed with the
4406 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4407 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4408 // These can continue an expression, so we can't stop parsing and warn.
4409 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4410 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4411 token::BinOp(token::And) | token::BinOp(token::Or) |
4412 token::AndAnd | token::OrOr |
4413 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4416 self.warn_missing_semicolon();
4417 StmtKind::Mac(P((mac, style, attrs.into())))
4419 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4420 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4421 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4425 id: ast::DUMMY_NODE_ID,
4430 // if it has a special ident, it's definitely an item
4432 // Require a semicolon or braces.
4433 if style != MacStmtStyle::Braces {
4434 if !self.eat(&token::Semi) {
4435 self.span_err(self.prev_span,
4436 "macros that expand to items must \
4437 either be surrounded with braces or \
4438 followed by a semicolon");
4441 let span = lo.to(hi);
4443 id: ast::DUMMY_NODE_ID,
4445 node: StmtKind::Item({
4447 span, id /*id is good here*/,
4448 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
4449 respan(lo, VisibilityKind::Inherited),
4455 // FIXME: Bad copy of attrs
4456 let old_directory_ownership =
4457 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4458 let item = self.parse_item_(attrs.clone(), false, true)?;
4459 self.directory.ownership = old_directory_ownership;
4463 id: ast::DUMMY_NODE_ID,
4464 span: lo.to(i.span),
4465 node: StmtKind::Item(i),
4468 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4469 if !attrs.is_empty() {
4470 if s.prev_token_kind == PrevTokenKind::DocComment {
4471 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4472 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4473 s.span_err(s.span, "expected statement after outer attribute");
4478 // Do not attempt to parse an expression if we're done here.
4479 if self.token == token::Semi {
4480 unused_attrs(&attrs, self);
4485 if self.token == token::CloseDelim(token::Brace) {
4486 unused_attrs(&attrs, self);
4490 // Remainder are line-expr stmts.
4491 let e = self.parse_expr_res(
4492 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4494 id: ast::DUMMY_NODE_ID,
4495 span: lo.to(e.span),
4496 node: StmtKind::Expr(e),
4503 /// Is this expression a successfully-parsed statement?
4504 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4505 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4506 !classify::expr_requires_semi_to_be_stmt(e)
4509 /// Parse a block. No inner attrs are allowed.
4510 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4511 maybe_whole!(self, NtBlock, |x| x);
4515 if !self.eat(&token::OpenDelim(token::Brace)) {
4517 let tok = self.this_token_to_string();
4518 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4520 // Check to see if the user has written something like
4525 // Which is valid in other languages, but not Rust.
4526 match self.parse_stmt_without_recovery(false) {
4528 let mut stmt_span = stmt.span;
4529 // expand the span to include the semicolon, if it exists
4530 if self.eat(&token::Semi) {
4531 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4533 let sugg = pprust::to_string(|s| {
4534 use print::pprust::{PrintState, INDENT_UNIT};
4535 s.ibox(INDENT_UNIT)?;
4537 s.print_stmt(&stmt)?;
4538 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4540 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4543 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4544 self.cancel(&mut e);
4551 self.parse_block_tail(lo, BlockCheckMode::Default)
4554 /// Parse a block. Inner attrs are allowed.
4555 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4556 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4559 self.expect(&token::OpenDelim(token::Brace))?;
4560 Ok((self.parse_inner_attributes()?,
4561 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4564 /// Parse the rest of a block expression or function body
4565 /// Precondition: already parsed the '{'.
4566 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4567 let mut stmts = vec![];
4568 let mut recovered = false;
4570 while !self.eat(&token::CloseDelim(token::Brace)) {
4571 let stmt = match self.parse_full_stmt(false) {
4574 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4575 self.eat(&token::CloseDelim(token::Brace));
4581 if let Some(stmt) = stmt {
4583 } else if self.token == token::Eof {
4586 // Found only `;` or `}`.
4592 id: ast::DUMMY_NODE_ID,
4594 span: lo.to(self.prev_span),
4599 /// Parse a statement, including the trailing semicolon.
4600 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4601 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4603 None => return Ok(None),
4607 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4608 // expression without semicolon
4609 if classify::expr_requires_semi_to_be_stmt(expr) {
4610 // Just check for errors and recover; do not eat semicolon yet.
4612 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4615 self.recover_stmt();
4619 StmtKind::Local(..) => {
4620 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4621 if macro_legacy_warnings && self.token != token::Semi {
4622 self.warn_missing_semicolon();
4624 self.expect_one_of(&[token::Semi], &[])?;
4630 if self.eat(&token::Semi) {
4631 stmt = stmt.add_trailing_semicolon();
4634 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4638 fn warn_missing_semicolon(&self) {
4639 self.diagnostic().struct_span_warn(self.span, {
4640 &format!("expected `;`, found `{}`", self.this_token_to_string())
4642 "This was erroneously allowed and will become a hard error in a future release"
4646 fn err_dotdotdot_syntax(&self, span: Span) {
4647 self.diagnostic().struct_span_err(span, {
4648 "`...` syntax cannot be used in expressions"
4650 "Use `..` if you need an exclusive range (a < b)"
4652 "or `..=` if you need an inclusive range (a <= b)"
4656 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4657 // BOUND = TY_BOUND | LT_BOUND
4658 // LT_BOUND = LIFETIME (e.g. `'a`)
4659 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4660 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4661 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4662 let mut bounds = Vec::new();
4664 // This needs to be syncronized with `Token::can_begin_bound`.
4665 let is_bound_start = self.check_path() || self.check_lifetime() ||
4666 self.check(&token::Question) ||
4667 self.check_keyword(keywords::For) ||
4668 self.check(&token::OpenDelim(token::Paren));
4670 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4671 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4672 if self.token.is_lifetime() {
4673 if let Some(question_span) = question {
4674 self.span_err(question_span,
4675 "`?` may only modify trait bounds, not lifetime bounds");
4677 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4680 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4681 let path = self.parse_path(PathStyle::Type)?;
4682 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4683 let modifier = if question.is_some() {
4684 TraitBoundModifier::Maybe
4686 TraitBoundModifier::None
4688 bounds.push(TraitTyParamBound(poly_trait, modifier));
4691 self.expect(&token::CloseDelim(token::Paren))?;
4692 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4693 self.span_err(self.prev_span,
4694 "parenthesized lifetime bounds are not supported");
4701 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4709 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4710 self.parse_ty_param_bounds_common(true)
4713 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4714 // BOUND = LT_BOUND (e.g. `'a`)
4715 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4716 let mut lifetimes = Vec::new();
4717 while self.check_lifetime() {
4718 lifetimes.push(self.expect_lifetime());
4720 if !self.eat(&token::BinOp(token::Plus)) {
4727 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4728 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4729 let span = self.span;
4730 let ident = self.parse_ident()?;
4732 // Parse optional colon and param bounds.
4733 let bounds = if self.eat(&token::Colon) {
4734 self.parse_ty_param_bounds()?
4739 let default = if self.eat(&token::Eq) {
4740 Some(self.parse_ty()?)
4746 attrs: preceding_attrs.into(),
4748 id: ast::DUMMY_NODE_ID,
4755 /// Parses the following grammar:
4756 /// TraitItemAssocTy = Ident ["<"...">"] [":" [TyParamBounds]] ["where" ...] ["=" Ty]
4757 fn parse_trait_item_assoc_ty(&mut self, preceding_attrs: Vec<Attribute>)
4758 -> PResult<'a, (ast::Generics, TyParam)> {
4759 let span = self.span;
4760 let ident = self.parse_ident()?;
4761 let mut generics = self.parse_generics()?;
4763 // Parse optional colon and param bounds.
4764 let bounds = if self.eat(&token::Colon) {
4765 self.parse_ty_param_bounds()?
4769 generics.where_clause = self.parse_where_clause()?;
4771 let default = if self.eat(&token::Eq) {
4772 Some(self.parse_ty()?)
4776 self.expect(&token::Semi)?;
4778 Ok((generics, TyParam {
4779 attrs: preceding_attrs.into(),
4781 id: ast::DUMMY_NODE_ID,
4788 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4789 /// trailing comma and erroneous trailing attributes.
4790 pub fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4791 let mut params = Vec::new();
4792 let mut seen_ty_param = false;
4794 let attrs = self.parse_outer_attributes()?;
4795 if self.check_lifetime() {
4796 let lifetime = self.expect_lifetime();
4797 // Parse lifetime parameter.
4798 let bounds = if self.eat(&token::Colon) {
4799 self.parse_lt_param_bounds()
4803 params.push(ast::GenericParam::Lifetime(LifetimeDef {
4804 attrs: attrs.into(),
4809 self.span_err(self.prev_span,
4810 "lifetime parameters must be declared prior to type parameters");
4812 } else if self.check_ident() {
4813 // Parse type parameter.
4814 params.push(ast::GenericParam::Type(self.parse_ty_param(attrs)?));
4815 seen_ty_param = true;
4817 // Check for trailing attributes and stop parsing.
4818 if !attrs.is_empty() {
4819 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4820 self.span_err(attrs[0].span,
4821 &format!("trailing attribute after {} parameters", param_kind));
4826 if !self.eat(&token::Comma) {
4833 /// Parse a set of optional generic type parameter declarations. Where
4834 /// clauses are not parsed here, and must be added later via
4835 /// `parse_where_clause()`.
4837 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4838 /// | ( < lifetimes , typaramseq ( , )? > )
4839 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4840 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4841 maybe_whole!(self, NtGenerics, |x| x);
4843 let span_lo = self.span;
4845 let params = self.parse_generic_params()?;
4849 where_clause: WhereClause {
4850 id: ast::DUMMY_NODE_ID,
4851 predicates: Vec::new(),
4852 span: syntax_pos::DUMMY_SP,
4854 span: span_lo.to(self.prev_span),
4857 Ok(ast::Generics::default())
4861 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4862 /// possibly including trailing comma.
4863 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4864 let mut lifetimes = Vec::new();
4865 let mut types = Vec::new();
4866 let mut bindings = Vec::new();
4867 let mut seen_type = false;
4868 let mut seen_binding = false;
4870 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4871 // Parse lifetime argument.
4872 lifetimes.push(self.expect_lifetime());
4873 if seen_type || seen_binding {
4874 self.span_err(self.prev_span,
4875 "lifetime parameters must be declared prior to type parameters");
4877 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4878 // Parse associated type binding.
4880 let ident = self.parse_ident()?;
4882 let ty = self.parse_ty()?;
4883 bindings.push(TypeBinding {
4884 id: ast::DUMMY_NODE_ID,
4887 span: lo.to(self.prev_span),
4889 seen_binding = true;
4890 } else if self.check_type() {
4891 // Parse type argument.
4892 types.push(self.parse_ty()?);
4894 self.span_err(types[types.len() - 1].span,
4895 "type parameters must be declared prior to associated type bindings");
4902 if !self.eat(&token::Comma) {
4906 Ok((lifetimes, types, bindings))
4909 /// Parses an optional `where` clause and places it in `generics`.
4911 /// ```ignore (only-for-syntax-highlight)
4912 /// where T : Trait<U, V> + 'b, 'a : 'b
4914 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4915 maybe_whole!(self, NtWhereClause, |x| x);
4917 let mut where_clause = WhereClause {
4918 id: ast::DUMMY_NODE_ID,
4919 predicates: Vec::new(),
4920 span: syntax_pos::DUMMY_SP,
4923 if !self.eat_keyword(keywords::Where) {
4924 return Ok(where_clause);
4926 let lo = self.prev_span;
4928 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4929 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4930 // change we parse those generics now, but report an error.
4931 if self.choose_generics_over_qpath() {
4932 let generics = self.parse_generics()?;
4933 self.span_err(generics.span,
4934 "generic parameters on `where` clauses are reserved for future use");
4939 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4940 let lifetime = self.expect_lifetime();
4941 // Bounds starting with a colon are mandatory, but possibly empty.
4942 self.expect(&token::Colon)?;
4943 let bounds = self.parse_lt_param_bounds();
4944 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4945 ast::WhereRegionPredicate {
4946 span: lo.to(self.prev_span),
4951 } else if self.check_type() {
4952 // Parse optional `for<'a, 'b>`.
4953 // This `for` is parsed greedily and applies to the whole predicate,
4954 // the bounded type can have its own `for` applying only to it.
4955 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4956 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4957 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4958 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4960 // Parse type with mandatory colon and (possibly empty) bounds,
4961 // or with mandatory equality sign and the second type.
4962 let ty = self.parse_ty()?;
4963 if self.eat(&token::Colon) {
4964 let bounds = self.parse_ty_param_bounds()?;
4965 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4966 ast::WhereBoundPredicate {
4967 span: lo.to(self.prev_span),
4968 bound_generic_params: lifetime_defs,
4973 // FIXME: Decide what should be used here, `=` or `==`.
4974 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
4975 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4976 let rhs_ty = self.parse_ty()?;
4977 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4978 ast::WhereEqPredicate {
4979 span: lo.to(self.prev_span),
4982 id: ast::DUMMY_NODE_ID,
4986 return self.unexpected();
4992 if !self.eat(&token::Comma) {
4997 where_clause.span = lo.to(self.prev_span);
5001 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5002 -> PResult<'a, (Vec<Arg> , bool)> {
5004 let mut variadic = false;
5005 let args: Vec<Option<Arg>> =
5006 self.parse_unspanned_seq(
5007 &token::OpenDelim(token::Paren),
5008 &token::CloseDelim(token::Paren),
5009 SeqSep::trailing_allowed(token::Comma),
5011 if p.token == token::DotDotDot {
5015 if p.token != token::CloseDelim(token::Paren) {
5018 "`...` must be last in argument list for variadic function");
5022 let span = p.prev_span;
5023 if p.token == token::CloseDelim(token::Paren) {
5024 // continue parsing to present any further errors
5027 "only foreign functions are allowed to be variadic"
5029 Ok(Some(dummy_arg(span)))
5031 // this function definition looks beyond recovery, stop parsing
5033 "only foreign functions are allowed to be variadic");
5038 match p.parse_arg_general(named_args) {
5039 Ok(arg) => Ok(Some(arg)),
5042 let lo = p.prev_span;
5043 // Skip every token until next possible arg or end.
5044 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5045 // Create a placeholder argument for proper arg count (#34264).
5046 let span = lo.to(p.prev_span);
5047 Ok(Some(dummy_arg(span)))
5054 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5056 if variadic && args.is_empty() {
5058 "variadic function must be declared with at least one named argument");
5061 Ok((args, variadic))
5064 /// Parse the argument list and result type of a function declaration
5065 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5067 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5068 let ret_ty = self.parse_ret_ty(true)?;
5077 /// Returns the parsed optional self argument and whether a self shortcut was used.
5078 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5079 let expect_ident = |this: &mut Self| match this.token {
5080 // Preserve hygienic context.
5081 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
5084 let isolated_self = |this: &mut Self, n| {
5085 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5086 this.look_ahead(n + 1, |t| t != &token::ModSep)
5089 // Parse optional self parameter of a method.
5090 // Only a limited set of initial token sequences is considered self parameters, anything
5091 // else is parsed as a normal function parameter list, so some lookahead is required.
5092 let eself_lo = self.span;
5093 let (eself, eself_ident) = match self.token {
5094 token::BinOp(token::And) => {
5100 if isolated_self(self, 1) {
5102 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
5103 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5104 isolated_self(self, 2) {
5107 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
5108 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5109 isolated_self(self, 2) {
5111 let lt = self.expect_lifetime();
5112 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
5113 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5114 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5115 isolated_self(self, 3) {
5117 let lt = self.expect_lifetime();
5119 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
5124 token::BinOp(token::Star) => {
5129 // Emit special error for `self` cases.
5130 if isolated_self(self, 1) {
5132 self.span_err(self.span, "cannot pass `self` by raw pointer");
5133 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
5134 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5135 isolated_self(self, 2) {
5138 self.span_err(self.span, "cannot pass `self` by raw pointer");
5139 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
5144 token::Ident(..) => {
5145 if isolated_self(self, 0) {
5148 let eself_ident = expect_ident(self);
5149 if self.eat(&token::Colon) {
5150 let ty = self.parse_ty()?;
5151 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
5153 (SelfKind::Value(Mutability::Immutable), eself_ident)
5155 } else if self.token.is_keyword(keywords::Mut) &&
5156 isolated_self(self, 1) {
5160 let eself_ident = expect_ident(self);
5161 if self.eat(&token::Colon) {
5162 let ty = self.parse_ty()?;
5163 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
5165 (SelfKind::Value(Mutability::Mutable), eself_ident)
5171 _ => return Ok(None),
5174 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
5175 Ok(Some(Arg::from_self(eself, eself_ident)))
5178 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5179 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5180 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5182 self.expect(&token::OpenDelim(token::Paren))?;
5184 // Parse optional self argument
5185 let self_arg = self.parse_self_arg()?;
5187 // Parse the rest of the function parameter list.
5188 let sep = SeqSep::trailing_allowed(token::Comma);
5189 let fn_inputs = if let Some(self_arg) = self_arg {
5190 if self.check(&token::CloseDelim(token::Paren)) {
5192 } else if self.eat(&token::Comma) {
5193 let mut fn_inputs = vec![self_arg];
5194 fn_inputs.append(&mut self.parse_seq_to_before_end(
5195 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5199 return self.unexpected();
5202 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5205 // Parse closing paren and return type.
5206 self.expect(&token::CloseDelim(token::Paren))?;
5209 output: self.parse_ret_ty(true)?,
5214 // parse the |arg, arg| header on a lambda
5215 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5216 let inputs_captures = {
5217 if self.eat(&token::OrOr) {
5220 self.expect(&token::BinOp(token::Or))?;
5221 let args = self.parse_seq_to_before_tokens(
5222 &[&token::BinOp(token::Or), &token::OrOr],
5223 SeqSep::trailing_allowed(token::Comma),
5224 TokenExpectType::NoExpect,
5225 |p| p.parse_fn_block_arg()
5231 let output = self.parse_ret_ty(true)?;
5234 inputs: inputs_captures,
5240 /// Parse the name and optional generic types of a function header.
5241 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5242 let id = self.parse_ident()?;
5243 let generics = self.parse_generics()?;
5247 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5248 attrs: Vec<Attribute>) -> P<Item> {
5252 id: ast::DUMMY_NODE_ID,
5260 /// Parse an item-position function declaration.
5261 fn parse_item_fn(&mut self,
5263 constness: Spanned<Constness>,
5265 -> PResult<'a, ItemInfo> {
5266 let (ident, mut generics) = self.parse_fn_header()?;
5267 let decl = self.parse_fn_decl(false)?;
5268 generics.where_clause = self.parse_where_clause()?;
5269 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5270 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
5273 /// true if we are looking at `const ID`, false for things like `const fn` etc
5274 pub fn is_const_item(&mut self) -> bool {
5275 self.token.is_keyword(keywords::Const) &&
5276 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5277 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5280 /// parses all the "front matter" for a `fn` declaration, up to
5281 /// and including the `fn` keyword:
5285 /// - `const unsafe fn`
5288 pub fn parse_fn_front_matter(&mut self) -> PResult<'a, (Spanned<Constness>, Unsafety, Abi)> {
5289 let is_const_fn = self.eat_keyword(keywords::Const);
5290 let const_span = self.prev_span;
5291 let unsafety = self.parse_unsafety();
5292 let (constness, unsafety, abi) = if is_const_fn {
5293 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5295 let abi = if self.eat_keyword(keywords::Extern) {
5296 self.parse_opt_abi()?.unwrap_or(Abi::C)
5300 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5302 self.expect_keyword(keywords::Fn)?;
5303 Ok((constness, unsafety, abi))
5306 /// Parse an impl item.
5307 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5308 maybe_whole!(self, NtImplItem, |x| x);
5309 let attrs = self.parse_outer_attributes()?;
5310 let (mut item, tokens) = self.collect_tokens(|this| {
5311 this.parse_impl_item_(at_end, attrs)
5314 // See `parse_item` for why this clause is here.
5315 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5316 item.tokens = Some(tokens);
5321 fn parse_impl_item_(&mut self,
5323 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5325 let vis = self.parse_visibility(false)?;
5326 let defaultness = self.parse_defaultness();
5327 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
5328 // This parses the grammar:
5329 // ImplItemAssocTy = Ident ["<"...">"] ["where" ...] "=" Ty ";"
5330 let name = self.parse_ident()?;
5331 let mut generics = self.parse_generics()?;
5332 generics.where_clause = self.parse_where_clause()?;
5333 self.expect(&token::Eq)?;
5334 let typ = self.parse_ty()?;
5335 self.expect(&token::Semi)?;
5336 (name, ast::ImplItemKind::Type(typ), generics)
5337 } else if self.is_const_item() {
5338 // This parses the grammar:
5339 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5340 self.expect_keyword(keywords::Const)?;
5341 let name = self.parse_ident()?;
5342 self.expect(&token::Colon)?;
5343 let typ = self.parse_ty()?;
5344 self.expect(&token::Eq)?;
5345 let expr = self.parse_expr()?;
5346 self.expect(&token::Semi)?;
5347 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5349 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5350 attrs.extend(inner_attrs);
5351 (name, node, generics)
5355 id: ast::DUMMY_NODE_ID,
5356 span: lo.to(self.prev_span),
5367 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5368 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5373 fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5375 VisibilityKind::Inherited => Ok(()),
5377 let is_macro_rules: bool = match self.token {
5378 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
5382 let mut err = self.diagnostic()
5383 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5384 err.span_suggestion(sp,
5385 "try exporting the macro",
5386 "#[macro_export]".to_owned());
5389 let mut err = self.diagnostic()
5390 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5391 err.help("try adjusting the macro to put `pub` inside the invocation");
5398 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5399 -> DiagnosticBuilder<'a>
5401 // Given this code `path(`, it seems like this is not
5402 // setting the visibility of a macro invocation, but rather
5403 // a mistyped method declaration.
5404 // Create a diagnostic pointing out that `fn` is missing.
5406 // x | pub path(&self) {
5407 // | ^ missing `fn`, `type`, or `const`
5409 // ^^ `sp` below will point to this
5410 let sp = prev_span.between(self.prev_span);
5411 let mut err = self.diagnostic().struct_span_err(
5413 &format!("missing `fn`, `type`, or `const` for {}-item declaration",
5415 err.span_label(sp, "missing `fn`, `type`, or `const`");
5419 /// Parse a method or a macro invocation in a trait impl.
5420 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5421 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5422 ast::ImplItemKind)> {
5423 // code copied from parse_macro_use_or_failure... abstraction!
5424 if self.token.is_path_start() && !self.is_extern_non_path() {
5427 let prev_span = self.prev_span;
5430 let pth = self.parse_path(PathStyle::Mod)?;
5431 if pth.segments.len() == 1 {
5432 if !self.eat(&token::Not) {
5433 return Err(self.missing_assoc_item_kind_err("impl", prev_span));
5436 self.expect(&token::Not)?;
5439 self.complain_if_pub_macro(&vis.node, prev_span);
5441 // eat a matched-delimiter token tree:
5443 let (delim, tts) = self.expect_delimited_token_tree()?;
5444 if delim != token::Brace {
5445 self.expect(&token::Semi)?
5448 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
5449 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5450 ast::ImplItemKind::Macro(mac)))
5452 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
5453 let ident = self.parse_ident()?;
5454 let mut generics = self.parse_generics()?;
5455 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5456 generics.where_clause = self.parse_where_clause()?;
5458 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5459 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(ast::MethodSig {
5468 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5469 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5470 let ident = self.parse_ident()?;
5471 let mut tps = self.parse_generics()?;
5473 // Parse optional colon and supertrait bounds.
5474 let bounds = if self.eat(&token::Colon) {
5475 self.parse_ty_param_bounds()?
5480 if self.eat(&token::Eq) {
5481 // it's a trait alias
5482 let bounds = self.parse_ty_param_bounds()?;
5483 tps.where_clause = self.parse_where_clause()?;
5484 self.expect(&token::Semi)?;
5485 if unsafety != Unsafety::Normal {
5486 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5488 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5490 // it's a normal trait
5491 tps.where_clause = self.parse_where_clause()?;
5492 self.expect(&token::OpenDelim(token::Brace))?;
5493 let mut trait_items = vec![];
5494 while !self.eat(&token::CloseDelim(token::Brace)) {
5495 let mut at_end = false;
5496 match self.parse_trait_item(&mut at_end) {
5497 Ok(item) => trait_items.push(item),
5501 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5506 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5510 fn choose_generics_over_qpath(&self) -> bool {
5511 // There's an ambiguity between generic parameters and qualified paths in impls.
5512 // If we see `<` it may start both, so we have to inspect some following tokens.
5513 // The following combinations can only start generics,
5514 // but not qualified paths (with one exception):
5515 // `<` `>` - empty generic parameters
5516 // `<` `#` - generic parameters with attributes
5517 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5518 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5519 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5520 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5521 // The only truly ambiguous case is
5522 // `<` IDENT `>` `::` IDENT ...
5523 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5524 // because this is what almost always expected in practice, qualified paths in impls
5525 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5526 self.token == token::Lt &&
5527 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5528 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5529 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5530 t == &token::Colon || t == &token::Eq))
5533 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5534 self.expect(&token::OpenDelim(token::Brace))?;
5535 let attrs = self.parse_inner_attributes()?;
5537 let mut impl_items = Vec::new();
5538 while !self.eat(&token::CloseDelim(token::Brace)) {
5539 let mut at_end = false;
5540 match self.parse_impl_item(&mut at_end) {
5541 Ok(impl_item) => impl_items.push(impl_item),
5545 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5550 Ok((impl_items, attrs))
5553 /// Parses an implementation item, `impl` keyword is already parsed.
5554 /// impl<'a, T> TYPE { /* impl items */ }
5555 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5556 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5557 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5558 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5559 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5560 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5561 -> PResult<'a, ItemInfo> {
5562 // First, parse generic parameters if necessary.
5563 let mut generics = if self.choose_generics_over_qpath() {
5564 self.parse_generics()?
5566 ast::Generics::default()
5569 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5570 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5572 ast::ImplPolarity::Negative
5574 ast::ImplPolarity::Positive
5577 // Parse both types and traits as a type, then reinterpret if necessary.
5578 let ty_first = self.parse_ty()?;
5580 // If `for` is missing we try to recover.
5581 let has_for = self.eat_keyword(keywords::For);
5582 let missing_for_span = self.prev_span.between(self.span);
5584 let ty_second = if self.token == token::DotDot {
5585 // We need to report this error after `cfg` expansion for compatibility reasons
5586 self.bump(); // `..`, do not add it to expected tokens
5587 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5588 } else if has_for || self.token.can_begin_type() {
5589 Some(self.parse_ty()?)
5594 generics.where_clause = self.parse_where_clause()?;
5596 let (impl_items, attrs) = self.parse_impl_body()?;
5598 let item_kind = match ty_second {
5599 Some(ty_second) => {
5600 // impl Trait for Type
5602 self.span_err(missing_for_span, "missing `for` in a trait impl");
5605 let ty_first = ty_first.into_inner();
5606 let path = match ty_first.node {
5607 // This notably includes paths passed through `ty` macro fragments (#46438).
5608 TyKind::Path(None, path) => path,
5610 self.span_err(ty_first.span, "expected a trait, found type");
5611 ast::Path::from_ident(ty_first.span, keywords::Invalid.ident())
5614 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5616 ItemKind::Impl(unsafety, polarity, defaultness,
5617 generics, Some(trait_ref), ty_second, impl_items)
5621 ItemKind::Impl(unsafety, polarity, defaultness,
5622 generics, None, ty_first, impl_items)
5626 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5629 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5630 if self.eat_keyword(keywords::For) {
5632 let params = self.parse_generic_params()?;
5634 // We rely on AST validation to rule out invalid cases: There must not be type
5635 // parameters, and the lifetime parameters must not have bounds.
5642 /// Parse struct Foo { ... }
5643 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5644 let class_name = self.parse_ident()?;
5646 let mut generics = self.parse_generics()?;
5648 // There is a special case worth noting here, as reported in issue #17904.
5649 // If we are parsing a tuple struct it is the case that the where clause
5650 // should follow the field list. Like so:
5652 // struct Foo<T>(T) where T: Copy;
5654 // If we are parsing a normal record-style struct it is the case
5655 // that the where clause comes before the body, and after the generics.
5656 // So if we look ahead and see a brace or a where-clause we begin
5657 // parsing a record style struct.
5659 // Otherwise if we look ahead and see a paren we parse a tuple-style
5662 let vdata = if self.token.is_keyword(keywords::Where) {
5663 generics.where_clause = self.parse_where_clause()?;
5664 if self.eat(&token::Semi) {
5665 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5666 VariantData::Unit(ast::DUMMY_NODE_ID)
5668 // If we see: `struct Foo<T> where T: Copy { ... }`
5669 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5671 // No `where` so: `struct Foo<T>;`
5672 } else if self.eat(&token::Semi) {
5673 VariantData::Unit(ast::DUMMY_NODE_ID)
5674 // Record-style struct definition
5675 } else if self.token == token::OpenDelim(token::Brace) {
5676 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5677 // Tuple-style struct definition with optional where-clause.
5678 } else if self.token == token::OpenDelim(token::Paren) {
5679 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5680 generics.where_clause = self.parse_where_clause()?;
5681 self.expect(&token::Semi)?;
5684 let token_str = self.this_token_to_string();
5685 let mut err = self.fatal(&format!(
5686 "expected `where`, `{{`, `(`, or `;` after struct name, found `{}`",
5689 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
5693 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5696 /// Parse union Foo { ... }
5697 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5698 let class_name = self.parse_ident()?;
5700 let mut generics = self.parse_generics()?;
5702 let vdata = if self.token.is_keyword(keywords::Where) {
5703 generics.where_clause = self.parse_where_clause()?;
5704 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5705 } else if self.token == token::OpenDelim(token::Brace) {
5706 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5708 let token_str = self.this_token_to_string();
5709 let mut err = self.fatal(&format!(
5710 "expected `where` or `{{` after union name, found `{}`", token_str));
5711 err.span_label(self.span, "expected `where` or `{` after union name");
5715 Ok((class_name, ItemKind::Union(vdata, generics), None))
5718 fn consume_block(&mut self, delim: token::DelimToken) {
5719 let mut brace_depth = 0;
5720 if !self.eat(&token::OpenDelim(delim)) {
5724 if self.eat(&token::OpenDelim(delim)) {
5726 } else if self.eat(&token::CloseDelim(delim)) {
5727 if brace_depth == 0 {
5733 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5741 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5742 let mut fields = Vec::new();
5743 if self.eat(&token::OpenDelim(token::Brace)) {
5744 while self.token != token::CloseDelim(token::Brace) {
5745 let field = self.parse_struct_decl_field().map_err(|e| {
5746 self.recover_stmt();
5750 Ok(field) => fields.push(field),
5756 self.eat(&token::CloseDelim(token::Brace));
5758 let token_str = self.this_token_to_string();
5759 let mut err = self.fatal(&format!(
5760 "expected `where`, or `{{` after struct name, found `{}`", token_str));
5761 err.span_label(self.span, "expected `where`, or `{` after struct name");
5768 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5769 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5770 // Unit like structs are handled in parse_item_struct function
5771 let fields = self.parse_unspanned_seq(
5772 &token::OpenDelim(token::Paren),
5773 &token::CloseDelim(token::Paren),
5774 SeqSep::trailing_allowed(token::Comma),
5776 let attrs = p.parse_outer_attributes()?;
5778 let vis = p.parse_visibility(true)?;
5779 let ty = p.parse_ty()?;
5781 span: lo.to(p.span),
5784 id: ast::DUMMY_NODE_ID,
5793 /// Parse a structure field declaration
5794 pub fn parse_single_struct_field(&mut self,
5797 attrs: Vec<Attribute> )
5798 -> PResult<'a, StructField> {
5799 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5804 token::CloseDelim(token::Brace) => {}
5805 token::DocComment(_) => {
5806 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
5807 self.bump(); // consume the doc comment
5808 if self.eat(&token::Comma) || self.token == token::CloseDelim(token::Brace) {
5814 _ => return Err(self.span_fatal_help(self.span,
5815 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5816 "struct fields should be separated by commas")),
5821 /// Parse an element of a struct definition
5822 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5823 let attrs = self.parse_outer_attributes()?;
5825 let vis = self.parse_visibility(false)?;
5826 self.parse_single_struct_field(lo, vis, attrs)
5829 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5830 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5831 /// a function definition, it's not a tuple struct field) and the contents within the parens
5832 /// isn't valid, emit a proper diagnostic.
5833 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5834 maybe_whole!(self, NtVis, |x| x);
5836 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
5837 if self.is_crate_vis() {
5838 self.bump(); // `crate`
5839 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
5842 if !self.eat_keyword(keywords::Pub) {
5843 return Ok(respan(self.prev_span, VisibilityKind::Inherited))
5845 let lo = self.prev_span;
5847 if self.check(&token::OpenDelim(token::Paren)) {
5848 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5849 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5850 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5851 // by the following tokens.
5852 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5855 self.bump(); // `crate`
5856 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5858 lo.to(self.prev_span),
5859 VisibilityKind::Crate(CrateSugar::PubCrate),
5862 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5865 self.bump(); // `in`
5866 let path = self.parse_path(PathStyle::Mod)?; // `path`
5867 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5868 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
5870 id: ast::DUMMY_NODE_ID,
5873 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5874 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5875 t.is_keyword(keywords::SelfValue))
5877 // `pub(self)` or `pub(super)`
5879 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
5880 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5881 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
5883 id: ast::DUMMY_NODE_ID,
5886 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5887 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5889 let msg = "incorrect visibility restriction";
5890 let suggestion = r##"some possible visibility restrictions are:
5891 `pub(crate)`: visible only on the current crate
5892 `pub(super)`: visible only in the current module's parent
5893 `pub(in path::to::module)`: visible only on the specified path"##;
5894 let path = self.parse_path(PathStyle::Mod)?;
5895 let path_span = self.prev_span;
5896 let help_msg = format!("make this visible only to module `{}` with `in`", path);
5897 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5898 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5899 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5900 err.emit(); // emit diagnostic, but continue with public visibility
5904 Ok(respan(lo, VisibilityKind::Public))
5907 /// Parse defaultness: `default` or nothing.
5908 fn parse_defaultness(&mut self) -> Defaultness {
5909 // `pub` is included for better error messages
5910 if self.check_keyword(keywords::Default) &&
5911 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
5912 t.is_keyword(keywords::Const) ||
5913 t.is_keyword(keywords::Fn) ||
5914 t.is_keyword(keywords::Unsafe) ||
5915 t.is_keyword(keywords::Extern) ||
5916 t.is_keyword(keywords::Type) ||
5917 t.is_keyword(keywords::Pub)) {
5918 self.bump(); // `default`
5919 Defaultness::Default
5925 /// Given a termination token, parse all of the items in a module
5926 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5927 let mut items = vec![];
5928 while let Some(item) = self.parse_item()? {
5932 if !self.eat(term) {
5933 let token_str = self.this_token_to_string();
5934 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
5935 if token_str == ";" {
5936 let msg = "consider removing this semicolon";
5937 err.span_suggestion_short(self.span, msg, "".to_string());
5939 err.span_label(self.span, "expected item");
5944 let hi = if self.span == syntax_pos::DUMMY_SP {
5951 inner: inner_lo.to(hi),
5956 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5957 let id = self.parse_ident()?;
5958 self.expect(&token::Colon)?;
5959 let ty = self.parse_ty()?;
5960 self.expect(&token::Eq)?;
5961 let e = self.parse_expr()?;
5962 self.expect(&token::Semi)?;
5963 let item = match m {
5964 Some(m) => ItemKind::Static(ty, m, e),
5965 None => ItemKind::Const(ty, e),
5967 Ok((id, item, None))
5970 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5971 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5972 let (in_cfg, outer_attrs) = {
5973 let mut strip_unconfigured = ::config::StripUnconfigured {
5975 should_test: false, // irrelevant
5976 features: None, // don't perform gated feature checking
5978 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5979 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5982 let id_span = self.span;
5983 let id = self.parse_ident()?;
5984 if self.check(&token::Semi) {
5986 if in_cfg && self.recurse_into_file_modules {
5987 // This mod is in an external file. Let's go get it!
5988 let ModulePathSuccess { path, directory_ownership, warn } =
5989 self.submod_path(id, &outer_attrs, id_span)?;
5990 let (module, mut attrs) =
5991 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5993 let attr = Attribute {
5994 id: attr::mk_attr_id(),
5995 style: ast::AttrStyle::Outer,
5996 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5997 Ident::from_str("warn_directory_ownership")),
5998 tokens: TokenStream::empty(),
5999 is_sugared_doc: false,
6000 span: syntax_pos::DUMMY_SP,
6002 attr::mark_known(&attr);
6005 Ok((id, module, Some(attrs)))
6007 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
6008 Ok((id, ItemKind::Mod(placeholder), None))
6011 let old_directory = self.directory.clone();
6012 self.push_directory(id, &outer_attrs);
6014 self.expect(&token::OpenDelim(token::Brace))?;
6015 let mod_inner_lo = self.span;
6016 let attrs = self.parse_inner_attributes()?;
6017 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6019 self.directory = old_directory;
6020 Ok((id, ItemKind::Mod(module), Some(attrs)))
6024 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6025 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6026 self.directory.path.push(&path.as_str());
6027 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6029 self.directory.path.push(&id.name.as_str());
6033 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6034 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
6037 /// Returns either a path to a module, or .
6038 pub fn default_submod_path(
6040 relative: Option<ast::Ident>,
6042 codemap: &CodeMap) -> ModulePath
6044 // If we're in a foo.rs file instead of a mod.rs file,
6045 // we need to look for submodules in
6046 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6047 // `./<id>.rs` and `./<id>/mod.rs`.
6048 let relative_prefix_string;
6049 let relative_prefix = if let Some(ident) = relative {
6050 relative_prefix_string = format!("{}{}", ident.name.as_str(), path::MAIN_SEPARATOR);
6051 &relative_prefix_string
6056 let mod_name = id.to_string();
6057 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6058 let secondary_path_str = format!("{}{}{}mod.rs",
6059 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6060 let default_path = dir_path.join(&default_path_str);
6061 let secondary_path = dir_path.join(&secondary_path_str);
6062 let default_exists = codemap.file_exists(&default_path);
6063 let secondary_exists = codemap.file_exists(&secondary_path);
6065 let result = match (default_exists, secondary_exists) {
6066 (true, false) => Ok(ModulePathSuccess {
6068 directory_ownership: DirectoryOwnership::Owned {
6073 (false, true) => Ok(ModulePathSuccess {
6074 path: secondary_path,
6075 directory_ownership: DirectoryOwnership::Owned {
6080 (false, false) => Err(Error::FileNotFoundForModule {
6081 mod_name: mod_name.clone(),
6082 default_path: default_path_str,
6083 secondary_path: secondary_path_str,
6084 dir_path: format!("{}", dir_path.display()),
6086 (true, true) => Err(Error::DuplicatePaths {
6087 mod_name: mod_name.clone(),
6088 default_path: default_path_str,
6089 secondary_path: secondary_path_str,
6095 path_exists: default_exists || secondary_exists,
6100 fn submod_path(&mut self,
6102 outer_attrs: &[Attribute],
6104 -> PResult<'a, ModulePathSuccess> {
6105 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6106 return Ok(ModulePathSuccess {
6107 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6108 // All `#[path]` files are treated as though they are a `mod.rs` file.
6109 // This means that `mod foo;` declarations inside `#[path]`-included
6110 // files are siblings,
6112 // Note that this will produce weirdness when a file named `foo.rs` is
6113 // `#[path]` included and contains a `mod foo;` declaration.
6114 // If you encounter this, it's your own darn fault :P
6115 Some(_) => DirectoryOwnership::Owned { relative: None },
6116 _ => DirectoryOwnership::UnownedViaMod(true),
6123 let relative = match self.directory.ownership {
6124 DirectoryOwnership::Owned { relative } => {
6125 // Push the usage onto the list of non-mod.rs mod uses.
6126 // This is used later for feature-gate error reporting.
6127 if let Some(cur_file_ident) = relative {
6129 .non_modrs_mods.borrow_mut()
6130 .push((cur_file_ident, id_sp));
6134 DirectoryOwnership::UnownedViaBlock |
6135 DirectoryOwnership::UnownedViaMod(_) => None,
6137 let paths = Parser::default_submod_path(
6138 id, relative, &self.directory.path, self.sess.codemap());
6140 match self.directory.ownership {
6141 DirectoryOwnership::Owned { .. } => {
6142 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6144 DirectoryOwnership::UnownedViaBlock => {
6146 "Cannot declare a non-inline module inside a block \
6147 unless it has a path attribute";
6148 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6149 if paths.path_exists {
6150 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6152 err.span_note(id_sp, &msg);
6156 DirectoryOwnership::UnownedViaMod(warn) => {
6158 if let Ok(result) = paths.result {
6159 return Ok(ModulePathSuccess { warn: true, ..result });
6162 let mut err = self.diagnostic().struct_span_err(id_sp,
6163 "cannot declare a new module at this location");
6164 if id_sp != syntax_pos::DUMMY_SP {
6165 let src_path = self.sess.codemap().span_to_filename(id_sp);
6166 if let FileName::Real(src_path) = src_path {
6167 if let Some(stem) = src_path.file_stem() {
6168 let mut dest_path = src_path.clone();
6169 dest_path.set_file_name(stem);
6170 dest_path.push("mod.rs");
6171 err.span_note(id_sp,
6172 &format!("maybe move this module `{}` to its own \
6173 directory via `{}`", src_path.display(),
6174 dest_path.display()));
6178 if paths.path_exists {
6179 err.span_note(id_sp,
6180 &format!("... or maybe `use` the module `{}` instead \
6181 of possibly redeclaring it",
6189 /// Read a module from a source file.
6190 fn eval_src_mod(&mut self,
6192 directory_ownership: DirectoryOwnership,
6195 -> PResult<'a, (ast::ItemKind, Vec<Attribute> )> {
6196 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6197 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6198 let mut err = String::from("circular modules: ");
6199 let len = included_mod_stack.len();
6200 for p in &included_mod_stack[i.. len] {
6201 err.push_str(&p.to_string_lossy());
6202 err.push_str(" -> ");
6204 err.push_str(&path.to_string_lossy());
6205 return Err(self.span_fatal(id_sp, &err[..]));
6207 included_mod_stack.push(path.clone());
6208 drop(included_mod_stack);
6211 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6212 p0.cfg_mods = self.cfg_mods;
6213 let mod_inner_lo = p0.span;
6214 let mod_attrs = p0.parse_inner_attributes()?;
6215 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6216 self.sess.included_mod_stack.borrow_mut().pop();
6217 Ok((ast::ItemKind::Mod(m0), mod_attrs))
6220 /// Parse a function declaration from a foreign module
6221 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6222 -> PResult<'a, ForeignItem> {
6223 self.expect_keyword(keywords::Fn)?;
6225 let (ident, mut generics) = self.parse_fn_header()?;
6226 let decl = self.parse_fn_decl(true)?;
6227 generics.where_clause = self.parse_where_clause()?;
6229 self.expect(&token::Semi)?;
6230 Ok(ast::ForeignItem {
6233 node: ForeignItemKind::Fn(decl, generics),
6234 id: ast::DUMMY_NODE_ID,
6240 /// Parse a static item from a foreign module.
6241 /// Assumes that the `static` keyword is already parsed.
6242 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6243 -> PResult<'a, ForeignItem> {
6244 let mutbl = self.eat_keyword(keywords::Mut);
6245 let ident = self.parse_ident()?;
6246 self.expect(&token::Colon)?;
6247 let ty = self.parse_ty()?;
6249 self.expect(&token::Semi)?;
6253 node: ForeignItemKind::Static(ty, mutbl),
6254 id: ast::DUMMY_NODE_ID,
6260 /// Parse a type from a foreign module
6261 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6262 -> PResult<'a, ForeignItem> {
6263 self.expect_keyword(keywords::Type)?;
6265 let ident = self.parse_ident()?;
6267 self.expect(&token::Semi)?;
6268 Ok(ast::ForeignItem {
6271 node: ForeignItemKind::Ty,
6272 id: ast::DUMMY_NODE_ID,
6278 /// Parse extern crate links
6282 /// extern crate foo;
6283 /// extern crate bar as foo;
6284 fn parse_item_extern_crate(&mut self,
6286 visibility: Visibility,
6287 attrs: Vec<Attribute>)
6288 -> PResult<'a, P<Item>> {
6289 let orig_name = self.parse_ident()?;
6290 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6291 (rename, Some(orig_name.name))
6295 self.expect(&token::Semi)?;
6297 let span = lo.to(self.prev_span);
6298 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6301 /// Parse `extern` for foreign ABIs
6304 /// `extern` is expected to have been
6305 /// consumed before calling this method
6311 fn parse_item_foreign_mod(&mut self,
6313 opt_abi: Option<Abi>,
6314 visibility: Visibility,
6315 mut attrs: Vec<Attribute>)
6316 -> PResult<'a, P<Item>> {
6317 self.expect(&token::OpenDelim(token::Brace))?;
6319 let abi = opt_abi.unwrap_or(Abi::C);
6321 attrs.extend(self.parse_inner_attributes()?);
6323 let mut foreign_items = vec![];
6324 while let Some(item) = self.parse_foreign_item()? {
6325 foreign_items.push(item);
6327 self.expect(&token::CloseDelim(token::Brace))?;
6329 let prev_span = self.prev_span;
6330 let m = ast::ForeignMod {
6332 items: foreign_items
6334 let invalid = keywords::Invalid.ident();
6335 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6338 /// Parse type Foo = Bar;
6339 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
6340 let ident = self.parse_ident()?;
6341 let mut tps = self.parse_generics()?;
6342 tps.where_clause = self.parse_where_clause()?;
6343 self.expect(&token::Eq)?;
6344 let ty = self.parse_ty()?;
6345 self.expect(&token::Semi)?;
6346 Ok((ident, ItemKind::Ty(ty, tps), None))
6349 /// Parse the part of an "enum" decl following the '{'
6350 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6351 let mut variants = Vec::new();
6352 let mut all_nullary = true;
6353 let mut any_disr = None;
6354 while self.token != token::CloseDelim(token::Brace) {
6355 let variant_attrs = self.parse_outer_attributes()?;
6356 let vlo = self.span;
6359 let mut disr_expr = None;
6360 let ident = self.parse_ident()?;
6361 if self.check(&token::OpenDelim(token::Brace)) {
6362 // Parse a struct variant.
6363 all_nullary = false;
6364 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6365 ast::DUMMY_NODE_ID);
6366 } else if self.check(&token::OpenDelim(token::Paren)) {
6367 all_nullary = false;
6368 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6369 ast::DUMMY_NODE_ID);
6370 } else if self.eat(&token::Eq) {
6371 disr_expr = Some(self.parse_expr()?);
6372 any_disr = disr_expr.as_ref().map(|expr| expr.span);
6373 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6375 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6378 let vr = ast::Variant_ {
6380 attrs: variant_attrs,
6384 variants.push(respan(vlo.to(self.prev_span), vr));
6386 if !self.eat(&token::Comma) { break; }
6388 self.expect(&token::CloseDelim(token::Brace))?;
6390 Some(disr_span) if !all_nullary =>
6391 self.span_err(disr_span,
6392 "discriminator values can only be used with a field-less enum"),
6396 Ok(ast::EnumDef { variants: variants })
6399 /// Parse an "enum" declaration
6400 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6401 let id = self.parse_ident()?;
6402 let mut generics = self.parse_generics()?;
6403 generics.where_clause = self.parse_where_clause()?;
6404 self.expect(&token::OpenDelim(token::Brace))?;
6406 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6407 self.recover_stmt();
6408 self.eat(&token::CloseDelim(token::Brace));
6411 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6414 /// Parses a string as an ABI spec on an extern type or module. Consumes
6415 /// the `extern` keyword, if one is found.
6416 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6418 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6420 self.expect_no_suffix(sp, "ABI spec", suf);
6422 match abi::lookup(&s.as_str()) {
6423 Some(abi) => Ok(Some(abi)),
6425 let prev_span = self.prev_span;
6428 &format!("invalid ABI: expected one of [{}], \
6430 abi::all_names().join(", "),
6441 fn is_static_global(&mut self) -> bool {
6442 if self.check_keyword(keywords::Static) {
6443 // Check if this could be a closure
6444 !self.look_ahead(1, |token| {
6445 if token.is_keyword(keywords::Move) {
6449 token::BinOp(token::Or) | token::OrOr => true,
6458 /// Parse one of the items allowed by the flags.
6459 /// NB: this function no longer parses the items inside an
6461 fn parse_item_(&mut self, attrs: Vec<Attribute>,
6462 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
6463 maybe_whole!(self, NtItem, |item| {
6464 let mut item = item.into_inner();
6465 let mut attrs = attrs;
6466 mem::swap(&mut item.attrs, &mut attrs);
6467 item.attrs.extend(attrs);
6473 let visibility = self.parse_visibility(false)?;
6475 if self.eat_keyword(keywords::Use) {
6477 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
6478 self.expect(&token::Semi)?;
6480 let span = lo.to(self.prev_span);
6481 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
6482 return Ok(Some(item));
6485 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6486 self.bump(); // `extern`
6487 if self.eat_keyword(keywords::Crate) {
6488 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6491 let opt_abi = self.parse_opt_abi()?;
6493 if self.eat_keyword(keywords::Fn) {
6494 // EXTERN FUNCTION ITEM
6495 let fn_span = self.prev_span;
6496 let abi = opt_abi.unwrap_or(Abi::C);
6497 let (ident, item_, extra_attrs) =
6498 self.parse_item_fn(Unsafety::Normal,
6499 respan(fn_span, Constness::NotConst),
6501 let prev_span = self.prev_span;
6502 let item = self.mk_item(lo.to(prev_span),
6506 maybe_append(attrs, extra_attrs));
6507 return Ok(Some(item));
6508 } else if self.check(&token::OpenDelim(token::Brace)) {
6509 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6515 if self.is_static_global() {
6518 let m = if self.eat_keyword(keywords::Mut) {
6521 Mutability::Immutable
6523 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6524 let prev_span = self.prev_span;
6525 let item = self.mk_item(lo.to(prev_span),
6529 maybe_append(attrs, extra_attrs));
6530 return Ok(Some(item));
6532 if self.eat_keyword(keywords::Const) {
6533 let const_span = self.prev_span;
6534 if self.check_keyword(keywords::Fn)
6535 || (self.check_keyword(keywords::Unsafe)
6536 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6537 // CONST FUNCTION ITEM
6538 let unsafety = self.parse_unsafety();
6540 let (ident, item_, extra_attrs) =
6541 self.parse_item_fn(unsafety,
6542 respan(const_span, Constness::Const),
6544 let prev_span = self.prev_span;
6545 let item = self.mk_item(lo.to(prev_span),
6549 maybe_append(attrs, extra_attrs));
6550 return Ok(Some(item));
6554 if self.eat_keyword(keywords::Mut) {
6555 let prev_span = self.prev_span;
6556 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6557 .help("did you mean to declare a static?")
6560 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6561 let prev_span = self.prev_span;
6562 let item = self.mk_item(lo.to(prev_span),
6566 maybe_append(attrs, extra_attrs));
6567 return Ok(Some(item));
6569 if self.check_keyword(keywords::Unsafe) &&
6570 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
6571 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
6573 // UNSAFE TRAIT ITEM
6574 self.bump(); // `unsafe`
6575 let is_auto = if self.eat_keyword(keywords::Trait) {
6578 self.expect_keyword(keywords::Auto)?;
6579 self.expect_keyword(keywords::Trait)?;
6582 let (ident, item_, extra_attrs) =
6583 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
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.check_keyword(keywords::Impl) ||
6593 self.check_keyword(keywords::Unsafe) &&
6594 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6595 self.check_keyword(keywords::Default) &&
6596 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6597 self.check_keyword(keywords::Default) &&
6598 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
6600 let defaultness = self.parse_defaultness();
6601 let unsafety = self.parse_unsafety();
6602 self.expect_keyword(keywords::Impl)?;
6603 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
6604 let span = lo.to(self.prev_span);
6605 return Ok(Some(self.mk_item(span, ident, item, visibility,
6606 maybe_append(attrs, extra_attrs))));
6608 if self.check_keyword(keywords::Fn) {
6611 let fn_span = self.prev_span;
6612 let (ident, item_, extra_attrs) =
6613 self.parse_item_fn(Unsafety::Normal,
6614 respan(fn_span, Constness::NotConst),
6616 let prev_span = self.prev_span;
6617 let item = self.mk_item(lo.to(prev_span),
6621 maybe_append(attrs, extra_attrs));
6622 return Ok(Some(item));
6624 if self.check_keyword(keywords::Unsafe)
6625 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
6626 // UNSAFE FUNCTION ITEM
6627 self.bump(); // `unsafe`
6628 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
6629 self.check(&token::OpenDelim(token::Brace));
6630 let abi = if self.eat_keyword(keywords::Extern) {
6631 self.parse_opt_abi()?.unwrap_or(Abi::C)
6635 self.expect_keyword(keywords::Fn)?;
6636 let fn_span = self.prev_span;
6637 let (ident, item_, extra_attrs) =
6638 self.parse_item_fn(Unsafety::Unsafe,
6639 respan(fn_span, Constness::NotConst),
6641 let prev_span = self.prev_span;
6642 let item = self.mk_item(lo.to(prev_span),
6646 maybe_append(attrs, extra_attrs));
6647 return Ok(Some(item));
6649 if self.eat_keyword(keywords::Mod) {
6651 let (ident, item_, extra_attrs) =
6652 self.parse_item_mod(&attrs[..])?;
6653 let prev_span = self.prev_span;
6654 let item = self.mk_item(lo.to(prev_span),
6658 maybe_append(attrs, extra_attrs));
6659 return Ok(Some(item));
6661 if self.eat_keyword(keywords::Type) {
6663 let (ident, item_, extra_attrs) = self.parse_item_type()?;
6664 let prev_span = self.prev_span;
6665 let item = self.mk_item(lo.to(prev_span),
6669 maybe_append(attrs, extra_attrs));
6670 return Ok(Some(item));
6672 if self.eat_keyword(keywords::Enum) {
6674 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
6675 let prev_span = self.prev_span;
6676 let item = self.mk_item(lo.to(prev_span),
6680 maybe_append(attrs, extra_attrs));
6681 return Ok(Some(item));
6683 if self.check_keyword(keywords::Trait)
6684 || (self.check_keyword(keywords::Auto)
6685 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
6687 let is_auto = if self.eat_keyword(keywords::Trait) {
6690 self.expect_keyword(keywords::Auto)?;
6691 self.expect_keyword(keywords::Trait)?;
6695 let (ident, item_, extra_attrs) =
6696 self.parse_item_trait(is_auto, Unsafety::Normal)?;
6697 let prev_span = self.prev_span;
6698 let item = self.mk_item(lo.to(prev_span),
6702 maybe_append(attrs, extra_attrs));
6703 return Ok(Some(item));
6705 if self.eat_keyword(keywords::Struct) {
6707 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6708 let prev_span = self.prev_span;
6709 let item = self.mk_item(lo.to(prev_span),
6713 maybe_append(attrs, extra_attrs));
6714 return Ok(Some(item));
6716 if self.is_union_item() {
6719 let (ident, item_, extra_attrs) = self.parse_item_union()?;
6720 let prev_span = self.prev_span;
6721 let item = self.mk_item(lo.to(prev_span),
6725 maybe_append(attrs, extra_attrs));
6726 return Ok(Some(item));
6728 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
6729 return Ok(Some(macro_def));
6732 // Verify whether we have encountered a struct or method definition where the user forgot to
6733 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
6734 if visibility.node == VisibilityKind::Public &&
6735 self.check_ident() &&
6736 self.look_ahead(1, |t| *t != token::Not)
6738 // Space between `pub` keyword and the identifier
6741 // ^^^ `sp` points here
6742 let sp = self.prev_span.between(self.span);
6743 let full_sp = self.prev_span.to(self.span);
6744 let ident_sp = self.span;
6745 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
6746 // possible public struct definition where `struct` was forgotten
6747 let ident = self.parse_ident().unwrap();
6748 let msg = format!("add `struct` here to parse `{}` as a public struct",
6750 let mut err = self.diagnostic()
6751 .struct_span_err(sp, "missing `struct` for struct definition");
6752 err.span_suggestion_short(sp, &msg, " struct ".into());
6754 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
6755 let ident = self.parse_ident().unwrap();
6756 self.consume_block(token::Paren);
6757 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
6758 self.check(&token::OpenDelim(token::Brace))
6760 ("fn", "method", false)
6761 } else if self.check(&token::Colon) {
6765 ("fn` or `struct", "method or struct", true)
6768 let msg = format!("missing `{}` for {} definition", kw, kw_name);
6769 let mut err = self.diagnostic().struct_span_err(sp, &msg);
6771 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
6775 err.span_suggestion_short(sp, &suggestion, format!(" {} ", kw));
6777 if let Ok(snippet) = self.sess.codemap().span_to_snippet(ident_sp) {
6778 err.span_suggestion(
6780 "if you meant to call a macro, write instead",
6781 format!("{}!", snippet));
6783 err.help("if you meant to call a macro, remove the `pub` \
6784 and add a trailing `!` after the identifier");
6790 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
6793 /// Parse a foreign item.
6794 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
6795 let attrs = self.parse_outer_attributes()?;
6797 let visibility = self.parse_visibility(false)?;
6799 // FOREIGN STATIC ITEM
6800 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
6801 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
6802 if self.token.is_keyword(keywords::Const) {
6804 .struct_span_err(self.span, "extern items cannot be `const`")
6805 .span_suggestion(self.span, "instead try using", "static".to_owned())
6808 self.bump(); // `static` or `const`
6809 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6811 // FOREIGN FUNCTION ITEM
6812 if self.check_keyword(keywords::Fn) {
6813 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6815 // FOREIGN TYPE ITEM
6816 if self.check_keyword(keywords::Type) {
6817 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
6820 // FIXME #5668: this will occur for a macro invocation:
6821 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
6823 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
6829 /// This is the fall-through for parsing items.
6830 fn parse_macro_use_or_failure(
6832 attrs: Vec<Attribute> ,
6833 macros_allowed: bool,
6834 attributes_allowed: bool,
6836 visibility: Visibility
6837 ) -> PResult<'a, Option<P<Item>>> {
6838 if macros_allowed && self.token.is_path_start() {
6839 // MACRO INVOCATION ITEM
6841 let prev_span = self.prev_span;
6842 self.complain_if_pub_macro(&visibility.node, prev_span);
6844 let mac_lo = self.span;
6847 let pth = self.parse_path(PathStyle::Mod)?;
6848 self.expect(&token::Not)?;
6850 // a 'special' identifier (like what `macro_rules!` uses)
6851 // is optional. We should eventually unify invoc syntax
6853 let id = if self.token.is_ident() {
6856 keywords::Invalid.ident() // no special identifier
6858 // eat a matched-delimiter token tree:
6859 let (delim, tts) = self.expect_delimited_token_tree()?;
6860 if delim != token::Brace {
6861 if !self.eat(&token::Semi) {
6862 self.span_err(self.prev_span,
6863 "macros that expand to items must either \
6864 be surrounded with braces or followed by \
6869 let hi = self.prev_span;
6870 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6871 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6872 return Ok(Some(item));
6875 // FAILURE TO PARSE ITEM
6876 match visibility.node {
6877 VisibilityKind::Inherited => {}
6879 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
6883 if !attributes_allowed && !attrs.is_empty() {
6884 self.expected_item_err(&attrs);
6889 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
6890 where F: FnOnce(&mut Self) -> PResult<'a, R>
6892 // Record all tokens we parse when parsing this item.
6893 let mut tokens = Vec::new();
6894 match self.token_cursor.frame.last_token {
6895 LastToken::Collecting(_) => {
6896 panic!("cannot collect tokens recursively yet")
6898 LastToken::Was(ref mut last) => tokens.extend(last.take()),
6900 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
6901 let prev = self.token_cursor.stack.len();
6903 let last_token = if self.token_cursor.stack.len() == prev {
6904 &mut self.token_cursor.frame.last_token
6906 &mut self.token_cursor.stack[prev].last_token
6908 let mut tokens = match *last_token {
6909 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
6910 LastToken::Was(_) => panic!("our vector went away?"),
6913 // If we're not at EOF our current token wasn't actually consumed by
6914 // `f`, but it'll still be in our list that we pulled out. In that case
6916 if self.token == token::Eof {
6917 *last_token = LastToken::Was(None);
6919 *last_token = LastToken::Was(tokens.pop());
6922 Ok((ret?, tokens.into_iter().collect()))
6925 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6926 let attrs = self.parse_outer_attributes()?;
6928 let (ret, tokens) = self.collect_tokens(|this| {
6929 this.parse_item_(attrs, true, false)
6932 // Once we've parsed an item and recorded the tokens we got while
6933 // parsing we may want to store `tokens` into the item we're about to
6934 // return. Note, though, that we specifically didn't capture tokens
6935 // related to outer attributes. The `tokens` field here may later be
6936 // used with procedural macros to convert this item back into a token
6937 // stream, but during expansion we may be removing attributes as we go
6940 // If we've got inner attributes then the `tokens` we've got above holds
6941 // these inner attributes. If an inner attribute is expanded we won't
6942 // actually remove it from the token stream, so we'll just keep yielding
6943 // it (bad!). To work around this case for now we just avoid recording
6944 // `tokens` if we detect any inner attributes. This should help keep
6945 // expansion correct, but we should fix this bug one day!
6948 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6949 i.tokens = Some(tokens);
6957 fn is_import_coupler(&mut self) -> bool {
6958 self.check(&token::ModSep) &&
6959 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6960 *t == token::BinOp(token::Star))
6965 /// USE_TREE = [`::`] `*` |
6966 /// [`::`] `{` USE_TREE_LIST `}` |
6968 /// PATH `::` `{` USE_TREE_LIST `}` |
6969 /// PATH [`as` IDENT]
6970 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
6973 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
6974 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
6975 self.check(&token::BinOp(token::Star)) ||
6976 self.is_import_coupler() {
6977 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
6978 if self.eat(&token::ModSep) {
6979 prefix.segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
6982 if self.eat(&token::BinOp(token::Star)) {
6985 UseTreeKind::Nested(self.parse_use_tree_list()?)
6988 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
6989 prefix = self.parse_path(PathStyle::Mod)?;
6991 if self.eat(&token::ModSep) {
6992 if self.eat(&token::BinOp(token::Star)) {
6995 UseTreeKind::Nested(self.parse_use_tree_list()?)
6998 UseTreeKind::Simple(self.parse_rename()?)
7002 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7005 /// Parse UseTreeKind::Nested(list)
7007 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7008 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7009 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7010 &token::CloseDelim(token::Brace),
7011 SeqSep::trailing_allowed(token::Comma), |this| {
7012 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7016 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7017 if self.eat_keyword(keywords::As) {
7019 token::Ident(ident) if ident.name == keywords::Underscore.name() => {
7021 Ok(Some(Ident { name: ident.name.gensymed(), ..ident }))
7023 _ => self.parse_ident().map(Some),
7030 /// Parses a source module as a crate. This is the main
7031 /// entry point for the parser.
7032 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7035 attrs: self.parse_inner_attributes()?,
7036 module: self.parse_mod_items(&token::Eof, lo)?,
7037 span: lo.to(self.span),
7041 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7042 let ret = match self.token {
7043 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7044 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7051 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7052 match self.parse_optional_str() {
7053 Some((s, style, suf)) => {
7054 let sp = self.prev_span;
7055 self.expect_no_suffix(sp, "string literal", suf);
7059 let msg = "expected string literal";
7060 let mut err = self.fatal(msg);
7061 err.span_label(self.span, msg);