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) | token::NtLiteral(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(), None);
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) | token::NtLiteral(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_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_ident = 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.ident.clone()),
1968 if let Some(path) = meta_ident {
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 pub 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(None, 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 if self.token == token::OpenDelim(token::Brace) {
2322 return self.parse_block_expr(Some(label),
2324 BlockCheckMode::Default,
2327 let msg = "expected `while`, `for`, `loop` or `{` after a label";
2328 let mut err = self.fatal(msg);
2329 err.span_label(self.span, msg);
2332 if self.eat_keyword(keywords::Loop) {
2333 let lo = self.prev_span;
2334 return self.parse_loop_expr(None, lo, attrs);
2336 if self.eat_keyword(keywords::Continue) {
2337 let label = self.eat_label();
2338 let ex = ExprKind::Continue(label);
2339 let hi = self.prev_span;
2340 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2342 if self.eat_keyword(keywords::Match) {
2343 return self.parse_match_expr(attrs);
2345 if self.eat_keyword(keywords::Unsafe) {
2346 return self.parse_block_expr(
2349 BlockCheckMode::Unsafe(ast::UserProvided),
2352 if self.is_catch_expr() {
2354 assert!(self.eat_keyword(keywords::Do));
2355 assert!(self.eat_keyword(keywords::Catch));
2356 return self.parse_catch_expr(lo, attrs);
2358 if self.eat_keyword(keywords::Return) {
2359 if self.token.can_begin_expr() {
2360 let e = self.parse_expr()?;
2362 ex = ExprKind::Ret(Some(e));
2364 ex = ExprKind::Ret(None);
2366 } else if self.eat_keyword(keywords::Break) {
2367 let label = self.eat_label();
2368 let e = if self.token.can_begin_expr()
2369 && !(self.token == token::OpenDelim(token::Brace)
2370 && self.restrictions.contains(
2371 Restrictions::NO_STRUCT_LITERAL)) {
2372 Some(self.parse_expr()?)
2376 ex = ExprKind::Break(label, e);
2377 hi = self.prev_span;
2378 } else if self.eat_keyword(keywords::Yield) {
2379 if self.token.can_begin_expr() {
2380 let e = self.parse_expr()?;
2382 ex = ExprKind::Yield(Some(e));
2384 ex = ExprKind::Yield(None);
2386 } else if self.token.is_keyword(keywords::Let) {
2387 // Catch this syntax error here, instead of in `parse_ident`, so
2388 // that we can explicitly mention that let is not to be used as an expression
2389 let mut db = self.fatal("expected expression, found statement (`let`)");
2390 db.span_label(self.span, "expected expression");
2391 db.note("variable declaration using `let` is a statement");
2393 } else if self.token.is_path_start() {
2394 let pth = self.parse_path(PathStyle::Expr)?;
2396 // `!`, as an operator, is prefix, so we know this isn't that
2397 if self.eat(&token::Not) {
2398 // MACRO INVOCATION expression
2399 let (_, tts) = self.expect_delimited_token_tree()?;
2400 let hi = self.prev_span;
2401 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2403 if self.check(&token::OpenDelim(token::Brace)) {
2404 // This is a struct literal, unless we're prohibited
2405 // from parsing struct literals here.
2406 let prohibited = self.restrictions.contains(
2407 Restrictions::NO_STRUCT_LITERAL
2410 return self.parse_struct_expr(lo, pth, attrs);
2415 ex = ExprKind::Path(None, pth);
2417 match self.parse_literal_maybe_minus() {
2420 ex = expr.node.clone();
2423 self.cancel(&mut err);
2424 let msg = format!("expected expression, found {}",
2425 self.this_token_descr());
2426 let mut err = self.fatal(&msg);
2427 err.span_label(self.span, "expected expression");
2435 let expr = Expr { node: ex, span: lo.to(hi), id: ast::DUMMY_NODE_ID, attrs };
2436 let expr = self.maybe_recover_from_bad_qpath(expr, true)?;
2441 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2442 -> PResult<'a, P<Expr>> {
2443 let struct_sp = lo.to(self.prev_span);
2445 let mut fields = Vec::new();
2446 let mut base = None;
2448 attrs.extend(self.parse_inner_attributes()?);
2450 while self.token != token::CloseDelim(token::Brace) {
2451 if self.eat(&token::DotDot) {
2452 let exp_span = self.prev_span;
2453 match self.parse_expr() {
2459 self.recover_stmt();
2462 if self.token == token::Comma {
2463 let mut err = self.sess.span_diagnostic.mut_span_err(
2464 exp_span.to(self.prev_span),
2465 "cannot use a comma after the base struct",
2467 err.span_suggestion_short(self.span, "remove this comma", "".to_owned());
2468 err.note("the base struct must always be the last field");
2470 self.recover_stmt();
2475 match self.parse_field() {
2476 Ok(f) => fields.push(f),
2478 e.span_label(struct_sp, "while parsing this struct");
2480 self.recover_stmt();
2485 match self.expect_one_of(&[token::Comma],
2486 &[token::CloseDelim(token::Brace)]) {
2490 self.recover_stmt();
2496 let span = lo.to(self.span);
2497 self.expect(&token::CloseDelim(token::Brace))?;
2498 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2501 fn parse_or_use_outer_attributes(&mut self,
2502 already_parsed_attrs: Option<ThinVec<Attribute>>)
2503 -> PResult<'a, ThinVec<Attribute>> {
2504 if let Some(attrs) = already_parsed_attrs {
2507 self.parse_outer_attributes().map(|a| a.into())
2511 /// Parse a block or unsafe block
2512 pub fn parse_block_expr(&mut self, opt_label: Option<Label>,
2513 lo: Span, blk_mode: BlockCheckMode,
2514 outer_attrs: ThinVec<Attribute>)
2515 -> PResult<'a, P<Expr>> {
2516 self.expect(&token::OpenDelim(token::Brace))?;
2518 let mut attrs = outer_attrs;
2519 attrs.extend(self.parse_inner_attributes()?);
2521 let blk = self.parse_block_tail(lo, blk_mode)?;
2522 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2525 /// parse a.b or a(13) or a[4] or just a
2526 pub fn parse_dot_or_call_expr(&mut self,
2527 already_parsed_attrs: Option<ThinVec<Attribute>>)
2528 -> PResult<'a, P<Expr>> {
2529 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2531 let b = self.parse_bottom_expr();
2532 let (span, b) = self.interpolated_or_expr_span(b)?;
2533 self.parse_dot_or_call_expr_with(b, span, attrs)
2536 pub fn parse_dot_or_call_expr_with(&mut self,
2539 mut attrs: ThinVec<Attribute>)
2540 -> PResult<'a, P<Expr>> {
2541 // Stitch the list of outer attributes onto the return value.
2542 // A little bit ugly, but the best way given the current code
2544 self.parse_dot_or_call_expr_with_(e0, lo)
2546 expr.map(|mut expr| {
2547 attrs.extend::<Vec<_>>(expr.attrs.into());
2550 ExprKind::If(..) | ExprKind::IfLet(..) => {
2551 if !expr.attrs.is_empty() {
2552 // Just point to the first attribute in there...
2553 let span = expr.attrs[0].span;
2556 "attributes are not yet allowed on `if` \
2567 // Assuming we have just parsed `.`, continue parsing into an expression.
2568 fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2569 let segment = self.parse_path_segment(PathStyle::Expr, true)?;
2570 Ok(match self.token {
2571 token::OpenDelim(token::Paren) => {
2572 // Method call `expr.f()`
2573 let mut args = self.parse_unspanned_seq(
2574 &token::OpenDelim(token::Paren),
2575 &token::CloseDelim(token::Paren),
2576 SeqSep::trailing_allowed(token::Comma),
2577 |p| Ok(p.parse_expr()?)
2579 args.insert(0, self_arg);
2581 let span = lo.to(self.prev_span);
2582 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
2585 // Field access `expr.f`
2586 if let Some(parameters) = segment.parameters {
2587 self.span_err(parameters.span(),
2588 "field expressions may not have generic arguments");
2591 let span = lo.to(self.prev_span);
2592 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
2597 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2602 while self.eat(&token::Question) {
2603 let hi = self.prev_span;
2604 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2608 if self.eat(&token::Dot) {
2610 token::Ident(..) => {
2611 e = self.parse_dot_suffix(e, lo)?;
2613 token::Literal(token::Integer(name), _) => {
2614 let span = self.span;
2616 let field = ExprKind::Field(e, Ident::new(name, span));
2617 e = self.mk_expr(lo.to(span), field, ThinVec::new());
2619 token::Literal(token::Float(n), _suf) => {
2621 let fstr = n.as_str();
2622 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2623 &format!("unexpected token: `{}`", n));
2624 err.span_label(self.prev_span, "unexpected token");
2625 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2626 let float = match fstr.parse::<f64>().ok() {
2630 let sugg = pprust::to_string(|s| {
2631 use print::pprust::PrintState;
2635 s.print_usize(float.trunc() as usize)?;
2638 s.s.word(fstr.splitn(2, ".").last().unwrap())
2640 err.span_suggestion(
2641 lo.to(self.prev_span),
2642 "try parenthesizing the first index",
2649 // FIXME Could factor this out into non_fatal_unexpected or something.
2650 let actual = self.this_token_to_string();
2651 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2656 if self.expr_is_complete(&e) { break; }
2659 token::OpenDelim(token::Paren) => {
2660 let es = self.parse_unspanned_seq(
2661 &token::OpenDelim(token::Paren),
2662 &token::CloseDelim(token::Paren),
2663 SeqSep::trailing_allowed(token::Comma),
2664 |p| Ok(p.parse_expr()?)
2666 hi = self.prev_span;
2668 let nd = self.mk_call(e, es);
2669 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2673 // Could be either an index expression or a slicing expression.
2674 token::OpenDelim(token::Bracket) => {
2676 let ix = self.parse_expr()?;
2678 self.expect(&token::CloseDelim(token::Bracket))?;
2679 let index = self.mk_index(e, ix);
2680 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2688 pub fn process_potential_macro_variable(&mut self) {
2689 let (token, span) = match self.token {
2690 token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
2691 self.look_ahead(1, |t| t.is_ident()) => {
2693 let name = match self.token {
2694 token::Ident(ident, _) => ident,
2697 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
2698 err.span_label(self.span, "unknown macro variable");
2702 token::Interpolated(ref nt) => {
2703 self.meta_var_span = Some(self.span);
2704 // Interpolated identifier and lifetime tokens are replaced with usual identifier
2705 // and lifetime tokens, so the former are never encountered during normal parsing.
2707 token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
2708 token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
2718 /// parse a single token tree from the input.
2719 pub fn parse_token_tree(&mut self) -> TokenTree {
2721 token::OpenDelim(..) => {
2722 let frame = mem::replace(&mut self.token_cursor.frame,
2723 self.token_cursor.stack.pop().unwrap());
2724 self.span = frame.span;
2726 TokenTree::Delimited(frame.span, Delimited {
2728 tts: frame.tree_cursor.original_stream().into(),
2731 token::CloseDelim(_) | token::Eof => unreachable!(),
2733 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
2735 TokenTree::Token(span, token)
2740 // parse a stream of tokens into a list of TokenTree's,
2742 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2743 let mut tts = Vec::new();
2744 while self.token != token::Eof {
2745 tts.push(self.parse_token_tree());
2750 pub fn parse_tokens(&mut self) -> TokenStream {
2751 let mut result = Vec::new();
2754 token::Eof | token::CloseDelim(..) => break,
2755 _ => result.push(self.parse_token_tree().into()),
2758 TokenStream::concat(result)
2761 /// Parse a prefix-unary-operator expr
2762 pub fn parse_prefix_expr(&mut self,
2763 already_parsed_attrs: Option<ThinVec<Attribute>>)
2764 -> PResult<'a, P<Expr>> {
2765 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2767 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2768 let (hi, ex) = match self.token {
2771 let e = self.parse_prefix_expr(None);
2772 let (span, e) = self.interpolated_or_expr_span(e)?;
2773 (lo.to(span), self.mk_unary(UnOp::Not, e))
2775 // Suggest `!` for bitwise negation when encountering a `~`
2778 let e = self.parse_prefix_expr(None);
2779 let (span, e) = self.interpolated_or_expr_span(e)?;
2780 let span_of_tilde = lo;
2781 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2782 "`~` cannot be used as a unary operator");
2783 err.span_suggestion_short(span_of_tilde,
2784 "use `!` to perform bitwise negation",
2787 (lo.to(span), self.mk_unary(UnOp::Not, e))
2789 token::BinOp(token::Minus) => {
2791 let e = self.parse_prefix_expr(None);
2792 let (span, e) = self.interpolated_or_expr_span(e)?;
2793 (lo.to(span), self.mk_unary(UnOp::Neg, e))
2795 token::BinOp(token::Star) => {
2797 let e = self.parse_prefix_expr(None);
2798 let (span, e) = self.interpolated_or_expr_span(e)?;
2799 (lo.to(span), self.mk_unary(UnOp::Deref, e))
2801 token::BinOp(token::And) | token::AndAnd => {
2803 let m = self.parse_mutability();
2804 let e = self.parse_prefix_expr(None);
2805 let (span, e) = self.interpolated_or_expr_span(e)?;
2806 (lo.to(span), ExprKind::AddrOf(m, e))
2808 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2810 let e = self.parse_prefix_expr(None);
2811 let (span, e) = self.interpolated_or_expr_span(e)?;
2812 (lo.to(span), ExprKind::Box(e))
2814 token::Ident(..) if self.token.is_ident_named("not") => {
2815 // `not` is just an ordinary identifier in Rust-the-language,
2816 // but as `rustc`-the-compiler, we can issue clever diagnostics
2817 // for confused users who really want to say `!`
2818 let token_cannot_continue_expr = |t: &token::Token| match *t {
2819 // These tokens can start an expression after `!`, but
2820 // can't continue an expression after an ident
2821 token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
2822 token::Literal(..) | token::Pound => true,
2823 token::Interpolated(ref nt) => match nt.0 {
2824 token::NtIdent(..) | token::NtExpr(..) |
2825 token::NtBlock(..) | token::NtPath(..) => true,
2830 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
2831 if cannot_continue_expr {
2833 // Emit the error ...
2834 let mut err = self.diagnostic()
2835 .struct_span_err(self.span,
2836 &format!("unexpected {} after identifier",
2837 self.this_token_descr()));
2838 // span the `not` plus trailing whitespace to avoid
2839 // trailing whitespace after the `!` in our suggestion
2840 let to_replace = self.sess.codemap()
2841 .span_until_non_whitespace(lo.to(self.span));
2842 err.span_suggestion_short(to_replace,
2843 "use `!` to perform logical negation",
2846 // —and recover! (just as if we were in the block
2847 // for the `token::Not` arm)
2848 let e = self.parse_prefix_expr(None);
2849 let (span, e) = self.interpolated_or_expr_span(e)?;
2850 (lo.to(span), self.mk_unary(UnOp::Not, e))
2852 return self.parse_dot_or_call_expr(Some(attrs));
2855 _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
2857 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2860 /// Parse an associative expression
2862 /// This parses an expression accounting for associativity and precedence of the operators in
2864 pub fn parse_assoc_expr(&mut self,
2865 already_parsed_attrs: Option<ThinVec<Attribute>>)
2866 -> PResult<'a, P<Expr>> {
2867 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2870 /// Parse an associative expression with operators of at least `min_prec` precedence
2871 pub fn parse_assoc_expr_with(&mut self,
2874 -> PResult<'a, P<Expr>> {
2875 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2878 let attrs = match lhs {
2879 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2882 if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
2883 return self.parse_prefix_range_expr(attrs);
2885 self.parse_prefix_expr(attrs)?
2889 if self.expr_is_complete(&lhs) {
2890 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2893 self.expected_tokens.push(TokenType::Operator);
2894 while let Some(op) = AssocOp::from_token(&self.token) {
2896 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2897 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2898 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2899 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2900 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2901 (PrevTokenKind::Interpolated, _) => self.prev_span,
2902 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2903 if path.segments.len() == 1 => self.prev_span,
2907 let cur_op_span = self.span;
2908 let restrictions = if op.is_assign_like() {
2909 self.restrictions & Restrictions::NO_STRUCT_LITERAL
2913 if op.precedence() < min_prec {
2916 // Check for deprecated `...` syntax
2917 if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
2918 self.err_dotdotdot_syntax(self.span);
2922 if op.is_comparison() {
2923 self.check_no_chained_comparison(&lhs, &op);
2926 if op == AssocOp::As {
2927 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2929 } else if op == AssocOp::Colon {
2930 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2933 err.span_label(self.span,
2934 "expecting a type here because of type ascription");
2935 let cm = self.sess.codemap();
2936 let cur_pos = cm.lookup_char_pos(self.span.lo());
2937 let op_pos = cm.lookup_char_pos(cur_op_span.hi());
2938 if cur_pos.line != op_pos.line {
2939 err.span_suggestion_short(cur_op_span,
2940 "did you mean to use `;` here?",
2947 } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
2948 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
2949 // generalise it to the Fixity::None code.
2951 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
2952 // two variants are handled with `parse_prefix_range_expr` call above.
2953 let rhs = if self.is_at_start_of_range_notation_rhs() {
2954 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2955 LhsExpr::NotYetParsed)?)
2959 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2964 let limits = if op == AssocOp::DotDot {
2965 RangeLimits::HalfOpen
2970 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2971 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2975 let rhs = match op.fixity() {
2976 Fixity::Right => self.with_res(
2977 restrictions - Restrictions::STMT_EXPR,
2979 this.parse_assoc_expr_with(op.precedence(),
2980 LhsExpr::NotYetParsed)
2982 Fixity::Left => self.with_res(
2983 restrictions - Restrictions::STMT_EXPR,
2985 this.parse_assoc_expr_with(op.precedence() + 1,
2986 LhsExpr::NotYetParsed)
2988 // We currently have no non-associative operators that are not handled above by
2989 // the special cases. The code is here only for future convenience.
2990 Fixity::None => self.with_res(
2991 restrictions - Restrictions::STMT_EXPR,
2993 this.parse_assoc_expr_with(op.precedence() + 1,
2994 LhsExpr::NotYetParsed)
2998 let span = lhs_span.to(rhs.span);
3000 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3001 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3002 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3003 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3004 AssocOp::Greater | AssocOp::GreaterEqual => {
3005 let ast_op = op.to_ast_binop().unwrap();
3006 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
3007 self.mk_expr(span, binary, ThinVec::new())
3010 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3011 AssocOp::AssignOp(k) => {
3013 token::Plus => BinOpKind::Add,
3014 token::Minus => BinOpKind::Sub,
3015 token::Star => BinOpKind::Mul,
3016 token::Slash => BinOpKind::Div,
3017 token::Percent => BinOpKind::Rem,
3018 token::Caret => BinOpKind::BitXor,
3019 token::And => BinOpKind::BitAnd,
3020 token::Or => BinOpKind::BitOr,
3021 token::Shl => BinOpKind::Shl,
3022 token::Shr => BinOpKind::Shr,
3024 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
3025 self.mk_expr(span, aopexpr, ThinVec::new())
3027 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3028 self.bug("AssocOp should have been handled by special case")
3032 if op.fixity() == Fixity::None { break }
3037 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3038 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3039 -> PResult<'a, P<Expr>> {
3040 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3041 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3044 // Save the state of the parser before parsing type normally, in case there is a
3045 // LessThan comparison after this cast.
3046 let parser_snapshot_before_type = self.clone();
3047 match self.parse_ty_no_plus() {
3049 Ok(mk_expr(self, rhs))
3051 Err(mut type_err) => {
3052 // Rewind to before attempting to parse the type with generics, to recover
3053 // from situations like `x as usize < y` in which we first tried to parse
3054 // `usize < y` as a type with generic arguments.
3055 let parser_snapshot_after_type = self.clone();
3056 mem::replace(self, parser_snapshot_before_type);
3058 match self.parse_path(PathStyle::Expr) {
3060 let (op_noun, op_verb) = match self.token {
3061 token::Lt => ("comparison", "comparing"),
3062 token::BinOp(token::Shl) => ("shift", "shifting"),
3064 // We can end up here even without `<` being the next token, for
3065 // example because `parse_ty_no_plus` returns `Err` on keywords,
3066 // but `parse_path` returns `Ok` on them due to error recovery.
3067 // Return original error and parser state.
3068 mem::replace(self, parser_snapshot_after_type);
3069 return Err(type_err);
3073 // Successfully parsed the type path leaving a `<` yet to parse.
3076 // Report non-fatal diagnostics, keep `x as usize` as an expression
3077 // in AST and continue parsing.
3078 let msg = format!("`<` is interpreted as a start of generic \
3079 arguments for `{}`, not a {}", path, op_noun);
3080 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3081 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3082 "interpreted as generic arguments");
3083 err.span_label(self.span, format!("not interpreted as {}", op_noun));
3085 let expr = mk_expr(self, P(Ty {
3087 node: TyKind::Path(None, path),
3088 id: ast::DUMMY_NODE_ID
3091 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
3092 .unwrap_or(pprust::expr_to_string(&expr));
3093 err.span_suggestion(expr.span,
3094 &format!("try {} the cast value", op_verb),
3095 format!("({})", expr_str));
3100 Err(mut path_err) => {
3101 // Couldn't parse as a path, return original error and parser state.
3103 mem::replace(self, parser_snapshot_after_type);
3111 /// Produce an error if comparison operators are chained (RFC #558).
3112 /// We only need to check lhs, not rhs, because all comparison ops
3113 /// have same precedence and are left-associative
3114 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3115 debug_assert!(outer_op.is_comparison(),
3116 "check_no_chained_comparison: {:?} is not comparison",
3119 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3120 // respan to include both operators
3121 let op_span = op.span.to(self.span);
3122 let mut err = self.diagnostic().struct_span_err(op_span,
3123 "chained comparison operators require parentheses");
3124 if op.node == BinOpKind::Lt &&
3125 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
3126 *outer_op == AssocOp::Greater // even in a case like the following:
3127 { // Foo<Bar<Baz<Qux, ()>>>
3129 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3130 err.help("or use `(...)` if you meant to specify fn arguments");
3138 /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3139 fn parse_prefix_range_expr(&mut self,
3140 already_parsed_attrs: Option<ThinVec<Attribute>>)
3141 -> PResult<'a, P<Expr>> {
3142 // Check for deprecated `...` syntax
3143 if self.token == token::DotDotDot {
3144 self.err_dotdotdot_syntax(self.span);
3147 debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3148 "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3150 let tok = self.token.clone();
3151 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3153 let mut hi = self.span;
3155 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3156 // RHS must be parsed with more associativity than the dots.
3157 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3158 Some(self.parse_assoc_expr_with(next_prec,
3159 LhsExpr::NotYetParsed)
3167 let limits = if tok == token::DotDot {
3168 RangeLimits::HalfOpen
3173 let r = try!(self.mk_range(None,
3176 Ok(self.mk_expr(lo.to(hi), r, attrs))
3179 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3180 if self.token.can_begin_expr() {
3181 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3182 if self.token == token::OpenDelim(token::Brace) {
3183 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3191 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3192 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3193 if self.check_keyword(keywords::Let) {
3194 return self.parse_if_let_expr(attrs);
3196 let lo = self.prev_span;
3197 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3199 // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3200 // verify that the last statement is either an implicit return (no `;`) or an explicit
3201 // return. This won't catch blocks with an explicit `return`, but that would be caught by
3202 // the dead code lint.
3203 if self.eat_keyword(keywords::Else) || !cond.returns() {
3204 let sp = self.sess.codemap().next_point(lo);
3205 let mut err = self.diagnostic()
3206 .struct_span_err(sp, "missing condition for `if` statemement");
3207 err.span_label(sp, "expected if condition here");
3210 let not_block = self.token != token::OpenDelim(token::Brace);
3211 let thn = self.parse_block().map_err(|mut err| {
3213 err.span_label(lo, "this `if` statement has a condition, but no block");
3217 let mut els: Option<P<Expr>> = None;
3218 let mut hi = thn.span;
3219 if self.eat_keyword(keywords::Else) {
3220 let elexpr = self.parse_else_expr()?;
3224 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3227 /// Parse an 'if let' expression ('if' token already eaten)
3228 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3229 -> PResult<'a, P<Expr>> {
3230 let lo = self.prev_span;
3231 self.expect_keyword(keywords::Let)?;
3232 let pats = self.parse_pats()?;
3233 self.expect(&token::Eq)?;
3234 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3235 let thn = self.parse_block()?;
3236 let (hi, els) = if self.eat_keyword(keywords::Else) {
3237 let expr = self.parse_else_expr()?;
3238 (expr.span, Some(expr))
3242 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3245 // `move |args| expr`
3246 pub fn parse_lambda_expr(&mut self,
3247 attrs: ThinVec<Attribute>)
3248 -> PResult<'a, P<Expr>>
3251 let movability = if self.eat_keyword(keywords::Static) {
3256 let capture_clause = if self.eat_keyword(keywords::Move) {
3261 let decl = self.parse_fn_block_decl()?;
3262 let decl_hi = self.prev_span;
3263 let body = match decl.output {
3264 FunctionRetTy::Default(_) => {
3265 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3266 self.parse_expr_res(restrictions, None)?
3269 // If an explicit return type is given, require a
3270 // block to appear (RFC 968).
3271 let body_lo = self.span;
3272 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3278 ExprKind::Closure(capture_clause, movability, decl, body, lo.to(decl_hi)),
3282 // `else` token already eaten
3283 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3284 if self.eat_keyword(keywords::If) {
3285 return self.parse_if_expr(ThinVec::new());
3287 let blk = self.parse_block()?;
3288 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3292 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3293 pub fn parse_for_expr(&mut self, opt_label: Option<Label>,
3295 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3296 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3298 let pat = self.parse_top_level_pat()?;
3299 if !self.eat_keyword(keywords::In) {
3300 let in_span = self.prev_span.between(self.span);
3301 let mut err = self.sess.span_diagnostic
3302 .struct_span_err(in_span, "missing `in` in `for` loop");
3303 err.span_suggestion_short(in_span, "try adding `in` here", " in ".into());
3306 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3307 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3308 attrs.extend(iattrs);
3310 let hi = self.prev_span;
3311 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
3314 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3315 pub fn parse_while_expr(&mut self, opt_label: Option<Label>,
3317 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3318 if self.token.is_keyword(keywords::Let) {
3319 return self.parse_while_let_expr(opt_label, span_lo, attrs);
3321 let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3322 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3323 attrs.extend(iattrs);
3324 let span = span_lo.to(body.span);
3325 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
3328 /// Parse a 'while let' expression ('while' token already eaten)
3329 pub fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
3331 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3332 self.expect_keyword(keywords::Let)?;
3333 let pats = self.parse_pats()?;
3334 self.expect(&token::Eq)?;
3335 let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3336 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3337 attrs.extend(iattrs);
3338 let span = span_lo.to(body.span);
3339 return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
3342 // parse `loop {...}`, `loop` token already eaten
3343 pub fn parse_loop_expr(&mut self, opt_label: Option<Label>,
3345 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3346 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3347 attrs.extend(iattrs);
3348 let span = span_lo.to(body.span);
3349 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
3352 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3353 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3354 -> PResult<'a, P<Expr>>
3356 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3357 attrs.extend(iattrs);
3358 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3361 // `match` token already eaten
3362 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3363 let match_span = self.prev_span;
3364 let lo = self.prev_span;
3365 let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
3367 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3368 if self.token == token::Token::Semi {
3369 e.span_suggestion_short(match_span, "try removing this `match`", "".to_owned());
3373 attrs.extend(self.parse_inner_attributes()?);
3375 let mut arms: Vec<Arm> = Vec::new();
3376 while self.token != token::CloseDelim(token::Brace) {
3377 match self.parse_arm() {
3378 Ok(arm) => arms.push(arm),
3380 // Recover by skipping to the end of the block.
3382 self.recover_stmt();
3383 let span = lo.to(self.span);
3384 if self.token == token::CloseDelim(token::Brace) {
3387 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3393 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3396 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3397 maybe_whole!(self, NtArm, |x| x);
3399 let attrs = self.parse_outer_attributes()?;
3400 // Allow a '|' before the pats (RFC 1925)
3401 self.eat(&token::BinOp(token::Or));
3402 let pats = self.parse_pats()?;
3403 let guard = if self.eat_keyword(keywords::If) {
3404 Some(self.parse_expr()?)
3408 let arrow_span = self.span;
3409 self.expect(&token::FatArrow)?;
3410 let arm_start_span = self.span;
3412 let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
3413 .map_err(|mut err| {
3414 err.span_label(arrow_span, "while parsing the `match` arm starting here");
3418 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3419 && self.token != token::CloseDelim(token::Brace);
3422 let cm = self.sess.codemap();
3423 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
3424 .map_err(|mut err| {
3425 match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
3426 (Ok(ref expr_lines), Ok(ref arm_start_lines))
3427 if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
3428 && expr_lines.lines.len() == 2
3429 && self.token == token::FatArrow => {
3430 // We check wether there's any trailing code in the parse span, if there
3431 // isn't, we very likely have the following:
3434 // | -- - missing comma
3440 // | parsed until here as `"y" & X`
3441 err.span_suggestion_short(
3442 cm.next_point(arm_start_span),
3443 "missing a comma here to end this `match` arm",
3448 err.span_label(arrow_span,
3449 "while parsing the `match` arm starting here");
3455 self.eat(&token::Comma);
3466 /// Parse an expression
3467 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3468 self.parse_expr_res(Restrictions::empty(), None)
3471 /// Evaluate the closure with restrictions in place.
3473 /// After the closure is evaluated, restrictions are reset.
3474 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3475 where F: FnOnce(&mut Self) -> T
3477 let old = self.restrictions;
3478 self.restrictions = r;
3480 self.restrictions = old;
3485 /// Parse an expression, subject to the given restrictions
3486 pub fn parse_expr_res(&mut self, r: Restrictions,
3487 already_parsed_attrs: Option<ThinVec<Attribute>>)
3488 -> PResult<'a, P<Expr>> {
3489 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3492 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3493 fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
3494 if self.check(&token::Eq) {
3496 Ok(Some(self.parse_expr()?))
3498 Ok(Some(self.parse_expr()?))
3504 /// Parse patterns, separated by '|' s
3505 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3506 let mut pats = Vec::new();
3508 pats.push(self.parse_top_level_pat()?);
3510 if self.token == token::OrOr {
3511 let mut err = self.struct_span_err(self.span,
3512 "unexpected token `||` after pattern");
3513 err.span_suggestion(self.span,
3514 "use a single `|` to specify multiple patterns",
3518 } else if self.check(&token::BinOp(token::Or)) {
3526 // Parses a parenthesized list of patterns like
3527 // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
3528 // - a vector of the patterns that were parsed
3529 // - an option indicating the index of the `..` element
3530 // - a boolean indicating whether a trailing comma was present.
3531 // Trailing commas are significant because (p) and (p,) are different patterns.
3532 fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3533 self.expect(&token::OpenDelim(token::Paren))?;
3534 let result = self.parse_pat_list()?;
3535 self.expect(&token::CloseDelim(token::Paren))?;
3539 fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
3540 let mut fields = Vec::new();
3541 let mut ddpos = None;
3542 let mut trailing_comma = false;
3544 if self.eat(&token::DotDot) {
3545 if ddpos.is_none() {
3546 ddpos = Some(fields.len());
3548 // Emit a friendly error, ignore `..` and continue parsing
3549 self.span_err(self.prev_span,
3550 "`..` can only be used once per tuple or tuple struct pattern");
3552 } else if !self.check(&token::CloseDelim(token::Paren)) {
3553 fields.push(self.parse_pat()?);
3558 trailing_comma = self.eat(&token::Comma);
3559 if !trailing_comma {
3564 if ddpos == Some(fields.len()) && trailing_comma {
3565 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3566 self.span_err(self.prev_span, "trailing comma is not permitted after `..`");
3569 Ok((fields, ddpos, trailing_comma))
3572 fn parse_pat_vec_elements(
3574 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3575 let mut before = Vec::new();
3576 let mut slice = None;
3577 let mut after = Vec::new();
3578 let mut first = true;
3579 let mut before_slice = true;
3581 while self.token != token::CloseDelim(token::Bracket) {
3585 self.expect(&token::Comma)?;
3587 if self.token == token::CloseDelim(token::Bracket)
3588 && (before_slice || !after.is_empty()) {
3594 if self.eat(&token::DotDot) {
3596 if self.check(&token::Comma) ||
3597 self.check(&token::CloseDelim(token::Bracket)) {
3598 slice = Some(P(Pat {
3599 id: ast::DUMMY_NODE_ID,
3600 node: PatKind::Wild,
3601 span: self.prev_span,
3603 before_slice = false;
3609 let subpat = self.parse_pat()?;
3610 if before_slice && self.eat(&token::DotDot) {
3611 slice = Some(subpat);
3612 before_slice = false;
3613 } else if before_slice {
3614 before.push(subpat);
3620 Ok((before, slice, after))
3623 /// Parse the fields of a struct-like pattern
3624 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3625 let mut fields = Vec::new();
3626 let mut etc = false;
3627 let mut first = true;
3628 while self.token != token::CloseDelim(token::Brace) {
3632 self.expect(&token::Comma)?;
3633 // accept trailing commas
3634 if self.check(&token::CloseDelim(token::Brace)) { break }
3637 let attrs = self.parse_outer_attributes()?;
3641 if self.check(&token::DotDot) || self.token == token::DotDotDot {
3642 if self.token == token::DotDotDot { // Issue #46718
3643 let mut err = self.struct_span_err(self.span,
3644 "expected field pattern, found `...`");
3645 err.span_suggestion(self.span,
3646 "to omit remaining fields, use one fewer `.`",
3652 if self.token != token::CloseDelim(token::Brace) {
3653 let token_str = self.this_token_to_string();
3654 let mut err = self.fatal(&format!("expected `{}`, found `{}`", "}", token_str));
3655 if self.token == token::Comma { // Issue #49257
3656 err.span_label(self.span,
3657 "`..` must be in the last position, \
3658 and cannot have a trailing comma");
3660 err.span_label(self.span, "expected `}`");
3668 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3669 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3670 // Parsing a pattern of the form "fieldname: pat"
3671 let fieldname = self.parse_field_name()?;
3673 let pat = self.parse_pat()?;
3675 (pat, fieldname, false)
3677 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3678 let is_box = self.eat_keyword(keywords::Box);
3679 let boxed_span = self.span;
3680 let is_ref = self.eat_keyword(keywords::Ref);
3681 let is_mut = self.eat_keyword(keywords::Mut);
3682 let fieldname = self.parse_ident()?;
3683 hi = self.prev_span;
3685 let bind_type = match (is_ref, is_mut) {
3686 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3687 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3688 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3689 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3691 let fieldpat = P(Pat {
3692 id: ast::DUMMY_NODE_ID,
3693 node: PatKind::Ident(bind_type, fieldname, None),
3694 span: boxed_span.to(hi),
3697 let subpat = if is_box {
3699 id: ast::DUMMY_NODE_ID,
3700 node: PatKind::Box(fieldpat),
3706 (subpat, fieldname, true)
3709 fields.push(codemap::Spanned { span: lo.to(hi),
3710 node: ast::FieldPat {
3714 attrs: attrs.into(),
3718 return Ok((fields, etc));
3721 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3722 if self.token.is_path_start() {
3724 let (qself, path) = if self.eat_lt() {
3725 // Parse a qualified path
3726 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3729 // Parse an unqualified path
3730 (None, self.parse_path(PathStyle::Expr)?)
3732 let hi = self.prev_span;
3733 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3735 self.parse_literal_maybe_minus()
3739 // helper function to decide whether to parse as ident binding or to try to do
3740 // something more complex like range patterns
3741 fn parse_as_ident(&mut self) -> bool {
3742 self.look_ahead(1, |t| match *t {
3743 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3744 token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
3745 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3746 // range pattern branch
3747 token::DotDot => None,
3749 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3750 token::Comma | token::CloseDelim(token::Bracket) => true,
3755 /// A wrapper around `parse_pat` with some special error handling for the
3756 /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contast
3757 /// to subpatterns within such).
3758 pub fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
3759 let pat = self.parse_pat()?;
3760 if self.token == token::Comma {
3761 // An unexpected comma after a top-level pattern is a clue that the
3762 // user (perhaps more accustomed to some other language) forgot the
3763 // parentheses in what should have been a tuple pattern; return a
3764 // suggestion-enhanced error here rather than choking on the comma
3766 let comma_span = self.span;
3768 if let Err(mut err) = self.parse_pat_list() {
3769 // We didn't expect this to work anyway; we just wanted
3770 // to advance to the end of the comma-sequence so we know
3771 // the span to suggest parenthesizing
3774 let seq_span = pat.span.to(self.prev_span);
3775 let mut err = self.struct_span_err(comma_span,
3776 "unexpected `,` in pattern");
3777 if let Ok(seq_snippet) = self.sess.codemap().span_to_snippet(seq_span) {
3778 err.span_suggestion(seq_span, "try adding parentheses",
3779 format!("({})", seq_snippet));
3786 /// Parse a pattern.
3787 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3788 self.parse_pat_with_range_pat(true)
3791 /// Parse a pattern, with a setting whether modern range patterns e.g. `a..=b`, `a..b` are
3793 fn parse_pat_with_range_pat(&mut self, allow_range_pat: bool) -> PResult<'a, P<Pat>> {
3794 maybe_whole!(self, NtPat, |x| x);
3799 token::BinOp(token::And) | token::AndAnd => {
3800 // Parse &pat / &mut pat
3802 let mutbl = self.parse_mutability();
3803 if let token::Lifetime(ident) = self.token {
3804 let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
3806 err.span_label(self.span, "unexpected lifetime");
3809 let subpat = self.parse_pat_with_range_pat(false)?;
3810 pat = PatKind::Ref(subpat, mutbl);
3812 token::OpenDelim(token::Paren) => {
3813 // Parse (pat,pat,pat,...) as tuple pattern
3814 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
3815 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
3816 PatKind::Paren(fields.into_iter().nth(0).unwrap())
3818 PatKind::Tuple(fields, ddpos)
3821 token::OpenDelim(token::Bracket) => {
3822 // Parse [pat,pat,...] as slice pattern
3824 let (before, slice, after) = self.parse_pat_vec_elements()?;
3825 self.expect(&token::CloseDelim(token::Bracket))?;
3826 pat = PatKind::Slice(before, slice, after);
3828 // At this point, token != &, &&, (, [
3829 _ => if self.eat_keyword(keywords::Underscore) {
3831 pat = PatKind::Wild;
3832 } else if self.eat_keyword(keywords::Mut) {
3833 // Parse mut ident @ pat / mut ref ident @ pat
3834 let mutref_span = self.prev_span.to(self.span);
3835 let binding_mode = if self.eat_keyword(keywords::Ref) {
3837 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3838 .span_suggestion(mutref_span, "try switching the order", "ref mut".into())
3840 BindingMode::ByRef(Mutability::Mutable)
3842 BindingMode::ByValue(Mutability::Mutable)
3844 pat = self.parse_pat_ident(binding_mode)?;
3845 } else if self.eat_keyword(keywords::Ref) {
3846 // Parse ref ident @ pat / ref mut ident @ pat
3847 let mutbl = self.parse_mutability();
3848 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3849 } else if self.eat_keyword(keywords::Box) {
3851 let subpat = self.parse_pat_with_range_pat(false)?;
3852 pat = PatKind::Box(subpat);
3853 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3854 self.parse_as_ident() {
3855 // Parse ident @ pat
3856 // This can give false positives and parse nullary enums,
3857 // they are dealt with later in resolve
3858 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3859 pat = self.parse_pat_ident(binding_mode)?;
3860 } else if self.token.is_path_start() {
3861 // Parse pattern starting with a path
3862 let (qself, path) = if self.eat_lt() {
3863 // Parse a qualified path
3864 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3867 // Parse an unqualified path
3868 (None, self.parse_path(PathStyle::Expr)?)
3871 token::Not if qself.is_none() => {
3872 // Parse macro invocation
3874 let (_, tts) = self.expect_delimited_token_tree()?;
3875 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3876 pat = PatKind::Mac(mac);
3878 token::DotDotDot | token::DotDotEq | token::DotDot => {
3879 let end_kind = match self.token {
3880 token::DotDot => RangeEnd::Excluded,
3881 token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
3882 token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
3883 _ => panic!("can only parse `..`/`...`/`..=` for ranges \
3887 let span = lo.to(self.prev_span);
3888 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3890 let end = self.parse_pat_range_end()?;
3891 pat = PatKind::Range(begin, end, end_kind);
3893 token::OpenDelim(token::Brace) => {
3894 if qself.is_some() {
3895 let msg = "unexpected `{` after qualified path";
3896 let mut err = self.fatal(msg);
3897 err.span_label(self.span, msg);
3900 // Parse struct pattern
3902 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3904 self.recover_stmt();
3908 pat = PatKind::Struct(path, fields, etc);
3910 token::OpenDelim(token::Paren) => {
3911 if qself.is_some() {
3912 let msg = "unexpected `(` after qualified path";
3913 let mut err = self.fatal(msg);
3914 err.span_label(self.span, msg);
3917 // Parse tuple struct or enum pattern
3918 let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
3919 pat = PatKind::TupleStruct(path, fields, ddpos)
3921 _ => pat = PatKind::Path(qself, path),
3924 // Try to parse everything else as literal with optional minus
3925 match self.parse_literal_maybe_minus() {
3927 if self.eat(&token::DotDotDot) {
3928 let end = self.parse_pat_range_end()?;
3929 pat = PatKind::Range(begin, end,
3930 RangeEnd::Included(RangeSyntax::DotDotDot));
3931 } else if self.eat(&token::DotDotEq) {
3932 let end = self.parse_pat_range_end()?;
3933 pat = PatKind::Range(begin, end,
3934 RangeEnd::Included(RangeSyntax::DotDotEq));
3935 } else if self.eat(&token::DotDot) {
3936 let end = self.parse_pat_range_end()?;
3937 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3939 pat = PatKind::Lit(begin);
3943 self.cancel(&mut err);
3944 let msg = format!("expected pattern, found {}", self.this_token_descr());
3945 let mut err = self.fatal(&msg);
3946 err.span_label(self.span, "expected pattern");
3953 let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
3954 let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
3956 if !allow_range_pat {
3958 PatKind::Range(_, _, RangeEnd::Included(RangeSyntax::DotDotDot)) => {}
3959 PatKind::Range(..) => {
3960 let mut err = self.struct_span_err(
3962 "the range pattern here has ambiguous interpretation",
3964 err.span_suggestion(
3966 "add parentheses to clarify the precedence",
3967 format!("({})", pprust::pat_to_string(&pat)),
3978 /// Parse ident or ident @ pat
3979 /// used by the copy foo and ref foo patterns to give a good
3980 /// error message when parsing mistakes like ref foo(a,b)
3981 fn parse_pat_ident(&mut self,
3982 binding_mode: ast::BindingMode)
3983 -> PResult<'a, PatKind> {
3984 let ident = self.parse_ident()?;
3985 let sub = if self.eat(&token::At) {
3986 Some(self.parse_pat()?)
3991 // just to be friendly, if they write something like
3993 // we end up here with ( as the current token. This shortly
3994 // leads to a parse error. Note that if there is no explicit
3995 // binding mode then we do not end up here, because the lookahead
3996 // will direct us over to parse_enum_variant()
3997 if self.token == token::OpenDelim(token::Paren) {
3998 return Err(self.span_fatal(
4000 "expected identifier, found enum pattern"))
4003 Ok(PatKind::Ident(binding_mode, ident, sub))
4006 /// Parse a local variable declaration
4007 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4008 let lo = self.prev_span;
4009 let pat = self.parse_top_level_pat()?;
4011 let (err, ty) = if self.eat(&token::Colon) {
4012 // Save the state of the parser before parsing type normally, in case there is a `:`
4013 // instead of an `=` typo.
4014 let parser_snapshot_before_type = self.clone();
4015 let colon_sp = self.prev_span;
4016 match self.parse_ty() {
4017 Ok(ty) => (None, Some(ty)),
4019 // Rewind to before attempting to parse the type and continue parsing
4020 let parser_snapshot_after_type = self.clone();
4021 mem::replace(self, parser_snapshot_before_type);
4023 let snippet = self.sess.codemap().span_to_snippet(pat.span).unwrap();
4024 err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4025 (Some((parser_snapshot_after_type, colon_sp, err)), None)
4031 let init = match (self.parse_initializer(err.is_some()), err) {
4032 (Ok(init), None) => { // init parsed, ty parsed
4035 (Ok(init), Some((_, colon_sp, mut err))) => { // init parsed, ty error
4036 // Could parse the type as if it were the initializer, it is likely there was a
4037 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4038 err.span_suggestion_short(colon_sp,
4039 "use `=` if you meant to assign",
4042 // As this was parsed successfully, continue as if the code has been fixed for the
4043 // rest of the file. It will still fail due to the emitted error, but we avoid
4047 (Err(mut init_err), Some((snapshot, _, ty_err))) => { // init error, ty error
4049 // Couldn't parse the type nor the initializer, only raise the type error and
4050 // return to the parser state before parsing the type as the initializer.
4051 // let x: <parse_error>;
4052 mem::replace(self, snapshot);
4055 (Err(err), None) => { // init error, ty parsed
4056 // Couldn't parse the initializer and we're not attempting to recover a failed
4057 // parse of the type, return the error.
4061 let hi = if self.token == token::Semi {
4070 id: ast::DUMMY_NODE_ID,
4076 /// Parse a structure field
4077 fn parse_name_and_ty(&mut self,
4080 attrs: Vec<Attribute>)
4081 -> PResult<'a, StructField> {
4082 let name = self.parse_ident()?;
4083 self.expect(&token::Colon)?;
4084 let ty = self.parse_ty()?;
4086 span: lo.to(self.prev_span),
4089 id: ast::DUMMY_NODE_ID,
4095 /// Emit an expected item after attributes error.
4096 fn expected_item_err(&self, attrs: &[Attribute]) {
4097 let message = match attrs.last() {
4098 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4099 _ => "expected item after attributes",
4102 self.span_err(self.prev_span, message);
4105 /// Parse a statement. This stops just before trailing semicolons on everything but items.
4106 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4107 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4108 Ok(self.parse_stmt_(true))
4111 // Eat tokens until we can be relatively sure we reached the end of the
4112 // statement. This is something of a best-effort heuristic.
4114 // We terminate when we find an unmatched `}` (without consuming it).
4115 fn recover_stmt(&mut self) {
4116 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4119 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4120 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4121 // approximate - it can mean we break too early due to macros, but that
4122 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
4124 // If `break_on_block` is `Break`, then we will stop consuming tokens
4125 // after finding (and consuming) a brace-delimited block.
4126 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4127 let mut brace_depth = 0;
4128 let mut bracket_depth = 0;
4129 let mut in_block = false;
4130 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4131 break_on_semi, break_on_block);
4133 debug!("recover_stmt_ loop {:?}", self.token);
4135 token::OpenDelim(token::DelimToken::Brace) => {
4138 if break_on_block == BlockMode::Break &&
4140 bracket_depth == 0 {
4144 token::OpenDelim(token::DelimToken::Bracket) => {
4148 token::CloseDelim(token::DelimToken::Brace) => {
4149 if brace_depth == 0 {
4150 debug!("recover_stmt_ return - close delim {:?}", self.token);
4155 if in_block && bracket_depth == 0 && brace_depth == 0 {
4156 debug!("recover_stmt_ return - block end {:?}", self.token);
4160 token::CloseDelim(token::DelimToken::Bracket) => {
4162 if bracket_depth < 0 {
4168 debug!("recover_stmt_ return - Eof");
4173 if break_on_semi == SemiColonMode::Break &&
4175 bracket_depth == 0 {
4176 debug!("recover_stmt_ return - Semi");
4187 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4188 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4190 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4195 fn is_catch_expr(&mut self) -> bool {
4196 self.token.is_keyword(keywords::Do) &&
4197 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4198 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4200 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
4201 !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4204 fn is_union_item(&self) -> bool {
4205 self.token.is_keyword(keywords::Union) &&
4206 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4209 fn is_crate_vis(&self) -> bool {
4210 self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4213 fn is_extern_non_path(&self) -> bool {
4214 self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4217 fn is_auto_trait_item(&mut self) -> bool {
4219 (self.token.is_keyword(keywords::Auto)
4220 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4221 || // unsafe auto trait
4222 (self.token.is_keyword(keywords::Unsafe) &&
4223 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4224 self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4227 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4228 -> PResult<'a, Option<P<Item>>> {
4229 let token_lo = self.span;
4230 let (ident, def) = match self.token {
4231 token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4233 let ident = self.parse_ident()?;
4234 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4235 match self.parse_token_tree() {
4236 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4237 _ => unreachable!(),
4239 } else if self.check(&token::OpenDelim(token::Paren)) {
4240 let args = self.parse_token_tree();
4241 let body = if self.check(&token::OpenDelim(token::Brace)) {
4242 self.parse_token_tree()
4247 TokenStream::concat(vec![
4249 TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4257 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4259 token::Ident(ident, _) if ident.name == "macro_rules" &&
4260 self.look_ahead(1, |t| *t == token::Not) => {
4261 let prev_span = self.prev_span;
4262 self.complain_if_pub_macro(&vis.node, prev_span);
4266 let ident = self.parse_ident()?;
4267 let (delim, tokens) = self.expect_delimited_token_tree()?;
4268 if delim != token::Brace {
4269 if !self.eat(&token::Semi) {
4270 let msg = "macros that expand to items must either \
4271 be surrounded with braces or followed by a semicolon";
4272 self.span_err(self.prev_span, msg);
4276 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4278 _ => return Ok(None),
4281 let span = lo.to(self.prev_span);
4282 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4285 fn parse_stmt_without_recovery(&mut self,
4286 macro_legacy_warnings: bool)
4287 -> PResult<'a, Option<Stmt>> {
4288 maybe_whole!(self, NtStmt, |x| Some(x));
4290 let attrs = self.parse_outer_attributes()?;
4293 Ok(Some(if self.eat_keyword(keywords::Let) {
4295 id: ast::DUMMY_NODE_ID,
4296 node: StmtKind::Local(self.parse_local(attrs.into())?),
4297 span: lo.to(self.prev_span),
4299 } else if let Some(macro_def) = self.eat_macro_def(
4301 &codemap::respan(lo, VisibilityKind::Inherited),
4305 id: ast::DUMMY_NODE_ID,
4306 node: StmtKind::Item(macro_def),
4307 span: lo.to(self.prev_span),
4309 // Starts like a simple path, being careful to avoid contextual keywords
4310 // such as a union items, item with `crate` visibility or auto trait items.
4311 // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4312 // like a path (1 token), but it fact not a path.
4313 // `union::b::c` - path, `union U { ... }` - not a path.
4314 // `crate::b::c` - path, `crate struct S;` - not a path.
4315 // `extern::b::c` - path, `extern crate c;` - not a path.
4316 } else if self.token.is_path_start() &&
4317 !self.token.is_qpath_start() &&
4318 !self.is_union_item() &&
4319 !self.is_crate_vis() &&
4320 !self.is_extern_non_path() &&
4321 !self.is_auto_trait_item() {
4322 let pth = self.parse_path(PathStyle::Expr)?;
4324 if !self.eat(&token::Not) {
4325 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4326 self.parse_struct_expr(lo, pth, ThinVec::new())?
4328 let hi = self.prev_span;
4329 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4332 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4333 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4334 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4337 return Ok(Some(Stmt {
4338 id: ast::DUMMY_NODE_ID,
4339 node: StmtKind::Expr(expr),
4340 span: lo.to(self.prev_span),
4344 // it's a macro invocation
4345 let id = match self.token {
4346 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4347 _ => self.parse_ident()?,
4350 // check that we're pointing at delimiters (need to check
4351 // again after the `if`, because of `parse_ident`
4352 // consuming more tokens).
4353 let delim = match self.token {
4354 token::OpenDelim(delim) => delim,
4356 // we only expect an ident if we didn't parse one
4358 let ident_str = if id.name == keywords::Invalid.name() {
4363 let tok_str = self.this_token_to_string();
4364 let mut err = self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4367 err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4372 let (_, tts) = self.expect_delimited_token_tree()?;
4373 let hi = self.prev_span;
4375 let style = if delim == token::Brace {
4376 MacStmtStyle::Braces
4378 MacStmtStyle::NoBraces
4381 if id.name == keywords::Invalid.name() {
4382 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
4383 let node = if delim == token::Brace ||
4384 self.token == token::Semi || self.token == token::Eof {
4385 StmtKind::Mac(P((mac, style, attrs.into())))
4387 // We used to incorrectly stop parsing macro-expanded statements here.
4388 // If the next token will be an error anyway but could have parsed with the
4389 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4390 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4391 // These can continue an expression, so we can't stop parsing and warn.
4392 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4393 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4394 token::BinOp(token::And) | token::BinOp(token::Or) |
4395 token::AndAnd | token::OrOr |
4396 token::DotDot | token::DotDotDot | token::DotDotEq => false,
4399 self.warn_missing_semicolon();
4400 StmtKind::Mac(P((mac, style, attrs.into())))
4402 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4403 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4404 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4408 id: ast::DUMMY_NODE_ID,
4413 // if it has a special ident, it's definitely an item
4415 // Require a semicolon or braces.
4416 if style != MacStmtStyle::Braces {
4417 if !self.eat(&token::Semi) {
4418 self.span_err(self.prev_span,
4419 "macros that expand to items must \
4420 either be surrounded with braces or \
4421 followed by a semicolon");
4424 let span = lo.to(hi);
4426 id: ast::DUMMY_NODE_ID,
4428 node: StmtKind::Item({
4430 span, id /*id is good here*/,
4431 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
4432 respan(lo, VisibilityKind::Inherited),
4438 // FIXME: Bad copy of attrs
4439 let old_directory_ownership =
4440 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4441 let item = self.parse_item_(attrs.clone(), false, true)?;
4442 self.directory.ownership = old_directory_ownership;
4446 id: ast::DUMMY_NODE_ID,
4447 span: lo.to(i.span),
4448 node: StmtKind::Item(i),
4451 let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4452 if !attrs.is_empty() {
4453 if s.prev_token_kind == PrevTokenKind::DocComment {
4454 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4455 } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4456 s.span_err(s.span, "expected statement after outer attribute");
4461 // Do not attempt to parse an expression if we're done here.
4462 if self.token == token::Semi {
4463 unused_attrs(&attrs, self);
4468 if self.token == token::CloseDelim(token::Brace) {
4469 unused_attrs(&attrs, self);
4473 // Remainder are line-expr stmts.
4474 let e = self.parse_expr_res(
4475 Restrictions::STMT_EXPR, Some(attrs.into()))?;
4477 id: ast::DUMMY_NODE_ID,
4478 span: lo.to(e.span),
4479 node: StmtKind::Expr(e),
4486 /// Is this expression a successfully-parsed statement?
4487 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4488 self.restrictions.contains(Restrictions::STMT_EXPR) &&
4489 !classify::expr_requires_semi_to_be_stmt(e)
4492 /// Parse a block. No inner attrs are allowed.
4493 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4494 maybe_whole!(self, NtBlock, |x| x);
4498 if !self.eat(&token::OpenDelim(token::Brace)) {
4500 let tok = self.this_token_to_string();
4501 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4503 // Check to see if the user has written something like
4508 // Which is valid in other languages, but not Rust.
4509 match self.parse_stmt_without_recovery(false) {
4511 if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) {
4512 // if the next token is an open brace (e.g., `if a b {`), the place-
4513 // inside-a-block suggestion would be more likely wrong than right
4516 let mut stmt_span = stmt.span;
4517 // expand the span to include the semicolon, if it exists
4518 if self.eat(&token::Semi) {
4519 stmt_span = stmt_span.with_hi(self.prev_span.hi());
4521 let sugg = pprust::to_string(|s| {
4522 use print::pprust::{PrintState, INDENT_UNIT};
4523 s.ibox(INDENT_UNIT)?;
4525 s.print_stmt(&stmt)?;
4526 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4528 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4531 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4532 self.cancel(&mut e);
4539 self.parse_block_tail(lo, BlockCheckMode::Default)
4542 /// Parse a block. Inner attrs are allowed.
4543 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4544 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4547 self.expect(&token::OpenDelim(token::Brace))?;
4548 Ok((self.parse_inner_attributes()?,
4549 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4552 /// Parse the rest of a block expression or function body
4553 /// Precondition: already parsed the '{'.
4554 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4555 let mut stmts = vec![];
4556 let mut recovered = false;
4558 while !self.eat(&token::CloseDelim(token::Brace)) {
4559 let stmt = match self.parse_full_stmt(false) {
4562 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4563 self.eat(&token::CloseDelim(token::Brace));
4569 if let Some(stmt) = stmt {
4571 } else if self.token == token::Eof {
4574 // Found only `;` or `}`.
4580 id: ast::DUMMY_NODE_ID,
4582 span: lo.to(self.prev_span),
4587 /// Parse a statement, including the trailing semicolon.
4588 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4589 // skip looking for a trailing semicolon when we have an interpolated statement
4590 maybe_whole!(self, NtStmt, |x| Some(x));
4592 let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4594 None => return Ok(None),
4598 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4599 // expression without semicolon
4600 if classify::expr_requires_semi_to_be_stmt(expr) {
4601 // Just check for errors and recover; do not eat semicolon yet.
4603 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4606 self.recover_stmt();
4610 StmtKind::Local(..) => {
4611 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4612 if macro_legacy_warnings && self.token != token::Semi {
4613 self.warn_missing_semicolon();
4615 self.expect_one_of(&[token::Semi], &[])?;
4621 if self.eat(&token::Semi) {
4622 stmt = stmt.add_trailing_semicolon();
4625 stmt.span = stmt.span.with_hi(self.prev_span.hi());
4629 fn warn_missing_semicolon(&self) {
4630 self.diagnostic().struct_span_warn(self.span, {
4631 &format!("expected `;`, found `{}`", self.this_token_to_string())
4633 "This was erroneously allowed and will become a hard error in a future release"
4637 fn err_dotdotdot_syntax(&self, span: Span) {
4638 self.diagnostic().struct_span_err(span, {
4639 "`...` syntax cannot be used in expressions"
4641 "Use `..` if you need an exclusive range (a < b)"
4643 "or `..=` if you need an inclusive range (a <= b)"
4647 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4648 // BOUND = TY_BOUND | LT_BOUND
4649 // LT_BOUND = LIFETIME (e.g. `'a`)
4650 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4651 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4652 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4653 let mut bounds = Vec::new();
4655 // This needs to be syncronized with `Token::can_begin_bound`.
4656 let is_bound_start = self.check_path() || self.check_lifetime() ||
4657 self.check(&token::Question) ||
4658 self.check_keyword(keywords::For) ||
4659 self.check(&token::OpenDelim(token::Paren));
4661 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4662 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4663 if self.token.is_lifetime() {
4664 if let Some(question_span) = question {
4665 self.span_err(question_span,
4666 "`?` may only modify trait bounds, not lifetime bounds");
4668 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4671 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4672 let path = self.parse_path(PathStyle::Type)?;
4673 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4674 let modifier = if question.is_some() {
4675 TraitBoundModifier::Maybe
4677 TraitBoundModifier::None
4679 bounds.push(TraitTyParamBound(poly_trait, modifier));
4682 self.expect(&token::CloseDelim(token::Paren))?;
4683 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4684 self.span_err(self.prev_span,
4685 "parenthesized lifetime bounds are not supported");
4692 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4700 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4701 self.parse_ty_param_bounds_common(true)
4704 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4705 // BOUND = LT_BOUND (e.g. `'a`)
4706 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4707 let mut lifetimes = Vec::new();
4708 while self.check_lifetime() {
4709 lifetimes.push(self.expect_lifetime());
4711 if !self.eat(&token::BinOp(token::Plus)) {
4718 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4719 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4720 let ident = self.parse_ident()?;
4722 // Parse optional colon and param bounds.
4723 let bounds = if self.eat(&token::Colon) {
4724 self.parse_ty_param_bounds()?
4729 let default = if self.eat(&token::Eq) {
4730 Some(self.parse_ty()?)
4736 attrs: preceding_attrs.into(),
4738 id: ast::DUMMY_NODE_ID,
4744 /// Parses the following grammar:
4745 /// TraitItemAssocTy = Ident ["<"...">"] [":" [TyParamBounds]] ["where" ...] ["=" Ty]
4746 fn parse_trait_item_assoc_ty(&mut self, preceding_attrs: Vec<Attribute>)
4747 -> PResult<'a, (ast::Generics, TyParam)> {
4748 let ident = self.parse_ident()?;
4749 let mut generics = self.parse_generics()?;
4751 // Parse optional colon and param bounds.
4752 let bounds = if self.eat(&token::Colon) {
4753 self.parse_ty_param_bounds()?
4757 generics.where_clause = self.parse_where_clause()?;
4759 let default = if self.eat(&token::Eq) {
4760 Some(self.parse_ty()?)
4764 self.expect(&token::Semi)?;
4766 Ok((generics, TyParam {
4767 attrs: preceding_attrs.into(),
4769 id: ast::DUMMY_NODE_ID,
4775 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4776 /// trailing comma and erroneous trailing attributes.
4777 pub fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4778 let mut params = Vec::new();
4779 let mut seen_ty_param = false;
4781 let attrs = self.parse_outer_attributes()?;
4782 if self.check_lifetime() {
4783 let lifetime = self.expect_lifetime();
4784 // Parse lifetime parameter.
4785 let bounds = if self.eat(&token::Colon) {
4786 self.parse_lt_param_bounds()
4790 params.push(ast::GenericParam::Lifetime(LifetimeDef {
4791 attrs: attrs.into(),
4796 self.span_err(self.prev_span,
4797 "lifetime parameters must be declared prior to type parameters");
4799 } else if self.check_ident() {
4800 // Parse type parameter.
4801 params.push(ast::GenericParam::Type(self.parse_ty_param(attrs)?));
4802 seen_ty_param = true;
4804 // Check for trailing attributes and stop parsing.
4805 if !attrs.is_empty() {
4806 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4807 self.span_err(attrs[0].span,
4808 &format!("trailing attribute after {} parameters", param_kind));
4813 if !self.eat(&token::Comma) {
4820 /// Parse a set of optional generic type parameter declarations. Where
4821 /// clauses are not parsed here, and must be added later via
4822 /// `parse_where_clause()`.
4824 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4825 /// | ( < lifetimes , typaramseq ( , )? > )
4826 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4827 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4828 maybe_whole!(self, NtGenerics, |x| x);
4830 let span_lo = self.span;
4832 let params = self.parse_generic_params()?;
4836 where_clause: WhereClause {
4837 id: ast::DUMMY_NODE_ID,
4838 predicates: Vec::new(),
4839 span: syntax_pos::DUMMY_SP,
4841 span: span_lo.to(self.prev_span),
4844 Ok(ast::Generics::default())
4848 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4849 /// possibly including trailing comma.
4850 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4851 let mut lifetimes = Vec::new();
4852 let mut types = Vec::new();
4853 let mut bindings = Vec::new();
4854 let mut seen_type = false;
4855 let mut seen_binding = false;
4857 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4858 // Parse lifetime argument.
4859 lifetimes.push(self.expect_lifetime());
4860 if seen_type || seen_binding {
4861 self.span_err(self.prev_span,
4862 "lifetime parameters must be declared prior to type parameters");
4864 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4865 // Parse associated type binding.
4867 let ident = self.parse_ident()?;
4869 let ty = self.parse_ty()?;
4870 bindings.push(TypeBinding {
4871 id: ast::DUMMY_NODE_ID,
4874 span: lo.to(self.prev_span),
4876 seen_binding = true;
4877 } else if self.check_type() {
4878 // Parse type argument.
4879 types.push(self.parse_ty()?);
4881 self.span_err(types[types.len() - 1].span,
4882 "type parameters must be declared prior to associated type bindings");
4889 if !self.eat(&token::Comma) {
4893 Ok((lifetimes, types, bindings))
4896 /// Parses an optional `where` clause and places it in `generics`.
4898 /// ```ignore (only-for-syntax-highlight)
4899 /// where T : Trait<U, V> + 'b, 'a : 'b
4901 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4902 maybe_whole!(self, NtWhereClause, |x| x);
4904 let mut where_clause = WhereClause {
4905 id: ast::DUMMY_NODE_ID,
4906 predicates: Vec::new(),
4907 span: syntax_pos::DUMMY_SP,
4910 if !self.eat_keyword(keywords::Where) {
4911 return Ok(where_clause);
4913 let lo = self.prev_span;
4915 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4916 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4917 // change we parse those generics now, but report an error.
4918 if self.choose_generics_over_qpath() {
4919 let generics = self.parse_generics()?;
4920 self.span_err(generics.span,
4921 "generic parameters on `where` clauses are reserved for future use");
4926 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4927 let lifetime = self.expect_lifetime();
4928 // Bounds starting with a colon are mandatory, but possibly empty.
4929 self.expect(&token::Colon)?;
4930 let bounds = self.parse_lt_param_bounds();
4931 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4932 ast::WhereRegionPredicate {
4933 span: lo.to(self.prev_span),
4938 } else if self.check_type() {
4939 // Parse optional `for<'a, 'b>`.
4940 // This `for` is parsed greedily and applies to the whole predicate,
4941 // the bounded type can have its own `for` applying only to it.
4942 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4943 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4944 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4945 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4947 // Parse type with mandatory colon and (possibly empty) bounds,
4948 // or with mandatory equality sign and the second type.
4949 let ty = self.parse_ty()?;
4950 if self.eat(&token::Colon) {
4951 let bounds = self.parse_ty_param_bounds()?;
4952 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4953 ast::WhereBoundPredicate {
4954 span: lo.to(self.prev_span),
4955 bound_generic_params: lifetime_defs,
4960 // FIXME: Decide what should be used here, `=` or `==`.
4961 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
4962 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4963 let rhs_ty = self.parse_ty()?;
4964 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4965 ast::WhereEqPredicate {
4966 span: lo.to(self.prev_span),
4969 id: ast::DUMMY_NODE_ID,
4973 return self.unexpected();
4979 if !self.eat(&token::Comma) {
4984 where_clause.span = lo.to(self.prev_span);
4988 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4989 -> PResult<'a, (Vec<Arg> , bool)> {
4991 let mut variadic = false;
4992 let args: Vec<Option<Arg>> =
4993 self.parse_unspanned_seq(
4994 &token::OpenDelim(token::Paren),
4995 &token::CloseDelim(token::Paren),
4996 SeqSep::trailing_allowed(token::Comma),
4998 if p.token == token::DotDotDot {
5002 if p.token != token::CloseDelim(token::Paren) {
5005 "`...` must be last in argument list for variadic function");
5009 let span = p.prev_span;
5010 if p.token == token::CloseDelim(token::Paren) {
5011 // continue parsing to present any further errors
5014 "only foreign functions are allowed to be variadic"
5016 Ok(Some(dummy_arg(span)))
5018 // this function definition looks beyond recovery, stop parsing
5020 "only foreign functions are allowed to be variadic");
5025 match p.parse_arg_general(named_args) {
5026 Ok(arg) => Ok(Some(arg)),
5029 let lo = p.prev_span;
5030 // Skip every token until next possible arg or end.
5031 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5032 // Create a placeholder argument for proper arg count (#34264).
5033 let span = lo.to(p.prev_span);
5034 Ok(Some(dummy_arg(span)))
5041 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5043 if variadic && args.is_empty() {
5045 "variadic function must be declared with at least one named argument");
5048 Ok((args, variadic))
5051 /// Parse the argument list and result type of a function declaration
5052 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5054 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5055 let ret_ty = self.parse_ret_ty(true)?;
5064 /// Returns the parsed optional self argument and whether a self shortcut was used.
5065 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5066 let expect_ident = |this: &mut Self| match this.token {
5067 // Preserve hygienic context.
5068 token::Ident(ident, _) =>
5069 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5072 let isolated_self = |this: &mut Self, n| {
5073 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5074 this.look_ahead(n + 1, |t| t != &token::ModSep)
5077 // Parse optional self parameter of a method.
5078 // Only a limited set of initial token sequences is considered self parameters, anything
5079 // else is parsed as a normal function parameter list, so some lookahead is required.
5080 let eself_lo = self.span;
5081 let (eself, eself_ident) = match self.token {
5082 token::BinOp(token::And) => {
5088 if isolated_self(self, 1) {
5090 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
5091 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5092 isolated_self(self, 2) {
5095 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
5096 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5097 isolated_self(self, 2) {
5099 let lt = self.expect_lifetime();
5100 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
5101 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5102 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5103 isolated_self(self, 3) {
5105 let lt = self.expect_lifetime();
5107 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
5112 token::BinOp(token::Star) => {
5117 // Emit special error for `self` cases.
5118 if isolated_self(self, 1) {
5120 self.span_err(self.span, "cannot pass `self` by raw pointer");
5121 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
5122 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5123 isolated_self(self, 2) {
5126 self.span_err(self.span, "cannot pass `self` by raw pointer");
5127 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
5132 token::Ident(..) => {
5133 if isolated_self(self, 0) {
5136 let eself_ident = expect_ident(self);
5137 if self.eat(&token::Colon) {
5138 let ty = self.parse_ty()?;
5139 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
5141 (SelfKind::Value(Mutability::Immutable), eself_ident)
5143 } else if self.token.is_keyword(keywords::Mut) &&
5144 isolated_self(self, 1) {
5148 let eself_ident = expect_ident(self);
5149 if self.eat(&token::Colon) {
5150 let ty = self.parse_ty()?;
5151 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
5153 (SelfKind::Value(Mutability::Mutable), eself_ident)
5159 _ => return Ok(None),
5162 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
5163 Ok(Some(Arg::from_self(eself, eself_ident)))
5166 /// Parse the parameter list and result type of a function that may have a `self` parameter.
5167 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5168 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
5170 self.expect(&token::OpenDelim(token::Paren))?;
5172 // Parse optional self argument
5173 let self_arg = self.parse_self_arg()?;
5175 // Parse the rest of the function parameter list.
5176 let sep = SeqSep::trailing_allowed(token::Comma);
5177 let fn_inputs = if let Some(self_arg) = self_arg {
5178 if self.check(&token::CloseDelim(token::Paren)) {
5180 } else if self.eat(&token::Comma) {
5181 let mut fn_inputs = vec![self_arg];
5182 fn_inputs.append(&mut self.parse_seq_to_before_end(
5183 &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5187 return self.unexpected();
5190 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5193 // Parse closing paren and return type.
5194 self.expect(&token::CloseDelim(token::Paren))?;
5197 output: self.parse_ret_ty(true)?,
5202 // parse the |arg, arg| header on a lambda
5203 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5204 let inputs_captures = {
5205 if self.eat(&token::OrOr) {
5208 self.expect(&token::BinOp(token::Or))?;
5209 let args = self.parse_seq_to_before_tokens(
5210 &[&token::BinOp(token::Or), &token::OrOr],
5211 SeqSep::trailing_allowed(token::Comma),
5212 TokenExpectType::NoExpect,
5213 |p| p.parse_fn_block_arg()
5219 let output = self.parse_ret_ty(true)?;
5222 inputs: inputs_captures,
5228 /// Parse the name and optional generic types of a function header.
5229 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5230 let id = self.parse_ident()?;
5231 let generics = self.parse_generics()?;
5235 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5236 attrs: Vec<Attribute>) -> P<Item> {
5240 id: ast::DUMMY_NODE_ID,
5248 /// Parse an item-position function declaration.
5249 fn parse_item_fn(&mut self,
5251 constness: Spanned<Constness>,
5253 -> PResult<'a, ItemInfo> {
5254 let (ident, mut generics) = self.parse_fn_header()?;
5255 let decl = self.parse_fn_decl(false)?;
5256 generics.where_clause = self.parse_where_clause()?;
5257 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5258 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
5261 /// true if we are looking at `const ID`, false for things like `const fn` etc
5262 pub fn is_const_item(&mut self) -> bool {
5263 self.token.is_keyword(keywords::Const) &&
5264 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5265 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5268 /// parses all the "front matter" for a `fn` declaration, up to
5269 /// and including the `fn` keyword:
5273 /// - `const unsafe fn`
5276 pub fn parse_fn_front_matter(&mut self) -> PResult<'a, (Spanned<Constness>, Unsafety, Abi)> {
5277 let is_const_fn = self.eat_keyword(keywords::Const);
5278 let const_span = self.prev_span;
5279 let unsafety = self.parse_unsafety();
5280 let (constness, unsafety, abi) = if is_const_fn {
5281 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5283 let abi = if self.eat_keyword(keywords::Extern) {
5284 self.parse_opt_abi()?.unwrap_or(Abi::C)
5288 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5290 self.expect_keyword(keywords::Fn)?;
5291 Ok((constness, unsafety, abi))
5294 /// Parse an impl item.
5295 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5296 maybe_whole!(self, NtImplItem, |x| x);
5297 let attrs = self.parse_outer_attributes()?;
5298 let (mut item, tokens) = self.collect_tokens(|this| {
5299 this.parse_impl_item_(at_end, attrs)
5302 // See `parse_item` for why this clause is here.
5303 if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5304 item.tokens = Some(tokens);
5309 fn parse_impl_item_(&mut self,
5311 mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5313 let vis = self.parse_visibility(false)?;
5314 let defaultness = self.parse_defaultness();
5315 let (name, node, generics) = if self.eat_keyword(keywords::Type) {
5316 // This parses the grammar:
5317 // ImplItemAssocTy = Ident ["<"...">"] ["where" ...] "=" Ty ";"
5318 let name = self.parse_ident()?;
5319 let mut generics = self.parse_generics()?;
5320 generics.where_clause = self.parse_where_clause()?;
5321 self.expect(&token::Eq)?;
5322 let typ = self.parse_ty()?;
5323 self.expect(&token::Semi)?;
5324 (name, ast::ImplItemKind::Type(typ), generics)
5325 } else if self.is_const_item() {
5326 // This parses the grammar:
5327 // ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5328 self.expect_keyword(keywords::Const)?;
5329 let name = self.parse_ident()?;
5330 self.expect(&token::Colon)?;
5331 let typ = self.parse_ty()?;
5332 self.expect(&token::Eq)?;
5333 let expr = self.parse_expr()?;
5334 self.expect(&token::Semi)?;
5335 (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5337 let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5338 attrs.extend(inner_attrs);
5339 (name, node, generics)
5343 id: ast::DUMMY_NODE_ID,
5344 span: lo.to(self.prev_span),
5355 fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5356 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5361 fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5363 VisibilityKind::Inherited => Ok(()),
5365 let is_macro_rules: bool = match self.token {
5366 token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5370 let mut err = self.diagnostic()
5371 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5372 err.span_suggestion(sp,
5373 "try exporting the macro",
5374 "#[macro_export]".to_owned());
5377 let mut err = self.diagnostic()
5378 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5379 err.help("try adjusting the macro to put `pub` inside the invocation");
5386 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5387 -> DiagnosticBuilder<'a>
5389 let expected_kinds = if item_type == "extern" {
5390 "missing `fn`, `type`, or `static`"
5392 "missing `fn`, `type`, or `const`"
5395 // Given this code `path(`, it seems like this is not
5396 // setting the visibility of a macro invocation, but rather
5397 // a mistyped method declaration.
5398 // Create a diagnostic pointing out that `fn` is missing.
5400 // x | pub path(&self) {
5401 // | ^ missing `fn`, `type`, or `const`
5403 // ^^ `sp` below will point to this
5404 let sp = prev_span.between(self.prev_span);
5405 let mut err = self.diagnostic().struct_span_err(
5407 &format!("{} for {}-item declaration",
5408 expected_kinds, item_type));
5409 err.span_label(sp, expected_kinds);
5413 /// Parse a method or a macro invocation in a trait impl.
5414 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5415 -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5416 ast::ImplItemKind)> {
5417 // code copied from parse_macro_use_or_failure... abstraction!
5418 if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5420 Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5421 ast::ImplItemKind::Macro(mac)))
5423 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
5424 let ident = self.parse_ident()?;
5425 let mut generics = self.parse_generics()?;
5426 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5427 generics.where_clause = self.parse_where_clause()?;
5429 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5430 Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(ast::MethodSig {
5439 /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5440 fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5441 let ident = self.parse_ident()?;
5442 let mut tps = self.parse_generics()?;
5444 // Parse optional colon and supertrait bounds.
5445 let bounds = if self.eat(&token::Colon) {
5446 self.parse_ty_param_bounds()?
5451 if self.eat(&token::Eq) {
5452 // it's a trait alias
5453 let bounds = self.parse_ty_param_bounds()?;
5454 tps.where_clause = self.parse_where_clause()?;
5455 self.expect(&token::Semi)?;
5456 if unsafety != Unsafety::Normal {
5457 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5459 Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5461 // it's a normal trait
5462 tps.where_clause = self.parse_where_clause()?;
5463 self.expect(&token::OpenDelim(token::Brace))?;
5464 let mut trait_items = vec![];
5465 while !self.eat(&token::CloseDelim(token::Brace)) {
5466 let mut at_end = false;
5467 match self.parse_trait_item(&mut at_end) {
5468 Ok(item) => trait_items.push(item),
5472 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5477 Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5481 fn choose_generics_over_qpath(&self) -> bool {
5482 // There's an ambiguity between generic parameters and qualified paths in impls.
5483 // If we see `<` it may start both, so we have to inspect some following tokens.
5484 // The following combinations can only start generics,
5485 // but not qualified paths (with one exception):
5486 // `<` `>` - empty generic parameters
5487 // `<` `#` - generic parameters with attributes
5488 // `<` (LIFETIME|IDENT) `>` - single generic parameter
5489 // `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5490 // `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5491 // `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5492 // The only truly ambiguous case is
5493 // `<` IDENT `>` `::` IDENT ...
5494 // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5495 // because this is what almost always expected in practice, qualified paths in impls
5496 // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5497 self.token == token::Lt &&
5498 (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5499 self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5500 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5501 t == &token::Colon || t == &token::Eq))
5504 fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5505 self.expect(&token::OpenDelim(token::Brace))?;
5506 let attrs = self.parse_inner_attributes()?;
5508 let mut impl_items = Vec::new();
5509 while !self.eat(&token::CloseDelim(token::Brace)) {
5510 let mut at_end = false;
5511 match self.parse_impl_item(&mut at_end) {
5512 Ok(impl_item) => impl_items.push(impl_item),
5516 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5521 Ok((impl_items, attrs))
5524 /// Parses an implementation item, `impl` keyword is already parsed.
5525 /// impl<'a, T> TYPE { /* impl items */ }
5526 /// impl<'a, T> TRAIT for TYPE { /* impl items */ }
5527 /// impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5528 /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5529 /// `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5530 /// `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5531 fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5532 -> PResult<'a, ItemInfo> {
5533 // First, parse generic parameters if necessary.
5534 let mut generics = if self.choose_generics_over_qpath() {
5535 self.parse_generics()?
5537 ast::Generics::default()
5540 // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5541 let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5543 ast::ImplPolarity::Negative
5545 ast::ImplPolarity::Positive
5548 // Parse both types and traits as a type, then reinterpret if necessary.
5549 let ty_first = self.parse_ty()?;
5551 // If `for` is missing we try to recover.
5552 let has_for = self.eat_keyword(keywords::For);
5553 let missing_for_span = self.prev_span.between(self.span);
5555 let ty_second = if self.token == token::DotDot {
5556 // We need to report this error after `cfg` expansion for compatibility reasons
5557 self.bump(); // `..`, do not add it to expected tokens
5558 Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5559 } else if has_for || self.token.can_begin_type() {
5560 Some(self.parse_ty()?)
5565 generics.where_clause = self.parse_where_clause()?;
5567 let (impl_items, attrs) = self.parse_impl_body()?;
5569 let item_kind = match ty_second {
5570 Some(ty_second) => {
5571 // impl Trait for Type
5573 self.span_err(missing_for_span, "missing `for` in a trait impl");
5576 let ty_first = ty_first.into_inner();
5577 let path = match ty_first.node {
5578 // This notably includes paths passed through `ty` macro fragments (#46438).
5579 TyKind::Path(None, path) => path,
5581 self.span_err(ty_first.span, "expected a trait, found type");
5582 ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
5585 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5587 ItemKind::Impl(unsafety, polarity, defaultness,
5588 generics, Some(trait_ref), ty_second, impl_items)
5592 ItemKind::Impl(unsafety, polarity, defaultness,
5593 generics, None, ty_first, impl_items)
5597 Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5600 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5601 if self.eat_keyword(keywords::For) {
5603 let params = self.parse_generic_params()?;
5605 // We rely on AST validation to rule out invalid cases: There must not be type
5606 // parameters, and the lifetime parameters must not have bounds.
5613 /// Parse struct Foo { ... }
5614 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5615 let class_name = self.parse_ident()?;
5617 let mut generics = self.parse_generics()?;
5619 // There is a special case worth noting here, as reported in issue #17904.
5620 // If we are parsing a tuple struct it is the case that the where clause
5621 // should follow the field list. Like so:
5623 // struct Foo<T>(T) where T: Copy;
5625 // If we are parsing a normal record-style struct it is the case
5626 // that the where clause comes before the body, and after the generics.
5627 // So if we look ahead and see a brace or a where-clause we begin
5628 // parsing a record style struct.
5630 // Otherwise if we look ahead and see a paren we parse a tuple-style
5633 let vdata = if self.token.is_keyword(keywords::Where) {
5634 generics.where_clause = self.parse_where_clause()?;
5635 if self.eat(&token::Semi) {
5636 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5637 VariantData::Unit(ast::DUMMY_NODE_ID)
5639 // If we see: `struct Foo<T> where T: Copy { ... }`
5640 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5642 // No `where` so: `struct Foo<T>;`
5643 } else if self.eat(&token::Semi) {
5644 VariantData::Unit(ast::DUMMY_NODE_ID)
5645 // Record-style struct definition
5646 } else if self.token == token::OpenDelim(token::Brace) {
5647 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5648 // Tuple-style struct definition with optional where-clause.
5649 } else if self.token == token::OpenDelim(token::Paren) {
5650 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5651 generics.where_clause = self.parse_where_clause()?;
5652 self.expect(&token::Semi)?;
5655 let token_str = self.this_token_to_string();
5656 let mut err = self.fatal(&format!(
5657 "expected `where`, `{{`, `(`, or `;` after struct name, found `{}`",
5660 err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
5664 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5667 /// Parse union Foo { ... }
5668 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5669 let class_name = self.parse_ident()?;
5671 let mut generics = self.parse_generics()?;
5673 let vdata = if self.token.is_keyword(keywords::Where) {
5674 generics.where_clause = self.parse_where_clause()?;
5675 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5676 } else if self.token == token::OpenDelim(token::Brace) {
5677 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5679 let token_str = self.this_token_to_string();
5680 let mut err = self.fatal(&format!(
5681 "expected `where` or `{{` after union name, found `{}`", token_str));
5682 err.span_label(self.span, "expected `where` or `{` after union name");
5686 Ok((class_name, ItemKind::Union(vdata, generics), None))
5689 fn consume_block(&mut self, delim: token::DelimToken) {
5690 let mut brace_depth = 0;
5691 if !self.eat(&token::OpenDelim(delim)) {
5695 if self.eat(&token::OpenDelim(delim)) {
5697 } else if self.eat(&token::CloseDelim(delim)) {
5698 if brace_depth == 0 {
5704 } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5712 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5713 let mut fields = Vec::new();
5714 if self.eat(&token::OpenDelim(token::Brace)) {
5715 while self.token != token::CloseDelim(token::Brace) {
5716 let field = self.parse_struct_decl_field().map_err(|e| {
5717 self.recover_stmt();
5721 Ok(field) => fields.push(field),
5727 self.eat(&token::CloseDelim(token::Brace));
5729 let token_str = self.this_token_to_string();
5730 let mut err = self.fatal(&format!(
5731 "expected `where`, or `{{` after struct name, found `{}`", token_str));
5732 err.span_label(self.span, "expected `where`, or `{` after struct name");
5739 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5740 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5741 // Unit like structs are handled in parse_item_struct function
5742 let fields = self.parse_unspanned_seq(
5743 &token::OpenDelim(token::Paren),
5744 &token::CloseDelim(token::Paren),
5745 SeqSep::trailing_allowed(token::Comma),
5747 let attrs = p.parse_outer_attributes()?;
5749 let vis = p.parse_visibility(true)?;
5750 let ty = p.parse_ty()?;
5752 span: lo.to(ty.span),
5755 id: ast::DUMMY_NODE_ID,
5764 /// Parse a structure field declaration
5765 pub fn parse_single_struct_field(&mut self,
5768 attrs: Vec<Attribute> )
5769 -> PResult<'a, StructField> {
5770 let mut seen_comma: bool = false;
5771 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5772 if self.token == token::Comma {
5779 token::CloseDelim(token::Brace) => {}
5780 token::DocComment(_) => {
5781 let previous_span = self.prev_span;
5782 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
5783 self.bump(); // consume the doc comment
5784 let comma_after_doc_seen = self.eat(&token::Comma);
5785 // `seen_comma` is always false, because we are inside doc block
5786 // condition is here to make code more readable
5787 if seen_comma == false && comma_after_doc_seen == true {
5790 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
5793 if seen_comma == false {
5794 let sp = self.sess.codemap().next_point(previous_span);
5795 err.span_suggestion(sp, "missing comma here", ",".into());
5800 _ => return Err(self.span_fatal_help(self.span,
5801 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5802 "struct fields should be separated by commas")),
5807 /// Parse an element of a struct definition
5808 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5809 let attrs = self.parse_outer_attributes()?;
5811 let vis = self.parse_visibility(false)?;
5812 self.parse_single_struct_field(lo, vis, attrs)
5815 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5816 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5817 /// a function definition, it's not a tuple struct field) and the contents within the parens
5818 /// isn't valid, emit a proper diagnostic.
5819 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5820 maybe_whole!(self, NtVis, |x| x);
5822 self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
5823 if self.is_crate_vis() {
5824 self.bump(); // `crate`
5825 return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
5828 if !self.eat_keyword(keywords::Pub) {
5829 return Ok(respan(self.prev_span, VisibilityKind::Inherited))
5831 let lo = self.prev_span;
5833 if self.check(&token::OpenDelim(token::Paren)) {
5834 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5835 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5836 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5837 // by the following tokens.
5838 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5841 self.bump(); // `crate`
5842 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5844 lo.to(self.prev_span),
5845 VisibilityKind::Crate(CrateSugar::PubCrate),
5848 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5851 self.bump(); // `in`
5852 let path = self.parse_path(PathStyle::Mod)?; // `path`
5853 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5854 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
5856 id: ast::DUMMY_NODE_ID,
5859 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5860 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5861 t.is_keyword(keywords::SelfValue))
5863 // `pub(self)` or `pub(super)`
5865 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
5866 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5867 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
5869 id: ast::DUMMY_NODE_ID,
5872 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5873 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5875 let msg = "incorrect visibility restriction";
5876 let suggestion = r##"some possible visibility restrictions are:
5877 `pub(crate)`: visible only on the current crate
5878 `pub(super)`: visible only in the current module's parent
5879 `pub(in path::to::module)`: visible only on the specified path"##;
5880 let path = self.parse_path(PathStyle::Mod)?;
5881 let path_span = self.prev_span;
5882 let help_msg = format!("make this visible only to module `{}` with `in`", path);
5883 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5884 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5885 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5886 err.emit(); // emit diagnostic, but continue with public visibility
5890 Ok(respan(lo, VisibilityKind::Public))
5893 /// Parse defaultness: `default` or nothing.
5894 fn parse_defaultness(&mut self) -> Defaultness {
5895 // `pub` is included for better error messages
5896 if self.check_keyword(keywords::Default) &&
5897 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
5898 t.is_keyword(keywords::Const) ||
5899 t.is_keyword(keywords::Fn) ||
5900 t.is_keyword(keywords::Unsafe) ||
5901 t.is_keyword(keywords::Extern) ||
5902 t.is_keyword(keywords::Type) ||
5903 t.is_keyword(keywords::Pub)) {
5904 self.bump(); // `default`
5905 Defaultness::Default
5911 /// Given a termination token, parse all of the items in a module
5912 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5913 let mut items = vec![];
5914 while let Some(item) = self.parse_item()? {
5918 if !self.eat(term) {
5919 let token_str = self.this_token_to_string();
5920 let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
5921 if token_str == ";" {
5922 let msg = "consider removing this semicolon";
5923 err.span_suggestion_short(self.span, msg, "".to_string());
5925 err.span_label(self.span, "expected item");
5930 let hi = if self.span == syntax_pos::DUMMY_SP {
5937 inner: inner_lo.to(hi),
5942 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5943 let id = self.parse_ident()?;
5944 self.expect(&token::Colon)?;
5945 let ty = self.parse_ty()?;
5946 self.expect(&token::Eq)?;
5947 let e = self.parse_expr()?;
5948 self.expect(&token::Semi)?;
5949 let item = match m {
5950 Some(m) => ItemKind::Static(ty, m, e),
5951 None => ItemKind::Const(ty, e),
5953 Ok((id, item, None))
5956 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5957 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5958 let (in_cfg, outer_attrs) = {
5959 let mut strip_unconfigured = ::config::StripUnconfigured {
5961 should_test: false, // irrelevant
5962 features: None, // don't perform gated feature checking
5964 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5965 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5968 let id_span = self.span;
5969 let id = self.parse_ident()?;
5970 if self.check(&token::Semi) {
5972 if in_cfg && self.recurse_into_file_modules {
5973 // This mod is in an external file. Let's go get it!
5974 let ModulePathSuccess { path, directory_ownership, warn } =
5975 self.submod_path(id, &outer_attrs, id_span)?;
5976 let (module, mut attrs) =
5977 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5979 let attr = Attribute {
5980 id: attr::mk_attr_id(),
5981 style: ast::AttrStyle::Outer,
5982 path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
5983 tokens: TokenStream::empty(),
5984 is_sugared_doc: false,
5985 span: syntax_pos::DUMMY_SP,
5987 attr::mark_known(&attr);
5990 Ok((id, module, Some(attrs)))
5992 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5993 Ok((id, ItemKind::Mod(placeholder), None))
5996 let old_directory = self.directory.clone();
5997 self.push_directory(id, &outer_attrs);
5999 self.expect(&token::OpenDelim(token::Brace))?;
6000 let mod_inner_lo = self.span;
6001 let attrs = self.parse_inner_attributes()?;
6002 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6004 self.directory = old_directory;
6005 Ok((id, ItemKind::Mod(module), Some(attrs)))
6009 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6010 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6011 self.directory.path.push(&path.as_str());
6012 self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6014 self.directory.path.push(&id.name.as_str());
6018 pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6019 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
6022 /// Returns either a path to a module, or .
6023 pub fn default_submod_path(
6025 relative: Option<ast::Ident>,
6027 codemap: &CodeMap) -> ModulePath
6029 // If we're in a foo.rs file instead of a mod.rs file,
6030 // we need to look for submodules in
6031 // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6032 // `./<id>.rs` and `./<id>/mod.rs`.
6033 let relative_prefix_string;
6034 let relative_prefix = if let Some(ident) = relative {
6035 relative_prefix_string = format!("{}{}", ident.name.as_str(), path::MAIN_SEPARATOR);
6036 &relative_prefix_string
6041 let mod_name = id.to_string();
6042 let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6043 let secondary_path_str = format!("{}{}{}mod.rs",
6044 relative_prefix, mod_name, path::MAIN_SEPARATOR);
6045 let default_path = dir_path.join(&default_path_str);
6046 let secondary_path = dir_path.join(&secondary_path_str);
6047 let default_exists = codemap.file_exists(&default_path);
6048 let secondary_exists = codemap.file_exists(&secondary_path);
6050 let result = match (default_exists, secondary_exists) {
6051 (true, false) => Ok(ModulePathSuccess {
6053 directory_ownership: DirectoryOwnership::Owned {
6058 (false, true) => Ok(ModulePathSuccess {
6059 path: secondary_path,
6060 directory_ownership: DirectoryOwnership::Owned {
6065 (false, false) => Err(Error::FileNotFoundForModule {
6066 mod_name: mod_name.clone(),
6067 default_path: default_path_str,
6068 secondary_path: secondary_path_str,
6069 dir_path: format!("{}", dir_path.display()),
6071 (true, true) => Err(Error::DuplicatePaths {
6072 mod_name: mod_name.clone(),
6073 default_path: default_path_str,
6074 secondary_path: secondary_path_str,
6080 path_exists: default_exists || secondary_exists,
6085 fn submod_path(&mut self,
6087 outer_attrs: &[Attribute],
6089 -> PResult<'a, ModulePathSuccess> {
6090 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6091 return Ok(ModulePathSuccess {
6092 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6093 // All `#[path]` files are treated as though they are a `mod.rs` file.
6094 // This means that `mod foo;` declarations inside `#[path]`-included
6095 // files are siblings,
6097 // Note that this will produce weirdness when a file named `foo.rs` is
6098 // `#[path]` included and contains a `mod foo;` declaration.
6099 // If you encounter this, it's your own darn fault :P
6100 Some(_) => DirectoryOwnership::Owned { relative: None },
6101 _ => DirectoryOwnership::UnownedViaMod(true),
6108 let relative = match self.directory.ownership {
6109 DirectoryOwnership::Owned { relative } => {
6110 // Push the usage onto the list of non-mod.rs mod uses.
6111 // This is used later for feature-gate error reporting.
6112 if let Some(cur_file_ident) = relative {
6114 .non_modrs_mods.borrow_mut()
6115 .push((cur_file_ident, id_sp));
6119 DirectoryOwnership::UnownedViaBlock |
6120 DirectoryOwnership::UnownedViaMod(_) => None,
6122 let paths = Parser::default_submod_path(
6123 id, relative, &self.directory.path, self.sess.codemap());
6125 match self.directory.ownership {
6126 DirectoryOwnership::Owned { .. } => {
6127 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6129 DirectoryOwnership::UnownedViaBlock => {
6131 "Cannot declare a non-inline module inside a block \
6132 unless it has a path attribute";
6133 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6134 if paths.path_exists {
6135 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6137 err.span_note(id_sp, &msg);
6141 DirectoryOwnership::UnownedViaMod(warn) => {
6143 if let Ok(result) = paths.result {
6144 return Ok(ModulePathSuccess { warn: true, ..result });
6147 let mut err = self.diagnostic().struct_span_err(id_sp,
6148 "cannot declare a new module at this location");
6149 if id_sp != syntax_pos::DUMMY_SP {
6150 let src_path = self.sess.codemap().span_to_filename(id_sp);
6151 if let FileName::Real(src_path) = src_path {
6152 if let Some(stem) = src_path.file_stem() {
6153 let mut dest_path = src_path.clone();
6154 dest_path.set_file_name(stem);
6155 dest_path.push("mod.rs");
6156 err.span_note(id_sp,
6157 &format!("maybe move this module `{}` to its own \
6158 directory via `{}`", src_path.display(),
6159 dest_path.display()));
6163 if paths.path_exists {
6164 err.span_note(id_sp,
6165 &format!("... or maybe `use` the module `{}` instead \
6166 of possibly redeclaring it",
6174 /// Read a module from a source file.
6175 fn eval_src_mod(&mut self,
6177 directory_ownership: DirectoryOwnership,
6180 -> PResult<'a, (ast::ItemKind, Vec<Attribute> )> {
6181 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6182 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6183 let mut err = String::from("circular modules: ");
6184 let len = included_mod_stack.len();
6185 for p in &included_mod_stack[i.. len] {
6186 err.push_str(&p.to_string_lossy());
6187 err.push_str(" -> ");
6189 err.push_str(&path.to_string_lossy());
6190 return Err(self.span_fatal(id_sp, &err[..]));
6192 included_mod_stack.push(path.clone());
6193 drop(included_mod_stack);
6196 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6197 p0.cfg_mods = self.cfg_mods;
6198 let mod_inner_lo = p0.span;
6199 let mod_attrs = p0.parse_inner_attributes()?;
6200 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6201 self.sess.included_mod_stack.borrow_mut().pop();
6202 Ok((ast::ItemKind::Mod(m0), mod_attrs))
6205 /// Parse a function declaration from a foreign module
6206 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6207 -> PResult<'a, ForeignItem> {
6208 self.expect_keyword(keywords::Fn)?;
6210 let (ident, mut generics) = self.parse_fn_header()?;
6211 let decl = self.parse_fn_decl(true)?;
6212 generics.where_clause = self.parse_where_clause()?;
6214 self.expect(&token::Semi)?;
6215 Ok(ast::ForeignItem {
6218 node: ForeignItemKind::Fn(decl, generics),
6219 id: ast::DUMMY_NODE_ID,
6225 /// Parse a static item from a foreign module.
6226 /// Assumes that the `static` keyword is already parsed.
6227 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6228 -> PResult<'a, ForeignItem> {
6229 let mutbl = self.eat_keyword(keywords::Mut);
6230 let ident = self.parse_ident()?;
6231 self.expect(&token::Colon)?;
6232 let ty = self.parse_ty()?;
6234 self.expect(&token::Semi)?;
6238 node: ForeignItemKind::Static(ty, mutbl),
6239 id: ast::DUMMY_NODE_ID,
6245 /// Parse a type from a foreign module
6246 fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6247 -> PResult<'a, ForeignItem> {
6248 self.expect_keyword(keywords::Type)?;
6250 let ident = self.parse_ident()?;
6252 self.expect(&token::Semi)?;
6253 Ok(ast::ForeignItem {
6256 node: ForeignItemKind::Ty,
6257 id: ast::DUMMY_NODE_ID,
6263 /// Parse extern crate links
6267 /// extern crate foo;
6268 /// extern crate bar as foo;
6269 fn parse_item_extern_crate(&mut self,
6271 visibility: Visibility,
6272 attrs: Vec<Attribute>)
6273 -> PResult<'a, P<Item>> {
6274 let orig_name = self.parse_ident()?;
6275 let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6276 (rename, Some(orig_name.name))
6280 self.expect(&token::Semi)?;
6282 let span = lo.to(self.prev_span);
6283 Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6286 /// Parse `extern` for foreign ABIs
6289 /// `extern` is expected to have been
6290 /// consumed before calling this method
6296 fn parse_item_foreign_mod(&mut self,
6298 opt_abi: Option<Abi>,
6299 visibility: Visibility,
6300 mut attrs: Vec<Attribute>)
6301 -> PResult<'a, P<Item>> {
6302 self.expect(&token::OpenDelim(token::Brace))?;
6304 let abi = opt_abi.unwrap_or(Abi::C);
6306 attrs.extend(self.parse_inner_attributes()?);
6308 let mut foreign_items = vec![];
6309 while let Some(item) = self.parse_foreign_item()? {
6310 foreign_items.push(item);
6312 self.expect(&token::CloseDelim(token::Brace))?;
6314 let prev_span = self.prev_span;
6315 let m = ast::ForeignMod {
6317 items: foreign_items
6319 let invalid = keywords::Invalid.ident();
6320 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6323 /// Parse type Foo = Bar;
6324 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
6325 let ident = self.parse_ident()?;
6326 let mut tps = self.parse_generics()?;
6327 tps.where_clause = self.parse_where_clause()?;
6328 self.expect(&token::Eq)?;
6329 let ty = self.parse_ty()?;
6330 self.expect(&token::Semi)?;
6331 Ok((ident, ItemKind::Ty(ty, tps), None))
6334 /// Parse the part of an "enum" decl following the '{'
6335 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6336 let mut variants = Vec::new();
6337 let mut all_nullary = true;
6338 let mut any_disr = None;
6339 while self.token != token::CloseDelim(token::Brace) {
6340 let variant_attrs = self.parse_outer_attributes()?;
6341 let vlo = self.span;
6344 let mut disr_expr = None;
6345 let ident = self.parse_ident()?;
6346 if self.check(&token::OpenDelim(token::Brace)) {
6347 // Parse a struct variant.
6348 all_nullary = false;
6349 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6350 ast::DUMMY_NODE_ID);
6351 } else if self.check(&token::OpenDelim(token::Paren)) {
6352 all_nullary = false;
6353 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6354 ast::DUMMY_NODE_ID);
6355 } else if self.eat(&token::Eq) {
6356 disr_expr = Some(self.parse_expr()?);
6357 any_disr = disr_expr.as_ref().map(|expr| expr.span);
6358 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6360 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6363 let vr = ast::Variant_ {
6365 attrs: variant_attrs,
6369 variants.push(respan(vlo.to(self.prev_span), vr));
6371 if !self.eat(&token::Comma) { break; }
6373 self.expect(&token::CloseDelim(token::Brace))?;
6375 Some(disr_span) if !all_nullary =>
6376 self.span_err(disr_span,
6377 "discriminator values can only be used with a field-less enum"),
6381 Ok(ast::EnumDef { variants: variants })
6384 /// Parse an "enum" declaration
6385 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6386 let id = self.parse_ident()?;
6387 let mut generics = self.parse_generics()?;
6388 generics.where_clause = self.parse_where_clause()?;
6389 self.expect(&token::OpenDelim(token::Brace))?;
6391 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6392 self.recover_stmt();
6393 self.eat(&token::CloseDelim(token::Brace));
6396 Ok((id, ItemKind::Enum(enum_definition, generics), None))
6399 /// Parses a string as an ABI spec on an extern type or module. Consumes
6400 /// the `extern` keyword, if one is found.
6401 fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6403 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6405 self.expect_no_suffix(sp, "ABI spec", suf);
6407 match abi::lookup(&s.as_str()) {
6408 Some(abi) => Ok(Some(abi)),
6410 let prev_span = self.prev_span;
6413 &format!("invalid ABI: expected one of [{}], \
6415 abi::all_names().join(", "),
6426 fn is_static_global(&mut self) -> bool {
6427 if self.check_keyword(keywords::Static) {
6428 // Check if this could be a closure
6429 !self.look_ahead(1, |token| {
6430 if token.is_keyword(keywords::Move) {
6434 token::BinOp(token::Or) | token::OrOr => true,
6443 /// Parse one of the items allowed by the flags.
6444 /// NB: this function no longer parses the items inside an
6446 fn parse_item_(&mut self, attrs: Vec<Attribute>,
6447 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
6448 maybe_whole!(self, NtItem, |item| {
6449 let mut item = item.into_inner();
6450 let mut attrs = attrs;
6451 mem::swap(&mut item.attrs, &mut attrs);
6452 item.attrs.extend(attrs);
6458 let visibility = self.parse_visibility(false)?;
6460 if self.eat_keyword(keywords::Use) {
6462 let item_ = ItemKind::Use(P(self.parse_use_tree()?));
6463 self.expect(&token::Semi)?;
6465 let span = lo.to(self.prev_span);
6466 let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
6467 return Ok(Some(item));
6470 if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6471 self.bump(); // `extern`
6472 if self.eat_keyword(keywords::Crate) {
6473 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6476 let opt_abi = self.parse_opt_abi()?;
6478 if self.eat_keyword(keywords::Fn) {
6479 // EXTERN FUNCTION ITEM
6480 let fn_span = self.prev_span;
6481 let abi = opt_abi.unwrap_or(Abi::C);
6482 let (ident, item_, extra_attrs) =
6483 self.parse_item_fn(Unsafety::Normal,
6484 respan(fn_span, Constness::NotConst),
6486 let prev_span = self.prev_span;
6487 let item = self.mk_item(lo.to(prev_span),
6491 maybe_append(attrs, extra_attrs));
6492 return Ok(Some(item));
6493 } else if self.check(&token::OpenDelim(token::Brace)) {
6494 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6500 if self.is_static_global() {
6503 let m = if self.eat_keyword(keywords::Mut) {
6506 Mutability::Immutable
6508 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6509 let prev_span = self.prev_span;
6510 let item = self.mk_item(lo.to(prev_span),
6514 maybe_append(attrs, extra_attrs));
6515 return Ok(Some(item));
6517 if self.eat_keyword(keywords::Const) {
6518 let const_span = self.prev_span;
6519 if self.check_keyword(keywords::Fn)
6520 || (self.check_keyword(keywords::Unsafe)
6521 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6522 // CONST FUNCTION ITEM
6523 let unsafety = self.parse_unsafety();
6525 let (ident, item_, extra_attrs) =
6526 self.parse_item_fn(unsafety,
6527 respan(const_span, Constness::Const),
6529 let prev_span = self.prev_span;
6530 let item = self.mk_item(lo.to(prev_span),
6534 maybe_append(attrs, extra_attrs));
6535 return Ok(Some(item));
6539 if self.eat_keyword(keywords::Mut) {
6540 let prev_span = self.prev_span;
6541 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6542 .help("did you mean to declare a static?")
6545 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6546 let prev_span = self.prev_span;
6547 let item = self.mk_item(lo.to(prev_span),
6551 maybe_append(attrs, extra_attrs));
6552 return Ok(Some(item));
6554 if self.check_keyword(keywords::Unsafe) &&
6555 (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
6556 self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
6558 // UNSAFE TRAIT ITEM
6559 self.bump(); // `unsafe`
6560 let is_auto = if self.eat_keyword(keywords::Trait) {
6563 self.expect_keyword(keywords::Auto)?;
6564 self.expect_keyword(keywords::Trait)?;
6567 let (ident, item_, extra_attrs) =
6568 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
6569 let prev_span = self.prev_span;
6570 let item = self.mk_item(lo.to(prev_span),
6574 maybe_append(attrs, extra_attrs));
6575 return Ok(Some(item));
6577 if self.check_keyword(keywords::Impl) ||
6578 self.check_keyword(keywords::Unsafe) &&
6579 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6580 self.check_keyword(keywords::Default) &&
6581 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6582 self.check_keyword(keywords::Default) &&
6583 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
6585 let defaultness = self.parse_defaultness();
6586 let unsafety = self.parse_unsafety();
6587 self.expect_keyword(keywords::Impl)?;
6588 let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
6589 let span = lo.to(self.prev_span);
6590 return Ok(Some(self.mk_item(span, ident, item, visibility,
6591 maybe_append(attrs, extra_attrs))));
6593 if self.check_keyword(keywords::Fn) {
6596 let fn_span = self.prev_span;
6597 let (ident, item_, extra_attrs) =
6598 self.parse_item_fn(Unsafety::Normal,
6599 respan(fn_span, Constness::NotConst),
6601 let prev_span = self.prev_span;
6602 let item = self.mk_item(lo.to(prev_span),
6606 maybe_append(attrs, extra_attrs));
6607 return Ok(Some(item));
6609 if self.check_keyword(keywords::Unsafe)
6610 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
6611 // UNSAFE FUNCTION ITEM
6612 self.bump(); // `unsafe`
6613 // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
6614 self.check(&token::OpenDelim(token::Brace));
6615 let abi = if self.eat_keyword(keywords::Extern) {
6616 self.parse_opt_abi()?.unwrap_or(Abi::C)
6620 self.expect_keyword(keywords::Fn)?;
6621 let fn_span = self.prev_span;
6622 let (ident, item_, extra_attrs) =
6623 self.parse_item_fn(Unsafety::Unsafe,
6624 respan(fn_span, Constness::NotConst),
6626 let prev_span = self.prev_span;
6627 let item = self.mk_item(lo.to(prev_span),
6631 maybe_append(attrs, extra_attrs));
6632 return Ok(Some(item));
6634 if self.eat_keyword(keywords::Mod) {
6636 let (ident, item_, extra_attrs) =
6637 self.parse_item_mod(&attrs[..])?;
6638 let prev_span = self.prev_span;
6639 let item = self.mk_item(lo.to(prev_span),
6643 maybe_append(attrs, extra_attrs));
6644 return Ok(Some(item));
6646 if self.eat_keyword(keywords::Type) {
6648 let (ident, item_, extra_attrs) = self.parse_item_type()?;
6649 let prev_span = self.prev_span;
6650 let item = self.mk_item(lo.to(prev_span),
6654 maybe_append(attrs, extra_attrs));
6655 return Ok(Some(item));
6657 if self.eat_keyword(keywords::Enum) {
6659 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
6660 let prev_span = self.prev_span;
6661 let item = self.mk_item(lo.to(prev_span),
6665 maybe_append(attrs, extra_attrs));
6666 return Ok(Some(item));
6668 if self.check_keyword(keywords::Trait)
6669 || (self.check_keyword(keywords::Auto)
6670 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
6672 let is_auto = if self.eat_keyword(keywords::Trait) {
6675 self.expect_keyword(keywords::Auto)?;
6676 self.expect_keyword(keywords::Trait)?;
6680 let (ident, item_, extra_attrs) =
6681 self.parse_item_trait(is_auto, Unsafety::Normal)?;
6682 let prev_span = self.prev_span;
6683 let item = self.mk_item(lo.to(prev_span),
6687 maybe_append(attrs, extra_attrs));
6688 return Ok(Some(item));
6690 if self.eat_keyword(keywords::Struct) {
6692 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6693 let prev_span = self.prev_span;
6694 let item = self.mk_item(lo.to(prev_span),
6698 maybe_append(attrs, extra_attrs));
6699 return Ok(Some(item));
6701 if self.is_union_item() {
6704 let (ident, item_, extra_attrs) = self.parse_item_union()?;
6705 let prev_span = self.prev_span;
6706 let item = self.mk_item(lo.to(prev_span),
6710 maybe_append(attrs, extra_attrs));
6711 return Ok(Some(item));
6713 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
6714 return Ok(Some(macro_def));
6717 // Verify whether we have encountered a struct or method definition where the user forgot to
6718 // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
6719 if visibility.node == VisibilityKind::Public &&
6720 self.check_ident() &&
6721 self.look_ahead(1, |t| *t != token::Not)
6723 // Space between `pub` keyword and the identifier
6726 // ^^^ `sp` points here
6727 let sp = self.prev_span.between(self.span);
6728 let full_sp = self.prev_span.to(self.span);
6729 let ident_sp = self.span;
6730 if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
6731 // possible public struct definition where `struct` was forgotten
6732 let ident = self.parse_ident().unwrap();
6733 let msg = format!("add `struct` here to parse `{}` as a public struct",
6735 let mut err = self.diagnostic()
6736 .struct_span_err(sp, "missing `struct` for struct definition");
6737 err.span_suggestion_short(sp, &msg, " struct ".into());
6739 } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
6740 let ident = self.parse_ident().unwrap();
6741 self.consume_block(token::Paren);
6742 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
6743 self.check(&token::OpenDelim(token::Brace))
6745 ("fn", "method", false)
6746 } else if self.check(&token::Colon) {
6750 ("fn` or `struct", "method or struct", true)
6753 let msg = format!("missing `{}` for {} definition", kw, kw_name);
6754 let mut err = self.diagnostic().struct_span_err(sp, &msg);
6756 let suggestion = format!("add `{}` here to parse `{}` as a public {}",
6760 err.span_suggestion_short(sp, &suggestion, format!(" {} ", kw));
6762 if let Ok(snippet) = self.sess.codemap().span_to_snippet(ident_sp) {
6763 err.span_suggestion(
6765 "if you meant to call a macro, write instead",
6766 format!("{}!", snippet));
6768 err.help("if you meant to call a macro, remove the `pub` \
6769 and add a trailing `!` after the identifier");
6775 self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
6778 /// Parse a foreign item.
6779 pub fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
6780 maybe_whole!(self, NtForeignItem, |ni| Some(ni));
6782 let attrs = self.parse_outer_attributes()?;
6784 let visibility = self.parse_visibility(false)?;
6786 // FOREIGN STATIC ITEM
6787 // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
6788 if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
6789 if self.token.is_keyword(keywords::Const) {
6791 .struct_span_err(self.span, "extern items cannot be `const`")
6792 .span_suggestion(self.span, "instead try using", "static".to_owned())
6795 self.bump(); // `static` or `const`
6796 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6798 // FOREIGN FUNCTION ITEM
6799 if self.check_keyword(keywords::Fn) {
6800 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6802 // FOREIGN TYPE ITEM
6803 if self.check_keyword(keywords::Type) {
6804 return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
6807 match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
6811 ident: keywords::Invalid.ident(),
6812 span: lo.to(self.prev_span),
6813 id: ast::DUMMY_NODE_ID,
6816 node: ForeignItemKind::Macro(mac),
6821 if !attrs.is_empty() {
6822 self.expected_item_err(&attrs);
6830 /// This is the fall-through for parsing items.
6831 fn parse_macro_use_or_failure(
6833 attrs: Vec<Attribute> ,
6834 macros_allowed: bool,
6835 attributes_allowed: bool,
6837 visibility: Visibility
6838 ) -> PResult<'a, Option<P<Item>>> {
6839 if macros_allowed && self.token.is_path_start() {
6840 // MACRO INVOCATION ITEM
6842 let prev_span = self.prev_span;
6843 self.complain_if_pub_macro(&visibility.node, prev_span);
6845 let mac_lo = self.span;
6848 let pth = self.parse_path(PathStyle::Mod)?;
6849 self.expect(&token::Not)?;
6851 // a 'special' identifier (like what `macro_rules!` uses)
6852 // is optional. We should eventually unify invoc syntax
6854 let id = if self.token.is_ident() {
6857 keywords::Invalid.ident() // no special identifier
6859 // eat a matched-delimiter token tree:
6860 let (delim, tts) = self.expect_delimited_token_tree()?;
6861 if delim != token::Brace {
6862 if !self.eat(&token::Semi) {
6863 self.span_err(self.prev_span,
6864 "macros that expand to items must either \
6865 be surrounded with braces or followed by \
6870 let hi = self.prev_span;
6871 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6872 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6873 return Ok(Some(item));
6876 // FAILURE TO PARSE ITEM
6877 match visibility.node {
6878 VisibilityKind::Inherited => {}
6880 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
6884 if !attributes_allowed && !attrs.is_empty() {
6885 self.expected_item_err(&attrs);
6890 /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
6891 fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
6892 at_end: &mut bool) -> PResult<'a, Option<Mac>>
6894 if self.token.is_path_start() && !self.is_extern_non_path() {
6895 let prev_span = self.prev_span;
6897 let pth = self.parse_path(PathStyle::Mod)?;
6899 if pth.segments.len() == 1 {
6900 if !self.eat(&token::Not) {
6901 return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
6904 self.expect(&token::Not)?;
6907 if let Some(vis) = vis {
6908 self.complain_if_pub_macro(&vis.node, prev_span);
6913 // eat a matched-delimiter token tree:
6914 let (delim, tts) = self.expect_delimited_token_tree()?;
6915 if delim != token::Brace {
6916 self.expect(&token::Semi)?
6919 Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts })))
6925 fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
6926 where F: FnOnce(&mut Self) -> PResult<'a, R>
6928 // Record all tokens we parse when parsing this item.
6929 let mut tokens = Vec::new();
6930 match self.token_cursor.frame.last_token {
6931 LastToken::Collecting(_) => {
6932 panic!("cannot collect tokens recursively yet")
6934 LastToken::Was(ref mut last) => tokens.extend(last.take()),
6936 self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
6937 let prev = self.token_cursor.stack.len();
6939 let last_token = if self.token_cursor.stack.len() == prev {
6940 &mut self.token_cursor.frame.last_token
6942 &mut self.token_cursor.stack[prev].last_token
6944 let mut tokens = match *last_token {
6945 LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
6946 LastToken::Was(_) => panic!("our vector went away?"),
6949 // If we're not at EOF our current token wasn't actually consumed by
6950 // `f`, but it'll still be in our list that we pulled out. In that case
6952 if self.token == token::Eof {
6953 *last_token = LastToken::Was(None);
6955 *last_token = LastToken::Was(tokens.pop());
6958 Ok((ret?, tokens.into_iter().collect()))
6961 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6962 let attrs = self.parse_outer_attributes()?;
6964 let (ret, tokens) = self.collect_tokens(|this| {
6965 this.parse_item_(attrs, true, false)
6968 // Once we've parsed an item and recorded the tokens we got while
6969 // parsing we may want to store `tokens` into the item we're about to
6970 // return. Note, though, that we specifically didn't capture tokens
6971 // related to outer attributes. The `tokens` field here may later be
6972 // used with procedural macros to convert this item back into a token
6973 // stream, but during expansion we may be removing attributes as we go
6976 // If we've got inner attributes then the `tokens` we've got above holds
6977 // these inner attributes. If an inner attribute is expanded we won't
6978 // actually remove it from the token stream, so we'll just keep yielding
6979 // it (bad!). To work around this case for now we just avoid recording
6980 // `tokens` if we detect any inner attributes. This should help keep
6981 // expansion correct, but we should fix this bug one day!
6984 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6985 i.tokens = Some(tokens);
6993 fn is_import_coupler(&mut self) -> bool {
6994 self.check(&token::ModSep) &&
6995 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6996 *t == token::BinOp(token::Star))
7001 /// USE_TREE = [`::`] `*` |
7002 /// [`::`] `{` USE_TREE_LIST `}` |
7004 /// PATH `::` `{` USE_TREE_LIST `}` |
7005 /// PATH [`as` IDENT]
7006 fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7009 let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7010 let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7011 self.check(&token::BinOp(token::Star)) ||
7012 self.is_import_coupler() {
7013 // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7014 if self.eat(&token::ModSep) {
7015 prefix.segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
7018 if self.eat(&token::BinOp(token::Star)) {
7021 UseTreeKind::Nested(self.parse_use_tree_list()?)
7024 // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7025 prefix = self.parse_path(PathStyle::Mod)?;
7027 if self.eat(&token::ModSep) {
7028 if self.eat(&token::BinOp(token::Star)) {
7031 UseTreeKind::Nested(self.parse_use_tree_list()?)
7034 UseTreeKind::Simple(self.parse_rename()?)
7038 Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7041 /// Parse UseTreeKind::Nested(list)
7043 /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7044 fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7045 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7046 &token::CloseDelim(token::Brace),
7047 SeqSep::trailing_allowed(token::Comma), |this| {
7048 Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7052 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7053 if self.eat_keyword(keywords::As) {
7055 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
7057 Ok(Some(Ident::new(ident.name.gensymed(), ident.span)))
7059 _ => self.parse_ident().map(Some),
7066 /// Parses a source module as a crate. This is the main
7067 /// entry point for the parser.
7068 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7071 attrs: self.parse_inner_attributes()?,
7072 module: self.parse_mod_items(&token::Eof, lo)?,
7073 span: lo.to(self.span),
7077 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7078 let ret = match self.token {
7079 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7080 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7087 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7088 match self.parse_optional_str() {
7089 Some((s, style, suf)) => {
7090 let sp = self.prev_span;
7091 self.expect_no_suffix(sp, "string literal", suf);
7095 let msg = "expected string literal";
7096 let mut err = self.fatal(msg);
7097 err.span_label(self.span, msg);