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.
11 use rustc_target::spec::abi::{self, Abi};
12 use ast::{AngleBracketedParameterData, ParenthesizedParameterData, AttrStyle, BareFnTy};
13 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
15 use ast::{Mod, Arg, Arm, Attribute, BindingMode, TraitItemKind};
17 use ast::{BlockCheckMode, CaptureBy, Movability};
18 use ast::{Constness, Crate};
21 use ast::{Expr, ExprKind, RangeLimits};
22 use ast::{Field, FnDecl};
23 use ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
24 use ast::GenericParam;
25 use ast::{Ident, ImplItem, IsAuto, Item, ItemKind};
26 use ast::{Label, Lifetime, LifetimeDef, Lit, LitKind, UintTy};
28 use ast::MacStmtStyle;
30 use ast::{MutTy, Mutability};
31 use ast::{Pat, PatKind, PathSegment};
32 use ast::{PolyTraitRef, QSelf};
33 use ast::{Stmt, StmtKind};
34 use ast::{VariantData, StructField};
37 use ast::{TraitItem, TraitRef, TraitObjectSyntax};
38 use ast::{Ty, TyKind, TypeBinding, TyParam, TyParamBounds};
39 use ast::{Visibility, VisibilityKind, WhereClause, CrateSugar};
40 use ast::{UseTree, UseTreeKind};
41 use ast::{BinOpKind, UnOp};
42 use ast::{RangeEnd, RangeSyntax};
44 use codemap::{self, CodeMap, Spanned, respan};
45 use syntax_pos::{self, Span, MultiSpan, BytePos, FileName, DUMMY_SP};
46 use errors::{self, DiagnosticBuilder};
47 use parse::{self, classify, token};
48 use parse::common::SeqSep;
49 use parse::lexer::TokenAndSpan;
50 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
51 use parse::{new_sub_parser_from_file, ParseSess, Directory, DirectoryOwnership};
52 use util::parser::{AssocOp, Fixity};
56 use tokenstream::{self, Delimited, ThinTokenStream, TokenTree, TokenStream};
57 use symbol::{Symbol, keywords};
62 use std::path::{self, Path, PathBuf};
66 pub struct Restrictions: u8 {
67 const STMT_EXPR = 1 << 0;
68 const NO_STRUCT_LITERAL = 1 << 1;
72 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute>>);
74 /// How to parse a path.
75 #[derive(Copy, Clone, PartialEq)]
77 /// In some contexts, notably in expressions, paths with generic arguments are ambiguous
78 /// with something else. For example, in expressions `segment < ....` can be interpreted
79 /// as a comparison and `segment ( ....` can be interpreted as a function call.
80 /// In all such contexts the non-path interpretation is preferred by default for practical
81 /// reasons, but the path interpretation can be forced by the disambiguator `::`, e.g.
82 /// `x<y>` - comparisons, `x::<y>` - unambiguously a path.
84 /// In other contexts, notably in types, no ambiguity exists and paths can be written
85 /// without the disambiguator, e.g. `x<y>` - unambiguously a path.
86 /// Paths with disambiguators are still accepted, `x::<Y>` - unambiguously a path too.
88 /// A path with generic arguments disallowed, e.g. `foo::bar::Baz`, used in imports,
89 /// visibilities or attributes.
90 /// Technically, this variant is unnecessary and e.g. `Expr` can be used instead
91 /// (paths in "mod" contexts have to be checked later for absence of generic arguments
92 /// anyway, due to macros), but it is used to avoid weird suggestions about expected
93 /// tokens when something goes wrong.
97 #[derive(Clone, Copy, Debug, PartialEq)]
98 pub enum SemiColonMode {
103 #[derive(Clone, Copy, Debug, PartialEq)]
109 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
110 /// dropped into the token stream, which happens while parsing the result of
111 /// macro expansion). Placement of these is not as complex as I feared it would
112 /// be. The important thing is to make sure that lookahead doesn't balk at
113 /// `token::Interpolated` tokens.
114 macro_rules! maybe_whole_expr {
116 if let token::Interpolated(nt) = $p.token.clone() {
118 token::NtExpr(ref e) => {
120 return Ok((*e).clone());
122 token::NtPath(ref path) => {
125 let kind = ExprKind::Path(None, (*path).clone());
126 return Ok($p.mk_expr(span, kind, ThinVec::new()));
128 token::NtBlock(ref block) => {
131 let kind = ExprKind::Block((*block).clone());
132 return Ok($p.mk_expr(span, kind, ThinVec::new()));
140 /// As maybe_whole_expr, but for things other than expressions
141 macro_rules! maybe_whole {
142 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
143 if let token::Interpolated(nt) = $p.token.clone() {
144 if let token::$constructor($x) = nt.0.clone() {
152 fn maybe_append(mut lhs: Vec<Attribute>, mut rhs: Option<Vec<Attribute>>) -> Vec<Attribute> {
153 if let Some(ref mut rhs) = rhs {
159 #[derive(Debug, Clone, Copy, PartialEq)]
170 trait RecoverQPath: Sized {
171 const PATH_STYLE: PathStyle = PathStyle::Expr;
172 fn to_ty(&self) -> Option<P<Ty>>;
173 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self;
174 fn to_string(&self) -> String;
177 impl RecoverQPath for Ty {
178 const PATH_STYLE: PathStyle = PathStyle::Type;
179 fn to_ty(&self) -> Option<P<Ty>> {
180 Some(P(self.clone()))
182 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
183 Self { span: path.span, node: TyKind::Path(qself, path), id: self.id }
185 fn to_string(&self) -> String {
186 pprust::ty_to_string(self)
190 impl RecoverQPath for Pat {
191 fn to_ty(&self) -> Option<P<Ty>> {
194 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
195 Self { span: path.span, node: PatKind::Path(qself, path), id: self.id }
197 fn to_string(&self) -> String {
198 pprust::pat_to_string(self)
202 impl RecoverQPath for Expr {
203 fn to_ty(&self) -> Option<P<Ty>> {
206 fn to_recovered(&self, qself: Option<QSelf>, path: ast::Path) -> Self {
207 Self { span: path.span, node: ExprKind::Path(qself, path),
208 id: self.id, attrs: self.attrs.clone() }
210 fn to_string(&self) -> String {
211 pprust::expr_to_string(self)
215 /* ident is handled by common.rs */
218 pub struct Parser<'a> {
219 pub sess: &'a ParseSess,
220 /// the current token:
221 pub token: token::Token,
222 /// the span of the current token:
224 /// the span of the previous token:
225 pub meta_var_span: Option<Span>,
227 /// the previous token kind
228 prev_token_kind: PrevTokenKind,
229 pub restrictions: Restrictions,
230 /// Used to determine the path to externally loaded source files
231 pub directory: Directory,
232 /// Whether to parse sub-modules in other files.
233 pub recurse_into_file_modules: bool,
234 /// Name of the root module this parser originated from. If `None`, then the
235 /// name is not known. This does not change while the parser is descending
236 /// into modules, and sub-parsers have new values for this name.
237 pub root_module_name: Option<String>,
238 pub expected_tokens: Vec<TokenType>,
239 token_cursor: TokenCursor,
240 pub desugar_doc_comments: bool,
241 /// Whether we should configure out of line modules as we parse.
248 frame: TokenCursorFrame,
249 stack: Vec<TokenCursorFrame>,
253 struct TokenCursorFrame {
254 delim: token::DelimToken,
257 tree_cursor: tokenstream::Cursor,
259 last_token: LastToken,
262 /// This is used in `TokenCursorFrame` above to track tokens that are consumed
263 /// by the parser, and then that's transitively used to record the tokens that
264 /// each parse AST item is created with.
266 /// Right now this has two states, either collecting tokens or not collecting
267 /// tokens. If we're collecting tokens we just save everything off into a local
268 /// `Vec`. This should eventually though likely save tokens from the original
269 /// token stream and just use slicing of token streams to avoid creation of a
270 /// whole new vector.
272 /// The second state is where we're passively not recording tokens, but the last
273 /// token is still tracked for when we want to start recording tokens. This
274 /// "last token" means that when we start recording tokens we'll want to ensure
275 /// that this, the first token, is included in the output.
277 /// You can find some more example usage of this in the `collect_tokens` method
281 Collecting(Vec<TokenTree>),
282 Was(Option<TokenTree>),
285 impl TokenCursorFrame {
286 fn new(sp: Span, delimited: &Delimited) -> Self {
288 delim: delimited.delim,
290 open_delim: delimited.delim == token::NoDelim,
291 tree_cursor: delimited.stream().into_trees(),
292 close_delim: delimited.delim == token::NoDelim,
293 last_token: LastToken::Was(None),
299 fn next(&mut self) -> TokenAndSpan {
301 let tree = if !self.frame.open_delim {
302 self.frame.open_delim = true;
303 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
304 .open_tt(self.frame.span)
305 } else if let Some(tree) = self.frame.tree_cursor.next() {
307 } else if !self.frame.close_delim {
308 self.frame.close_delim = true;
309 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
310 .close_tt(self.frame.span)
311 } else if let Some(frame) = self.stack.pop() {
315 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
318 match self.frame.last_token {
319 LastToken::Collecting(ref mut v) => v.push(tree.clone()),
320 LastToken::Was(ref mut t) => *t = Some(tree.clone()),
324 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
325 TokenTree::Delimited(sp, ref delimited) => {
326 let frame = TokenCursorFrame::new(sp, delimited);
327 self.stack.push(mem::replace(&mut self.frame, frame));
333 fn next_desugared(&mut self) -> TokenAndSpan {
334 let (sp, name) = match self.next() {
335 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
339 let stripped = strip_doc_comment_decoration(&name.as_str());
341 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
342 // required to wrap the text.
343 let mut num_of_hashes = 0;
345 for ch in stripped.chars() {
348 '#' if count > 0 => count + 1,
351 num_of_hashes = cmp::max(num_of_hashes, count);
354 let body = TokenTree::Delimited(sp, Delimited {
355 delim: token::Bracket,
356 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"), false)),
357 TokenTree::Token(sp, token::Eq),
358 TokenTree::Token(sp, token::Literal(
359 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
360 .iter().cloned().collect::<TokenStream>().into(),
363 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
364 delim: token::NoDelim,
365 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
366 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
367 .iter().cloned().collect::<TokenStream>().into()
369 [TokenTree::Token(sp, token::Pound), body]
370 .iter().cloned().collect::<TokenStream>().into()
378 #[derive(PartialEq, Eq, Clone)]
381 Keyword(keywords::Keyword),
390 fn to_string(&self) -> String {
392 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
393 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
394 TokenType::Operator => "an operator".to_string(),
395 TokenType::Lifetime => "lifetime".to_string(),
396 TokenType::Ident => "identifier".to_string(),
397 TokenType::Path => "path".to_string(),
398 TokenType::Type => "type".to_string(),
403 /// Returns true if `IDENT t` can start a type - `IDENT::a::b`, `IDENT<u8, u8>`,
404 /// `IDENT<<u8 as Trait>::AssocTy>`.
406 /// Types can also be of the form `IDENT(u8, u8) -> u8`, however this assumes
407 /// that IDENT is not the ident of a fn trait
408 fn can_continue_type_after_non_fn_ident(t: &token::Token) -> bool {
409 t == &token::ModSep || t == &token::Lt ||
410 t == &token::BinOp(token::Shl)
413 /// Information about the path to a module.
414 pub struct ModulePath {
416 pub path_exists: bool,
417 pub result: Result<ModulePathSuccess, Error>,
420 pub struct ModulePathSuccess {
422 pub directory_ownership: DirectoryOwnership,
426 pub struct ModulePathError {
428 pub help_msg: String,
432 FileNotFoundForModule {
434 default_path: String,
435 secondary_path: String,
440 default_path: String,
441 secondary_path: String,
444 InclusiveRangeWithNoEnd,
448 pub fn span_err<S: Into<MultiSpan>>(self,
450 handler: &errors::Handler) -> DiagnosticBuilder {
452 Error::FileNotFoundForModule { ref mod_name,
456 let mut err = struct_span_err!(handler, sp, E0583,
457 "file not found for module `{}`", mod_name);
458 err.help(&format!("name the file either {} or {} inside the directory \"{}\"",
464 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
465 let mut err = struct_span_err!(handler, sp, E0584,
466 "file for module `{}` found at both {} and {}",
470 err.help("delete or rename one of them to remove the ambiguity");
473 Error::UselessDocComment => {
474 let mut err = struct_span_err!(handler, sp, E0585,
475 "found a documentation comment that doesn't document anything");
476 err.help("doc comments must come before what they document, maybe a comment was \
477 intended with `//`?");
480 Error::InclusiveRangeWithNoEnd => {
481 let mut err = struct_span_err!(handler, sp, E0586,
482 "inclusive range with no end");
483 err.help("inclusive ranges must be bounded at the end (`..=b` or `a..=b`)");
493 AttributesParsed(ThinVec<Attribute>),
494 AlreadyParsed(P<Expr>),
497 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
498 fn from(o: Option<ThinVec<Attribute>>) -> Self {
499 if let Some(attrs) = o {
500 LhsExpr::AttributesParsed(attrs)
502 LhsExpr::NotYetParsed
507 impl From<P<Expr>> for LhsExpr {
508 fn from(expr: P<Expr>) -> Self {
509 LhsExpr::AlreadyParsed(expr)
513 /// Create a placeholder argument.
514 fn dummy_arg(span: Span) -> Arg {
515 let ident = Ident::new(keywords::Invalid.name(), span);
517 id: ast::DUMMY_NODE_ID,
518 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
524 id: ast::DUMMY_NODE_ID
526 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
529 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
530 enum TokenExpectType {
535 impl<'a> Parser<'a> {
536 pub fn new(sess: &'a ParseSess,
538 directory: Option<Directory>,
539 recurse_into_file_modules: bool,
540 desugar_doc_comments: bool)
542 let mut parser = Parser {
544 token: token::Whitespace,
545 span: syntax_pos::DUMMY_SP,
546 prev_span: syntax_pos::DUMMY_SP,
548 prev_token_kind: PrevTokenKind::Other,
549 restrictions: Restrictions::empty(),
550 recurse_into_file_modules,
551 directory: Directory {
552 path: PathBuf::new(),
553 ownership: DirectoryOwnership::Owned { relative: None }
555 root_module_name: None,
556 expected_tokens: Vec::new(),
557 token_cursor: TokenCursor {
558 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
559 delim: token::NoDelim,
564 desugar_doc_comments,
568 let tok = parser.next_tok();
569 parser.token = tok.tok;
570 parser.span = tok.sp;
572 if let Some(directory) = directory {
573 parser.directory = directory;
574 } else if !parser.span.source_equal(&DUMMY_SP) {
575 if let FileName::Real(path) = sess.codemap().span_to_unmapped_path(parser.span) {
576 parser.directory.path = path;
577 parser.directory.path.pop();
581 parser.process_potential_macro_variable();
585 fn next_tok(&mut self) -> TokenAndSpan {
586 let mut next = if self.desugar_doc_comments {
587 self.token_cursor.next_desugared()
589 self.token_cursor.next()
591 if next.sp == syntax_pos::DUMMY_SP {
592 // Tweak the location for better diagnostics, but keep syntactic context intact.
593 next.sp = self.prev_span.with_ctxt(next.sp.ctxt());
598 /// Convert a token to a string using self's reader
599 pub fn token_to_string(token: &token::Token) -> String {
600 pprust::token_to_string(token)
603 /// Convert the current token to a string using self's reader
604 pub fn this_token_to_string(&self) -> String {
605 Parser::token_to_string(&self.token)
608 pub fn token_descr(&self) -> Option<&'static str> {
609 Some(match &self.token {
610 t if t.is_special_ident() => "reserved identifier",
611 t if t.is_used_keyword() => "keyword",
612 t if t.is_unused_keyword() => "reserved keyword",
617 pub fn this_token_descr(&self) -> String {
618 if let Some(prefix) = self.token_descr() {
619 format!("{} `{}`", prefix, self.this_token_to_string())
621 format!("`{}`", self.this_token_to_string())
625 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
626 let token_str = Parser::token_to_string(t);
627 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
630 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
631 match self.expect_one_of(&[], &[]) {
633 Ok(_) => unreachable!(),
637 /// Expect and consume the token t. Signal an error if
638 /// the next token is not t.
639 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
640 if self.expected_tokens.is_empty() {
641 if self.token == *t {
645 let token_str = Parser::token_to_string(t);
646 let this_token_str = self.this_token_to_string();
647 let mut err = self.fatal(&format!("expected `{}`, found `{}`",
650 err.span_label(self.span, format!("expected `{}`", token_str));
654 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
658 /// Expect next token to be edible or inedible token. If edible,
659 /// then consume it; if inedible, then return without consuming
660 /// anything. Signal a fatal error if next token is unexpected.
661 pub fn expect_one_of(&mut self,
662 edible: &[token::Token],
663 inedible: &[token::Token]) -> PResult<'a, ()>{
664 fn tokens_to_string(tokens: &[TokenType]) -> String {
665 let mut i = tokens.iter();
666 // This might be a sign we need a connect method on Iterator.
668 .map_or("".to_string(), |t| t.to_string());
669 i.enumerate().fold(b, |mut b, (i, a)| {
670 if tokens.len() > 2 && i == tokens.len() - 2 {
672 } else if tokens.len() == 2 && i == tokens.len() - 2 {
677 b.push_str(&a.to_string());
681 if edible.contains(&self.token) {
684 } else if inedible.contains(&self.token) {
685 // leave it in the input
688 let mut expected = edible.iter()
689 .map(|x| TokenType::Token(x.clone()))
690 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
691 .chain(self.expected_tokens.iter().cloned())
692 .collect::<Vec<_>>();
693 expected.sort_by_cached_key(|x| x.to_string());
695 let expect = tokens_to_string(&expected[..]);
696 let actual = self.this_token_to_string();
697 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
698 let short_expect = if expected.len() > 6 {
699 format!("{} possible tokens", expected.len())
703 (format!("expected one of {}, found `{}`", expect, actual),
704 (self.sess.codemap().next_point(self.prev_span),
705 format!("expected one of {} here", short_expect)))
706 } else if expected.is_empty() {
707 (format!("unexpected token: `{}`", actual),
708 (self.prev_span, "unexpected token after this".to_string()))
710 (format!("expected {}, found `{}`", expect, actual),
711 (self.sess.codemap().next_point(self.prev_span),
712 format!("expected {} here", expect)))
714 let mut err = self.fatal(&msg_exp);
715 let sp = if self.token == token::Token::Eof {
716 // This is EOF, don't want to point at the following char, but rather the last token
722 let cm = self.sess.codemap();
723 match (cm.lookup_line(self.span.lo()), cm.lookup_line(sp.lo())) {
724 (Ok(ref a), Ok(ref b)) if a.line == b.line => {
725 // When the spans are in the same line, it means that the only content between
726 // them is whitespace, point at the found token in that case:
728 // X | () => { syntax error };
729 // | ^^^^^ expected one of 8 possible tokens here
731 // instead of having:
733 // X | () => { syntax error };
734 // | -^^^^^ unexpected token
736 // | expected one of 8 possible tokens here
737 err.span_label(self.span, label_exp);
740 err.span_label(sp, label_exp);
741 err.span_label(self.span, "unexpected token");
748 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
749 fn interpolated_or_expr_span(&self,
750 expr: PResult<'a, P<Expr>>)
751 -> PResult<'a, (Span, P<Expr>)> {
753 if self.prev_token_kind == PrevTokenKind::Interpolated {
761 fn expected_ident_found(&self) -> DiagnosticBuilder<'a> {
762 let mut err = self.struct_span_err(self.span,
763 &format!("expected identifier, found {}",
764 self.this_token_descr()));
765 if let Some(token_descr) = self.token_descr() {
766 err.span_label(self.span, format!("expected identifier, found {}", token_descr));
768 err.span_label(self.span, "expected identifier");
773 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
774 self.parse_ident_common(true)
777 fn parse_ident_common(&mut self, recover: bool) -> PResult<'a, ast::Ident> {
779 token::Ident(ident, _) => {
780 if self.token.is_reserved_ident() {
781 let mut err = self.expected_ident_found();
788 let span = self.span;
790 Ok(Ident::new(ident.name, span))
793 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
794 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
796 self.expected_ident_found()
802 /// Check if the next token is `tok`, and return `true` if so.
804 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
806 pub fn check(&mut self, tok: &token::Token) -> bool {
807 let is_present = self.token == *tok;
808 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
812 /// Consume token 'tok' if it exists. Returns true if the given
813 /// token was present, false otherwise.
814 pub fn eat(&mut self, tok: &token::Token) -> bool {
815 let is_present = self.check(tok);
816 if is_present { self.bump() }
820 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
821 self.expected_tokens.push(TokenType::Keyword(kw));
822 self.token.is_keyword(kw)
825 /// If the next token is the given keyword, eat it and return
826 /// true. Otherwise, return false.
827 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
828 if self.check_keyword(kw) {
836 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
837 if self.token.is_keyword(kw) {
845 /// If the given word is not a keyword, signal an error.
846 /// If the next token is not the given word, signal an error.
847 /// Otherwise, eat it.
848 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
849 if !self.eat_keyword(kw) {
856 fn check_ident(&mut self) -> bool {
857 if self.token.is_ident() {
860 self.expected_tokens.push(TokenType::Ident);
865 fn check_path(&mut self) -> bool {
866 if self.token.is_path_start() {
869 self.expected_tokens.push(TokenType::Path);
874 fn check_type(&mut self) -> bool {
875 if self.token.can_begin_type() {
878 self.expected_tokens.push(TokenType::Type);
883 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
884 /// `&` and continue. If an `&` is not seen, signal an error.
885 fn expect_and(&mut self) -> PResult<'a, ()> {
886 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
888 token::BinOp(token::And) => {
893 let span = self.span.with_lo(self.span.lo() + BytePos(1));
894 Ok(self.bump_with(token::BinOp(token::And), span))
896 _ => self.unexpected()
900 /// Expect and consume an `|`. If `||` is seen, replace it with a single
901 /// `|` and continue. If an `|` is not seen, signal an error.
902 fn expect_or(&mut self) -> PResult<'a, ()> {
903 self.expected_tokens.push(TokenType::Token(token::BinOp(token::Or)));
905 token::BinOp(token::Or) => {
910 let span = self.span.with_lo(self.span.lo() + BytePos(1));
911 Ok(self.bump_with(token::BinOp(token::Or), span))
913 _ => self.unexpected()
917 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
919 None => {/* everything ok */}
921 let text = suf.as_str();
923 self.span_bug(sp, "found empty literal suffix in Some")
925 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
930 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
931 /// `<` and continue. If a `<` is not seen, return false.
933 /// This is meant to be used when parsing generics on a path to get the
935 fn eat_lt(&mut self) -> bool {
936 self.expected_tokens.push(TokenType::Token(token::Lt));
942 token::BinOp(token::Shl) => {
943 let span = self.span.with_lo(self.span.lo() + BytePos(1));
944 self.bump_with(token::Lt, span);
951 fn expect_lt(&mut self) -> PResult<'a, ()> {
959 /// Expect and consume a GT. if a >> is seen, replace it
960 /// with a single > and continue. If a GT is not seen,
962 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
963 self.expected_tokens.push(TokenType::Token(token::Gt));
969 token::BinOp(token::Shr) => {
970 let span = self.span.with_lo(self.span.lo() + BytePos(1));
971 Ok(self.bump_with(token::Gt, span))
973 token::BinOpEq(token::Shr) => {
974 let span = self.span.with_lo(self.span.lo() + BytePos(1));
975 Ok(self.bump_with(token::Ge, span))
978 let span = self.span.with_lo(self.span.lo() + BytePos(1));
979 Ok(self.bump_with(token::Eq, span))
981 _ => self.unexpected()
985 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
986 sep: Option<token::Token>,
988 -> PResult<'a, (Vec<T>, bool)>
989 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
991 let mut v = Vec::new();
992 // This loop works by alternating back and forth between parsing types
993 // and commas. For example, given a string `A, B,>`, the parser would
994 // first parse `A`, then a comma, then `B`, then a comma. After that it
995 // would encounter a `>` and stop. This lets the parser handle trailing
996 // commas in generic parameters, because it can stop either after
997 // parsing a type or after parsing a comma.
999 if self.check(&token::Gt)
1000 || self.token == token::BinOp(token::Shr)
1001 || self.token == token::Ge
1002 || self.token == token::BinOpEq(token::Shr) {
1008 Some(result) => v.push(result),
1009 None => return Ok((v, true))
1012 if let Some(t) = sep.as_ref() {
1018 return Ok((v, false));
1021 /// Parse a sequence bracketed by '<' and '>', stopping
1023 pub fn parse_seq_to_before_gt<T, F>(&mut self,
1024 sep: Option<token::Token>,
1026 -> PResult<'a, Vec<T>> where
1027 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1029 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
1030 |p| Ok(Some(f(p)?)))?;
1035 pub fn parse_seq_to_gt<T, F>(&mut self,
1036 sep: Option<token::Token>,
1038 -> PResult<'a, Vec<T>> where
1039 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1041 let v = self.parse_seq_to_before_gt(sep, f)?;
1046 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
1047 sep: Option<token::Token>,
1049 -> PResult<'a, (Vec<T>, bool)> where
1050 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
1052 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
1056 return Ok((v, returned));
1059 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
1060 /// passes through any errors encountered. Used for error recovery.
1061 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
1062 let handler = self.diagnostic();
1064 if let Err(ref mut err) = self.parse_seq_to_before_tokens(kets,
1066 TokenExpectType::Expect,
1067 |p| Ok(p.parse_token_tree())) {
1068 handler.cancel(err);
1072 /// Parse a sequence, including the closing delimiter. The function
1073 /// f must consume tokens until reaching the next separator or
1074 /// closing bracket.
1075 pub fn parse_seq_to_end<T, F>(&mut self,
1079 -> PResult<'a, Vec<T>> where
1080 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1082 let val = self.parse_seq_to_before_end(ket, sep, f)?;
1087 /// Parse a sequence, not including the closing delimiter. The function
1088 /// f must consume tokens until reaching the next separator or
1089 /// closing bracket.
1090 pub fn parse_seq_to_before_end<T, F>(&mut self,
1094 -> PResult<'a, Vec<T>>
1095 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1097 self.parse_seq_to_before_tokens(&[ket], sep, TokenExpectType::Expect, f)
1100 fn parse_seq_to_before_tokens<T, F>(&mut self,
1101 kets: &[&token::Token],
1103 expect: TokenExpectType,
1105 -> PResult<'a, Vec<T>>
1106 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
1108 let mut first: bool = true;
1110 while !kets.contains(&&self.token) {
1112 token::CloseDelim(..) | token::Eof => break,
1115 if let Some(ref t) = sep.sep {
1119 if let Err(mut e) = self.expect(t) {
1120 // Attempt to keep parsing if it was a similar separator
1121 if let Some(ref tokens) = t.similar_tokens() {
1122 if tokens.contains(&self.token) {
1127 // Attempt to keep parsing if it was an omitted separator
1141 if sep.trailing_sep_allowed && kets.iter().any(|k| {
1143 TokenExpectType::Expect => self.check(k),
1144 TokenExpectType::NoExpect => self.token == **k,
1157 /// Parse a sequence, including the closing delimiter. The function
1158 /// f must consume tokens until reaching the next separator or
1159 /// closing bracket.
1160 pub fn parse_unspanned_seq<T, F>(&mut self,
1165 -> PResult<'a, Vec<T>> where
1166 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1169 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1170 if self.token == *ket {
1176 // NB: Do not use this function unless you actually plan to place the
1177 // spanned list in the AST.
1178 pub fn parse_seq<T, F>(&mut self,
1183 -> PResult<'a, Spanned<Vec<T>>> where
1184 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1188 let result = self.parse_seq_to_before_end(ket, sep, f)?;
1191 Ok(respan(lo.to(hi), result))
1194 /// Advance the parser by one token
1195 pub fn bump(&mut self) {
1196 if self.prev_token_kind == PrevTokenKind::Eof {
1197 // Bumping after EOF is a bad sign, usually an infinite loop.
1198 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1201 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1203 // Record last token kind for possible error recovery.
1204 self.prev_token_kind = match self.token {
1205 token::DocComment(..) => PrevTokenKind::DocComment,
1206 token::Comma => PrevTokenKind::Comma,
1207 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1208 token::Interpolated(..) => PrevTokenKind::Interpolated,
1209 token::Eof => PrevTokenKind::Eof,
1210 token::Ident(..) => PrevTokenKind::Ident,
1211 _ => PrevTokenKind::Other,
1214 let next = self.next_tok();
1215 self.span = next.sp;
1216 self.token = next.tok;
1217 self.expected_tokens.clear();
1218 // check after each token
1219 self.process_potential_macro_variable();
1222 /// Advance the parser using provided token as a next one. Use this when
1223 /// consuming a part of a token. For example a single `<` from `<<`.
1224 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1225 self.prev_span = self.span.with_hi(span.lo());
1226 // It would be incorrect to record the kind of the current token, but
1227 // fortunately for tokens currently using `bump_with`, the
1228 // prev_token_kind will be of no use anyway.
1229 self.prev_token_kind = PrevTokenKind::Other;
1232 self.expected_tokens.clear();
1235 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1236 F: FnOnce(&token::Token) -> R,
1239 return f(&self.token)
1242 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1243 Some(tree) => match tree {
1244 TokenTree::Token(_, tok) => tok,
1245 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1247 None => token::CloseDelim(self.token_cursor.frame.delim),
1251 fn look_ahead_span(&self, dist: usize) -> Span {
1256 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1257 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1258 None => self.look_ahead_span(dist - 1),
1261 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1262 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1264 pub fn span_fatal<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1265 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1267 pub fn span_fatal_err<S: Into<MultiSpan>>(&self, sp: S, err: Error) -> DiagnosticBuilder<'a> {
1268 err.span_err(sp, self.diagnostic())
1270 pub fn span_fatal_help<S: Into<MultiSpan>>(&self,
1273 help: &str) -> DiagnosticBuilder<'a> {
1274 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1278 pub fn bug(&self, m: &str) -> ! {
1279 self.sess.span_diagnostic.span_bug(self.span, m)
1281 pub fn warn(&self, m: &str) {
1282 self.sess.span_diagnostic.span_warn(self.span, m)
1284 pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1285 self.sess.span_diagnostic.span_warn(sp, m)
1287 pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) {
1288 self.sess.span_diagnostic.span_err(sp, m)
1290 pub fn struct_span_err<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> DiagnosticBuilder<'a> {
1291 self.sess.span_diagnostic.struct_span_err(sp, m)
1293 pub fn span_err_help<S: Into<MultiSpan>>(&self, sp: S, m: &str, h: &str) {
1294 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1298 pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, m: &str) -> ! {
1299 self.sess.span_diagnostic.span_bug(sp, m)
1301 pub fn abort_if_errors(&self) {
1302 self.sess.span_diagnostic.abort_if_errors();
1305 fn cancel(&self, err: &mut DiagnosticBuilder) {
1306 self.sess.span_diagnostic.cancel(err)
1309 pub fn diagnostic(&self) -> &'a errors::Handler {
1310 &self.sess.span_diagnostic
1313 /// Is the current token one of the keywords that signals a bare function
1315 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1316 self.check_keyword(keywords::Fn) ||
1317 self.check_keyword(keywords::Unsafe) ||
1318 self.check_keyword(keywords::Extern) && self.is_extern_non_path()
1321 /// parse a TyKind::BareFn type:
1322 pub fn parse_ty_bare_fn(&mut self, generic_params: Vec<GenericParam>)
1323 -> PResult<'a, TyKind> {
1326 [unsafe] [extern "ABI"] fn (S) -> T
1336 let unsafety = self.parse_unsafety();
1337 let abi = if self.eat_keyword(keywords::Extern) {
1338 self.parse_opt_abi()?.unwrap_or(Abi::C)
1343 self.expect_keyword(keywords::Fn)?;
1344 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1345 let ret_ty = self.parse_ret_ty(false)?;
1346 let decl = P(FnDecl {
1351 Ok(TyKind::BareFn(P(BareFnTy {
1359 /// Parse unsafety: `unsafe` or nothing.
1360 fn parse_unsafety(&mut self) -> Unsafety {
1361 if self.eat_keyword(keywords::Unsafe) {
1368 /// Parse the items in a trait declaration
1369 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1370 maybe_whole!(self, NtTraitItem, |x| x);
1371 let attrs = self.parse_outer_attributes()?;
1372 let (mut item, tokens) = self.collect_tokens(|this| {
1373 this.parse_trait_item_(at_end, attrs)
1375 // See `parse_item` for why this clause is here.
1376 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
1377 item.tokens = Some(tokens);
1382 fn parse_trait_item_(&mut self,
1384 mut attrs: Vec<Attribute>) -> PResult<'a, TraitItem> {
1387 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
1388 let (generics, TyParam {ident, bounds, default, ..}) =
1389 self.parse_trait_item_assoc_ty(vec![])?;
1390 (ident, TraitItemKind::Type(bounds, default), generics)
1391 } else if self.is_const_item() {
1392 self.expect_keyword(keywords::Const)?;
1393 let ident = self.parse_ident()?;
1394 self.expect(&token::Colon)?;
1395 let ty = self.parse_ty()?;
1396 let default = if self.check(&token::Eq) {
1398 let expr = self.parse_expr()?;
1399 self.expect(&token::Semi)?;
1402 self.expect(&token::Semi)?;
1405 (ident, TraitItemKind::Const(ty, default), ast::Generics::default())
1406 } else if let Some(mac) = self.parse_assoc_macro_invoc("trait", None, &mut false)? {
1407 // trait item macro.
1408 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac), ast::Generics::default())
1410 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
1412 let ident = self.parse_ident()?;
1413 let mut generics = self.parse_generics()?;
1415 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1416 // This is somewhat dubious; We don't want to allow
1417 // argument names to be left off if there is a
1419 p.parse_arg_general(false)
1421 generics.where_clause = self.parse_where_clause()?;
1423 let sig = ast::MethodSig {
1430 let body = match self.token {
1434 debug!("parse_trait_methods(): parsing required method");
1437 token::OpenDelim(token::Brace) => {
1438 debug!("parse_trait_methods(): parsing provided method");
1440 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1441 attrs.extend(inner_attrs.iter().cloned());
1445 let token_str = self.this_token_to_string();
1446 let mut err = self.fatal(&format!("expected `;` or `{{`, found `{}`",
1448 err.span_label(self.span, "expected `;` or `{`");
1452 (ident, ast::TraitItemKind::Method(sig, body), generics)
1456 id: ast::DUMMY_NODE_ID,
1461 span: lo.to(self.prev_span),
1466 /// Parse optional return type [ -> TY ] in function decl
1467 fn parse_ret_ty(&mut self, allow_plus: bool) -> PResult<'a, FunctionRetTy> {
1468 if self.eat(&token::RArrow) {
1469 Ok(FunctionRetTy::Ty(self.parse_ty_common(allow_plus, true)?))
1471 Ok(FunctionRetTy::Default(self.span.shrink_to_lo()))
1476 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1477 self.parse_ty_common(true, true)
1480 /// Parse a type in restricted contexts where `+` is not permitted.
1481 /// Example 1: `&'a TYPE`
1482 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1483 /// Example 2: `value1 as TYPE + value2`
1484 /// `+` is prohibited to avoid interactions with expression grammar.
1485 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1486 self.parse_ty_common(false, true)
1489 fn parse_ty_common(&mut self, allow_plus: bool, allow_qpath_recovery: bool)
1490 -> PResult<'a, P<Ty>> {
1491 maybe_whole!(self, NtTy, |x| x);
1494 let mut impl_dyn_multi = false;
1495 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1496 // `(TYPE)` is a parenthesized type.
1497 // `(TYPE,)` is a tuple with a single field of type TYPE.
1498 let mut ts = vec![];
1499 let mut last_comma = false;
1500 while self.token != token::CloseDelim(token::Paren) {
1501 ts.push(self.parse_ty()?);
1502 if self.eat(&token::Comma) {
1509 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1510 self.expect(&token::CloseDelim(token::Paren))?;
1512 if ts.len() == 1 && !last_comma {
1513 let ty = ts.into_iter().nth(0).unwrap().into_inner();
1514 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1516 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1517 TyKind::Path(None, ref path) if maybe_bounds => {
1518 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1520 TyKind::TraitObject(ref bounds, TraitObjectSyntax::None)
1521 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1522 let path = match bounds[0] {
1523 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1524 _ => self.bug("unexpected lifetime bound"),
1526 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1529 _ => TyKind::Paren(P(ty))
1534 } else if self.eat(&token::Not) {
1537 } else if self.eat(&token::BinOp(token::Star)) {
1539 TyKind::Ptr(self.parse_ptr()?)
1540 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1542 let t = self.parse_ty()?;
1543 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1544 let t = match self.maybe_parse_fixed_length_of_vec()? {
1545 None => TyKind::Slice(t),
1546 Some(suffix) => TyKind::Array(t, suffix),
1548 self.expect(&token::CloseDelim(token::Bracket))?;
1550 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1553 self.parse_borrowed_pointee()?
1554 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1556 // In order to not be ambiguous, the type must be surrounded by parens.
1557 self.expect(&token::OpenDelim(token::Paren))?;
1558 let e = self.parse_expr()?;
1559 self.expect(&token::CloseDelim(token::Paren))?;
1561 } else if self.eat_keyword(keywords::Underscore) {
1562 // A type to be inferred `_`
1564 } else if self.token_is_bare_fn_keyword() {
1565 // Function pointer type
1566 self.parse_ty_bare_fn(Vec::new())?
1567 } else if self.check_keyword(keywords::For) {
1568 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1569 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1570 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1572 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1573 if self.token_is_bare_fn_keyword() {
1574 self.parse_ty_bare_fn(lifetime_defs)?
1576 let path = self.parse_path(PathStyle::Type)?;
1577 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1578 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1580 } else if self.eat_keyword(keywords::Impl) {
1581 // Always parse bounds greedily for better error recovery.
1582 let bounds = self.parse_ty_param_bounds()?;
1583 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1584 TyKind::ImplTrait(bounds)
1585 } else if self.check_keyword(keywords::Dyn) &&
1586 self.look_ahead(1, |t| t.can_begin_bound() &&
1587 !can_continue_type_after_non_fn_ident(t)) {
1588 self.bump(); // `dyn`
1589 // Always parse bounds greedily for better error recovery.
1590 let bounds = self.parse_ty_param_bounds()?;
1591 impl_dyn_multi = bounds.len() > 1 || self.prev_token_kind == PrevTokenKind::Plus;
1592 TyKind::TraitObject(bounds, TraitObjectSyntax::Dyn)
1593 } else if self.check(&token::Question) ||
1594 self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)) {
1595 // Bound list (trait object type)
1596 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?,
1597 TraitObjectSyntax::None)
1598 } else if self.eat_lt() {
1600 let (qself, path) = self.parse_qpath(PathStyle::Type)?;
1601 TyKind::Path(Some(qself), path)
1602 } else if self.token.is_path_start() {
1604 let path = self.parse_path(PathStyle::Type)?;
1605 if self.eat(&token::Not) {
1606 // Macro invocation in type position
1607 let (_, tts) = self.expect_delimited_token_tree()?;
1608 TyKind::Mac(respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts }))
1610 // Just a type path or bound list (trait object type) starting with a trait.
1612 // `Trait1 + Trait2 + 'a`
1613 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1614 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1616 TyKind::Path(None, path)
1620 let msg = format!("expected type, found {}", self.this_token_descr());
1621 return Err(self.fatal(&msg));
1624 let span = lo.to(self.prev_span);
1625 let ty = Ty { node, span, id: ast::DUMMY_NODE_ID };
1627 // Try to recover from use of `+` with incorrect priority.
1628 self.maybe_report_ambiguous_plus(allow_plus, impl_dyn_multi, &ty);
1629 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1630 let ty = self.maybe_recover_from_bad_qpath(ty, allow_qpath_recovery)?;
1635 fn parse_remaining_bounds(&mut self, generic_params: Vec<GenericParam>, path: ast::Path,
1636 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1637 let poly_trait_ref = PolyTraitRef::new(generic_params, path, lo.to(self.prev_span));
1638 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1641 bounds.append(&mut self.parse_ty_param_bounds()?);
1643 Ok(TyKind::TraitObject(bounds, TraitObjectSyntax::None))
1646 fn maybe_report_ambiguous_plus(&mut self, allow_plus: bool, impl_dyn_multi: bool, ty: &Ty) {
1647 if !allow_plus && impl_dyn_multi {
1648 let sum_with_parens = format!("({})", pprust::ty_to_string(&ty));
1649 self.struct_span_err(ty.span, "ambiguous `+` in a type")
1650 .span_suggestion(ty.span, "use parentheses to disambiguate", sum_with_parens)
1655 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1656 // Do not add `+` to expected tokens.
1657 if !allow_plus || self.token != token::BinOp(token::Plus) {
1662 let bounds = self.parse_ty_param_bounds()?;
1663 let sum_span = ty.span.to(self.prev_span);
1665 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1666 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1669 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1670 let sum_with_parens = pprust::to_string(|s| {
1671 use print::pprust::PrintState;
1674 s.print_opt_lifetime(lifetime)?;
1675 s.print_mutability(mut_ty.mutbl)?;
1677 s.print_type(&mut_ty.ty)?;
1678 s.print_bounds(" +", &bounds)?;
1681 err.span_suggestion(sum_span, "try adding parentheses", sum_with_parens);
1683 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1684 err.span_label(sum_span, "perhaps you forgot parentheses?");
1687 err.span_label(sum_span, "expected a path");
1694 // Try to recover from associated item paths like `[T]::AssocItem`/`(T, U)::AssocItem`.
1695 fn maybe_recover_from_bad_qpath<T: RecoverQPath>(&mut self, base: T, allow_recovery: bool)
1697 // Do not add `::` to expected tokens.
1698 if !allow_recovery || self.token != token::ModSep {
1701 let ty = match base.to_ty() {
1703 None => return Ok(base),
1706 self.bump(); // `::`
1707 let mut segments = Vec::new();
1708 self.parse_path_segments(&mut segments, T::PATH_STYLE, true)?;
1710 let span = ty.span.to(self.prev_span);
1712 base.to_recovered(Some(QSelf { ty, position: 0 }), ast::Path { segments, span });
1715 .struct_span_err(span, "missing angle brackets in associated item path")
1716 .span_suggestion(span, "try", recovered.to_string()).emit();
1721 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1722 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1723 let mutbl = self.parse_mutability();
1724 let ty = self.parse_ty_no_plus()?;
1725 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1728 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1729 let mutbl = if self.eat_keyword(keywords::Mut) {
1731 } else if self.eat_keyword(keywords::Const) {
1732 Mutability::Immutable
1734 let span = self.prev_span;
1736 "expected mut or const in raw pointer type (use \
1737 `*mut T` or `*const T` as appropriate)");
1738 Mutability::Immutable
1740 let t = self.parse_ty_no_plus()?;
1741 Ok(MutTy { ty: t, mutbl: mutbl })
1744 fn is_named_argument(&mut self) -> bool {
1745 let offset = match self.token {
1746 token::Interpolated(ref nt) => match nt.0 {
1747 token::NtPat(..) => return self.look_ahead(1, |t| t == &token::Colon),
1750 token::BinOp(token::And) | token::AndAnd => 1,
1751 _ if self.token.is_keyword(keywords::Mut) => 1,
1755 self.look_ahead(offset, |t| t.is_ident()) &&
1756 self.look_ahead(offset + 1, |t| t == &token::Colon)
1759 /// This version of parse arg doesn't necessarily require
1760 /// identifier names.
1761 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1762 maybe_whole!(self, NtArg, |x| x);
1764 let pat = if require_name || self.is_named_argument() {
1765 debug!("parse_arg_general parse_pat (require_name:{})",
1767 let pat = self.parse_pat()?;
1769 self.expect(&token::Colon)?;
1772 debug!("parse_arg_general ident_to_pat");
1773 let ident = Ident::new(keywords::Invalid.name(), self.prev_span);
1775 id: ast::DUMMY_NODE_ID,
1776 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), ident, None),
1781 let t = self.parse_ty()?;
1786 id: ast::DUMMY_NODE_ID,
1790 /// Parse a single function argument
1791 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1792 self.parse_arg_general(true)
1795 /// Parse an argument in a lambda header e.g. |arg, arg|
1796 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1797 let pat = self.parse_pat()?;
1798 let t = if self.eat(&token::Colon) {
1802 id: ast::DUMMY_NODE_ID,
1803 node: TyKind::Infer,
1810 id: ast::DUMMY_NODE_ID
1814 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1815 if self.eat(&token::Semi) {
1816 Ok(Some(self.parse_expr()?))
1822 /// Matches token_lit = LIT_INTEGER | ...
1823 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1824 let out = match self.token {
1825 token::Interpolated(ref nt) => match nt.0 {
1826 token::NtExpr(ref v) => match v.node {
1827 ExprKind::Lit(ref lit) => { lit.node.clone() }
1828 _ => { return self.unexpected_last(&self.token); }
1830 _ => { return self.unexpected_last(&self.token); }
1832 token::Literal(lit, suf) => {
1833 let diag = Some((self.span, &self.sess.span_diagnostic));
1834 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1838 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1843 _ => { return self.unexpected_last(&self.token); }
1850 /// Matches lit = true | false | token_lit
1851 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1853 let lit = if self.eat_keyword(keywords::True) {
1855 } else if self.eat_keyword(keywords::False) {
1856 LitKind::Bool(false)
1858 let lit = self.parse_lit_token()?;
1861 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1864 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1865 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1866 maybe_whole_expr!(self);
1868 let minus_lo = self.span;
1869 let minus_present = self.eat(&token::BinOp(token::Minus));
1871 let literal = P(self.parse_lit()?);
1872 let hi = self.prev_span;
1873 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1876 let minus_hi = self.prev_span;
1877 let unary = self.mk_unary(UnOp::Neg, expr);
1878 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1884 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1886 token::Ident(ident, _) if self.token.is_path_segment_keyword() => {
1887 let span = self.span;
1889 Ok(Ident::new(ident.name, span))
1891 _ => self.parse_ident(),
1895 /// Parses qualified path.
1896 /// Assumes that the leading `<` has been parsed already.
1898 /// `qualified_path = <type [as trait_ref]>::path`
1902 /// `<T as U>::F::a<S>` (without disambiguator)
1903 /// `<T as U>::F::a::<S>` (with disambiguator)
1904 fn parse_qpath(&mut self, style: PathStyle) -> PResult<'a, (QSelf, ast::Path)> {
1905 let lo = self.prev_span;
1906 let ty = self.parse_ty()?;
1907 let mut path = if self.eat_keyword(keywords::As) {
1908 self.parse_path(PathStyle::Type)?
1910 ast::Path { segments: Vec::new(), span: syntax_pos::DUMMY_SP }
1912 self.expect(&token::Gt)?;
1913 self.expect(&token::ModSep)?;
1915 let qself = QSelf { ty, position: path.segments.len() };
1916 self.parse_path_segments(&mut path.segments, style, true)?;
1918 Ok((qself, ast::Path { segments: path.segments, span: lo.to(self.prev_span) }))
1921 /// Parses simple paths.
1923 /// `path = [::] segment+`
1924 /// `segment = ident | ident[::]<args> | ident[::](args) [-> type]`
1927 /// `a::b::C<D>` (without disambiguator)
1928 /// `a::b::C::<D>` (with disambiguator)
1929 /// `Fn(Args)` (without disambiguator)
1930 /// `Fn::(Args)` (with disambiguator)
1931 pub fn parse_path(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1932 self.parse_path_common(style, true)
1935 pub fn parse_path_common(&mut self, style: PathStyle, enable_warning: bool)
1936 -> PResult<'a, ast::Path> {
1937 maybe_whole!(self, NtPath, |path| {
1938 if style == PathStyle::Mod &&
1939 path.segments.iter().any(|segment| segment.parameters.is_some()) {
1940 self.diagnostic().span_err(path.span, "unexpected generic arguments in path");
1945 let lo = self.meta_var_span.unwrap_or(self.span);
1946 let mut segments = Vec::new();
1947 if self.eat(&token::ModSep) {
1948 segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
1950 self.parse_path_segments(&mut segments, style, enable_warning)?;
1952 Ok(ast::Path { segments, span: lo.to(self.prev_span) })
1955 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1956 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1957 pub fn parse_path_allowing_meta(&mut self, style: PathStyle) -> PResult<'a, ast::Path> {
1958 let meta_name = match self.token {
1959 token::Interpolated(ref nt) => match nt.0 {
1960 token::NtMeta(ref meta) => match meta.node {
1961 ast::MetaItemKind::Word => Some(meta.name.clone()),
1968 if let Some(path) = meta_name {
1972 self.parse_path(style)
1975 fn parse_path_segments(&mut self,
1976 segments: &mut Vec<PathSegment>,
1978 enable_warning: bool)
1979 -> PResult<'a, ()> {
1981 segments.push(self.parse_path_segment(style, enable_warning)?);
1983 if self.is_import_coupler() || !self.eat(&token::ModSep) {
1989 fn parse_path_segment(&mut self, style: PathStyle, enable_warning: bool)
1990 -> PResult<'a, PathSegment> {
1991 let ident = self.parse_path_segment_ident()?;
1993 let is_args_start = |token: &token::Token| match *token {
1994 token::Lt | token::BinOp(token::Shl) | token::OpenDelim(token::Paren) => true,
1997 let check_args_start = |this: &mut Self| {
1998 this.expected_tokens.extend_from_slice(
1999 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2001 is_args_start(&this.token)
2004 Ok(if style == PathStyle::Type && check_args_start(self) ||
2005 style != PathStyle::Mod && self.check(&token::ModSep)
2006 && self.look_ahead(1, |t| is_args_start(t)) {
2007 // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2009 if self.eat(&token::ModSep) && style == PathStyle::Type && enable_warning {
2010 self.diagnostic().struct_span_warn(self.prev_span, "unnecessary path disambiguator")
2011 .span_label(self.prev_span, "try removing `::`").emit();
2014 let parameters = if self.eat_lt() {
2016 let (lifetimes, types, bindings) = self.parse_generic_args()?;
2018 let span = lo.to(self.prev_span);
2019 AngleBracketedParameterData { lifetimes, types, bindings, span }.into()
2023 let inputs = self.parse_seq_to_before_tokens(
2024 &[&token::CloseDelim(token::Paren)],
2025 SeqSep::trailing_allowed(token::Comma),
2026 TokenExpectType::Expect,
2029 let output = if self.eat(&token::RArrow) {
2030 Some(self.parse_ty_common(false, false)?)
2034 let span = lo.to(self.prev_span);
2035 ParenthesizedParameterData { inputs, output, span }.into()
2038 PathSegment { ident, parameters }
2040 // Generic arguments are not found.
2041 PathSegment::from_ident(ident)
2045 fn check_lifetime(&mut self) -> bool {
2046 self.expected_tokens.push(TokenType::Lifetime);
2047 self.token.is_lifetime()
2050 /// Parse single lifetime 'a or panic.
2051 pub fn expect_lifetime(&mut self) -> Lifetime {
2052 if let Some(ident) = self.token.lifetime() {
2053 let span = self.span;
2055 Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2057 self.span_bug(self.span, "not a lifetime")
2061 fn eat_label(&mut self) -> Option<Label> {
2062 if let Some(ident) = self.token.lifetime() {
2063 let span = self.span;
2065 Some(Label { ident: Ident::new(ident.name, span) })
2071 /// Parse mutability (`mut` or nothing).
2072 fn parse_mutability(&mut self) -> Mutability {
2073 if self.eat_keyword(keywords::Mut) {
2076 Mutability::Immutable
2080 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2081 if let token::Literal(token::Integer(name), None) = self.token {
2083 Ok(Ident::new(name, self.prev_span))
2085 self.parse_ident_common(false)
2089 /// Parse ident (COLON expr)?
2090 pub fn parse_field(&mut self) -> PResult<'a, Field> {
2091 let attrs = self.parse_outer_attributes()?;
2094 // Check if a colon exists one ahead. This means we're parsing a fieldname.
2095 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
2096 let fieldname = self.parse_field_name()?;
2098 (fieldname, self.parse_expr()?, false)
2100 let fieldname = self.parse_ident_common(false)?;
2102 // Mimic `x: x` for the `x` field shorthand.
2103 let path = ast::Path::from_ident(fieldname);
2104 let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2105 (fieldname, expr, true)
2109 span: lo.to(expr.span),
2112 attrs: attrs.into(),
2116 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2117 P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2120 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2121 ExprKind::Unary(unop, expr)
2124 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2125 ExprKind::Binary(binop, lhs, rhs)
2128 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2129 ExprKind::Call(f, args)
2132 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2133 ExprKind::Index(expr, idx)
2136 pub fn mk_range(&mut self,
2137 start: Option<P<Expr>>,
2138 end: Option<P<Expr>>,
2139 limits: RangeLimits)
2140 -> PResult<'a, ast::ExprKind> {
2141 if end.is_none() && limits == RangeLimits::Closed {
2142 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2144 Ok(ExprKind::Range(start, end, limits))
2148 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2149 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2150 ExprKind::AssignOp(binop, lhs, rhs)
2153 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2155 id: ast::DUMMY_NODE_ID,
2156 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2162 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2163 let span = &self.span;
2164 let lv_lit = P(codemap::Spanned {
2165 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2170 id: ast::DUMMY_NODE_ID,
2171 node: ExprKind::Lit(lv_lit),
2177 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2179 token::OpenDelim(delim) => match self.parse_token_tree() {
2180 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2181 _ => unreachable!(),
2184 let msg = "expected open delimiter";
2185 let mut err = self.fatal(msg);
2186 err.span_label(self.span, msg);
2192 /// At the bottom (top?) of the precedence hierarchy,
2193 /// parse things like parenthesized exprs,
2194 /// macros, return, etc.
2196 /// NB: This does not parse outer attributes,
2197 /// and is private because it only works
2198 /// correctly if called from parse_dot_or_call_expr().
2199 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2200 maybe_whole_expr!(self);
2202 // Outer attributes are already parsed and will be
2203 // added to the return value after the fact.
2205 // Therefore, prevent sub-parser from parsing
2206 // attributes by giving them a empty "already parsed" list.
2207 let mut attrs = ThinVec::new();
2210 let mut hi = self.span;
2214 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2216 token::OpenDelim(token::Paren) => {
2219 attrs.extend(self.parse_inner_attributes()?);
2221 // (e) is parenthesized e
2222 // (e,) is a tuple with only one field, e
2223 let mut es = vec![];
2224 let mut trailing_comma = false;
2225 while self.token != token::CloseDelim(token::Paren) {
2226 es.push(self.parse_expr()?);
2227 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2228 if self.check(&token::Comma) {
2229 trailing_comma = true;
2233 trailing_comma = false;
2239 hi = self.prev_span;
2240 ex = if es.len() == 1 && !trailing_comma {
2241 ExprKind::Paren(es.into_iter().nth(0).unwrap())
2246 token::OpenDelim(token::Brace) => {
2247 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2249 token::BinOp(token::Or) | token::OrOr => {
2250 return self.parse_lambda_expr(attrs);
2252 token::OpenDelim(token::Bracket) => {
2255 attrs.extend(self.parse_inner_attributes()?);
2257 if self.check(&token::CloseDelim(token::Bracket)) {
2260 ex = ExprKind::Array(Vec::new());
2263 let first_expr = self.parse_expr()?;
2264 if self.check(&token::Semi) {
2265 // Repeating array syntax: [ 0; 512 ]
2267 let count = self.parse_expr()?;
2268 self.expect(&token::CloseDelim(token::Bracket))?;
2269 ex = ExprKind::Repeat(first_expr, count);
2270 } else if self.check(&token::Comma) {
2271 // Vector with two or more elements.
2273 let remaining_exprs = self.parse_seq_to_end(
2274 &token::CloseDelim(token::Bracket),
2275 SeqSep::trailing_allowed(token::Comma),
2276 |p| Ok(p.parse_expr()?)
2278 let mut exprs = vec![first_expr];
2279 exprs.extend(remaining_exprs);
2280 ex = ExprKind::Array(exprs);
2282 // Vector with one element.
2283 self.expect(&token::CloseDelim(token::Bracket))?;
2284 ex = ExprKind::Array(vec![first_expr]);
2287 hi = self.prev_span;
2291 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2293 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2295 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2296 return self.parse_lambda_expr(attrs);
2298 if self.eat_keyword(keywords::If) {
2299 return self.parse_if_expr(attrs);
2301 if self.eat_keyword(keywords::For) {
2302 let lo = self.prev_span;
2303 return self.parse_for_expr(None, lo, attrs);
2305 if self.eat_keyword(keywords::While) {
2306 let lo = self.prev_span;
2307 return self.parse_while_expr(None, lo, attrs);
2309 if let Some(label) = self.eat_label() {
2310 let lo = label.ident.span;
2311 self.expect(&token::Colon)?;
2312 if self.eat_keyword(keywords::While) {
2313 return self.parse_while_expr(Some(label), lo, attrs)
2315 if self.eat_keyword(keywords::For) {
2316 return self.parse_for_expr(Some(label), lo, attrs)
2318 if self.eat_keyword(keywords::Loop) {
2319 return self.parse_loop_expr(Some(label), lo, attrs)
2321 let msg = "expected `while`, `for`, or `loop` after a label";
2322 let mut err = self.fatal(msg);
2323 err.span_label(self.span, msg);
2326 if self.eat_keyword(keywords::Loop) {
2327 let lo = self.prev_span;
2328 return self.parse_loop_expr(None, lo, attrs);
2330 if self.eat_keyword(keywords::Continue) {
2331 let label = self.eat_label();
2332 let ex = ExprKind::Continue(label);
2333 let hi = self.prev_span;
2334 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2336 if self.eat_keyword(keywords::Match) {
2337 return self.parse_match_expr(attrs);
2339 if self.eat_keyword(keywords::Unsafe) {
2340 return self.parse_block_expr(
2342 BlockCheckMode::Unsafe(ast::UserProvided),
2345 if self.is_catch_expr() {
2347 assert!(self.eat_keyword(keywords::Do));
2348 assert!(self.eat_keyword(keywords::Catch));
2349 return self.parse_catch_expr(lo, attrs);
2351 if self.eat_keyword(keywords::Return) {
2352 if self.token.can_begin_expr() {
2353 let e = self.parse_expr()?;
2355 ex = ExprKind::Ret(Some(e));
2357 ex = ExprKind::Ret(None);
2359 } else if self.eat_keyword(keywords::Break) {
2360 let label = self.eat_label();
2361 let e = if self.token.can_begin_expr()
2362 && !(self.token == token::OpenDelim(token::Brace)
2363 && self.restrictions.contains(
2364 Restrictions::NO_STRUCT_LITERAL)) {
2365 Some(self.parse_expr()?)
2369 ex = ExprKind::Break(label, e);
2370 hi = self.prev_span;
2371 } else if self.eat_keyword(keywords::Yield) {
2372 if self.token.can_begin_expr() {
2373 let e = self.parse_expr()?;
2375 ex = ExprKind::Yield(Some(e));
2377 ex = ExprKind::Yield(None);
2379 } else if self.token.is_keyword(keywords::Let) {
2380 // Catch this syntax error here, instead of in `parse_ident`, so
2381 // that we can explicitly mention that let is not to be used as an expression
2382 let mut db = self.fatal("expected expression, found statement (`let`)");
2383 db.span_label(self.span, "expected expression");
2384 db.note("variable declaration using `let` is a statement");
2386 } else if self.token.is_path_start() {
2387 let pth = self.parse_path(PathStyle::Expr)?;
2389 // `!`, as an operator, is prefix, so we know this isn't that
2390 if self.eat(&token::Not) {
2391 // MACRO INVOCATION expression
2392 let (_, tts) = self.expect_delimited_token_tree()?;
2393 let hi = self.prev_span;
2394 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2396 if self.check(&token::OpenDelim(token::Brace)) {
2397 // This is a struct literal, unless we're prohibited
2398 // from parsing struct literals here.
2399 let prohibited = self.restrictions.contains(
2400 Restrictions::NO_STRUCT_LITERAL
2403 return self.parse_struct_expr(lo, pth, attrs);
2408 ex = ExprKind::Path(None, pth);
2410 match self.parse_lit() {
2413 ex = ExprKind::Lit(P(lit));
2416 self.cancel(&mut err);
2417 let msg = format!("expected expression, found {}",
2418 self.this_token_descr());
2419 let mut err = self.fatal(&msg);
2420 err.span_label(self.span, "expected expression");
2428 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2429 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2434 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2435 -> PResult<'a, P<Expr>> {
2436 let struct_sp = lo.to(self.prev_span);
2438 let mut fields = Vec::new();
2439 let mut base = None;
2441 attrs.extend(self.parse_inner_attributes()?);
2443 while self.token != token::CloseDelim(token::Brace) {
2444 if self.eat(&token::DotDot) {
2445 let exp_span = self.prev_span;
2446 match self.parse_expr() {
2452 self.recover_stmt();
2455 if self.token == token::Comma {
2456 let mut err = self.sess.span_diagnostic.mut_span_err(
2457 exp_span.to(self.prev_span),
2458 "cannot use a comma after the base struct",
2460 err.span_suggestion_short(self.span, "remove this comma", "".to_owned());
2461 err.note("the base struct must always be the last field");
2463 self.recover_stmt();
2468 match self.parse_field() {
2469 Ok(f) => fields.push(f),
2471 e.span_label(struct_sp, "while parsing this struct");
2473 self.recover_stmt();
2478 match self.expect_one_of(&[token::Comma],
2479 &[token::CloseDelim(token::Brace)]) {
2483 self.recover_stmt();
2489 let span = lo.to(self.span);
2490 self.expect(&token::CloseDelim(token::Brace))?;
2491 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2494 fn parse_or_use_outer_attributes(&mut self,
2495 already_parsed_attrs: Option<ThinVec<Attribute>>)
2496 -> PResult<'a, ThinVec<Attribute>> {
2497 if let Some(attrs) = already_parsed_attrs {
2500 self.parse_outer_attributes().map(|a| a.into())
2504 /// Parse a block or unsafe block
2505 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2506 outer_attrs: ThinVec<Attribute>)
2507 -> PResult<'a, P<Expr>> {
2508 self.expect(&token::OpenDelim(token::Brace))?;
2510 let mut attrs = outer_attrs;
2511 attrs.extend(self.parse_inner_attributes()?);
2513 let blk = self.parse_block_tail(lo, blk_mode)?;
2514 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2517 /// parse a.b or a(13) or a[4] or just a
2518 pub fn parse_dot_or_call_expr(&mut self,
2519 already_parsed_attrs: Option<ThinVec<Attribute>>)
2520 -> PResult<'a, P<Expr>> {
2521 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2523 let b = self.parse_bottom_expr();
2524 let (span, b) = self.interpolated_or_expr_span(b)?;
2525 self.parse_dot_or_call_expr_with(b, span, attrs)
2528 pub fn parse_dot_or_call_expr_with(&mut self,
2531 mut attrs: ThinVec<Attribute>)
2532 -> PResult<'a, P<Expr>> {
2533 // Stitch the list of outer attributes onto the return value.
2534 // A little bit ugly, but the best way given the current code
2536 self.parse_dot_or_call_expr_with_(e0, lo)
2538 expr.map(|mut expr| {
2539 attrs.extend::<Vec<_>>(expr.attrs.into());
2542 ExprKind::If(..) | ExprKind::IfLet(..) => {
2543 if !expr.attrs.is_empty() {
2544 // Just point to the first attribute in there...
2545 let span = expr.attrs[0].span;
2548 "attributes are not yet allowed on `if` \
2559 // Assuming we have just parsed `.`, continue parsing into an expression.
2560 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2561 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2562 Ok(match self.token {
2563 token::OpenDelim(token::Paren) => {
2564 // Method call `expr.f()`
2565 let mut args = self.parse_unspanned_seq(
2566 &token::OpenDelim(token::Paren),
2567 &token::CloseDelim(token::Paren),
2568 SeqSep::trailing_allowed(token::Comma),
2569 |p| Ok(p.parse_expr()?)
2571 args.insert(0, self_arg);
2573 let span = lo.to(self.prev_span);
2574 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2577 // Field access `expr.f`
2578 if let Some(parameters) = segment.parameters {
2579 self.span_err(parameters.span(),
2580 "field expressions may not have generic arguments");
2583 let span = lo.to(self.prev_span);
2584 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2589 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2594 while self.eat(&token::Question) {
2595 let hi = self.prev_span;
2596 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2600 if self.eat(&token::Dot) {
2602 token::Ident(..) => {
2603 e = self.parse_dot_suffix(e, lo)?;
2605 token::Literal(token::Integer(name), _) => {
2606 let span = self.span;
2608 let field = ExprKind::Field(e, Ident::new(name, span));
2609 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2611 token::Literal(token::Float(n), _suf) => {
2613 let fstr = n.as_str();
2614 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2615 &format!("unexpected token: `{}`", n));
2616 err.span_label(self.prev_span, "unexpected token");
2617 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2618 let float = match fstr.parse::<f64>().ok() {
2622 let sugg = pprust::to_string(|s| {
2623 use print::pprust::PrintState;
2627 s.print_usize(float.trunc() as usize)?;
2630 s.s.word(fstr.splitn(2, ".").last().unwrap())
2632 err.span_suggestion(
2633 lo.to(self.prev_span),
2634 "try parenthesizing the first index",
2641 // FIXME Could factor this out into non_fatal_unexpected or something.
2642 let actual = self.this_token_to_string();
2643 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2648 if self.expr_is_complete(&e) { break; }
2651 token::OpenDelim(token::Paren) => {
2652 let es = self.parse_unspanned_seq(
2653 &token::OpenDelim(token::Paren),
2654 &token::CloseDelim(token::Paren),
2655 SeqSep::trailing_allowed(token::Comma),
2656 |p| Ok(p.parse_expr()?)
2658 hi = self.prev_span;
2660 let nd = self.mk_call(e, es);
2661 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2665 // Could be either an index expression or a slicing expression.
2666 token::OpenDelim(token::Bracket) => {
2668 let ix = self.parse_expr()?;
2670 self.expect(&token::CloseDelim(token::Bracket))?;
2671 let index = self.mk_index(e, ix);
2672 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2680 pub fn process_potential_macro_variable(&mut self) {
2681 let (token, span) = match self.token {
2682 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2683 self.look_ahead(1, |t| t.is_ident()) => {
2685 let name = match self.token {
2686 token::Ident(ident, _) => ident,
2689 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2690 err.span_label(self.span, "unknown macro variable");
2694 token::Interpolated(ref nt) => {
2695 self.meta_var_span = Some(self.span);
2696 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2697 // and lifetime tokens, so the former are never encountered during normal parsing.
2699 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2700 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2710 /// parse a single token tree from the input.
2711 pub fn parse_token_tree(&mut self) -> TokenTree {
2713 token::OpenDelim(..) => {
2714 let frame = mem::replace(&mut self.token_cursor.frame,
2715 self.token_cursor.stack.pop().unwrap());
2716 self.span = frame.span;
2718 TokenTree::Delimited(frame.span, Delimited {
2720 tts: frame.tree_cursor.original_stream().into(),
2723 token::CloseDelim(_) | token::Eof => unreachable!(),
2725 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2727 TokenTree::Token(span, token)
2732 // parse a stream of tokens into a list of TokenTree's,
2734 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2735 let mut tts = Vec::new();
2736 while self.token != token::Eof {
2737 tts.push(self.parse_token_tree());
2742 pub fn parse_tokens(&mut self) -> TokenStream {
2743 let mut result = Vec::new();
2746 token::Eof | token::CloseDelim(..) => break,
2747 _ => result.push(self.parse_token_tree().into()),
2750 TokenStream::concat(result)
2753 /// Parse a prefix-unary-operator expr
2754 pub fn parse_prefix_expr(&mut self,
2755 already_parsed_attrs: Option<ThinVec<Attribute>>)
2756 -> PResult<'a, P<Expr>> {
2757 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2759 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2760 let (hi, ex) = match self.token {
2763 let e = self.parse_prefix_expr(None);
2764 let (span, e) = self.interpolated_or_expr_span(e)?;
2765 (lo.to(span), self.mk_unary(UnOp::Not, e))
2767 // Suggest `!` for bitwise negation when encountering a `~`
2770 let e = self.parse_prefix_expr(None);
2771 let (span, e) = self.interpolated_or_expr_span(e)?;
2772 let span_of_tilde = lo;
2773 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2774 "`~` cannot be used as a unary operator");
2775 err.span_suggestion_short(span_of_tilde,
2776 "use `!` to perform bitwise negation",
2779 (lo.to(span), self.mk_unary(UnOp::Not, e))
2781 token::BinOp(token::Minus) => {
2783 let e = self.parse_prefix_expr(None);
2784 let (span, e) = self.interpolated_or_expr_span(e)?;
2785 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2787 token::BinOp(token::Star) => {
2789 let e = self.parse_prefix_expr(None);
2790 let (span, e) = self.interpolated_or_expr_span(e)?;
2791 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2793 token::BinOp(token::And) | token::AndAnd => {
2795 let m = self.parse_mutability();
2796 let e = self.parse_prefix_expr(None);
2797 let (span, e) = self.interpolated_or_expr_span(e)?;
2798 (lo.to(span), ExprKind::AddrOf(m, e))
2800 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2802 let e = self.parse_prefix_expr(None);
2803 let (span, e) = self.interpolated_or_expr_span(e)?;
2804 (lo.to(span), ExprKind::Box(e))
2806 token::Ident(..) if self.token.is_ident_named("not") => {
2807 // `not` is just an ordinary identifier in Rust-the-language,
2808 // but as `rustc`-the-compiler, we can issue clever diagnostics
2809 // for confused users who really want to say `!`
2810 let token_cannot_continue_expr = |t: &token::Token| match *t {
2811 // These tokens can start an expression after `!`, but
2812 // can't continue an expression after an ident
2813 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
2814 token::Literal(..) | token::Pound => true,
2815 token::Interpolated(ref nt) => match nt.0 {
2816 token::NtIdent(..) | token::NtExpr(..) |
2817 token::NtBlock(..) | token::NtPath(..) => true,
2822 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2823 if cannot_continue_expr {
2825 // Emit the error ...
2826 let mut err = self.diagnostic()
2827 .struct_span_err(self.span,
2828 &format!("unexpected {} after identifier",
2829 self.this_token_descr()));
2830 // span the `not` plus trailing whitespace to avoid
2831 // trailing whitespace after the `!` in our suggestion
2832 let to_replace = self.sess.codemap()
2833 .span_until_non_whitespace(lo.to(self.span));
2834 err.span_suggestion_short(to_replace,
2835 "use `!` to perform logical negation",
2838 // —and recover! (just as if we were in the block
2839 // for the `token::Not` arm)
2840 let e = self.parse_prefix_expr(None);
2841 let (span, e) = self.interpolated_or_expr_span(e)?;
2842 (lo.to(span), self.mk_unary(UnOp::Not, e))
2844 return self.parse_dot_or_call_expr(Some(attrs));
2847 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2849 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2852 /// Parse an associative expression
2854 /// This parses an expression accounting for associativity and precedence of the operators in
2856 pub fn parse_assoc_expr(&mut self,
2857 already_parsed_attrs: Option<ThinVec<Attribute>>)
2858 -> PResult<'a, P<Expr>> {
2859 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2862 /// Parse an associative expression with operators of at least `min_prec` precedence
2863 pub fn parse_assoc_expr_with(&mut self,
2866 -> PResult<'a, P<Expr>> {
2867 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2870 let attrs = match lhs {
2871 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2874 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2875 return self.parse_prefix_range_expr(attrs);
2877 self.parse_prefix_expr(attrs)?
2881 if self.expr_is_complete(&lhs) {
2882 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2885 self.expected_tokens.push(TokenType::Operator);
2886 while let Some(op) = AssocOp::from_token(&self.token) {
2888 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2889 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2890 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2891 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2892 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2893 (PrevTokenKind::Interpolated, _) => self.prev_span,
2894 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2895 if path.segments.len() == 1 => self.prev_span,
2899 let cur_op_span = self.span;
2900 let restrictions = if op.is_assign_like() {
2901 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2905 if op.precedence() < min_prec {
2908 // Check for deprecated `...` syntax
2909 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2910 self.err_dotdotdot_syntax(self.span);
2914 if op.is_comparison() {
2915 self.check_no_chained_comparison(&lhs, &op);
2918 if op == AssocOp::As {
2919 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2921 } else if op == AssocOp::Colon {
2922 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2925 err.span_label(self.span,
2926 "expecting a type here because of type ascription");
2927 let cm = self.sess.codemap();
2928 let cur_pos = cm.lookup_char_pos(self.span.lo());
2929 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
2930 if cur_pos.line != op_pos.line {
2931 err.span_suggestion_short(cur_op_span,
2932 "did you mean to use `;` here?",
2939 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2940 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2941 // generalise it to the Fixity::None code.
2943 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2944 // two variants are handled with `parse_prefix_range_expr` call above.
2945 let rhs = if self.is_at_start_of_range_notation_rhs() {
2946 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2947 LhsExpr::NotYetParsed)?)
2951 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2956 let limits = if op == AssocOp::DotDot {
2957 RangeLimits::HalfOpen
2962 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2963 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2967 let rhs = match op.fixity() {
2968 Fixity::Right => self.with_res(
2969 restrictions - Restrictions::STMT_EXPR,
2971 this.parse_assoc_expr_with(op.precedence(),
2972 LhsExpr::NotYetParsed)
2974 Fixity::Left => self.with_res(
2975 restrictions - Restrictions::STMT_EXPR,
2977 this.parse_assoc_expr_with(op.precedence() + 1,
2978 LhsExpr::NotYetParsed)
2980 // We currently have no non-associative operators that are not handled above by
2981 // the special cases. The code is here only for future convenience.
2982 Fixity::None => self.with_res(
2983 restrictions - Restrictions::STMT_EXPR,
2985 this.parse_assoc_expr_with(op.precedence() + 1,
2986 LhsExpr::NotYetParsed)
2990 let span = lhs_span.to(rhs.span);
2992 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2993 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2994 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2995 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2996 AssocOp::Greater | AssocOp::GreaterEqual => {
2997 let ast_op = op.to_ast_binop().unwrap();
2998 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2999 self.mk_expr(span, binary, ThinVec::new())
3002 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3003 AssocOp::AssignOp(k) => {
3005 token::Plus => BinOpKind::Add,
3006 token::Minus => BinOpKind::Sub,
3007 token::Star => BinOpKind::Mul,
3008 token::Slash => BinOpKind::Div,
3009 token::Percent => BinOpKind::Rem,
3010 token::Caret => BinOpKind::BitXor,
3011 token::And => BinOpKind::BitAnd,
3012 token::Or => BinOpKind::BitOr,
3013 token::Shl => BinOpKind::Shl,
3014 token::Shr => BinOpKind::Shr,
3016 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
3017 self.mk_expr(span, aopexpr, ThinVec::new())
3019 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3020 self.bug("AssocOp should have been handled by special case")
3024 if op.fixity() == Fixity::None { break }
3029 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3030 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3031 -> PResult<'a, P<Expr>> {
3032 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3033 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3036 // Save the state of the parser before parsing type normally, in case there is a
3037 // LessThan comparison after this cast.
3038 let parser_snapshot_before_type = self.clone();
3039 match self.parse_ty_no_plus() {
3041 Ok(mk_expr(self, rhs))
3043 Err(mut type_err) => {
3044 // Rewind to before attempting to parse the type with generics, to recover
3045 // from situations like `x as usize < y` in which we first tried to parse
3046 // `usize < y` as a type with generic arguments.
3047 let parser_snapshot_after_type = self.clone();
3048 mem::replace(self, parser_snapshot_before_type);
3050 match self.parse_path(PathStyle::Expr) {
3052 let (op_noun, op_verb) = match self.token {
3053 token::Lt => ("comparison", "comparing"),
3054 token::BinOp(token::Shl) => ("shift", "shifting"),
3056 // We can end up here even without `<` being the next token, for
3057 // example because `parse_ty_no_plus` returns `Err` on keywords,
3058 // but `parse_path` returns `Ok` on them due to error recovery.
3059 // Return original error and parser state.
3060 mem::replace(self, parser_snapshot_after_type);
3061 return Err(type_err);
3065 // Successfully parsed the type path leaving a `<` yet to parse.
3068 // Report non-fatal diagnostics, keep `x as usize` as an expression
3069 // in AST and continue parsing.
3070 let msg = format!("`<` is interpreted as a start of generic \
3071 arguments for `{}`, not a {}", path, op_noun);
3072 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3073 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3074 "interpreted as generic arguments");
3075 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3077 let expr = mk_expr(self, P(Ty {
3079 node: TyKind::Path(None, path),
3080 id: ast::DUMMY_NODE_ID
3083 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
3084 .unwrap_or(pprust::expr_to_string(&expr));
3085 err.span_suggestion(expr.span,
3086 &format!("try {} the cast value", op_verb),
3087 format!("({})", expr_str));
3092 Err(mut path_err) => {
3093 // Couldn't parse as a path, return original error and parser state.
3095 mem::replace(self, parser_snapshot_after_type);
3103 /// Produce an error if comparison operators are chained (RFC #558).
3104 /// We only need to check lhs, not rhs, because all comparison ops
3105 /// have same precedence and are left-associative
3106 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3107 debug_assert!(outer_op.is_comparison(),
3108 "check_no_chained_comparison: {:?} is not comparison",
3111 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3112 // respan to include both operators
3113 let op_span = op.span.to(self.span);
3114 let mut err = self.diagnostic().struct_span_err(op_span,
3115 "chained comparison operators require parentheses");
3116 if op.node == BinOpKind::Lt &&
3117 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3118 *outer_op == AssocOp::Greater // even in a case like the following:
3119 { // Foo<Bar<Baz<Qux, ()>>>
3121 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3122 err.help("or use `(...)` if you meant to specify fn arguments");
3130 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3131 fn parse_prefix_range_expr(&mut self,
3132 already_parsed_attrs: Option<ThinVec<Attribute>>)
3133 -> PResult<'a, P<Expr>> {
3134 // Check for deprecated `...` syntax
3135 if self.token == token::DotDotDot {
3136 self.err_dotdotdot_syntax(self.span);
3139 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3140 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3142 let tok = self.token.clone();
3143 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3145 let mut hi = self.span;
3147 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3148 // RHS must be parsed with more associativity than the dots.
3149 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3150 Some(self.parse_assoc_expr_with(next_prec,
3151 LhsExpr::NotYetParsed)
3159 let limits = if tok == token::DotDot {
3160 RangeLimits::HalfOpen
3165 let r = try!(self.mk_range(None,
3168 Ok(self.mk_expr(lo.to(hi), r, attrs))
3171 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3172 if self.token.can_begin_expr() {
3173 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3174 if self.token == token::OpenDelim(token::Brace) {
3175 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3183 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3184 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3185 if self.check_keyword(keywords::Let) {
3186 return self.parse_if_let_expr(attrs);
3188 let lo = self.prev_span;
3189 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3191 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3192 // verify that the last statement is either an implicit return (no `;`) or an explicit
3193 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3194 // the dead code lint.
3195 if self.eat_keyword(keywords::Else) || !cond.returns() {
3196 let sp = self.sess.codemap().next_point(lo);
3197 let mut err = self.diagnostic()
3198 .struct_span_err(sp, "missing condition for `if` statemement");
3199 err.span_label(sp, "expected if condition here");
3202 let not_block = self.token != token::OpenDelim(token::Brace);
3203 let thn = self.parse_block().map_err(|mut err| {
3205 err.span_label(lo, "this `if` statement has a condition, but no block");
3209 let mut els: Option<P<Expr>> = None;
3210 let mut hi = thn.span;
3211 if self.eat_keyword(keywords::Else) {
3212 let elexpr = self.parse_else_expr()?;
3216 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3219 /// Parse an 'if let' expression ('if' token already eaten)
3220 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3221 -> PResult<'a, P<Expr>> {
3222 let lo = self.prev_span;
3223 self.expect_keyword(keywords::Let)?;
3224 let pats = self.parse_pats()?;
3225 self.expect(&token::Eq)?;
3226 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3227 let thn = self.parse_block()?;
3228 let (hi, els) = if self.eat_keyword(keywords::Else) {
3229 let expr = self.parse_else_expr()?;
3230 (expr.span, Some(expr))
3234 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3237 // `move |args| expr`
3238 pub fn parse_lambda_expr(&mut self,
3239 attrs: ThinVec<Attribute>)
3240 -> PResult<'a, P<Expr>>
3243 let movability = if self.eat_keyword(keywords::Static) {
3248 let capture_clause = if self.eat_keyword(keywords::Move) {
3253 let decl = self.parse_fn_block_decl()?;
3254 let decl_hi = self.prev_span;
3255 let body = match decl.output {
3256 FunctionRetTy::Default(_) => {
3257 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3258 self.parse_expr_res(restrictions, None)?
3261 // If an explicit return type is given, require a
3262 // block to appear (RFC 968).
3263 let body_lo = self.span;
3264 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3270 ExprKind::Closure(capture_clause, movability, decl, body, lo.to(decl_hi)),
3274 // `else` token already eaten
3275 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3276 if self.eat_keyword(keywords::If) {
3277 return self.parse_if_expr(ThinVec::new());
3279 let blk = self.parse_block()?;
3280 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3284 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3285 pub fn parse_for_expr(&mut self, opt_label: Option<Label>,
3287 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3288 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3290 let pat = self.parse_top_level_pat()?;
3291 if !self.eat_keyword(keywords::In) {
3292 let in_span = self.prev_span.between(self.span);
3293 let mut err = self.sess.span_diagnostic
3294 .struct_span_err(in_span, "missing `in` in `for` loop");
3295 err.span_suggestion_short(in_span, "try adding `in` here", " in ".into());
3298 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3299 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3300 attrs.extend(iattrs);
3302 let hi = self.prev_span;
3303 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3306 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3307 pub fn parse_while_expr(&mut self, opt_label: Option<Label>,
3309 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3310 if self.token.is_keyword(keywords::Let) {
3311 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3313 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3314 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3315 attrs.extend(iattrs);
3316 let span = span_lo.to(body.span);
3317 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3320 /// Parse a 'while let' expression ('while' token already eaten)
3321 pub fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3323 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3324 self.expect_keyword(keywords::Let)?;
3325 let pats = self.parse_pats()?;
3326 self.expect(&token::Eq)?;
3327 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3328 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3329 attrs.extend(iattrs);
3330 let span = span_lo.to(body.span);
3331 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3334 // parse `loop {...}`, `loop` token already eaten
3335 pub fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3337 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3338 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3339 attrs.extend(iattrs);
3340 let span = span_lo.to(body.span);
3341 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3344 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3345 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3346 -> PResult<'a, P<Expr>>
3348 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3349 attrs.extend(iattrs);
3350 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3353 // `match` token already eaten
3354 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3355 let match_span = self.prev_span;
3356 let lo = self.prev_span;
3357 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3359 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3360 if self.token == token::Token::Semi {
3361 e.span_suggestion_short(match_span, "try removing this `match`", "".to_owned());
3365 attrs.extend(self.parse_inner_attributes()?);
3367 let mut arms: Vec<Arm> = Vec::new();
3368 while self.token != token::CloseDelim(token::Brace) {
3369 match self.parse_arm() {
3370 Ok(arm) => arms.push(arm),
3372 // Recover by skipping to the end of the block.
3374 self.recover_stmt();
3375 let span = lo.to(self.span);
3376 if self.token == token::CloseDelim(token::Brace) {
3379 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3385 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3388 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3389 maybe_whole!(self, NtArm, |x| x);
3391 let attrs = self.parse_outer_attributes()?;
3392 // Allow a '|' before the pats (RFC 1925)
3393 self.eat(&token::BinOp(token::Or));
3394 let pats = self.parse_pats()?;
3395 let guard = if self.eat_keyword(keywords::If) {
3396 Some(self.parse_expr()?)
3400 let arrow_span = self.span;
3401 self.expect(&token::FatArrow)?;
3402 let arm_start_span = self.span;
3404 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3405 .map_err(|mut err| {
3406 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3410 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3411 && self.token != token::CloseDelim(token::Brace);
3414 let cm = self.sess.codemap();
3415 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3416 .map_err(|mut err| {
3417 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3418 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3419 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3420 && expr_lines.lines.len() == 2
3421 && self.token == token::FatArrow => {
3422 // We check wether there's any trailing code in the parse span, if there
3423 // isn't, we very likely have the following:
3426 // | -- - missing comma
3432 // | parsed until here as `"y" & X`
3433 err.span_suggestion_short(
3434 cm.next_point(arm_start_span),
3435 "missing a comma here to end this `match` arm",
3440 err.span_label(arrow_span,
3441 "while parsing the `match` arm starting here");
3447 self.eat(&token::Comma);
3458 /// Parse an expression
3459 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3460 self.parse_expr_res(Restrictions::empty(), None)
3463 /// Evaluate the closure with restrictions in place.
3465 /// After the closure is evaluated, restrictions are reset.
3466 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3467 where F: FnOnce(&mut Self) -> T
3469 let old = self.restrictions;
3470 self.restrictions = r;
3472 self.restrictions = old;
3477 /// Parse an expression, subject to the given restrictions
3478 pub fn parse_expr_res(&mut self, r: Restrictions,
3479 already_parsed_attrs: Option<ThinVec<Attribute>>)
3480 -> PResult<'a, P<Expr>> {
3481 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3484 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3485 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3486 if self.check(&token::Eq) {
3488 Ok(Some(self.parse_expr()?))
3490 Ok(Some(self.parse_expr()?))
3496 /// Parse patterns, separated by '|' s
3497 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3498 let mut pats = Vec::new();
3500 pats.push(self.parse_top_level_pat()?);
3502 if self.token == token::OrOr {
3503 let mut err = self.struct_span_err(self.span,
3504 "unexpected token `||` after pattern");
3505 err.span_suggestion(self.span,
3506 "use a single `|` to specify multiple patterns",
3510 } else if self.check(&token::BinOp(token::Or)) {
3518 // Parses a parenthesized list of patterns like
3519 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3520 // - a vector of the patterns that were parsed
3521 // - an option indicating the index of the `..` element
3522 // - a boolean indicating whether a trailing comma was present.
3523 // Trailing commas are significant because (p) and (p,) are different patterns.
3524 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3525 self.expect(&token::OpenDelim(token::Paren))?;
3526 let result = self.parse_pat_list()?;
3527 self.expect(&token::CloseDelim(token::Paren))?;
3531 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3532 let mut fields = Vec::new();
3533 let mut ddpos = None;
3534 let mut trailing_comma = false;
3536 if self.eat(&token::DotDot) {
3537 if ddpos.is_none() {
3538 ddpos = Some(fields.len());
3540 // Emit a friendly error, ignore `..` and continue parsing
3541 self.span_err(self.prev_span,
3542 "`..` can only be used once per tuple or tuple struct pattern");
3544 } else if !self.check(&token::CloseDelim(token::Paren)) {
3545 fields.push(self.parse_pat()?);
3550 trailing_comma = self.eat(&token::Comma);
3551 if !trailing_comma {
3556 if ddpos == Some(fields.len()) && trailing_comma {
3557 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3558 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3561 Ok((fields, ddpos, trailing_comma))
3564 fn parse_pat_vec_elements(
3566 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3567 let mut before = Vec::new();
3568 let mut slice = None;
3569 let mut after = Vec::new();
3570 let mut first = true;
3571 let mut before_slice = true;
3573 while self.token != token::CloseDelim(token::Bracket) {
3577 self.expect(&token::Comma)?;
3579 if self.token == token::CloseDelim(token::Bracket)
3580 && (before_slice || !after.is_empty()) {
3586 if self.eat(&token::DotDot) {
3588 if self.check(&token::Comma) ||
3589 self.check(&token::CloseDelim(token::Bracket)) {
3590 slice = Some(P(Pat {
3591 id: ast::DUMMY_NODE_ID,
3592 node: PatKind::Wild,
3593 span: self.prev_span,
3595 before_slice = false;
3601 let subpat = self.parse_pat()?;
3602 if before_slice && self.eat(&token::DotDot) {
3603 slice = Some(subpat);
3604 before_slice = false;
3605 } else if before_slice {
3606 before.push(subpat);
3612 Ok((before, slice, after))
3615 /// Parse the fields of a struct-like pattern
3616 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3617 let mut fields = Vec::new();
3618 let mut etc = false;
3619 let mut first = true;
3620 while self.token != token::CloseDelim(token::Brace) {
3624 self.expect(&token::Comma)?;
3625 // accept trailing commas
3626 if self.check(&token::CloseDelim(token::Brace)) { break }
3629 let attrs = self.parse_outer_attributes()?;
3633 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3634 if self.token == token::DotDotDot { // Issue #46718
3635 let mut err = self.struct_span_err(self.span,
3636 "expected field pattern, found `...`");
3637 err.span_suggestion(self.span,
3638 "to omit remaining fields, use one fewer `.`",
3644 if self.token != token::CloseDelim(token::Brace) {
3645 let token_str = self.this_token_to_string();
3646 let mut err = self.fatal(&format!("expected `{}`, found `{}`", "}", token_str));
3647 if self.token == token::Comma { // Issue #49257
3648 err.span_label(self.span,
3649 "`..` must be in the last position, \
3650 and cannot have a trailing comma");
3652 err.span_label(self.span, "expected `}`");
3660 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3661 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3662 // Parsing a pattern of the form "fieldname: pat"
3663 let fieldname = self.parse_field_name()?;
3665 let pat = self.parse_pat()?;
3667 (pat, fieldname, false)
3669 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3670 let is_box = self.eat_keyword(keywords::Box);
3671 let boxed_span = self.span;
3672 let is_ref = self.eat_keyword(keywords::Ref);
3673 let is_mut = self.eat_keyword(keywords::Mut);
3674 let fieldname = self.parse_ident()?;
3675 hi = self.prev_span;
3677 let bind_type = match (is_ref, is_mut) {
3678 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3679 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3680 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3681 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3683 let fieldpat = P(Pat {
3684 id: ast::DUMMY_NODE_ID,
3685 node: PatKind::Ident(bind_type, fieldname, None),
3686 span: boxed_span.to(hi),
3689 let subpat = if is_box {
3691 id: ast::DUMMY_NODE_ID,
3692 node: PatKind::Box(fieldpat),
3698 (subpat, fieldname, true)
3701 fields.push(codemap::Spanned { span: lo.to(hi),
3702 node: ast::FieldPat {
3706 attrs: attrs.into(),
3710 return Ok((fields, etc));
3713 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3714 if self.token.is_path_start() {
3716 let (qself, path) = if self.eat_lt() {
3717 // Parse a qualified path
3718 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3721 // Parse an unqualified path
3722 (None, self.parse_path(PathStyle::Expr)?)
3724 let hi = self.prev_span;
3725 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3727 self.parse_pat_literal_maybe_minus()
3731 // helper function to decide whether to parse as ident binding or to try to do
3732 // something more complex like range patterns
3733 fn parse_as_ident(&mut self) -> bool {
3734 self.look_ahead(1, |t| match *t {
3735 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3736 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3737 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3738 // range pattern branch
3739 token::DotDot => None,
3741 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3742 token::Comma | token::CloseDelim(token::Bracket) => true,
3747 /// A wrapper around `parse_pat` with some special error handling for the
3748 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contast
3749 /// to subpatterns within such).
3750 pub fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3751 let pat = self.parse_pat()?;
3752 if self.token == token::Comma {
3753 // An unexpected comma after a top-level pattern is a clue that the
3754 // user (perhaps more accustomed to some other language) forgot the
3755 // parentheses in what should have been a tuple pattern; return a
3756 // suggestion-enhanced error here rather than choking on the comma
3758 let comma_span = self.span;
3760 if let Err(mut err) = self.parse_pat_list() {
3761 // We didn't expect this to work anyway; we just wanted
3762 // to advance to the end of the comma-sequence so we know
3763 // the span to suggest parenthesizing
3766 let seq_span = pat.span.to(self.prev_span);
3767 let mut err = self.struct_span_err(comma_span,
3768 "unexpected `,` in pattern");
3769 if let Ok(seq_snippet) = self.sess.codemap().span_to_snippet(seq_span) {
3770 err.span_suggestion(seq_span, "try adding parentheses",
3771 format!("({})", seq_snippet));
3778 /// Parse a pattern.
3779 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3780 self.parse_pat_with_range_pat(true)
3783 /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
3785 fn parse_pat_with_range_pat(&mut self, allow_range_pat: bool) -> PResult<'a, P<Pat>> {
3786 maybe_whole!(self, NtPat, |x| x);
3791 token::BinOp(token::And) | token::AndAnd => {
3792 // Parse &pat / &mut pat
3794 let mutbl = self.parse_mutability();
3795 if let token::Lifetime(ident) = self.token {
3796 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
3798 err.span_label(self.span, "unexpected lifetime");
3801 let subpat = self.parse_pat_with_range_pat(false)?;
3802 pat = PatKind::Ref(subpat, mutbl);
3804 token::OpenDelim(token::Paren) => {
3805 // Parse (pat,pat,pat,...) as tuple pattern
3806 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
3807 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
3808 PatKind::Paren(fields.into_iter().nth(0).unwrap())
3810 PatKind::Tuple(fields, ddpos)
3813 token::OpenDelim(token::Bracket) => {
3814 // Parse [pat,pat,...] as slice pattern
3816 let (before, slice, after) = self.parse_pat_vec_elements()?;
3817 self.expect(&token::CloseDelim(token::Bracket))?;
3818 pat = PatKind::Slice(before, slice, after);
3820 // At this point, token != &, &&, (, [
3821 _ => if self.eat_keyword(keywords::Underscore) {
3823 pat = PatKind::Wild;
3824 } else if self.eat_keyword(keywords::Mut) {
3825 // Parse mut ident @ pat / mut ref ident @ pat
3826 let mutref_span = self.prev_span.to(self.span);
3827 let binding_mode = if self.eat_keyword(keywords::Ref) {
3829 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3830 .span_suggestion(mutref_span, "try switching the order", "ref mut".into())
3832 BindingMode::ByRef(Mutability::Mutable)
3834 BindingMode::ByValue(Mutability::Mutable)
3836 pat = self.parse_pat_ident(binding_mode)?;
3837 } else if self.eat_keyword(keywords::Ref) {
3838 // Parse ref ident @ pat / ref mut ident @ pat
3839 let mutbl = self.parse_mutability();
3840 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3841 } else if self.eat_keyword(keywords::Box) {
3843 let subpat = self.parse_pat_with_range_pat(false)?;
3844 pat = PatKind::Box(subpat);
3845 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3846 self.parse_as_ident() {
3847 // Parse ident @ pat
3848 // This can give false positives and parse nullary enums,
3849 // they are dealt with later in resolve
3850 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3851 pat = self.parse_pat_ident(binding_mode)?;
3852 } else if self.token.is_path_start() {
3853 // Parse pattern starting with a path
3854 let (qself, path) = if self.eat_lt() {
3855 // Parse a qualified path
3856 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3859 // Parse an unqualified path
3860 (None, self.parse_path(PathStyle::Expr)?)
3863 token::Not if qself.is_none() => {
3864 // Parse macro invocation
3866 let (_, tts) = self.expect_delimited_token_tree()?;
3867 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3868 pat = PatKind::Mac(mac);
3870 token::DotDotDot | token::DotDotEq | token::DotDot => {
3871 let end_kind = match self.token {
3872 token::DotDot => RangeEnd::Excluded,
3873 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
3874 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
3875 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
3879 let span = lo.to(self.prev_span);
3880 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3882 let end = self.parse_pat_range_end()?;
3883 pat = PatKind::Range(begin, end, end_kind);
3885 token::OpenDelim(token::Brace) => {
3886 if qself.is_some() {
3887 let msg = "unexpected `{` after qualified path";
3888 let mut err = self.fatal(msg);
3889 err.span_label(self.span, msg);
3892 // Parse struct pattern
3894 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3896 self.recover_stmt();
3900 pat = PatKind::Struct(path, fields, etc);
3902 token::OpenDelim(token::Paren) => {
3903 if qself.is_some() {
3904 let msg = "unexpected `(` after qualified path";
3905 let mut err = self.fatal(msg);
3906 err.span_label(self.span, msg);
3909 // Parse tuple struct or enum pattern
3910 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
3911 pat = PatKind::TupleStruct(path, fields, ddpos)
3913 _ => pat = PatKind::Path(qself, path),
3916 // Try to parse everything else as literal with optional minus
3917 match self.parse_pat_literal_maybe_minus() {
3919 if self.eat(&token::DotDotDot) {
3920 let end = self.parse_pat_range_end()?;
3921 pat = PatKind::Range(begin, end,
3922 RangeEnd::Included(RangeSyntax::DotDotDot));
3923 } else if self.eat(&token::DotDotEq) {
3924 let end = self.parse_pat_range_end()?;
3925 pat = PatKind::Range(begin, end,
3926 RangeEnd::Included(RangeSyntax::DotDotEq));
3927 } else if self.eat(&token::DotDot) {
3928 let end = self.parse_pat_range_end()?;
3929 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3931 pat = PatKind::Lit(begin);
3935 self.cancel(&mut err);
3936 let msg = format!("expected pattern, found {}", self.this_token_descr());
3937 let mut err = self.fatal(&msg);
3938 err.span_label(self.span, "expected pattern");
3945 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
3946 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
3948 if !allow_range_pat {
3950 PatKind::Range(_, _, RangeEnd::Included(RangeSyntax::DotDotDot)) => {}
3951 PatKind::Range(..) => {
3952 let mut err = self.struct_span_err(
3954 "the range pattern here has ambiguous interpretation",
3956 err.span_suggestion(
3958 "add parentheses to clarify the precedence",
3959 format!("({})", pprust::pat_to_string(&pat)),
3970 /// Parse ident or ident @ pat
3971 /// used by the copy foo and ref foo patterns to give a good
3972 /// error message when parsing mistakes like ref foo(a,b)
3973 fn parse_pat_ident(&mut self,
3974 binding_mode: ast::BindingMode)
3975 -> PResult<'a, PatKind> {
3976 let ident = self.parse_ident()?;
3977 let sub = if self.eat(&token::At) {
3978 Some(self.parse_pat()?)
3983 // just to be friendly, if they write something like
3985 // we end up here with ( as the current token. This shortly
3986 // leads to a parse error. Note that if there is no explicit
3987 // binding mode then we do not end up here, because the lookahead
3988 // will direct us over to parse_enum_variant()
3989 if self.token == token::OpenDelim(token::Paren) {
3990 return Err(self.span_fatal(
3992 "expected identifier, found enum pattern"))
3995 Ok(PatKind::Ident(binding_mode, ident, sub))
3998 /// Parse a local variable declaration
3999 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4000 let lo = self.prev_span;
4001 let pat = self.parse_top_level_pat()?;
4003 let (err, ty) = if self.eat(&token::Colon) {
4004 // Save the state of the parser before parsing type normally, in case there is a `:`
4005 // instead of an `=` typo.
4006 let parser_snapshot_before_type = self.clone();
4007 let colon_sp = self.prev_span;
4008 match self.parse_ty() {
4009 Ok(ty) => (None, Some(ty)),
4011 // Rewind to before attempting to parse the type and continue parsing
4012 let parser_snapshot_after_type = self.clone();
4013 mem::replace(self, parser_snapshot_before_type);
4015 let snippet = self.sess.codemap().span_to_snippet(pat.span).unwrap();
4016 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4017 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4023 let init = match (self.parse_initializer(err.is_some()), err) {
4024 (Ok(init), None) => { // init parsed, ty parsed
4027 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4028 // Could parse the type as if it were the initializer, it is likely there was a
4029 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4030 err.span_suggestion_short(colon_sp,
4031 "use `=` if you meant to assign",
4034 // As this was parsed successfully, continue as if the code has been fixed for the
4035 // rest of the file. It will still fail due to the emitted error, but we avoid
4039 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4041 // Couldn't parse the type nor the initializer, only raise the type error and
4042 // return to the parser state before parsing the type as the initializer.
4043 // let x: <parse_error>;
4044 mem::replace(self, snapshot);
4047 (Err(err), None) => { // init error, ty parsed
4048 // Couldn't parse the initializer and we're not attempting to recover a failed
4049 // parse of the type, return the error.
4053 let hi = if self.token == token::Semi {
4062 id: ast::DUMMY_NODE_ID,
4068 /// Parse a structure field
4069 fn parse_name_and_ty(&mut self,
4072 attrs: Vec<Attribute>)
4073 -> PResult<'a, StructField> {
4074 let name = self.parse_ident()?;
4075 self.expect(&token::Colon)?;
4076 let ty = self.parse_ty()?;
4078 span: lo.to(self.prev_span),
4081 id: ast::DUMMY_NODE_ID,
4087 /// Emit an expected item after attributes error.
4088 fn expected_item_err(&self, attrs: &[Attribute]) {
4089 let message = match attrs.last() {
4090 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4091 _ => "expected item after attributes",
4094 self.span_err(self.prev_span, message);
4097 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4098 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4099 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4100 Ok(self.parse_stmt_(true))
4103 // Eat tokens until we can be relatively sure we reached the end of the
4104 // statement. This is something of a best-effort heuristic.
4106 // We terminate when we find an unmatched `}` (without consuming it).
4107 fn recover_stmt(&mut self) {
4108 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4111 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4112 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4113 // approximate - it can mean we break too early due to macros, but that
4114 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
4116 // If `break_on_block` is `Break`, then we will stop consuming tokens
4117 // after finding (and consuming) a brace-delimited block.
4118 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4119 let mut brace_depth = 0;
4120 let mut bracket_depth = 0;
4121 let mut in_block = false;
4122 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4123 break_on_semi, break_on_block);
4125 debug!("recover_stmt_ loop {:?}", self.token);
4127 token::OpenDelim(token::DelimToken::Brace) => {
4130 if break_on_block == BlockMode::Break &&
4132 bracket_depth == 0 {
4136 token::OpenDelim(token::DelimToken::Bracket) => {
4140 token::CloseDelim(token::DelimToken::Brace) => {
4141 if brace_depth == 0 {
4142 debug!("recover_stmt_ return - close delim {:?}", self.token);
4147 if in_block && bracket_depth == 0 && brace_depth == 0 {
4148 debug!("recover_stmt_ return - block end {:?}", self.token);
4152 token::CloseDelim(token::DelimToken::Bracket) => {
4154 if bracket_depth < 0 {
4160 debug!("recover_stmt_ return - Eof");
4165 if break_on_semi == SemiColonMode::Break &&
4167 bracket_depth == 0 {
4168 debug!("recover_stmt_ return - Semi");
4179 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4180 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4182 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4187 fn is_catch_expr(&mut self) -> bool {
4188 self.token.is_keyword(keywords::Do) &&
4189 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4190 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4192 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
4193 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4196 fn is_union_item(&self) -> bool {
4197 self.token.is_keyword(keywords::Union) &&
4198 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4201 fn is_crate_vis(&self) -> bool {
4202 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4205 fn is_extern_non_path(&self) -> bool {
4206 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4209 fn is_auto_trait_item(&mut self) -> bool {
4211 (self.token.is_keyword(keywords::Auto)
4212 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4213 || // unsafe auto trait
4214 (self.token.is_keyword(keywords::Unsafe) &&
4215 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4216 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4219 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4220 -> PResult<'a, Option<P<Item>>> {
4221 let token_lo = self.span;
4222 let (ident, def) = match self.token {
4223 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4225 let ident = self.parse_ident()?;
4226 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4227 match self.parse_token_tree() {
4228 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4229 _ => unreachable!(),
4231 } else if self.check(&token::OpenDelim(token::Paren)) {
4232 let args = self.parse_token_tree();
4233 let body = if self.check(&token::OpenDelim(token::Brace)) {
4234 self.parse_token_tree()
4239 TokenStream::concat(vec![
4241 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4249 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4251 token::Ident(ident, _) if ident.name == "macro_rules" &&
4252 self.look_ahead(1, |t| *t == token::Not) => {
4253 let prev_span = self.prev_span;
4254 self.complain_if_pub_macro(&vis.node, prev_span);
4258 let ident = self.parse_ident()?;
4259 let (delim, tokens) = self.expect_delimited_token_tree()?;
4260 if delim != token::Brace {
4261 if !self.eat(&token::Semi) {
4262 let msg = "macros that expand to items must either \
4263 be surrounded with braces or followed by a semicolon";
4264 self.span_err(self.prev_span, msg);
4268 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4270 _ => return Ok(None),
4273 let span = lo.to(self.prev_span);
4274 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4277 fn parse_stmt_without_recovery(&mut self,
4278 macro_legacy_warnings: bool)
4279 -> PResult<'a, Option<Stmt>> {
4280 maybe_whole!(self, NtStmt, |x| Some(x));
4282 let attrs = self.parse_outer_attributes()?;
4285 Ok(Some(if self.eat_keyword(keywords::Let) {
4287 id: ast::DUMMY_NODE_ID,
4288 node: StmtKind::Local(self.parse_local(attrs.into())?),
4289 span: lo.to(self.prev_span),
4291 } else if let Some(macro_def) = self.eat_macro_def(
4293 &codemap::respan(lo, VisibilityKind::Inherited),
4297 id: ast::DUMMY_NODE_ID,
4298 node: StmtKind::Item(macro_def),
4299 span: lo.to(self.prev_span),
4301 // Starts like a simple path, being careful to avoid contextual keywords
4302 // such as a union items, item with `crate` visibility or auto trait items.
4303 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4304 // like a path (1 token), but it fact not a path.
4305 // `union::b::c` - path, `union U { ... }` - not a path.
4306 // `crate::b::c` - path, `crate struct S;` - not a path.
4307 // `extern::b::c` - path, `extern crate c;` - not a path.
4308 } else if self.token.is_path_start() &&
4309 !self.token.is_qpath_start() &&
4310 !self.is_union_item() &&
4311 !self.is_crate_vis() &&
4312 !self.is_extern_non_path() &&
4313 !self.is_auto_trait_item() {
4314 let pth = self.parse_path(PathStyle::Expr)?;
4316 if !self.eat(&token::Not) {
4317 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4318 self.parse_struct_expr(lo, pth, ThinVec::new())?
4320 let hi = self.prev_span;
4321 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4324 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4325 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4326 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4329 return Ok(Some(Stmt {
4330 id: ast::DUMMY_NODE_ID,
4331 node: StmtKind::Expr(expr),
4332 span: lo.to(self.prev_span),
4336 // it's a macro invocation
4337 let id = match self.token {
4338 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4339 _ => self.parse_ident()?,
4342 // check that we're pointing at delimiters (need to check
4343 // again after the `if`, because of `parse_ident`
4344 // consuming more tokens).
4345 let delim = match self.token {
4346 token::OpenDelim(delim) => delim,
4348 // we only expect an ident if we didn't parse one
4350 let ident_str = if id.name == keywords::Invalid.name() {
4355 let tok_str = self.this_token_to_string();
4356 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4359 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4364 let (_, tts) = self.expect_delimited_token_tree()?;
4365 let hi = self.prev_span;
4367 let style = if delim == token::Brace {
4368 MacStmtStyle::Braces
4370 MacStmtStyle::NoBraces
4373 if id.name == keywords::Invalid.name() {
4374 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
4375 let node = if delim == token::Brace ||
4376 self.token == token::Semi || self.token == token::Eof {
4377 StmtKind::Mac(P((mac, style, attrs.into())))
4379 // We used to incorrectly stop parsing macro-expanded statements here.
4380 // If the next token will be an error anyway but could have parsed with the
4381 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4382 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4383 // These can continue an expression, so we can't stop parsing and warn.
4384 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4385 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4386 token::BinOp(token::And) | token::BinOp(token::Or) |
4387 token::AndAnd | token::OrOr |
4388 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4391 self.warn_missing_semicolon();
4392 StmtKind::Mac(P((mac, style, attrs.into())))
4394 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4395 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4396 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4400 id: ast::DUMMY_NODE_ID,
4405 // if it has a special ident, it's definitely an item
4407 // Require a semicolon or braces.
4408 if style != MacStmtStyle::Braces {
4409 if !self.eat(&token::Semi) {
4410 self.span_err(self.prev_span,
4411 "macros that expand to items must \
4412 either be surrounded with braces or \
4413 followed by a semicolon");
4416 let span = lo.to(hi);
4418 id: ast::DUMMY_NODE_ID,
4420 node: StmtKind::Item({
4422 span, id /*id is good here*/,
4423 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
4424 respan(lo, VisibilityKind::Inherited),
4430 // FIXME: Bad copy of attrs
4431 let old_directory_ownership =
4432 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4433 let item = self.parse_item_(attrs.clone(), false, true)?;
4434 self.directory.ownership = old_directory_ownership;
4438 id: ast::DUMMY_NODE_ID,
4439 span: lo.to(i.span),
4440 node: StmtKind::Item(i),
4443 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4444 if !attrs.is_empty() {
4445 if s.prev_token_kind == PrevTokenKind::DocComment {
4446 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4447 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4448 s.span_err(s.span, "expected statement after outer attribute");
4453 // Do not attempt to parse an expression if we're done here.
4454 if self.token == token::Semi {
4455 unused_attrs(&attrs, self);
4460 if self.token == token::CloseDelim(token::Brace) {
4461 unused_attrs(&attrs, self);
4465 // Remainder are line-expr stmts.
4466 let e = self.parse_expr_res(
4467 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4469 id: ast::DUMMY_NODE_ID,
4470 span: lo.to(e.span),
4471 node: StmtKind::Expr(e),
4478 /// Is this expression a successfully-parsed statement?
4479 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4480 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4481 !classify::expr_requires_semi_to_be_stmt(e)
4484 /// Parse a block. No inner attrs are allowed.
4485 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4486 maybe_whole!(self, NtBlock, |x| x);
4490 if !self.eat(&token::OpenDelim(token::Brace)) {
4492 let tok = self.this_token_to_string();
4493 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4495 // Check to see if the user has written something like
4500 // Which is valid in other languages, but not Rust.
4501 match self.parse_stmt_without_recovery(false) {
4503 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) {
4504 // if the next token is an open brace (e.g., `if a b {`), the place-
4505 // inside-a-block suggestion would be more likely wrong than right
4508 let mut stmt_span = stmt.span;
4509 // expand the span to include the semicolon, if it exists
4510 if self.eat(&token::Semi) {
4511 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4513 let sugg = pprust::to_string(|s| {
4514 use print::pprust::{PrintState, INDENT_UNIT};
4515 s.ibox(INDENT_UNIT)?;
4517 s.print_stmt(&stmt)?;
4518 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4520 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4523 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4524 self.cancel(&mut e);
4531 self.parse_block_tail(lo, BlockCheckMode::Default)
4534 /// Parse a block. Inner attrs are allowed.
4535 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4536 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4539 self.expect(&token::OpenDelim(token::Brace))?;
4540 Ok((self.parse_inner_attributes()?,
4541 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4544 /// Parse the rest of a block expression or function body
4545 /// Precondition: already parsed the '{'.
4546 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4547 let mut stmts = vec![];
4548 let mut recovered = false;
4550 while !self.eat(&token::CloseDelim(token::Brace)) {
4551 let stmt = match self.parse_full_stmt(false) {
4554 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4555 self.eat(&token::CloseDelim(token::Brace));
4561 if let Some(stmt) = stmt {
4563 } else if self.token == token::Eof {
4566 // Found only `;` or `}`.
4572 id: ast::DUMMY_NODE_ID,
4574 span: lo.to(self.prev_span),
4579 /// Parse a statement, including the trailing semicolon.
4580 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4581 // skip looking for a trailing semicolon when we have an interpolated statement
4582 maybe_whole!(self, NtStmt, |x| Some(x));
4584 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4586 None => return Ok(None),
4590 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4591 // expression without semicolon
4592 if classify::expr_requires_semi_to_be_stmt(expr) {
4593 // Just check for errors and recover; do not eat semicolon yet.
4595 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4598 self.recover_stmt();
4602 StmtKind::Local(..) => {
4603 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4604 if macro_legacy_warnings && self.token != token::Semi {
4605 self.warn_missing_semicolon();
4607 self.expect_one_of(&[token::Semi], &[])?;
4613 if self.eat(&token::Semi) {
4614 stmt = stmt.add_trailing_semicolon();
4617 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4621 fn warn_missing_semicolon(&self) {
4622 self.diagnostic().struct_span_warn(self.span, {
4623 &format!("expected `;`, found `{}`", self.this_token_to_string())
4625 "This was erroneously allowed and will become a hard error in a future release"
4629 fn err_dotdotdot_syntax(&self, span: Span) {
4630 self.diagnostic().struct_span_err(span, {
4631 "`...` syntax cannot be used in expressions"
4633 "Use `..` if you need an exclusive range (a < b)"
4635 "or `..=` if you need an inclusive range (a <= b)"
4639 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4640 // BOUND = TY_BOUND | LT_BOUND
4641 // LT_BOUND = LIFETIME (e.g. `'a`)
4642 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4643 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4644 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4645 let mut bounds = Vec::new();
4647 // This needs to be syncronized with `Token::can_begin_bound`.
4648 let is_bound_start = self.check_path() || self.check_lifetime() ||
4649 self.check(&token::Question) ||
4650 self.check_keyword(keywords::For) ||
4651 self.check(&token::OpenDelim(token::Paren));
4653 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4654 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4655 if self.token.is_lifetime() {
4656 if let Some(question_span) = question {
4657 self.span_err(question_span,
4658 "`?` may only modify trait bounds, not lifetime bounds");
4660 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4663 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4664 let path = self.parse_path(PathStyle::Type)?;
4665 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4666 let modifier = if question.is_some() {
4667 TraitBoundModifier::Maybe
4669 TraitBoundModifier::None
4671 bounds.push(TraitTyParamBound(poly_trait, modifier));
4674 self.expect(&token::CloseDelim(token::Paren))?;
4675 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4676 self.span_err(self.prev_span,
4677 "parenthesized lifetime bounds are not supported");
4684 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4692 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4693 self.parse_ty_param_bounds_common(true)
4696 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4697 // BOUND = LT_BOUND (e.g. `'a`)
4698 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4699 let mut lifetimes = Vec::new();
4700 while self.check_lifetime() {
4701 lifetimes.push(self.expect_lifetime());
4703 if !self.eat(&token::BinOp(token::Plus)) {
4710 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4711 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4712 let ident = self.parse_ident()?;
4714 // Parse optional colon and param bounds.
4715 let bounds = if self.eat(&token::Colon) {
4716 self.parse_ty_param_bounds()?
4721 let default = if self.eat(&token::Eq) {
4722 Some(self.parse_ty()?)
4728 attrs: preceding_attrs.into(),
4730 id: ast::DUMMY_NODE_ID,
4736 /// Parses the following grammar:
4737 /// TraitItemAssocTy = Ident ["<"...">"] [":" [TyParamBounds]] ["where" ...] ["=" Ty]
4738 fn parse_trait_item_assoc_ty(&mut self, preceding_attrs: Vec<Attribute>)
4739 -> PResult<'a, (ast::Generics, TyParam)> {
4740 let ident = self.parse_ident()?;
4741 let mut generics = self.parse_generics()?;
4743 // Parse optional colon and param bounds.
4744 let bounds = if self.eat(&token::Colon) {
4745 self.parse_ty_param_bounds()?
4749 generics.where_clause = self.parse_where_clause()?;
4751 let default = if self.eat(&token::Eq) {
4752 Some(self.parse_ty()?)
4756 self.expect(&token::Semi)?;
4758 Ok((generics, TyParam {
4759 attrs: preceding_attrs.into(),
4761 id: ast::DUMMY_NODE_ID,
4767 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4768 /// trailing comma and erroneous trailing attributes.
4769 pub fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4770 let mut params = Vec::new();
4771 let mut seen_ty_param = false;
4773 let attrs = self.parse_outer_attributes()?;
4774 if self.check_lifetime() {
4775 let lifetime = self.expect_lifetime();
4776 // Parse lifetime parameter.
4777 let bounds = if self.eat(&token::Colon) {
4778 self.parse_lt_param_bounds()
4782 params.push(ast::GenericParam::Lifetime(LifetimeDef {
4783 attrs: attrs.into(),
4788 self.span_err(self.prev_span,
4789 "lifetime parameters must be declared prior to type parameters");
4791 } else if self.check_ident() {
4792 // Parse type parameter.
4793 params.push(ast::GenericParam::Type(self.parse_ty_param(attrs)?));
4794 seen_ty_param = true;
4796 // Check for trailing attributes and stop parsing.
4797 if !attrs.is_empty() {
4798 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4799 self.span_err(attrs[0].span,
4800 &format!("trailing attribute after {} parameters", param_kind));
4805 if !self.eat(&token::Comma) {
4812 /// Parse a set of optional generic type parameter declarations. Where
4813 /// clauses are not parsed here, and must be added later via
4814 /// `parse_where_clause()`.
4816 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4817 /// | ( < lifetimes , typaramseq ( , )? > )
4818 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4819 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4820 maybe_whole!(self, NtGenerics, |x| x);
4822 let span_lo = self.span;
4824 let params = self.parse_generic_params()?;
4828 where_clause: WhereClause {
4829 id: ast::DUMMY_NODE_ID,
4830 predicates: Vec::new(),
4831 span: syntax_pos::DUMMY_SP,
4833 span: span_lo.to(self.prev_span),
4836 Ok(ast::Generics::default())
4840 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4841 /// possibly including trailing comma.
4842 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4843 let mut lifetimes = Vec::new();
4844 let mut types = Vec::new();
4845 let mut bindings = Vec::new();
4846 let mut seen_type = false;
4847 let mut seen_binding = false;
4849 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4850 // Parse lifetime argument.
4851 lifetimes.push(self.expect_lifetime());
4852 if seen_type || seen_binding {
4853 self.span_err(self.prev_span,
4854 "lifetime parameters must be declared prior to type parameters");
4856 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4857 // Parse associated type binding.
4859 let ident = self.parse_ident()?;
4861 let ty = self.parse_ty()?;
4862 bindings.push(TypeBinding {
4863 id: ast::DUMMY_NODE_ID,
4866 span: lo.to(self.prev_span),
4868 seen_binding = true;
4869 } else if self.check_type() {
4870 // Parse type argument.
4871 types.push(self.parse_ty()?);
4873 self.span_err(types[types.len() - 1].span,
4874 "type parameters must be declared prior to associated type bindings");
4881 if !self.eat(&token::Comma) {
4885 Ok((lifetimes, types, bindings))
4888 /// Parses an optional `where` clause and places it in `generics`.
4890 /// ```ignore (only-for-syntax-highlight)
4891 /// where T : Trait<U, V> + 'b, 'a : 'b
4893 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4894 maybe_whole!(self, NtWhereClause, |x| x);
4896 let mut where_clause = WhereClause {
4897 id: ast::DUMMY_NODE_ID,
4898 predicates: Vec::new(),
4899 span: syntax_pos::DUMMY_SP,
4902 if !self.eat_keyword(keywords::Where) {
4903 return Ok(where_clause);
4905 let lo = self.prev_span;
4907 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4908 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4909 // change we parse those generics now, but report an error.
4910 if self.choose_generics_over_qpath() {
4911 let generics = self.parse_generics()?;
4912 self.span_err(generics.span,
4913 "generic parameters on `where` clauses are reserved for future use");
4918 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4919 let lifetime = self.expect_lifetime();
4920 // Bounds starting with a colon are mandatory, but possibly empty.
4921 self.expect(&token::Colon)?;
4922 let bounds = self.parse_lt_param_bounds();
4923 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4924 ast::WhereRegionPredicate {
4925 span: lo.to(self.prev_span),
4930 } else if self.check_type() {
4931 // Parse optional `for<'a, 'b>`.
4932 // This `for` is parsed greedily and applies to the whole predicate,
4933 // the bounded type can have its own `for` applying only to it.
4934 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4935 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4936 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4937 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4939 // Parse type with mandatory colon and (possibly empty) bounds,
4940 // or with mandatory equality sign and the second type.
4941 let ty = self.parse_ty()?;
4942 if self.eat(&token::Colon) {
4943 let bounds = self.parse_ty_param_bounds()?;
4944 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4945 ast::WhereBoundPredicate {
4946 span: lo.to(self.prev_span),
4947 bound_generic_params: lifetime_defs,
4952 // FIXME: Decide what should be used here, `=` or `==`.
4953 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
4954 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4955 let rhs_ty = self.parse_ty()?;
4956 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4957 ast::WhereEqPredicate {
4958 span: lo.to(self.prev_span),
4961 id: ast::DUMMY_NODE_ID,
4965 return self.unexpected();
4971 if !self.eat(&token::Comma) {
4976 where_clause.span = lo.to(self.prev_span);
4980 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4981 -> PResult<'a, (Vec<Arg> , bool)> {
4983 let mut variadic = false;
4984 let args: Vec<Option<Arg>> =
4985 self.parse_unspanned_seq(
4986 &token::OpenDelim(token::Paren),
4987 &token::CloseDelim(token::Paren),
4988 SeqSep::trailing_allowed(token::Comma),
4990 if p.token == token::DotDotDot {
4994 if p.token != token::CloseDelim(token::Paren) {
4997 "`...` must be last in argument list for variadic function");
5001 let span = p.prev_span;
5002 if p.token == token::CloseDelim(token::Paren) {
5003 // continue parsing to present any further errors
5006 "only foreign functions are allowed to be variadic"
5008 Ok(Some(dummy_arg(span)))
5010 // this function definition looks beyond recovery, stop parsing
5012 "only foreign functions are allowed to be variadic");
5017 match p.parse_arg_general(named_args) {
5018 Ok(arg) => Ok(Some(arg)),
5021 let lo = p.prev_span;
5022 // Skip every token until next possible arg or end.
5023 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5024 // Create a placeholder argument for proper arg count (#34264).
5025 let span = lo.to(p.prev_span);
5026 Ok(Some(dummy_arg(span)))
5033 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5035 if variadic && args.is_empty() {
5037 "variadic function must be declared with at least one named argument");
5040 Ok((args, variadic))
5043 /// Parse the argument list and result type of a function declaration
5044 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5046 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5047 let ret_ty = self.parse_ret_ty(true)?;
5056 /// Returns the parsed optional self argument and whether a self shortcut was used.
5057 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5058 let expect_ident = |this: &mut Self| match this.token {
5059 // Preserve hygienic context.
5060 token::Ident(ident, _) =>
5061 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5064 let isolated_self = |this: &mut Self, n| {
5065 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5066 this.look_ahead(n + 1, |t| t != &token::ModSep)
5069 // Parse optional self parameter of a method.
5070 // Only a limited set of initial token sequences is considered self parameters, anything
5071 // else is parsed as a normal function parameter list, so some lookahead is required.
5072 let eself_lo = self.span;
5073 let (eself, eself_ident) = match self.token {
5074 token::BinOp(token::And) => {
5080 if isolated_self(self, 1) {
5082 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
5083 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5084 isolated_self(self, 2) {
5087 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
5088 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5089 isolated_self(self, 2) {
5091 let lt = self.expect_lifetime();
5092 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
5093 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5094 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5095 isolated_self(self, 3) {
5097 let lt = self.expect_lifetime();
5099 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
5104 token::BinOp(token::Star) => {
5109 // Emit special error for `self` cases.
5110 if isolated_self(self, 1) {
5112 self.span_err(self.span, "cannot pass `self` by raw pointer");
5113 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
5114 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5115 isolated_self(self, 2) {
5118 self.span_err(self.span, "cannot pass `self` by raw pointer");
5119 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
5124 token::Ident(..) => {
5125 if isolated_self(self, 0) {
5128 let eself_ident = expect_ident(self);
5129 if self.eat(&token::Colon) {
5130 let ty = self.parse_ty()?;
5131 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
5133 (SelfKind::Value(Mutability::Immutable), eself_ident)
5135 } else if self.token.is_keyword(keywords::Mut) &&
5136 isolated_self(self, 1) {
5140 let eself_ident = expect_ident(self);
5141 if self.eat(&token::Colon) {
5142 let ty = self.parse_ty()?;
5143 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
5145 (SelfKind::Value(Mutability::Mutable), eself_ident)
5151 _ => return Ok(None),
5154 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
5155 Ok(Some(Arg::from_self(eself, eself_ident)))
5158 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5159 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5160 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5162 self.expect(&token::OpenDelim(token::Paren))?;
5164 // Parse optional self argument
5165 let self_arg = self.parse_self_arg()?;
5167 // Parse the rest of the function parameter list.
5168 let sep = SeqSep::trailing_allowed(token::Comma);
5169 let fn_inputs = if let Some(self_arg) = self_arg {
5170 if self.check(&token::CloseDelim(token::Paren)) {
5172 } else if self.eat(&token::Comma) {
5173 let mut fn_inputs = vec![self_arg];
5174 fn_inputs.append(&mut self.parse_seq_to_before_end(
5175 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5179 return self.unexpected();
5182 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5185 // Parse closing paren and return type.
5186 self.expect(&token::CloseDelim(token::Paren))?;
5189 output: self.parse_ret_ty(true)?,
5194 // parse the |arg, arg| header on a lambda
5195 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5196 let inputs_captures = {
5197 if self.eat(&token::OrOr) {
5200 self.expect(&token::BinOp(token::Or))?;
5201 let args = self.parse_seq_to_before_tokens(
5202 &[&token::BinOp(token::Or), &token::OrOr],
5203 SeqSep::trailing_allowed(token::Comma),
5204 TokenExpectType::NoExpect,
5205 |p| p.parse_fn_block_arg()
5211 let output = self.parse_ret_ty(true)?;
5214 inputs: inputs_captures,
5220 /// Parse the name and optional generic types of a function header.
5221 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5222 let id = self.parse_ident()?;
5223 let generics = self.parse_generics()?;
5227 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5228 attrs: Vec<Attribute>) -> P<Item> {
5232 id: ast::DUMMY_NODE_ID,
5240 /// Parse an item-position function declaration.
5241 fn parse_item_fn(&mut self,
5243 constness: Spanned<Constness>,
5245 -> PResult<'a, ItemInfo> {
5246 let (ident, mut generics) = self.parse_fn_header()?;
5247 let decl = self.parse_fn_decl(false)?;
5248 generics.where_clause = self.parse_where_clause()?;
5249 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5250 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
5253 /// true if we are looking at `const ID`, false for things like `const fn` etc
5254 pub fn is_const_item(&mut self) -> bool {
5255 self.token.is_keyword(keywords::Const) &&
5256 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5257 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5260 /// parses all the "front matter" for a `fn` declaration, up to
5261 /// and including the `fn` keyword:
5265 /// - `const unsafe fn`
5268 pub fn parse_fn_front_matter(&mut self) -> PResult<'a, (Spanned<Constness>, Unsafety, Abi)> {
5269 let is_const_fn = self.eat_keyword(keywords::Const);
5270 let const_span = self.prev_span;
5271 let unsafety = self.parse_unsafety();
5272 let (constness, unsafety, abi) = if is_const_fn {
5273 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5275 let abi = if self.eat_keyword(keywords::Extern) {
5276 self.parse_opt_abi()?.unwrap_or(Abi::C)
5280 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5282 self.expect_keyword(keywords::Fn)?;
5283 Ok((constness, unsafety, abi))
5286 /// Parse an impl item.
5287 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5288 maybe_whole!(self, NtImplItem, |x| x);
5289 let attrs = self.parse_outer_attributes()?;
5290 let (mut item, tokens) = self.collect_tokens(|this| {
5291 this.parse_impl_item_(at_end, attrs)
5294 // See `parse_item` for why this clause is here.
5295 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5296 item.tokens = Some(tokens);
5301 fn parse_impl_item_(&mut self,
5303 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5305 let vis = self.parse_visibility(false)?;
5306 let defaultness = self.parse_defaultness();
5307 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
5308 // This parses the grammar:
5309 // ImplItemAssocTy = Ident ["<"...">"] ["where" ...] "=" Ty ";"
5310 let name = self.parse_ident()?;
5311 let mut generics = self.parse_generics()?;
5312 generics.where_clause = self.parse_where_clause()?;
5313 self.expect(&token::Eq)?;
5314 let typ = self.parse_ty()?;
5315 self.expect(&token::Semi)?;
5316 (name, ast::ImplItemKind::Type(typ), generics)
5317 } else if self.is_const_item() {
5318 // This parses the grammar:
5319 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5320 self.expect_keyword(keywords::Const)?;
5321 let name = self.parse_ident()?;
5322 self.expect(&token::Colon)?;
5323 let typ = self.parse_ty()?;
5324 self.expect(&token::Eq)?;
5325 let expr = self.parse_expr()?;
5326 self.expect(&token::Semi)?;
5327 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5329 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5330 attrs.extend(inner_attrs);
5331 (name, node, generics)
5335 id: ast::DUMMY_NODE_ID,
5336 span: lo.to(self.prev_span),
5347 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5348 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5353 fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5355 VisibilityKind::Inherited => Ok(()),
5357 let is_macro_rules: bool = match self.token {
5358 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5362 let mut err = self.diagnostic()
5363 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5364 err.span_suggestion(sp,
5365 "try exporting the macro",
5366 "#[macro_export]".to_owned());
5369 let mut err = self.diagnostic()
5370 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5371 err.help("try adjusting the macro to put `pub` inside the invocation");
5378 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5379 -> DiagnosticBuilder<'a>
5381 let expected_kinds = if item_type == "extern" {
5382 "missing `fn`, `type`, or `static`"
5384 "missing `fn`, `type`, or `const`"
5387 // Given this code `path(`, it seems like this is not
5388 // setting the visibility of a macro invocation, but rather
5389 // a mistyped method declaration.
5390 // Create a diagnostic pointing out that `fn` is missing.
5392 // x | pub path(&self) {
5393 // | ^ missing `fn`, `type`, or `const`
5395 // ^^ `sp` below will point to this
5396 let sp = prev_span.between(self.prev_span);
5397 let mut err = self.diagnostic().struct_span_err(
5399 &format!("{} for {}-item declaration",
5400 expected_kinds, item_type));
5401 err.span_label(sp, expected_kinds);
5405 /// Parse a method or a macro invocation in a trait impl.
5406 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5407 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5408 ast::ImplItemKind)> {
5409 // code copied from parse_macro_use_or_failure... abstraction!
5410 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5412 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5413 ast::ImplItemKind::Macro(mac)))
5415 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
5416 let ident = self.parse_ident()?;
5417 let mut generics = self.parse_generics()?;
5418 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5419 generics.where_clause = self.parse_where_clause()?;
5421 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5422 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(ast::MethodSig {
5431 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5432 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5433 let ident = self.parse_ident()?;
5434 let mut tps = self.parse_generics()?;
5436 // Parse optional colon and supertrait bounds.
5437 let bounds = if self.eat(&token::Colon) {
5438 self.parse_ty_param_bounds()?
5443 if self.eat(&token::Eq) {
5444 // it's a trait alias
5445 let bounds = self.parse_ty_param_bounds()?;
5446 tps.where_clause = self.parse_where_clause()?;
5447 self.expect(&token::Semi)?;
5448 if unsafety != Unsafety::Normal {
5449 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5451 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5453 // it's a normal trait
5454 tps.where_clause = self.parse_where_clause()?;
5455 self.expect(&token::OpenDelim(token::Brace))?;
5456 let mut trait_items = vec![];
5457 while !self.eat(&token::CloseDelim(token::Brace)) {
5458 let mut at_end = false;
5459 match self.parse_trait_item(&mut at_end) {
5460 Ok(item) => trait_items.push(item),
5464 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5469 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5473 fn choose_generics_over_qpath(&self) -> bool {
5474 // There's an ambiguity between generic parameters and qualified paths in impls.
5475 // If we see `<` it may start both, so we have to inspect some following tokens.
5476 // The following combinations can only start generics,
5477 // but not qualified paths (with one exception):
5478 // `<` `>` - empty generic parameters
5479 // `<` `#` - generic parameters with attributes
5480 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5481 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5482 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5483 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5484 // The only truly ambiguous case is
5485 // `<` IDENT `>` `::` IDENT ...
5486 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5487 // because this is what almost always expected in practice, qualified paths in impls
5488 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5489 self.token == token::Lt &&
5490 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5491 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5492 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5493 t == &token::Colon || t == &token::Eq))
5496 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5497 self.expect(&token::OpenDelim(token::Brace))?;
5498 let attrs = self.parse_inner_attributes()?;
5500 let mut impl_items = Vec::new();
5501 while !self.eat(&token::CloseDelim(token::Brace)) {
5502 let mut at_end = false;
5503 match self.parse_impl_item(&mut at_end) {
5504 Ok(impl_item) => impl_items.push(impl_item),
5508 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5513 Ok((impl_items, attrs))
5516 /// Parses an implementation item, `impl` keyword is already parsed.
5517 /// impl<'a, T> TYPE { /* impl items */ }
5518 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5519 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5520 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5521 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5522 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5523 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5524 -> PResult<'a, ItemInfo> {
5525 // First, parse generic parameters if necessary.
5526 let mut generics = if self.choose_generics_over_qpath() {
5527 self.parse_generics()?
5529 ast::Generics::default()
5532 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5533 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5535 ast::ImplPolarity::Negative
5537 ast::ImplPolarity::Positive
5540 // Parse both types and traits as a type, then reinterpret if necessary.
5541 let ty_first = self.parse_ty()?;
5543 // If `for` is missing we try to recover.
5544 let has_for = self.eat_keyword(keywords::For);
5545 let missing_for_span = self.prev_span.between(self.span);
5547 let ty_second = if self.token == token::DotDot {
5548 // We need to report this error after `cfg` expansion for compatibility reasons
5549 self.bump(); // `..`, do not add it to expected tokens
5550 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5551 } else if has_for || self.token.can_begin_type() {
5552 Some(self.parse_ty()?)
5557 generics.where_clause = self.parse_where_clause()?;
5559 let (impl_items, attrs) = self.parse_impl_body()?;
5561 let item_kind = match ty_second {
5562 Some(ty_second) => {
5563 // impl Trait for Type
5565 self.span_err(missing_for_span, "missing `for` in a trait impl");
5568 let ty_first = ty_first.into_inner();
5569 let path = match ty_first.node {
5570 // This notably includes paths passed through `ty` macro fragments (#46438).
5571 TyKind::Path(None, path) => path,
5573 self.span_err(ty_first.span, "expected a trait, found type");
5574 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
5577 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5579 ItemKind::Impl(unsafety, polarity, defaultness,
5580 generics, Some(trait_ref), ty_second, impl_items)
5584 ItemKind::Impl(unsafety, polarity, defaultness,
5585 generics, None, ty_first, impl_items)
5589 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5592 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5593 if self.eat_keyword(keywords::For) {
5595 let params = self.parse_generic_params()?;
5597 // We rely on AST validation to rule out invalid cases: There must not be type
5598 // parameters, and the lifetime parameters must not have bounds.
5605 /// Parse struct Foo { ... }
5606 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5607 let class_name = self.parse_ident()?;
5609 let mut generics = self.parse_generics()?;
5611 // There is a special case worth noting here, as reported in issue #17904.
5612 // If we are parsing a tuple struct it is the case that the where clause
5613 // should follow the field list. Like so:
5615 // struct Foo<T>(T) where T: Copy;
5617 // If we are parsing a normal record-style struct it is the case
5618 // that the where clause comes before the body, and after the generics.
5619 // So if we look ahead and see a brace or a where-clause we begin
5620 // parsing a record style struct.
5622 // Otherwise if we look ahead and see a paren we parse a tuple-style
5625 let vdata = if self.token.is_keyword(keywords::Where) {
5626 generics.where_clause = self.parse_where_clause()?;
5627 if self.eat(&token::Semi) {
5628 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5629 VariantData::Unit(ast::DUMMY_NODE_ID)
5631 // If we see: `struct Foo<T> where T: Copy { ... }`
5632 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5634 // No `where` so: `struct Foo<T>;`
5635 } else if self.eat(&token::Semi) {
5636 VariantData::Unit(ast::DUMMY_NODE_ID)
5637 // Record-style struct definition
5638 } else if self.token == token::OpenDelim(token::Brace) {
5639 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5640 // Tuple-style struct definition with optional where-clause.
5641 } else if self.token == token::OpenDelim(token::Paren) {
5642 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5643 generics.where_clause = self.parse_where_clause()?;
5644 self.expect(&token::Semi)?;
5647 let token_str = self.this_token_to_string();
5648 let mut err = self.fatal(&format!(
5649 "expected `where`, `{{`, `(`, or `;` after struct name, found `{}`",
5652 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
5656 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5659 /// Parse union Foo { ... }
5660 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5661 let class_name = self.parse_ident()?;
5663 let mut generics = self.parse_generics()?;
5665 let vdata = if self.token.is_keyword(keywords::Where) {
5666 generics.where_clause = self.parse_where_clause()?;
5667 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5668 } else if self.token == token::OpenDelim(token::Brace) {
5669 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5671 let token_str = self.this_token_to_string();
5672 let mut err = self.fatal(&format!(
5673 "expected `where` or `{{` after union name, found `{}`", token_str));
5674 err.span_label(self.span, "expected `where` or `{` after union name");
5678 Ok((class_name, ItemKind::Union(vdata, generics), None))
5681 fn consume_block(&mut self, delim: token::DelimToken) {
5682 let mut brace_depth = 0;
5683 if !self.eat(&token::OpenDelim(delim)) {
5687 if self.eat(&token::OpenDelim(delim)) {
5689 } else if self.eat(&token::CloseDelim(delim)) {
5690 if brace_depth == 0 {
5696 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5704 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5705 let mut fields = Vec::new();
5706 if self.eat(&token::OpenDelim(token::Brace)) {
5707 while self.token != token::CloseDelim(token::Brace) {
5708 let field = self.parse_struct_decl_field().map_err(|e| {
5709 self.recover_stmt();
5713 Ok(field) => fields.push(field),
5719 self.eat(&token::CloseDelim(token::Brace));
5721 let token_str = self.this_token_to_string();
5722 let mut err = self.fatal(&format!(
5723 "expected `where`, or `{{` after struct name, found `{}`", token_str));
5724 err.span_label(self.span, "expected `where`, or `{` after struct name");
5731 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5732 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5733 // Unit like structs are handled in parse_item_struct function
5734 let fields = self.parse_unspanned_seq(
5735 &token::OpenDelim(token::Paren),
5736 &token::CloseDelim(token::Paren),
5737 SeqSep::trailing_allowed(token::Comma),
5739 let attrs = p.parse_outer_attributes()?;
5741 let vis = p.parse_visibility(true)?;
5742 let ty = p.parse_ty()?;
5744 span: lo.to(p.span),
5747 id: ast::DUMMY_NODE_ID,
5756 /// Parse a structure field declaration
5757 pub fn parse_single_struct_field(&mut self,
5760 attrs: Vec<Attribute> )
5761 -> PResult<'a, StructField> {
5762 let mut seen_comma: bool = false;
5763 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5764 if self.token == token::Comma {
5771 token::CloseDelim(token::Brace) => {}
5772 token::DocComment(_) => {
5773 let previous_span = self.prev_span;
5774 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
5775 self.bump(); // consume the doc comment
5776 let comma_after_doc_seen = self.eat(&token::Comma);
5777 // `seen_comma` is always false, because we are inside doc block
5778 // condition is here to make code more readable
5779 if seen_comma == false && comma_after_doc_seen == true {
5782 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
5785 if seen_comma == false {
5786 let sp = self.sess.codemap().next_point(previous_span);
5787 err.span_suggestion(sp, "missing comma here", ",".into());
5792 _ => return Err(self.span_fatal_help(self.span,
5793 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5794 "struct fields should be separated by commas")),
5799 /// Parse an element of a struct definition
5800 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5801 let attrs = self.parse_outer_attributes()?;
5803 let vis = self.parse_visibility(false)?;
5804 self.parse_single_struct_field(lo, vis, attrs)
5807 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5808 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5809 /// a function definition, it's not a tuple struct field) and the contents within the parens
5810 /// isn't valid, emit a proper diagnostic.
5811 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5812 maybe_whole!(self, NtVis, |x| x);
5814 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
5815 if self.is_crate_vis() {
5816 self.bump(); // `crate`
5817 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
5820 if !self.eat_keyword(keywords::Pub) {
5821 return Ok(respan(self.prev_span, VisibilityKind::Inherited))
5823 let lo = self.prev_span;
5825 if self.check(&token::OpenDelim(token::Paren)) {
5826 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5827 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5828 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5829 // by the following tokens.
5830 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5833 self.bump(); // `crate`
5834 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5836 lo.to(self.prev_span),
5837 VisibilityKind::Crate(CrateSugar::PubCrate),
5840 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5843 self.bump(); // `in`
5844 let path = self.parse_path(PathStyle::Mod)?; // `path`
5845 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5846 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
5848 id: ast::DUMMY_NODE_ID,
5851 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5852 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5853 t.is_keyword(keywords::SelfValue))
5855 // `pub(self)` or `pub(super)`
5857 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
5858 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5859 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
5861 id: ast::DUMMY_NODE_ID,
5864 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5865 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5867 let msg = "incorrect visibility restriction";
5868 let suggestion = r##"some possible visibility restrictions are:
5869 `pub(crate)`: visible only on the current crate
5870 `pub(super)`: visible only in the current module's parent
5871 `pub(in path::to::module)`: visible only on the specified path"##;
5872 let path = self.parse_path(PathStyle::Mod)?;
5873 let path_span = self.prev_span;
5874 let help_msg = format!("make this visible only to module `{}` with `in`", path);
5875 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5876 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5877 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5878 err.emit(); // emit diagnostic, but continue with public visibility
5882 Ok(respan(lo, VisibilityKind::Public))
5885 /// Parse defaultness: `default` or nothing.
5886 fn parse_defaultness(&mut self) -> Defaultness {
5887 // `pub` is included for better error messages
5888 if self.check_keyword(keywords::Default) &&
5889 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
5890 t.is_keyword(keywords::Const) ||
5891 t.is_keyword(keywords::Fn) ||
5892 t.is_keyword(keywords::Unsafe) ||
5893 t.is_keyword(keywords::Extern) ||
5894 t.is_keyword(keywords::Type) ||
5895 t.is_keyword(keywords::Pub)) {
5896 self.bump(); // `default`
5897 Defaultness::Default
5903 /// Given a termination token, parse all of the items in a module
5904 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5905 let mut items = vec![];
5906 while let Some(item) = self.parse_item()? {
5910 if !self.eat(term) {
5911 let token_str = self.this_token_to_string();
5912 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
5913 if token_str == ";" {
5914 let msg = "consider removing this semicolon";
5915 err.span_suggestion_short(self.span, msg, "".to_string());
5917 err.span_label(self.span, "expected item");
5922 let hi = if self.span == syntax_pos::DUMMY_SP {
5929 inner: inner_lo.to(hi),
5934 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5935 let id = self.parse_ident()?;
5936 self.expect(&token::Colon)?;
5937 let ty = self.parse_ty()?;
5938 self.expect(&token::Eq)?;
5939 let e = self.parse_expr()?;
5940 self.expect(&token::Semi)?;
5941 let item = match m {
5942 Some(m) => ItemKind::Static(ty, m, e),
5943 None => ItemKind::Const(ty, e),
5945 Ok((id, item, None))
5948 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5949 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5950 let (in_cfg, outer_attrs) = {
5951 let mut strip_unconfigured = ::config::StripUnconfigured {
5953 should_test: false, // irrelevant
5954 features: None, // don't perform gated feature checking
5956 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5957 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5960 let id_span = self.span;
5961 let id = self.parse_ident()?;
5962 if self.check(&token::Semi) {
5964 if in_cfg && self.recurse_into_file_modules {
5965 // This mod is in an external file. Let's go get it!
5966 let ModulePathSuccess { path, directory_ownership, warn } =
5967 self.submod_path(id, &outer_attrs, id_span)?;
5968 let (module, mut attrs) =
5969 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5971 let attr = Attribute {
5972 id: attr::mk_attr_id(),
5973 style: ast::AttrStyle::Outer,
5974 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
5975 tokens: TokenStream::empty(),
5976 is_sugared_doc: false,
5977 span: syntax_pos::DUMMY_SP,
5979 attr::mark_known(&attr);
5982 Ok((id, module, Some(attrs)))
5984 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5985 Ok((id, ItemKind::Mod(placeholder), None))
5988 let old_directory = self.directory.clone();
5989 self.push_directory(id, &outer_attrs);
5991 self.expect(&token::OpenDelim(token::Brace))?;
5992 let mod_inner_lo = self.span;
5993 let attrs = self.parse_inner_attributes()?;
5994 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5996 self.directory = old_directory;
5997 Ok((id, ItemKind::Mod(module), Some(attrs)))
6001 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6002 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6003 self.directory.path.push(&path.as_str());
6004 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6006 self.directory.path.push(&id.name.as_str());
6010 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6011 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
6014 /// Returns either a path to a module, or .
6015 pub fn default_submod_path(
6017 relative: Option<ast::Ident>,
6019 codemap: &CodeMap) -> ModulePath
6021 // If we're in a foo.rs file instead of a mod.rs file,
6022 // we need to look for submodules in
6023 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6024 // `./<id>.rs` and `./<id>/mod.rs`.
6025 let relative_prefix_string;
6026 let relative_prefix = if let Some(ident) = relative {
6027 relative_prefix_string = format!("{}{}", ident.name.as_str(), path::MAIN_SEPARATOR);
6028 &relative_prefix_string
6033 let mod_name = id.to_string();
6034 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6035 let secondary_path_str = format!("{}{}{}mod.rs",
6036 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6037 let default_path = dir_path.join(&default_path_str);
6038 let secondary_path = dir_path.join(&secondary_path_str);
6039 let default_exists = codemap.file_exists(&default_path);
6040 let secondary_exists = codemap.file_exists(&secondary_path);
6042 let result = match (default_exists, secondary_exists) {
6043 (true, false) => Ok(ModulePathSuccess {
6045 directory_ownership: DirectoryOwnership::Owned {
6050 (false, true) => Ok(ModulePathSuccess {
6051 path: secondary_path,
6052 directory_ownership: DirectoryOwnership::Owned {
6057 (false, false) => Err(Error::FileNotFoundForModule {
6058 mod_name: mod_name.clone(),
6059 default_path: default_path_str,
6060 secondary_path: secondary_path_str,
6061 dir_path: format!("{}", dir_path.display()),
6063 (true, true) => Err(Error::DuplicatePaths {
6064 mod_name: mod_name.clone(),
6065 default_path: default_path_str,
6066 secondary_path: secondary_path_str,
6072 path_exists: default_exists || secondary_exists,
6077 fn submod_path(&mut self,
6079 outer_attrs: &[Attribute],
6081 -> PResult<'a, ModulePathSuccess> {
6082 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6083 return Ok(ModulePathSuccess {
6084 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6085 // All `#[path]` files are treated as though they are a `mod.rs` file.
6086 // This means that `mod foo;` declarations inside `#[path]`-included
6087 // files are siblings,
6089 // Note that this will produce weirdness when a file named `foo.rs` is
6090 // `#[path]` included and contains a `mod foo;` declaration.
6091 // If you encounter this, it's your own darn fault :P
6092 Some(_) => DirectoryOwnership::Owned { relative: None },
6093 _ => DirectoryOwnership::UnownedViaMod(true),
6100 let relative = match self.directory.ownership {
6101 DirectoryOwnership::Owned { relative } => {
6102 // Push the usage onto the list of non-mod.rs mod uses.
6103 // This is used later for feature-gate error reporting.
6104 if let Some(cur_file_ident) = relative {
6106 .non_modrs_mods.borrow_mut()
6107 .push((cur_file_ident, id_sp));
6111 DirectoryOwnership::UnownedViaBlock |
6112 DirectoryOwnership::UnownedViaMod(_) => None,
6114 let paths = Parser::default_submod_path(
6115 id, relative, &self.directory.path, self.sess.codemap());
6117 match self.directory.ownership {
6118 DirectoryOwnership::Owned { .. } => {
6119 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6121 DirectoryOwnership::UnownedViaBlock => {
6123 "Cannot declare a non-inline module inside a block \
6124 unless it has a path attribute";
6125 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6126 if paths.path_exists {
6127 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6129 err.span_note(id_sp, &msg);
6133 DirectoryOwnership::UnownedViaMod(warn) => {
6135 if let Ok(result) = paths.result {
6136 return Ok(ModulePathSuccess { warn: true, ..result });
6139 let mut err = self.diagnostic().struct_span_err(id_sp,
6140 "cannot declare a new module at this location");
6141 if id_sp != syntax_pos::DUMMY_SP {
6142 let src_path = self.sess.codemap().span_to_filename(id_sp);
6143 if let FileName::Real(src_path) = src_path {
6144 if let Some(stem) = src_path.file_stem() {
6145 let mut dest_path = src_path.clone();
6146 dest_path.set_file_name(stem);
6147 dest_path.push("mod.rs");
6148 err.span_note(id_sp,
6149 &format!("maybe move this module `{}` to its own \
6150 directory via `{}`", src_path.display(),
6151 dest_path.display()));
6155 if paths.path_exists {
6156 err.span_note(id_sp,
6157 &format!("... or maybe `use` the module `{}` instead \
6158 of possibly redeclaring it",
6166 /// Read a module from a source file.
6167 fn eval_src_mod(&mut self,
6169 directory_ownership: DirectoryOwnership,
6172 -> PResult<'a, (ast::ItemKind, Vec<Attribute> )> {
6173 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6174 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6175 let mut err = String::from("circular modules: ");
6176 let len = included_mod_stack.len();
6177 for p in &included_mod_stack[i.. len] {
6178 err.push_str(&p.to_string_lossy());
6179 err.push_str(" -> ");
6181 err.push_str(&path.to_string_lossy());
6182 return Err(self.span_fatal(id_sp, &err[..]));
6184 included_mod_stack.push(path.clone());
6185 drop(included_mod_stack);
6188 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6189 p0.cfg_mods = self.cfg_mods;
6190 let mod_inner_lo = p0.span;
6191 let mod_attrs = p0.parse_inner_attributes()?;
6192 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6193 self.sess.included_mod_stack.borrow_mut().pop();
6194 Ok((ast::ItemKind::Mod(m0), mod_attrs))
6197 /// Parse a function declaration from a foreign module
6198 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6199 -> PResult<'a, ForeignItem> {
6200 self.expect_keyword(keywords::Fn)?;
6202 let (ident, mut generics) = self.parse_fn_header()?;
6203 let decl = self.parse_fn_decl(true)?;
6204 generics.where_clause = self.parse_where_clause()?;
6206 self.expect(&token::Semi)?;
6207 Ok(ast::ForeignItem {
6210 node: ForeignItemKind::Fn(decl, generics),
6211 id: ast::DUMMY_NODE_ID,
6217 /// Parse a static item from a foreign module.
6218 /// Assumes that the `static` keyword is already parsed.
6219 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6220 -> PResult<'a, ForeignItem> {
6221 let mutbl = self.eat_keyword(keywords::Mut);
6222 let ident = self.parse_ident()?;
6223 self.expect(&token::Colon)?;
6224 let ty = self.parse_ty()?;
6226 self.expect(&token::Semi)?;
6230 node: ForeignItemKind::Static(ty, mutbl),
6231 id: ast::DUMMY_NODE_ID,
6237 /// Parse a type from a foreign module
6238 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6239 -> PResult<'a, ForeignItem> {
6240 self.expect_keyword(keywords::Type)?;
6242 let ident = self.parse_ident()?;
6244 self.expect(&token::Semi)?;
6245 Ok(ast::ForeignItem {
6248 node: ForeignItemKind::Ty,
6249 id: ast::DUMMY_NODE_ID,
6255 /// Parse extern crate links
6259 /// extern crate foo;
6260 /// extern crate bar as foo;
6261 fn parse_item_extern_crate(&mut self,
6263 visibility: Visibility,
6264 attrs: Vec<Attribute>)
6265 -> PResult<'a, P<Item>> {
6266 let orig_name = self.parse_ident()?;
6267 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6268 (rename, Some(orig_name.name))
6272 self.expect(&token::Semi)?;
6274 let span = lo.to(self.prev_span);
6275 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6278 /// Parse `extern` for foreign ABIs
6281 /// `extern` is expected to have been
6282 /// consumed before calling this method
6288 fn parse_item_foreign_mod(&mut self,
6290 opt_abi: Option<Abi>,
6291 visibility: Visibility,
6292 mut attrs: Vec<Attribute>)
6293 -> PResult<'a, P<Item>> {
6294 self.expect(&token::OpenDelim(token::Brace))?;
6296 let abi = opt_abi.unwrap_or(Abi::C);
6298 attrs.extend(self.parse_inner_attributes()?);
6300 let mut foreign_items = vec![];
6301 while let Some(item) = self.parse_foreign_item()? {
6302 foreign_items.push(item);
6304 self.expect(&token::CloseDelim(token::Brace))?;
6306 let prev_span = self.prev_span;
6307 let m = ast::ForeignMod {
6309 items: foreign_items
6311 let invalid = keywords::Invalid.ident();
6312 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6315 /// Parse type Foo = Bar;
6316 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
6317 let ident = self.parse_ident()?;
6318 let mut tps = self.parse_generics()?;
6319 tps.where_clause = self.parse_where_clause()?;
6320 self.expect(&token::Eq)?;
6321 let ty = self.parse_ty()?;
6322 self.expect(&token::Semi)?;
6323 Ok((ident, ItemKind::Ty(ty, tps), None))
6326 /// Parse the part of an "enum" decl following the '{'
6327 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6328 let mut variants = Vec::new();
6329 let mut all_nullary = true;
6330 let mut any_disr = None;
6331 while self.token != token::CloseDelim(token::Brace) {
6332 let variant_attrs = self.parse_outer_attributes()?;
6333 let vlo = self.span;
6336 let mut disr_expr = None;
6337 let ident = self.parse_ident()?;
6338 if self.check(&token::OpenDelim(token::Brace)) {
6339 // Parse a struct variant.
6340 all_nullary = false;
6341 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6342 ast::DUMMY_NODE_ID);
6343 } else if self.check(&token::OpenDelim(token::Paren)) {
6344 all_nullary = false;
6345 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6346 ast::DUMMY_NODE_ID);
6347 } else if self.eat(&token::Eq) {
6348 disr_expr = Some(self.parse_expr()?);
6349 any_disr = disr_expr.as_ref().map(|expr| expr.span);
6350 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6352 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6355 let vr = ast::Variant_ {
6357 attrs: variant_attrs,
6361 variants.push(respan(vlo.to(self.prev_span), vr));
6363 if !self.eat(&token::Comma) { break; }
6365 self.expect(&token::CloseDelim(token::Brace))?;
6367 Some(disr_span) if !all_nullary =>
6368 self.span_err(disr_span,
6369 "discriminator values can only be used with a field-less enum"),
6373 Ok(ast::EnumDef { variants: variants })
6376 /// Parse an "enum" declaration
6377 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6378 let id = self.parse_ident()?;
6379 let mut generics = self.parse_generics()?;
6380 generics.where_clause = self.parse_where_clause()?;
6381 self.expect(&token::OpenDelim(token::Brace))?;
6383 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6384 self.recover_stmt();
6385 self.eat(&token::CloseDelim(token::Brace));
6388 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6391 /// Parses a string as an ABI spec on an extern type or module. Consumes
6392 /// the `extern` keyword, if one is found.
6393 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6395 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6397 self.expect_no_suffix(sp, "ABI spec", suf);
6399 match abi::lookup(&s.as_str()) {
6400 Some(abi) => Ok(Some(abi)),
6402 let prev_span = self.prev_span;
6405 &format!("invalid ABI: expected one of [{}], \
6407 abi::all_names().join(", "),
6418 fn is_static_global(&mut self) -> bool {
6419 if self.check_keyword(keywords::Static) {
6420 // Check if this could be a closure
6421 !self.look_ahead(1, |token| {
6422 if token.is_keyword(keywords::Move) {
6426 token::BinOp(token::Or) | token::OrOr => true,
6435 /// Parse one of the items allowed by the flags.
6436 /// NB: this function no longer parses the items inside an
6438 fn parse_item_(&mut self, attrs: Vec<Attribute>,
6439 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
6440 maybe_whole!(self, NtItem, |item| {
6441 let mut item = item.into_inner();
6442 let mut attrs = attrs;
6443 mem::swap(&mut item.attrs, &mut attrs);
6444 item.attrs.extend(attrs);
6450 let visibility = self.parse_visibility(false)?;
6452 if self.eat_keyword(keywords::Use) {
6454 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
6455 self.expect(&token::Semi)?;
6457 let span = lo.to(self.prev_span);
6458 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
6459 return Ok(Some(item));
6462 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6463 self.bump(); // `extern`
6464 if self.eat_keyword(keywords::Crate) {
6465 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6468 let opt_abi = self.parse_opt_abi()?;
6470 if self.eat_keyword(keywords::Fn) {
6471 // EXTERN FUNCTION ITEM
6472 let fn_span = self.prev_span;
6473 let abi = opt_abi.unwrap_or(Abi::C);
6474 let (ident, item_, extra_attrs) =
6475 self.parse_item_fn(Unsafety::Normal,
6476 respan(fn_span, Constness::NotConst),
6478 let prev_span = self.prev_span;
6479 let item = self.mk_item(lo.to(prev_span),
6483 maybe_append(attrs, extra_attrs));
6484 return Ok(Some(item));
6485 } else if self.check(&token::OpenDelim(token::Brace)) {
6486 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6492 if self.is_static_global() {
6495 let m = if self.eat_keyword(keywords::Mut) {
6498 Mutability::Immutable
6500 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
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));
6509 if self.eat_keyword(keywords::Const) {
6510 let const_span = self.prev_span;
6511 if self.check_keyword(keywords::Fn)
6512 || (self.check_keyword(keywords::Unsafe)
6513 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6514 // CONST FUNCTION ITEM
6515 let unsafety = self.parse_unsafety();
6517 let (ident, item_, extra_attrs) =
6518 self.parse_item_fn(unsafety,
6519 respan(const_span, Constness::Const),
6521 let prev_span = self.prev_span;
6522 let item = self.mk_item(lo.to(prev_span),
6526 maybe_append(attrs, extra_attrs));
6527 return Ok(Some(item));
6531 if self.eat_keyword(keywords::Mut) {
6532 let prev_span = self.prev_span;
6533 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6534 .help("did you mean to declare a static?")
6537 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6538 let prev_span = self.prev_span;
6539 let item = self.mk_item(lo.to(prev_span),
6543 maybe_append(attrs, extra_attrs));
6544 return Ok(Some(item));
6546 if self.check_keyword(keywords::Unsafe) &&
6547 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
6548 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
6550 // UNSAFE TRAIT ITEM
6551 self.bump(); // `unsafe`
6552 let is_auto = if self.eat_keyword(keywords::Trait) {
6555 self.expect_keyword(keywords::Auto)?;
6556 self.expect_keyword(keywords::Trait)?;
6559 let (ident, item_, extra_attrs) =
6560 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
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::Impl) ||
6570 self.check_keyword(keywords::Unsafe) &&
6571 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6572 self.check_keyword(keywords::Default) &&
6573 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6574 self.check_keyword(keywords::Default) &&
6575 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
6577 let defaultness = self.parse_defaultness();
6578 let unsafety = self.parse_unsafety();
6579 self.expect_keyword(keywords::Impl)?;
6580 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
6581 let span = lo.to(self.prev_span);
6582 return Ok(Some(self.mk_item(span, ident, item, visibility,
6583 maybe_append(attrs, extra_attrs))));
6585 if self.check_keyword(keywords::Fn) {
6588 let fn_span = self.prev_span;
6589 let (ident, item_, extra_attrs) =
6590 self.parse_item_fn(Unsafety::Normal,
6591 respan(fn_span, Constness::NotConst),
6593 let prev_span = self.prev_span;
6594 let item = self.mk_item(lo.to(prev_span),
6598 maybe_append(attrs, extra_attrs));
6599 return Ok(Some(item));
6601 if self.check_keyword(keywords::Unsafe)
6602 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
6603 // UNSAFE FUNCTION ITEM
6604 self.bump(); // `unsafe`
6605 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
6606 self.check(&token::OpenDelim(token::Brace));
6607 let abi = if self.eat_keyword(keywords::Extern) {
6608 self.parse_opt_abi()?.unwrap_or(Abi::C)
6612 self.expect_keyword(keywords::Fn)?;
6613 let fn_span = self.prev_span;
6614 let (ident, item_, extra_attrs) =
6615 self.parse_item_fn(Unsafety::Unsafe,
6616 respan(fn_span, Constness::NotConst),
6618 let prev_span = self.prev_span;
6619 let item = self.mk_item(lo.to(prev_span),
6623 maybe_append(attrs, extra_attrs));
6624 return Ok(Some(item));
6626 if self.eat_keyword(keywords::Mod) {
6628 let (ident, item_, extra_attrs) =
6629 self.parse_item_mod(&attrs[..])?;
6630 let prev_span = self.prev_span;
6631 let item = self.mk_item(lo.to(prev_span),
6635 maybe_append(attrs, extra_attrs));
6636 return Ok(Some(item));
6638 if self.eat_keyword(keywords::Type) {
6640 let (ident, item_, extra_attrs) = self.parse_item_type()?;
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::Enum) {
6651 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
6652 let prev_span = self.prev_span;
6653 let item = self.mk_item(lo.to(prev_span),
6657 maybe_append(attrs, extra_attrs));
6658 return Ok(Some(item));
6660 if self.check_keyword(keywords::Trait)
6661 || (self.check_keyword(keywords::Auto)
6662 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
6664 let is_auto = if self.eat_keyword(keywords::Trait) {
6667 self.expect_keyword(keywords::Auto)?;
6668 self.expect_keyword(keywords::Trait)?;
6672 let (ident, item_, extra_attrs) =
6673 self.parse_item_trait(is_auto, Unsafety::Normal)?;
6674 let prev_span = self.prev_span;
6675 let item = self.mk_item(lo.to(prev_span),
6679 maybe_append(attrs, extra_attrs));
6680 return Ok(Some(item));
6682 if self.eat_keyword(keywords::Struct) {
6684 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6685 let prev_span = self.prev_span;
6686 let item = self.mk_item(lo.to(prev_span),
6690 maybe_append(attrs, extra_attrs));
6691 return Ok(Some(item));
6693 if self.is_union_item() {
6696 let (ident, item_, extra_attrs) = self.parse_item_union()?;
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 let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
6706 return Ok(Some(macro_def));
6709 // Verify whether we have encountered a struct or method definition where the user forgot to
6710 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
6711 if visibility.node == VisibilityKind::Public &&
6712 self.check_ident() &&
6713 self.look_ahead(1, |t| *t != token::Not)
6715 // Space between `pub` keyword and the identifier
6718 // ^^^ `sp` points here
6719 let sp = self.prev_span.between(self.span);
6720 let full_sp = self.prev_span.to(self.span);
6721 let ident_sp = self.span;
6722 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
6723 // possible public struct definition where `struct` was forgotten
6724 let ident = self.parse_ident().unwrap();
6725 let msg = format!("add `struct` here to parse `{}` as a public struct",
6727 let mut err = self.diagnostic()
6728 .struct_span_err(sp, "missing `struct` for struct definition");
6729 err.span_suggestion_short(sp, &msg, " struct ".into());
6731 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
6732 let ident = self.parse_ident().unwrap();
6733 self.consume_block(token::Paren);
6734 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
6735 self.check(&token::OpenDelim(token::Brace))
6737 ("fn", "method", false)
6738 } else if self.check(&token::Colon) {
6742 ("fn` or `struct", "method or struct", true)
6745 let msg = format!("missing `{}` for {} definition", kw, kw_name);
6746 let mut err = self.diagnostic().struct_span_err(sp, &msg);
6748 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
6752 err.span_suggestion_short(sp, &suggestion, format!(" {} ", kw));
6754 if let Ok(snippet) = self.sess.codemap().span_to_snippet(ident_sp) {
6755 err.span_suggestion(
6757 "if you meant to call a macro, write instead",
6758 format!("{}!", snippet));
6760 err.help("if you meant to call a macro, remove the `pub` \
6761 and add a trailing `!` after the identifier");
6767 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
6770 /// Parse a foreign item.
6771 pub fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
6772 maybe_whole!(self, NtForeignItem, |ni| Some(ni));
6774 let attrs = self.parse_outer_attributes()?;
6776 let visibility = self.parse_visibility(false)?;
6778 // FOREIGN STATIC ITEM
6779 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
6780 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
6781 if self.token.is_keyword(keywords::Const) {
6783 .struct_span_err(self.span, "extern items cannot be `const`")
6784 .span_suggestion(self.span, "instead try using", "static".to_owned())
6787 self.bump(); // `static` or `const`
6788 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6790 // FOREIGN FUNCTION ITEM
6791 if self.check_keyword(keywords::Fn) {
6792 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6794 // FOREIGN TYPE ITEM
6795 if self.check_keyword(keywords::Type) {
6796 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
6799 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
6803 ident: keywords::Invalid.ident(),
6804 span: lo.to(self.prev_span),
6805 id: ast::DUMMY_NODE_ID,
6808 node: ForeignItemKind::Macro(mac),
6813 if !attrs.is_empty() {
6814 self.expected_item_err(&attrs);
6822 /// This is the fall-through for parsing items.
6823 fn parse_macro_use_or_failure(
6825 attrs: Vec<Attribute> ,
6826 macros_allowed: bool,
6827 attributes_allowed: bool,
6829 visibility: Visibility
6830 ) -> PResult<'a, Option<P<Item>>> {
6831 if macros_allowed && self.token.is_path_start() {
6832 // MACRO INVOCATION ITEM
6834 let prev_span = self.prev_span;
6835 self.complain_if_pub_macro(&visibility.node, prev_span);
6837 let mac_lo = self.span;
6840 let pth = self.parse_path(PathStyle::Mod)?;
6841 self.expect(&token::Not)?;
6843 // a 'special' identifier (like what `macro_rules!` uses)
6844 // is optional. We should eventually unify invoc syntax
6846 let id = if self.token.is_ident() {
6849 keywords::Invalid.ident() // no special identifier
6851 // eat a matched-delimiter token tree:
6852 let (delim, tts) = self.expect_delimited_token_tree()?;
6853 if delim != token::Brace {
6854 if !self.eat(&token::Semi) {
6855 self.span_err(self.prev_span,
6856 "macros that expand to items must either \
6857 be surrounded with braces or followed by \
6862 let hi = self.prev_span;
6863 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6864 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6865 return Ok(Some(item));
6868 // FAILURE TO PARSE ITEM
6869 match visibility.node {
6870 VisibilityKind::Inherited => {}
6872 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
6876 if !attributes_allowed && !attrs.is_empty() {
6877 self.expected_item_err(&attrs);
6882 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
6883 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
6884 at_end: &mut bool) -> PResult<'a, Option<Mac>>
6886 if self.token.is_path_start() && !self.is_extern_non_path() {
6887 let prev_span = self.prev_span;
6889 let pth = self.parse_path(PathStyle::Mod)?;
6891 if pth.segments.len() == 1 {
6892 if !self.eat(&token::Not) {
6893 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
6896 self.expect(&token::Not)?;
6899 if let Some(vis) = vis {
6900 self.complain_if_pub_macro(&vis.node, prev_span);
6905 // eat a matched-delimiter token tree:
6906 let (delim, tts) = self.expect_delimited_token_tree()?;
6907 if delim != token::Brace {
6908 self.expect(&token::Semi)?
6911 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts })))
6917 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
6918 where F: FnOnce(&mut Self) -> PResult<'a, R>
6920 // Record all tokens we parse when parsing this item.
6921 let mut tokens = Vec::new();
6922 match self.token_cursor.frame.last_token {
6923 LastToken::Collecting(_) => {
6924 panic!("cannot collect tokens recursively yet")
6926 LastToken::Was(ref mut last) => tokens.extend(last.take()),
6928 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
6929 let prev = self.token_cursor.stack.len();
6931 let last_token = if self.token_cursor.stack.len() == prev {
6932 &mut self.token_cursor.frame.last_token
6934 &mut self.token_cursor.stack[prev].last_token
6936 let mut tokens = match *last_token {
6937 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
6938 LastToken::Was(_) => panic!("our vector went away?"),
6941 // If we're not at EOF our current token wasn't actually consumed by
6942 // `f`, but it'll still be in our list that we pulled out. In that case
6944 if self.token == token::Eof {
6945 *last_token = LastToken::Was(None);
6947 *last_token = LastToken::Was(tokens.pop());
6950 Ok((ret?, tokens.into_iter().collect()))
6953 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6954 let attrs = self.parse_outer_attributes()?;
6956 let (ret, tokens) = self.collect_tokens(|this| {
6957 this.parse_item_(attrs, true, false)
6960 // Once we've parsed an item and recorded the tokens we got while
6961 // parsing we may want to store `tokens` into the item we're about to
6962 // return. Note, though, that we specifically didn't capture tokens
6963 // related to outer attributes. The `tokens` field here may later be
6964 // used with procedural macros to convert this item back into a token
6965 // stream, but during expansion we may be removing attributes as we go
6968 // If we've got inner attributes then the `tokens` we've got above holds
6969 // these inner attributes. If an inner attribute is expanded we won't
6970 // actually remove it from the token stream, so we'll just keep yielding
6971 // it (bad!). To work around this case for now we just avoid recording
6972 // `tokens` if we detect any inner attributes. This should help keep
6973 // expansion correct, but we should fix this bug one day!
6976 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6977 i.tokens = Some(tokens);
6985 fn is_import_coupler(&mut self) -> bool {
6986 self.check(&token::ModSep) &&
6987 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6988 *t == token::BinOp(token::Star))
6993 /// USE_TREE = [`::`] `*` |
6994 /// [`::`] `{` USE_TREE_LIST `}` |
6996 /// PATH `::` `{` USE_TREE_LIST `}` |
6997 /// PATH [`as` IDENT]
6998 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7001 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7002 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7003 self.check(&token::BinOp(token::Star)) ||
7004 self.is_import_coupler() {
7005 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7006 if self.eat(&token::ModSep) {
7007 prefix.segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
7010 if self.eat(&token::BinOp(token::Star)) {
7013 UseTreeKind::Nested(self.parse_use_tree_list()?)
7016 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7017 prefix = self.parse_path(PathStyle::Mod)?;
7019 if self.eat(&token::ModSep) {
7020 if self.eat(&token::BinOp(token::Star)) {
7023 UseTreeKind::Nested(self.parse_use_tree_list()?)
7026 UseTreeKind::Simple(self.parse_rename()?)
7030 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7033 /// Parse UseTreeKind::Nested(list)
7035 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7036 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7037 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7038 &token::CloseDelim(token::Brace),
7039 SeqSep::trailing_allowed(token::Comma), |this| {
7040 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7044 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7045 if self.eat_keyword(keywords::As) {
7047 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
7049 Ok(Some(Ident::new(ident.name.gensymed(), ident.span)))
7051 _ => self.parse_ident().map(Some),
7058 /// Parses a source module as a crate. This is the main
7059 /// entry point for the parser.
7060 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7063 attrs: self.parse_inner_attributes()?,
7064 module: self.parse_mod_items(&token::Eof, lo)?,
7065 span: lo.to(self.span),
7069 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7070 let ret = match self.token {
7071 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7072 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7079 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7080 match self.parse_optional_str() {
7081 Some((s, style, suf)) => {
7082 let sp = self.prev_span;
7083 self.expect_no_suffix(sp, "string literal", suf);
7087 let msg = "expected string literal";
7088 let mut err = self.fatal(msg);
7089 err.span_label(self.span, msg);