1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use ast::{AngleBracketedParameterData, AttrStyle, BareFnTy};
13 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
15 use ast::{Mod, Arg, Arm, Attribute, BindingMode, TraitItemKind};
17 use ast::{BlockCheckMode, CaptureBy};
18 use ast::{Constness, Crate};
21 use ast::{Expr, ExprKind, RangeLimits};
22 use ast::{Field, FnDecl};
23 use ast::{ForeignItem, ForeignItemKind, FunctionRetTy};
24 use ast::{Ident, ImplItem, Item, ItemKind};
25 use ast::{Lifetime, LifetimeDef, Lit, LitKind, UintTy};
27 use ast::MacStmtStyle;
29 use ast::{MutTy, Mutability};
30 use ast::{Pat, PatKind, PathSegment};
31 use ast::{PolyTraitRef, QSelf};
32 use ast::{Stmt, StmtKind};
33 use ast::{VariantData, StructField};
36 use ast::{TraitItem, TraitRef};
37 use ast::{Ty, TyKind, TypeBinding, TyParam, TyParamBounds};
38 use ast::{ViewPath, ViewPathGlob, ViewPathList, ViewPathSimple};
39 use ast::{Visibility, WhereClause};
40 use ast::{BinOpKind, UnOp};
43 use codemap::{self, CodeMap, Spanned, respan};
44 use syntax_pos::{self, Span, BytePos};
45 use errors::{self, DiagnosticBuilder};
46 use parse::{self, classify, token};
47 use parse::common::SeqSep;
48 use parse::lexer::TokenAndSpan;
49 use parse::lexer::comments::{doc_comment_style, strip_doc_comment_decoration};
50 use parse::obsolete::ObsoleteSyntax;
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};
61 use std::collections::HashSet;
63 use std::path::{self, Path, PathBuf};
67 pub flags Restrictions: u8 {
68 const RESTRICTION_STMT_EXPR = 1 << 0,
69 const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1,
73 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute> >);
75 /// How to parse a path. There are three different kinds of paths, all of which
76 /// are parsed somewhat differently.
77 #[derive(Copy, Clone, PartialEq)]
79 /// A path with no type parameters, e.g. `foo::bar::Baz`, used in imports or visibilities.
81 /// A path with a lifetime and type parameters, with no double colons
82 /// before the type parameters; e.g. `foo::bar<'a>::Baz<T>`, used in types.
83 /// Paths using this style can be passed into macros expecting `path` nonterminals.
85 /// A path with a lifetime and type parameters with double colons before
86 /// the type parameters; e.g. `foo::bar::<'a>::Baz::<T>`, used in expressions or patterns.
90 #[derive(Clone, Copy, Debug, PartialEq)]
91 pub enum SemiColonMode {
96 #[derive(Clone, Copy, Debug, PartialEq)]
102 /// Possibly accept an `token::Interpolated` expression (a pre-parsed expression
103 /// dropped into the token stream, which happens while parsing the result of
104 /// macro expansion). Placement of these is not as complex as I feared it would
105 /// be. The important thing is to make sure that lookahead doesn't balk at
106 /// `token::Interpolated` tokens.
107 macro_rules! maybe_whole_expr {
109 if let token::Interpolated(nt) = $p.token.clone() {
111 token::NtExpr(ref e) => {
113 return Ok((*e).clone());
115 token::NtPath(ref path) => {
118 let kind = ExprKind::Path(None, (*path).clone());
119 return Ok($p.mk_expr(span, kind, ThinVec::new()));
121 token::NtBlock(ref block) => {
124 let kind = ExprKind::Block((*block).clone());
125 return Ok($p.mk_expr(span, kind, ThinVec::new()));
133 /// As maybe_whole_expr, but for things other than expressions
134 macro_rules! maybe_whole {
135 ($p:expr, $constructor:ident, |$x:ident| $e:expr) => {
136 if let token::Interpolated(nt) = $p.token.clone() {
137 if let token::$constructor($x) = nt.0.clone() {
145 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
147 if let Some(ref attrs) = rhs {
148 lhs.extend(attrs.iter().cloned())
153 #[derive(Debug, Clone, Copy, PartialEq)]
164 /* ident is handled by common.rs */
167 pub struct Parser<'a> {
168 pub sess: &'a ParseSess,
169 /// the current token:
170 pub token: token::Token,
171 /// the span of the current token:
173 /// the span of the previous token:
174 pub meta_var_span: Option<Span>,
176 /// the previous token kind
177 prev_token_kind: PrevTokenKind,
178 pub restrictions: Restrictions,
179 /// The set of seen errors about obsolete syntax. Used to suppress
180 /// extra detail when the same error is seen twice
181 pub obsolete_set: HashSet<ObsoleteSyntax>,
182 /// Used to determine the path to externally loaded source files
183 pub directory: Directory,
184 /// Whether to parse sub-modules in other files.
185 pub recurse_into_file_modules: bool,
186 /// Name of the root module this parser originated from. If `None`, then the
187 /// name is not known. This does not change while the parser is descending
188 /// into modules, and sub-parsers have new values for this name.
189 pub root_module_name: Option<String>,
190 pub expected_tokens: Vec<TokenType>,
191 token_cursor: TokenCursor,
192 pub desugar_doc_comments: bool,
193 /// Whether we should configure out of line modules as we parse.
200 frame: TokenCursorFrame,
201 stack: Vec<TokenCursorFrame>,
205 struct TokenCursorFrame {
206 delim: token::DelimToken,
209 tree_cursor: tokenstream::Cursor,
213 impl TokenCursorFrame {
214 fn new(sp: Span, delimited: &Delimited) -> Self {
216 delim: delimited.delim,
218 open_delim: delimited.delim == token::NoDelim,
219 tree_cursor: delimited.stream().into_trees(),
220 close_delim: delimited.delim == token::NoDelim,
226 fn next(&mut self) -> TokenAndSpan {
228 let tree = if !self.frame.open_delim {
229 self.frame.open_delim = true;
230 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
231 .open_tt(self.frame.span)
232 } else if let Some(tree) = self.frame.tree_cursor.next() {
234 } else if !self.frame.close_delim {
235 self.frame.close_delim = true;
236 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
237 .close_tt(self.frame.span)
238 } else if let Some(frame) = self.stack.pop() {
242 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
246 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
247 TokenTree::Delimited(sp, ref delimited) => {
248 let frame = TokenCursorFrame::new(sp, delimited);
249 self.stack.push(mem::replace(&mut self.frame, frame));
255 fn next_desugared(&mut self) -> TokenAndSpan {
256 let (sp, name) = match self.next() {
257 TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
261 let stripped = strip_doc_comment_decoration(&name.as_str());
263 // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
264 // required to wrap the text.
265 let mut num_of_hashes = 0;
267 for ch in stripped.chars() {
270 '#' if count > 0 => count + 1,
273 num_of_hashes = cmp::max(num_of_hashes, count);
276 let body = TokenTree::Delimited(sp, Delimited {
277 delim: token::Bracket,
278 tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"))),
279 TokenTree::Token(sp, token::Eq),
280 TokenTree::Token(sp, token::Literal(
281 token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
282 .iter().cloned().collect::<TokenStream>().into(),
285 self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
286 delim: token::NoDelim,
287 tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
288 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
289 .iter().cloned().collect::<TokenStream>().into()
291 [TokenTree::Token(sp, token::Pound), body]
292 .iter().cloned().collect::<TokenStream>().into()
300 #[derive(PartialEq, Eq, Clone)]
303 Keyword(keywords::Keyword),
312 fn to_string(&self) -> String {
314 TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
315 TokenType::Keyword(kw) => format!("`{}`", kw.name()),
316 TokenType::Operator => "an operator".to_string(),
317 TokenType::Lifetime => "lifetime".to_string(),
318 TokenType::Ident => "identifier".to_string(),
319 TokenType::Path => "path".to_string(),
320 TokenType::Type => "type".to_string(),
325 fn is_ident_or_underscore(t: &token::Token) -> bool {
326 t.is_ident() || *t == token::Underscore
329 /// Information about the path to a module.
330 pub struct ModulePath {
332 pub path_exists: bool,
333 pub result: Result<ModulePathSuccess, Error>,
336 pub struct ModulePathSuccess {
338 pub directory_ownership: DirectoryOwnership,
342 pub struct ModulePathError {
344 pub help_msg: String,
348 FileNotFoundForModule {
350 default_path: String,
351 secondary_path: String,
356 default_path: String,
357 secondary_path: String,
360 InclusiveRangeWithNoEnd,
364 pub fn span_err(self, sp: Span, handler: &errors::Handler) -> DiagnosticBuilder {
366 Error::FileNotFoundForModule { ref mod_name,
370 let mut err = struct_span_err!(handler, sp, E0583,
371 "file not found for module `{}`", mod_name);
372 err.help(&format!("name the file either {} or {} inside the directory {:?}",
378 Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
379 let mut err = struct_span_err!(handler, sp, E0584,
380 "file for module `{}` found at both {} and {}",
384 err.help("delete or rename one of them to remove the ambiguity");
387 Error::UselessDocComment => {
388 let mut err = struct_span_err!(handler, sp, E0585,
389 "found a documentation comment that doesn't document anything");
390 err.help("doc comments must come before what they document, maybe a comment was \
391 intended with `//`?");
394 Error::InclusiveRangeWithNoEnd => {
395 let mut err = struct_span_err!(handler, sp, E0586,
396 "inclusive range with no end");
397 err.help("inclusive ranges must be bounded at the end (`...b` or `a...b`)");
407 AttributesParsed(ThinVec<Attribute>),
408 AlreadyParsed(P<Expr>),
411 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
412 fn from(o: Option<ThinVec<Attribute>>) -> Self {
413 if let Some(attrs) = o {
414 LhsExpr::AttributesParsed(attrs)
416 LhsExpr::NotYetParsed
421 impl From<P<Expr>> for LhsExpr {
422 fn from(expr: P<Expr>) -> Self {
423 LhsExpr::AlreadyParsed(expr)
427 /// Create a placeholder argument.
428 fn dummy_arg(span: Span) -> Arg {
429 let spanned = Spanned {
431 node: keywords::Invalid.ident()
434 id: ast::DUMMY_NODE_ID,
435 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), spanned, None),
441 id: ast::DUMMY_NODE_ID
443 Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
446 impl<'a> Parser<'a> {
447 pub fn new(sess: &'a ParseSess,
449 directory: Option<Directory>,
450 recurse_into_file_modules: bool,
451 desugar_doc_comments: bool)
453 let mut parser = Parser {
455 token: token::Underscore,
456 span: syntax_pos::DUMMY_SP,
457 prev_span: syntax_pos::DUMMY_SP,
459 prev_token_kind: PrevTokenKind::Other,
460 restrictions: Restrictions::empty(),
461 obsolete_set: HashSet::new(),
462 recurse_into_file_modules: recurse_into_file_modules,
463 directory: Directory { path: PathBuf::new(), ownership: DirectoryOwnership::Owned },
464 root_module_name: None,
465 expected_tokens: Vec::new(),
466 token_cursor: TokenCursor {
467 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
468 delim: token::NoDelim,
473 desugar_doc_comments: desugar_doc_comments,
477 let tok = parser.next_tok();
478 parser.token = tok.tok;
479 parser.span = tok.sp;
481 if let Some(directory) = directory {
482 parser.directory = directory;
483 } else if parser.span != syntax_pos::DUMMY_SP {
484 parser.directory.path = PathBuf::from(sess.codemap().span_to_filename(parser.span));
485 parser.directory.path.pop();
488 parser.process_potential_macro_variable();
492 fn next_tok(&mut self) -> TokenAndSpan {
493 let mut next = if self.desugar_doc_comments {
494 self.token_cursor.next_desugared()
496 self.token_cursor.next()
498 if next.sp == syntax_pos::DUMMY_SP {
499 next.sp = self.prev_span;
504 /// Convert a token to a string using self's reader
505 pub fn token_to_string(token: &token::Token) -> String {
506 pprust::token_to_string(token)
509 /// Convert the current token to a string using self's reader
510 pub fn this_token_to_string(&self) -> String {
511 Parser::token_to_string(&self.token)
514 pub fn this_token_descr(&self) -> String {
515 let prefix = match &self.token {
516 t if t.is_special_ident() => "reserved identifier ",
517 t if t.is_used_keyword() => "keyword ",
518 t if t.is_unused_keyword() => "reserved keyword ",
521 format!("{}`{}`", prefix, self.this_token_to_string())
524 pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
525 let token_str = Parser::token_to_string(t);
526 Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
529 pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
530 match self.expect_one_of(&[], &[]) {
532 Ok(_) => unreachable!(),
536 /// Expect and consume the token t. Signal an error if
537 /// the next token is not t.
538 pub fn expect(&mut self, t: &token::Token) -> PResult<'a, ()> {
539 if self.expected_tokens.is_empty() {
540 if self.token == *t {
544 let token_str = Parser::token_to_string(t);
545 let this_token_str = self.this_token_to_string();
546 Err(self.fatal(&format!("expected `{}`, found `{}`",
551 self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
555 /// Expect next token to be edible or inedible token. If edible,
556 /// then consume it; if inedible, then return without consuming
557 /// anything. Signal a fatal error if next token is unexpected.
558 pub fn expect_one_of(&mut self,
559 edible: &[token::Token],
560 inedible: &[token::Token]) -> PResult<'a, ()>{
561 fn tokens_to_string(tokens: &[TokenType]) -> String {
562 let mut i = tokens.iter();
563 // This might be a sign we need a connect method on Iterator.
565 .map_or("".to_string(), |t| t.to_string());
566 i.enumerate().fold(b, |mut b, (i, a)| {
567 if tokens.len() > 2 && i == tokens.len() - 2 {
569 } else if tokens.len() == 2 && i == tokens.len() - 2 {
574 b.push_str(&a.to_string());
578 if edible.contains(&self.token) {
581 } else if inedible.contains(&self.token) {
582 // leave it in the input
585 let mut expected = edible.iter()
586 .map(|x| TokenType::Token(x.clone()))
587 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
588 .chain(self.expected_tokens.iter().cloned())
589 .collect::<Vec<_>>();
590 expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
592 let expect = tokens_to_string(&expected[..]);
593 let actual = self.this_token_to_string();
594 let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
595 let short_expect = if expected.len() > 6 {
596 format!("{} possible tokens", expected.len())
600 (format!("expected one of {}, found `{}`", expect, actual),
601 (self.prev_span.next_point(), format!("expected one of {} here", short_expect)))
602 } else if expected.is_empty() {
603 (format!("unexpected token: `{}`", actual),
604 (self.prev_span, "unexpected token after this".to_string()))
606 (format!("expected {}, found `{}`", expect, actual),
607 (self.prev_span.next_point(), format!("expected {} here", expect)))
609 let mut err = self.fatal(&msg_exp);
610 let sp = if self.token == token::Token::Eof {
611 // This is EOF, don't want to point at the following char, but rather the last token
616 if self.span.contains(sp) {
617 err.span_label(self.span, label_exp);
619 err.span_label(sp, label_exp);
620 err.span_label(self.span, "unexpected token");
626 /// returns the span of expr, if it was not interpolated or the span of the interpolated token
627 fn interpolated_or_expr_span(&self,
628 expr: PResult<'a, P<Expr>>)
629 -> PResult<'a, (Span, P<Expr>)> {
631 if self.prev_token_kind == PrevTokenKind::Interpolated {
639 pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
642 if self.token.is_reserved_ident() {
643 self.span_err(self.span, &format!("expected identifier, found {}",
644 self.this_token_descr()));
650 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
651 self.span_fatal_err(self.prev_span, Error::UselessDocComment)
653 let mut err = self.fatal(&format!("expected identifier, found `{}`",
654 self.this_token_to_string()));
655 if self.token == token::Underscore {
656 err.note("`_` is a wildcard pattern, not an identifier");
664 /// Check if the next token is `tok`, and return `true` if so.
666 /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
668 pub fn check(&mut self, tok: &token::Token) -> bool {
669 let is_present = self.token == *tok;
670 if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
674 /// Consume token 'tok' if it exists. Returns true if the given
675 /// token was present, false otherwise.
676 pub fn eat(&mut self, tok: &token::Token) -> bool {
677 let is_present = self.check(tok);
678 if is_present { self.bump() }
682 pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
683 self.expected_tokens.push(TokenType::Keyword(kw));
684 self.token.is_keyword(kw)
687 /// If the next token is the given keyword, eat it and return
688 /// true. Otherwise, return false.
689 pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
690 if self.check_keyword(kw) {
698 pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
699 if self.token.is_keyword(kw) {
707 /// If the given word is not a keyword, signal an error.
708 /// If the next token is not the given word, signal an error.
709 /// Otherwise, eat it.
710 pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
711 if !self.eat_keyword(kw) {
718 fn check_ident(&mut self) -> bool {
719 if self.token.is_ident() {
722 self.expected_tokens.push(TokenType::Ident);
727 fn check_path(&mut self) -> bool {
728 if self.token.is_path_start() {
731 self.expected_tokens.push(TokenType::Path);
736 fn check_type(&mut self) -> bool {
737 if self.token.can_begin_type() {
740 self.expected_tokens.push(TokenType::Type);
745 /// Expect and consume an `&`. If `&&` is seen, replace it with a single
746 /// `&` and continue. If an `&` is not seen, signal an error.
747 fn expect_and(&mut self) -> PResult<'a, ()> {
748 self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
750 token::BinOp(token::And) => {
755 let span = self.span;
756 let lo = span.lo + BytePos(1);
757 Ok(self.bump_with(token::BinOp(token::And), Span { lo: lo, ..span }))
759 _ => self.unexpected()
763 pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
765 None => {/* everything ok */}
767 let text = suf.as_str();
769 self.span_bug(sp, "found empty literal suffix in Some")
771 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
776 /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
777 /// `<` and continue. If a `<` is not seen, return false.
779 /// This is meant to be used when parsing generics on a path to get the
781 fn eat_lt(&mut self) -> bool {
782 self.expected_tokens.push(TokenType::Token(token::Lt));
788 token::BinOp(token::Shl) => {
789 let span = self.span;
790 let lo = span.lo + BytePos(1);
791 self.bump_with(token::Lt, Span { lo: lo, ..span });
798 fn expect_lt(&mut self) -> PResult<'a, ()> {
806 /// Expect and consume a GT. if a >> is seen, replace it
807 /// with a single > and continue. If a GT is not seen,
809 pub fn expect_gt(&mut self) -> PResult<'a, ()> {
810 self.expected_tokens.push(TokenType::Token(token::Gt));
816 token::BinOp(token::Shr) => {
817 let span = self.span;
818 let lo = span.lo + BytePos(1);
819 Ok(self.bump_with(token::Gt, Span { lo: lo, ..span }))
821 token::BinOpEq(token::Shr) => {
822 let span = self.span;
823 let lo = span.lo + BytePos(1);
824 Ok(self.bump_with(token::Ge, Span { lo: lo, ..span }))
827 let span = self.span;
828 let lo = span.lo + BytePos(1);
829 Ok(self.bump_with(token::Eq, Span { lo: lo, ..span }))
831 _ => self.unexpected()
835 pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
836 sep: Option<token::Token>,
838 -> PResult<'a, (Vec<T>, bool)>
839 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
841 let mut v = Vec::new();
842 // This loop works by alternating back and forth between parsing types
843 // and commas. For example, given a string `A, B,>`, the parser would
844 // first parse `A`, then a comma, then `B`, then a comma. After that it
845 // would encounter a `>` and stop. This lets the parser handle trailing
846 // commas in generic parameters, because it can stop either after
847 // parsing a type or after parsing a comma.
849 if self.check(&token::Gt)
850 || self.token == token::BinOp(token::Shr)
851 || self.token == token::Ge
852 || self.token == token::BinOpEq(token::Shr) {
858 Some(result) => v.push(result),
859 None => return Ok((v, true))
862 if let Some(t) = sep.as_ref() {
868 return Ok((v, false));
871 /// Parse a sequence bracketed by '<' and '>', stopping
873 pub fn parse_seq_to_before_gt<T, F>(&mut self,
874 sep: Option<token::Token>,
876 -> PResult<'a, Vec<T>> where
877 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
879 let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
880 |p| Ok(Some(f(p)?)))?;
885 pub fn parse_seq_to_gt<T, F>(&mut self,
886 sep: Option<token::Token>,
888 -> PResult<'a, Vec<T>> where
889 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
891 let v = self.parse_seq_to_before_gt(sep, f)?;
896 pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
897 sep: Option<token::Token>,
899 -> PResult<'a, (Vec<T>, bool)> where
900 F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
902 let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
906 return Ok((v, returned));
909 /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
910 /// passes through any errors encountered. Used for error recovery.
911 pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
912 let handler = self.diagnostic();
914 self.parse_seq_to_before_tokens(kets,
916 |p| Ok(p.parse_token_tree()),
917 |mut e| handler.cancel(&mut e));
920 /// Parse a sequence, including the closing delimiter. The function
921 /// f must consume tokens until reaching the next separator or
923 pub fn parse_seq_to_end<T, F>(&mut self,
927 -> PResult<'a, Vec<T>> where
928 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
930 let val = self.parse_seq_to_before_end(ket, sep, f);
935 /// Parse a sequence, not including the closing delimiter. The function
936 /// f must consume tokens until reaching the next separator or
938 pub fn parse_seq_to_before_end<T, F>(&mut self,
943 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>
945 self.parse_seq_to_before_tokens(&[ket], sep, f, |mut e| e.emit())
948 // `fe` is an error handler.
949 fn parse_seq_to_before_tokens<T, F, Fe>(&mut self,
950 kets: &[&token::Token],
955 where F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
956 Fe: FnMut(DiagnosticBuilder)
958 let mut first: bool = true;
960 while !kets.contains(&&self.token) {
962 token::CloseDelim(..) | token::Eof => break,
965 if let Some(ref t) = sep.sep {
969 if let Err(e) = self.expect(t) {
975 if sep.trailing_sep_allowed && kets.iter().any(|k| self.check(k)) {
991 /// Parse a sequence, including the closing delimiter. The function
992 /// f must consume tokens until reaching the next separator or
994 pub fn parse_unspanned_seq<T, F>(&mut self,
999 -> PResult<'a, Vec<T>> where
1000 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1003 let result = self.parse_seq_to_before_end(ket, sep, f);
1004 if self.token == *ket {
1010 // NB: Do not use this function unless you actually plan to place the
1011 // spanned list in the AST.
1012 pub fn parse_seq<T, F>(&mut self,
1017 -> PResult<'a, Spanned<Vec<T>>> where
1018 F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
1022 let result = self.parse_seq_to_before_end(ket, sep, f);
1025 Ok(respan(lo.to(hi), result))
1028 /// Advance the parser by one token
1029 pub fn bump(&mut self) {
1030 if self.prev_token_kind == PrevTokenKind::Eof {
1031 // Bumping after EOF is a bad sign, usually an infinite loop.
1032 self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1035 self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1037 // Record last token kind for possible error recovery.
1038 self.prev_token_kind = match self.token {
1039 token::DocComment(..) => PrevTokenKind::DocComment,
1040 token::Comma => PrevTokenKind::Comma,
1041 token::BinOp(token::Plus) => PrevTokenKind::Plus,
1042 token::Interpolated(..) => PrevTokenKind::Interpolated,
1043 token::Eof => PrevTokenKind::Eof,
1044 token::Ident(..) => PrevTokenKind::Ident,
1045 _ => PrevTokenKind::Other,
1048 let next = self.next_tok();
1049 self.span = next.sp;
1050 self.token = next.tok;
1051 self.expected_tokens.clear();
1052 // check after each token
1053 self.process_potential_macro_variable();
1056 /// Advance the parser using provided token as a next one. Use this when
1057 /// consuming a part of a token. For example a single `<` from `<<`.
1058 pub fn bump_with(&mut self, next: token::Token, span: Span) {
1059 self.prev_span = Span { hi: span.lo, ..self.span };
1060 // It would be incorrect to record the kind of the current token, but
1061 // fortunately for tokens currently using `bump_with`, the
1062 // prev_token_kind will be of no use anyway.
1063 self.prev_token_kind = PrevTokenKind::Other;
1066 self.expected_tokens.clear();
1069 pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1070 F: FnOnce(&token::Token) -> R,
1073 return f(&self.token)
1076 f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1077 Some(tree) => match tree {
1078 TokenTree::Token(_, tok) => tok,
1079 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1081 None => token::CloseDelim(self.token_cursor.frame.delim),
1084 fn look_ahead_span(&self, dist: usize) -> Span {
1089 match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1090 Some(TokenTree::Token(span, _)) | Some(TokenTree::Delimited(span, _)) => span,
1091 None => self.look_ahead_span(dist - 1),
1094 pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1095 self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1097 pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1098 self.sess.span_diagnostic.struct_span_fatal(sp, m)
1100 pub fn span_fatal_err(&self, sp: Span, err: Error) -> DiagnosticBuilder<'a> {
1101 err.span_err(sp, self.diagnostic())
1103 pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1104 let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1108 pub fn bug(&self, m: &str) -> ! {
1109 self.sess.span_diagnostic.span_bug(self.span, m)
1111 pub fn warn(&self, m: &str) {
1112 self.sess.span_diagnostic.span_warn(self.span, m)
1114 pub fn span_warn(&self, sp: Span, m: &str) {
1115 self.sess.span_diagnostic.span_warn(sp, m)
1117 pub fn span_err(&self, sp: Span, m: &str) {
1118 self.sess.span_diagnostic.span_err(sp, m)
1120 pub fn span_err_help(&self, sp: Span, m: &str, h: &str) {
1121 let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1125 pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1126 self.sess.span_diagnostic.span_bug(sp, m)
1128 pub fn abort_if_errors(&self) {
1129 self.sess.span_diagnostic.abort_if_errors();
1132 fn cancel(&self, err: &mut DiagnosticBuilder) {
1133 self.sess.span_diagnostic.cancel(err)
1136 pub fn diagnostic(&self) -> &'a errors::Handler {
1137 &self.sess.span_diagnostic
1140 /// Is the current token one of the keywords that signals a bare function
1142 pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1143 self.check_keyword(keywords::Fn) ||
1144 self.check_keyword(keywords::Unsafe) ||
1145 self.check_keyword(keywords::Extern)
1148 fn get_label(&mut self) -> ast::Ident {
1150 token::Lifetime(ref ident) => *ident,
1151 _ => self.bug("not a lifetime"),
1155 /// parse a TyKind::BareFn type:
1156 pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<LifetimeDef>)
1157 -> PResult<'a, TyKind> {
1160 [unsafe] [extern "ABI"] fn (S) -> T
1170 let unsafety = self.parse_unsafety()?;
1171 let abi = if self.eat_keyword(keywords::Extern) {
1172 self.parse_opt_abi()?.unwrap_or(Abi::C)
1177 self.expect_keyword(keywords::Fn)?;
1178 let (inputs, variadic) = self.parse_fn_args(false, true)?;
1179 let ret_ty = self.parse_ret_ty()?;
1180 let decl = P(FnDecl {
1185 Ok(TyKind::BareFn(P(BareFnTy {
1188 lifetimes: lifetime_defs,
1193 pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1194 if self.eat_keyword(keywords::Unsafe) {
1195 return Ok(Unsafety::Unsafe);
1197 return Ok(Unsafety::Normal);
1201 /// Parse the items in a trait declaration
1202 pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1203 maybe_whole!(self, NtTraitItem, |x| x);
1204 let mut attrs = self.parse_outer_attributes()?;
1207 let (name, node) = if self.eat_keyword(keywords::Type) {
1208 let TyParam {ident, bounds, default, ..} = self.parse_ty_param(vec![])?;
1209 self.expect(&token::Semi)?;
1210 (ident, TraitItemKind::Type(bounds, default))
1211 } else if self.is_const_item() {
1212 self.expect_keyword(keywords::Const)?;
1213 let ident = self.parse_ident()?;
1214 self.expect(&token::Colon)?;
1215 let ty = self.parse_ty()?;
1216 let default = if self.check(&token::Eq) {
1218 let expr = self.parse_expr()?;
1219 self.expect(&token::Semi)?;
1222 self.expect(&token::Semi)?;
1225 (ident, TraitItemKind::Const(ty, default))
1226 } else if self.token.is_path_start() {
1227 // trait item macro.
1228 // code copied from parse_macro_use_or_failure... abstraction!
1229 let prev_span = self.prev_span;
1231 let pth = self.parse_path(PathStyle::Mod)?;
1233 if pth.segments.len() == 1 {
1234 if !self.eat(&token::Not) {
1235 return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1238 self.expect(&token::Not)?;
1241 // eat a matched-delimiter token tree:
1242 let (delim, tts) = self.expect_delimited_token_tree()?;
1243 if delim != token::Brace {
1244 self.expect(&token::Semi)?
1247 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1248 (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac))
1250 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
1252 let ident = self.parse_ident()?;
1253 let mut generics = self.parse_generics()?;
1255 let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1256 // This is somewhat dubious; We don't want to allow
1257 // argument names to be left off if there is a
1259 p.parse_arg_general(false)
1262 generics.where_clause = self.parse_where_clause()?;
1263 let sig = ast::MethodSig {
1265 constness: constness,
1271 let body = match self.token {
1275 debug!("parse_trait_methods(): parsing required method");
1278 token::OpenDelim(token::Brace) => {
1279 debug!("parse_trait_methods(): parsing provided method");
1281 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1282 attrs.extend(inner_attrs.iter().cloned());
1286 let token_str = self.this_token_to_string();
1287 return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1290 (ident, ast::TraitItemKind::Method(sig, body))
1294 id: ast::DUMMY_NODE_ID,
1298 span: lo.to(self.prev_span),
1302 /// Parse optional return type [ -> TY ] in function decl
1303 pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1304 if self.eat(&token::RArrow) {
1305 Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
1307 Ok(FunctionRetTy::Default(Span { hi: self.span.lo, ..self.span }))
1312 pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1313 self.parse_ty_common(true)
1316 /// Parse a type in restricted contexts where `+` is not permitted.
1317 /// Example 1: `&'a TYPE`
1318 /// `+` is prohibited to maintain operator priority (P(+) < P(&)).
1319 /// Example 2: `value1 as TYPE + value2`
1320 /// `+` is prohibited to avoid interactions with expression grammar.
1321 fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1322 self.parse_ty_common(false)
1325 fn parse_ty_common(&mut self, allow_plus: bool) -> PResult<'a, P<Ty>> {
1326 maybe_whole!(self, NtTy, |x| x);
1329 let node = if self.eat(&token::OpenDelim(token::Paren)) {
1330 // `(TYPE)` is a parenthesized type.
1331 // `(TYPE,)` is a tuple with a single field of type TYPE.
1332 let mut ts = vec![];
1333 let mut last_comma = false;
1334 while self.token != token::CloseDelim(token::Paren) {
1335 ts.push(self.parse_ty()?);
1336 if self.eat(&token::Comma) {
1343 let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1344 self.expect(&token::CloseDelim(token::Paren))?;
1346 if ts.len() == 1 && !last_comma {
1347 let ty = ts.into_iter().nth(0).unwrap().unwrap();
1348 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1350 // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1351 TyKind::Path(None, ref path) if maybe_bounds => {
1352 self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1354 TyKind::TraitObject(ref bounds)
1355 if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1356 let path = match bounds[0] {
1357 TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1358 _ => self.bug("unexpected lifetime bound"),
1360 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1363 _ => TyKind::Paren(P(ty))
1368 } else if self.eat(&token::Not) {
1371 } else if self.eat(&token::BinOp(token::Star)) {
1373 TyKind::Ptr(self.parse_ptr()?)
1374 } else if self.eat(&token::OpenDelim(token::Bracket)) {
1376 let t = self.parse_ty()?;
1377 // Parse optional `; EXPR` in `[TYPE; EXPR]`
1378 let t = match self.maybe_parse_fixed_length_of_vec()? {
1379 None => TyKind::Slice(t),
1380 Some(suffix) => TyKind::Array(t, suffix),
1382 self.expect(&token::CloseDelim(token::Bracket))?;
1384 } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1387 self.parse_borrowed_pointee()?
1388 } else if self.eat_keyword_noexpect(keywords::Typeof) {
1390 // In order to not be ambiguous, the type must be surrounded by parens.
1391 self.expect(&token::OpenDelim(token::Paren))?;
1392 let e = self.parse_expr()?;
1393 self.expect(&token::CloseDelim(token::Paren))?;
1395 } else if self.eat(&token::Underscore) {
1396 // A type to be inferred `_`
1398 } else if self.eat_lt() {
1400 let (qself, path) = self.parse_qualified_path(PathStyle::Type)?;
1401 TyKind::Path(Some(qself), path)
1402 } else if self.token.is_path_start() {
1404 let path = self.parse_path(PathStyle::Type)?;
1405 if self.eat(&token::Not) {
1406 // Macro invocation in type position
1407 let (_, tts) = self.expect_delimited_token_tree()?;
1408 TyKind::Mac(respan(lo.to(self.span), Mac_ { path: path, tts: tts }))
1410 // Just a type path or bound list (trait object type) starting with a trait.
1412 // `Trait1 + Trait2 + 'a`
1413 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1414 self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1416 TyKind::Path(None, path)
1419 } else if self.token_is_bare_fn_keyword() {
1420 // Function pointer type
1421 self.parse_ty_bare_fn(Vec::new())?
1422 } else if self.check_keyword(keywords::For) {
1423 // Function pointer type or bound list (trait object type) starting with a poly-trait.
1424 // `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1425 // `for<'lt> Trait1<'lt> + Trait2 + 'a`
1427 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1428 if self.token_is_bare_fn_keyword() {
1429 self.parse_ty_bare_fn(lifetime_defs)?
1431 let path = self.parse_path(PathStyle::Type)?;
1432 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1433 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1435 } else if self.eat_keyword(keywords::Impl) {
1436 // FIXME: figure out priority of `+` in `impl Trait1 + Trait2` (#34511).
1437 TyKind::ImplTrait(self.parse_ty_param_bounds()?)
1438 } else if self.check(&token::Question) ||
1439 self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)){
1440 // Bound list (trait object type)
1441 TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?)
1443 let msg = format!("expected type, found {}", self.this_token_descr());
1444 return Err(self.fatal(&msg));
1447 let span = lo.to(self.prev_span);
1448 let ty = Ty { node: node, span: span, id: ast::DUMMY_NODE_ID };
1450 // Try to recover from use of `+` with incorrect priority.
1451 self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1456 fn parse_remaining_bounds(&mut self, lifetime_defs: Vec<LifetimeDef>, path: ast::Path,
1457 lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1458 let poly_trait_ref = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
1459 let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1462 bounds.append(&mut self.parse_ty_param_bounds()?);
1464 Ok(TyKind::TraitObject(bounds))
1467 fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1468 // Do not add `+` to expected tokens.
1469 if !allow_plus || self.token != token::BinOp(token::Plus) {
1474 let bounds = self.parse_ty_param_bounds()?;
1475 let sum_span = ty.span.to(self.prev_span);
1477 let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1478 "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1481 TyKind::Rptr(ref lifetime, ref mut_ty) => {
1482 let sum_with_parens = pprust::to_string(|s| {
1483 use print::pprust::PrintState;
1486 s.print_opt_lifetime(lifetime)?;
1487 s.print_mutability(mut_ty.mutbl)?;
1489 s.print_type(&mut_ty.ty)?;
1490 s.print_bounds(" +", &bounds)?;
1493 err.span_suggestion(sum_span, "try adding parentheses", sum_with_parens);
1495 TyKind::Ptr(..) | TyKind::BareFn(..) => {
1496 err.span_label(sum_span, "perhaps you forgot parentheses?");
1499 err.span_label(sum_span, "expected a path");
1506 fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1507 let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1508 let mutbl = self.parse_mutability();
1509 let ty = self.parse_ty_no_plus()?;
1510 return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1513 pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1514 let mutbl = if self.eat_keyword(keywords::Mut) {
1516 } else if self.eat_keyword(keywords::Const) {
1517 Mutability::Immutable
1519 let span = self.prev_span;
1521 "expected mut or const in raw pointer type (use \
1522 `*mut T` or `*const T` as appropriate)");
1523 Mutability::Immutable
1525 let t = self.parse_ty_no_plus()?;
1526 Ok(MutTy { ty: t, mutbl: mutbl })
1529 pub fn is_named_argument(&mut self) -> bool {
1530 let offset = match self.token {
1531 token::BinOp(token::And) |
1533 _ if self.token.is_keyword(keywords::Mut) => 1,
1537 debug!("parser is_named_argument offset:{}", offset);
1540 is_ident_or_underscore(&self.token)
1541 && self.look_ahead(1, |t| *t == token::Colon)
1543 self.look_ahead(offset, |t| is_ident_or_underscore(t))
1544 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1548 /// This version of parse arg doesn't necessarily require
1549 /// identifier names.
1550 pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1551 maybe_whole!(self, NtArg, |x| x);
1553 let pat = if require_name || self.is_named_argument() {
1554 debug!("parse_arg_general parse_pat (require_name:{})",
1556 let pat = self.parse_pat()?;
1558 self.expect(&token::Colon)?;
1561 debug!("parse_arg_general ident_to_pat");
1562 let sp = self.prev_span;
1563 let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1565 id: ast::DUMMY_NODE_ID,
1566 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1572 let t = self.parse_ty()?;
1577 id: ast::DUMMY_NODE_ID,
1581 /// Parse a single function argument
1582 pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1583 self.parse_arg_general(true)
1586 /// Parse an argument in a lambda header e.g. |arg, arg|
1587 pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1588 let pat = self.parse_pat()?;
1589 let t = if self.eat(&token::Colon) {
1593 id: ast::DUMMY_NODE_ID,
1594 node: TyKind::Infer,
1601 id: ast::DUMMY_NODE_ID
1605 pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1606 if self.eat(&token::Semi) {
1607 Ok(Some(self.parse_expr()?))
1613 /// Matches token_lit = LIT_INTEGER | ...
1614 pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1615 let out = match self.token {
1616 token::Interpolated(ref nt) => match nt.0 {
1617 token::NtExpr(ref v) => match v.node {
1618 ExprKind::Lit(ref lit) => { lit.node.clone() }
1619 _ => { return self.unexpected_last(&self.token); }
1621 _ => { return self.unexpected_last(&self.token); }
1623 token::Literal(lit, suf) => {
1624 let diag = Some((self.span, &self.sess.span_diagnostic));
1625 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1629 self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1634 _ => { return self.unexpected_last(&self.token); }
1641 /// Matches lit = true | false | token_lit
1642 pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1644 let lit = if self.eat_keyword(keywords::True) {
1646 } else if self.eat_keyword(keywords::False) {
1647 LitKind::Bool(false)
1649 let lit = self.parse_lit_token()?;
1652 Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1655 /// matches '-' lit | lit (cf. ast_validation::AstValidator::check_expr_within_pat)
1656 pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1657 maybe_whole_expr!(self);
1659 let minus_lo = self.span;
1660 let minus_present = self.eat(&token::BinOp(token::Minus));
1662 let literal = P(self.parse_lit()?);
1663 let hi = self.prev_span;
1664 let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1667 let minus_hi = self.prev_span;
1668 let unary = self.mk_unary(UnOp::Neg, expr);
1669 Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1675 pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1677 token::Ident(sid) if self.token.is_path_segment_keyword() => {
1681 _ => self.parse_ident(),
1685 /// Parses qualified path.
1687 /// Assumes that the leading `<` has been parsed already.
1689 /// Qualifed paths are a part of the universal function call
1692 /// `qualified_path = <type [as trait_ref]>::path`
1694 /// See `parse_path` for `mode` meaning.
1699 /// `<T as U>::F::a::<S>`
1700 pub fn parse_qualified_path(&mut self, mode: PathStyle)
1701 -> PResult<'a, (QSelf, ast::Path)> {
1702 let span = self.prev_span;
1703 let self_type = self.parse_ty()?;
1704 let mut path = if self.eat_keyword(keywords::As) {
1705 self.parse_path(PathStyle::Type)?
1715 position: path.segments.len()
1718 self.expect(&token::Gt)?;
1719 self.expect(&token::ModSep)?;
1721 let segments = match mode {
1722 PathStyle::Type => {
1723 self.parse_path_segments_without_colons(true)?
1725 PathStyle::Expr => {
1726 self.parse_path_segments_with_colons()?
1729 self.parse_path_segments_without_types()?
1732 path.segments.extend(segments);
1734 path.span.hi = self.prev_span.hi;
1739 /// Parses a path and optional type parameter bounds, depending on the
1740 /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1741 /// bounds are permitted and whether `::` must precede type parameter
1743 pub fn parse_path(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1744 self.parse_path_common(mode, true)
1747 pub fn parse_path_without_generics(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1748 self.parse_path_common(mode, false)
1751 fn parse_path_common(&mut self, mode: PathStyle, parse_generics: bool)
1752 -> PResult<'a, ast::Path>
1754 maybe_whole!(self, NtPath, |x| x);
1756 let lo = self.meta_var_span.unwrap_or(self.span);
1757 let is_global = self.eat(&token::ModSep);
1759 // Parse any number of segments and bound sets. A segment is an
1760 // identifier followed by an optional lifetime and a set of types.
1761 // A bound set is a set of type parameter bounds.
1762 let mut segments = match mode {
1763 PathStyle::Type => {
1764 self.parse_path_segments_without_colons(parse_generics)?
1766 PathStyle::Expr => {
1767 self.parse_path_segments_with_colons()?
1770 self.parse_path_segments_without_types()?
1775 segments.insert(0, PathSegment::crate_root(lo));
1778 // Assemble the result.
1780 span: lo.to(self.prev_span),
1785 /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1786 /// This is used when parsing derive macro paths in `#[derive]` attributes.
1787 pub fn parse_path_allowing_meta(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1788 let meta_ident = match self.token {
1789 token::Interpolated(ref nt) => match nt.0 {
1790 token::NtMeta(ref meta) => match meta.node {
1791 ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
1798 if let Some(ident) = meta_ident {
1800 return Ok(ast::Path::from_ident(self.prev_span, ident));
1802 self.parse_path(mode)
1806 /// - `a::b<T,U>::c<V,W>`
1807 /// - `a::b<T,U>::c(V) -> W`
1808 /// - `a::b<T,U>::c(V)`
1809 pub fn parse_path_segments_without_colons(&mut self, parse_generics: bool)
1810 -> PResult<'a, Vec<PathSegment>>
1812 let mut segments = Vec::new();
1814 // First, parse an identifier.
1815 let ident_span = self.span;
1816 let identifier = self.parse_path_segment_ident()?;
1818 if self.check(&token::ModSep) && self.look_ahead(1, |t| *t == token::Lt) {
1820 let prev_span = self.prev_span;
1822 let mut err = self.diagnostic().struct_span_err(prev_span,
1823 "unexpected token: `::`");
1825 "use `<...>` instead of `::<...>` if you meant to specify type arguments");
1829 // Parse types, optionally.
1830 let parameters = if parse_generics && self.eat_lt() {
1831 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1833 AngleBracketedParameterData { lifetimes, types, bindings }.into()
1834 } else if self.eat(&token::OpenDelim(token::Paren)) {
1835 let lo = self.prev_span;
1837 let inputs = self.parse_seq_to_end(
1838 &token::CloseDelim(token::Paren),
1839 SeqSep::trailing_allowed(token::Comma),
1842 let output_ty = if self.eat(&token::RArrow) {
1843 Some(self.parse_ty_no_plus()?)
1848 let hi = self.prev_span;
1850 Some(P(ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData {
1859 // Assemble and push the result.
1860 segments.push(PathSegment {
1861 identifier: identifier,
1863 parameters: parameters
1866 // Continue only if we see a `::`
1867 if !self.eat(&token::ModSep) {
1868 return Ok(segments);
1874 /// - `a::b::<T,U>::c`
1875 pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1876 let mut segments = Vec::new();
1878 // First, parse an identifier.
1879 let ident_span = self.span;
1880 let identifier = self.parse_path_segment_ident()?;
1882 // If we do not see a `::`, stop.
1883 if !self.eat(&token::ModSep) {
1884 segments.push(PathSegment::from_ident(identifier, ident_span));
1885 return Ok(segments);
1888 // Check for a type segment.
1890 // Consumed `a::b::<`, go look for types
1891 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1893 segments.push(PathSegment {
1894 identifier: identifier,
1896 parameters: AngleBracketedParameterData { lifetimes, types, bindings }.into(),
1899 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1900 if !self.eat(&token::ModSep) {
1901 return Ok(segments);
1904 // Consumed `a::`, go look for `b`
1905 segments.push(PathSegment::from_ident(identifier, ident_span));
1912 pub fn parse_path_segments_without_types(&mut self)
1913 -> PResult<'a, Vec<PathSegment>> {
1914 let mut segments = Vec::new();
1916 // First, parse an identifier.
1917 let ident_span = self.span;
1918 let identifier = self.parse_path_segment_ident()?;
1920 // Assemble and push the result.
1921 segments.push(PathSegment::from_ident(identifier, ident_span));
1923 // If we do not see a `::` or see `::{`/`::*`, stop.
1924 if !self.check(&token::ModSep) || self.is_import_coupler() {
1925 return Ok(segments);
1932 fn check_lifetime(&mut self) -> bool {
1933 self.expected_tokens.push(TokenType::Lifetime);
1934 self.token.is_lifetime()
1937 /// Parse single lifetime 'a or panic.
1938 fn expect_lifetime(&mut self) -> Lifetime {
1940 token::Lifetime(ident) => {
1941 let ident_span = self.span;
1943 Lifetime { ident: ident, span: ident_span, id: ast::DUMMY_NODE_ID }
1945 _ => self.span_bug(self.span, "not a lifetime")
1949 /// Parse mutability (`mut` or nothing).
1950 fn parse_mutability(&mut self) -> Mutability {
1951 if self.eat_keyword(keywords::Mut) {
1954 Mutability::Immutable
1958 pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1959 if let token::Literal(token::Integer(name), None) = self.token {
1961 Ok(Ident::with_empty_ctxt(name))
1967 /// Parse ident (COLON expr)?
1968 pub fn parse_field(&mut self) -> PResult<'a, Field> {
1969 let attrs = self.parse_outer_attributes()?;
1973 // Check if a colon exists one ahead. This means we're parsing a fieldname.
1974 let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1975 let fieldname = self.parse_field_name()?;
1977 hi = self.prev_span;
1978 (fieldname, self.parse_expr()?, false)
1980 let fieldname = self.parse_ident()?;
1981 hi = self.prev_span;
1983 // Mimic `x: x` for the `x` field shorthand.
1984 let path = ast::Path::from_ident(lo.to(hi), fieldname);
1985 (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
1988 ident: respan(lo.to(hi), fieldname),
1989 span: lo.to(expr.span),
1991 is_shorthand: is_shorthand,
1992 attrs: attrs.into(),
1996 pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
1998 id: ast::DUMMY_NODE_ID,
2001 attrs: attrs.into(),
2005 pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2006 ExprKind::Unary(unop, expr)
2009 pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2010 ExprKind::Binary(binop, lhs, rhs)
2013 pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2014 ExprKind::Call(f, args)
2017 pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2018 ExprKind::Index(expr, idx)
2021 pub fn mk_range(&mut self,
2022 start: Option<P<Expr>>,
2023 end: Option<P<Expr>>,
2024 limits: RangeLimits)
2025 -> PResult<'a, ast::ExprKind> {
2026 if end.is_none() && limits == RangeLimits::Closed {
2027 Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2029 Ok(ExprKind::Range(start, end, limits))
2033 pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::ExprKind {
2034 ExprKind::Field(expr, ident)
2037 pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2038 ExprKind::TupField(expr, idx)
2041 pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2042 lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2043 ExprKind::AssignOp(binop, lhs, rhs)
2046 pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2048 id: ast::DUMMY_NODE_ID,
2049 node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2055 pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2056 let span = &self.span;
2057 let lv_lit = P(codemap::Spanned {
2058 node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2063 id: ast::DUMMY_NODE_ID,
2064 node: ExprKind::Lit(lv_lit),
2070 fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2072 token::OpenDelim(delim) => match self.parse_token_tree() {
2073 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2074 _ => unreachable!(),
2076 _ => Err(self.fatal("expected open delimiter")),
2080 /// At the bottom (top?) of the precedence hierarchy,
2081 /// parse things like parenthesized exprs,
2082 /// macros, return, etc.
2084 /// NB: This does not parse outer attributes,
2085 /// and is private because it only works
2086 /// correctly if called from parse_dot_or_call_expr().
2087 fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2088 maybe_whole_expr!(self);
2090 // Outer attributes are already parsed and will be
2091 // added to the return value after the fact.
2093 // Therefore, prevent sub-parser from parsing
2094 // attributes by giving them a empty "already parsed" list.
2095 let mut attrs = ThinVec::new();
2098 let mut hi = self.span;
2102 // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2104 token::OpenDelim(token::Paren) => {
2107 attrs.extend(self.parse_inner_attributes()?);
2109 // (e) is parenthesized e
2110 // (e,) is a tuple with only one field, e
2111 let mut es = vec![];
2112 let mut trailing_comma = false;
2113 while self.token != token::CloseDelim(token::Paren) {
2114 es.push(self.parse_expr()?);
2115 self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2116 if self.check(&token::Comma) {
2117 trailing_comma = true;
2121 trailing_comma = false;
2127 hi = self.prev_span;
2128 let span = lo.to(hi);
2129 return if es.len() == 1 && !trailing_comma {
2130 Ok(self.mk_expr(span, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2132 Ok(self.mk_expr(span, ExprKind::Tup(es), attrs))
2135 token::OpenDelim(token::Brace) => {
2136 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2138 token::BinOp(token::Or) | token::OrOr => {
2140 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2142 token::OpenDelim(token::Bracket) => {
2145 attrs.extend(self.parse_inner_attributes()?);
2147 if self.check(&token::CloseDelim(token::Bracket)) {
2150 ex = ExprKind::Array(Vec::new());
2153 let first_expr = self.parse_expr()?;
2154 if self.check(&token::Semi) {
2155 // Repeating array syntax: [ 0; 512 ]
2157 let count = self.parse_expr()?;
2158 self.expect(&token::CloseDelim(token::Bracket))?;
2159 ex = ExprKind::Repeat(first_expr, count);
2160 } else if self.check(&token::Comma) {
2161 // Vector with two or more elements.
2163 let remaining_exprs = self.parse_seq_to_end(
2164 &token::CloseDelim(token::Bracket),
2165 SeqSep::trailing_allowed(token::Comma),
2166 |p| Ok(p.parse_expr()?)
2168 let mut exprs = vec![first_expr];
2169 exprs.extend(remaining_exprs);
2170 ex = ExprKind::Array(exprs);
2172 // Vector with one element.
2173 self.expect(&token::CloseDelim(token::Bracket))?;
2174 ex = ExprKind::Array(vec![first_expr]);
2177 hi = self.prev_span;
2182 self.parse_qualified_path(PathStyle::Expr)?;
2184 return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2186 if self.eat_keyword(keywords::Move) {
2187 let lo = self.prev_span;
2188 return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2190 if self.eat_keyword(keywords::If) {
2191 return self.parse_if_expr(attrs);
2193 if self.eat_keyword(keywords::For) {
2194 let lo = self.prev_span;
2195 return self.parse_for_expr(None, lo, attrs);
2197 if self.eat_keyword(keywords::While) {
2198 let lo = self.prev_span;
2199 return self.parse_while_expr(None, lo, attrs);
2201 if self.token.is_lifetime() {
2202 let label = Spanned { node: self.get_label(),
2206 self.expect(&token::Colon)?;
2207 if self.eat_keyword(keywords::While) {
2208 return self.parse_while_expr(Some(label), lo, attrs)
2210 if self.eat_keyword(keywords::For) {
2211 return self.parse_for_expr(Some(label), lo, attrs)
2213 if self.eat_keyword(keywords::Loop) {
2214 return self.parse_loop_expr(Some(label), lo, attrs)
2216 return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2218 if self.eat_keyword(keywords::Loop) {
2219 let lo = self.prev_span;
2220 return self.parse_loop_expr(None, lo, attrs);
2222 if self.eat_keyword(keywords::Continue) {
2223 let ex = if self.token.is_lifetime() {
2224 let ex = ExprKind::Continue(Some(Spanned{
2225 node: self.get_label(),
2231 ExprKind::Continue(None)
2233 let hi = self.prev_span;
2234 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2236 if self.eat_keyword(keywords::Match) {
2237 return self.parse_match_expr(attrs);
2239 if self.eat_keyword(keywords::Unsafe) {
2240 return self.parse_block_expr(
2242 BlockCheckMode::Unsafe(ast::UserProvided),
2245 if self.is_catch_expr() {
2247 assert!(self.eat_keyword(keywords::Do));
2248 assert!(self.eat_keyword(keywords::Catch));
2249 return self.parse_catch_expr(lo, attrs);
2251 if self.eat_keyword(keywords::Return) {
2252 if self.token.can_begin_expr() {
2253 let e = self.parse_expr()?;
2255 ex = ExprKind::Ret(Some(e));
2257 ex = ExprKind::Ret(None);
2259 } else if self.eat_keyword(keywords::Break) {
2260 let lt = if self.token.is_lifetime() {
2261 let spanned_lt = Spanned {
2262 node: self.get_label(),
2270 let e = if self.token.can_begin_expr()
2271 && !(self.token == token::OpenDelim(token::Brace)
2272 && self.restrictions.contains(
2273 RESTRICTION_NO_STRUCT_LITERAL)) {
2274 Some(self.parse_expr()?)
2278 ex = ExprKind::Break(lt, e);
2279 hi = self.prev_span;
2280 } else if self.token.is_keyword(keywords::Let) {
2281 // Catch this syntax error here, instead of in `parse_ident`, so
2282 // that we can explicitly mention that let is not to be used as an expression
2283 let mut db = self.fatal("expected expression, found statement (`let`)");
2284 db.note("variable declaration using `let` is a statement");
2286 } else if self.token.is_path_start() {
2287 let pth = self.parse_path(PathStyle::Expr)?;
2289 // `!`, as an operator, is prefix, so we know this isn't that
2290 if self.eat(&token::Not) {
2291 // MACRO INVOCATION expression
2292 let (_, tts) = self.expect_delimited_token_tree()?;
2293 let hi = self.prev_span;
2294 return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2296 if self.check(&token::OpenDelim(token::Brace)) {
2297 // This is a struct literal, unless we're prohibited
2298 // from parsing struct literals here.
2299 let prohibited = self.restrictions.contains(
2300 RESTRICTION_NO_STRUCT_LITERAL
2303 return self.parse_struct_expr(lo, pth, attrs);
2308 ex = ExprKind::Path(None, pth);
2310 match self.parse_lit() {
2313 ex = ExprKind::Lit(P(lit));
2316 self.cancel(&mut err);
2317 let msg = format!("expected expression, found {}",
2318 self.this_token_descr());
2319 return Err(self.fatal(&msg));
2326 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2329 fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2330 -> PResult<'a, P<Expr>> {
2332 let mut fields = Vec::new();
2333 let mut base = None;
2335 attrs.extend(self.parse_inner_attributes()?);
2337 while self.token != token::CloseDelim(token::Brace) {
2338 if self.eat(&token::DotDot) {
2339 match self.parse_expr() {
2345 self.recover_stmt();
2351 match self.parse_field() {
2352 Ok(f) => fields.push(f),
2355 self.recover_stmt();
2360 match self.expect_one_of(&[token::Comma],
2361 &[token::CloseDelim(token::Brace)]) {
2365 self.recover_stmt();
2371 let span = lo.to(self.span);
2372 self.expect(&token::CloseDelim(token::Brace))?;
2373 return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2376 fn parse_or_use_outer_attributes(&mut self,
2377 already_parsed_attrs: Option<ThinVec<Attribute>>)
2378 -> PResult<'a, ThinVec<Attribute>> {
2379 if let Some(attrs) = already_parsed_attrs {
2382 self.parse_outer_attributes().map(|a| a.into())
2386 /// Parse a block or unsafe block
2387 pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2388 outer_attrs: ThinVec<Attribute>)
2389 -> PResult<'a, P<Expr>> {
2390 self.expect(&token::OpenDelim(token::Brace))?;
2392 let mut attrs = outer_attrs;
2393 attrs.extend(self.parse_inner_attributes()?);
2395 let blk = self.parse_block_tail(lo, blk_mode)?;
2396 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2399 /// parse a.b or a(13) or a[4] or just a
2400 pub fn parse_dot_or_call_expr(&mut self,
2401 already_parsed_attrs: Option<ThinVec<Attribute>>)
2402 -> PResult<'a, P<Expr>> {
2403 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2405 let b = self.parse_bottom_expr();
2406 let (span, b) = self.interpolated_or_expr_span(b)?;
2407 self.parse_dot_or_call_expr_with(b, span, attrs)
2410 pub fn parse_dot_or_call_expr_with(&mut self,
2413 mut attrs: ThinVec<Attribute>)
2414 -> PResult<'a, P<Expr>> {
2415 // Stitch the list of outer attributes onto the return value.
2416 // A little bit ugly, but the best way given the current code
2418 self.parse_dot_or_call_expr_with_(e0, lo)
2420 expr.map(|mut expr| {
2421 attrs.extend::<Vec<_>>(expr.attrs.into());
2423 if if let Some(ref doc) = expr.attrs.iter().find(|x| x.is_sugared_doc) {
2424 self.span_fatal_err(doc.span, Error::UselessDocComment).emit();
2430 ExprKind::If(..) | ExprKind::IfLet(..) => {
2431 if !expr.attrs.is_empty() {
2432 // Just point to the first attribute in there...
2433 let span = expr.attrs[0].span;
2436 "attributes are not yet allowed on `if` \
2447 // Assuming we have just parsed `.foo` (i.e., a dot and an ident), continue
2448 // parsing into an expression.
2449 fn parse_dot_suffix(&mut self, ident: Ident, ident_span: Span, self_value: P<Expr>, lo: Span)
2450 -> PResult<'a, P<Expr>> {
2451 let (lifetimes, types, bindings) = if self.eat(&token::ModSep) {
2453 let args = self.parse_generic_args()?;
2457 (Vec::new(), Vec::new(), Vec::new())
2460 Ok(match self.token {
2461 // expr.f() method call.
2462 token::OpenDelim(token::Paren) => {
2463 let mut es = self.parse_unspanned_seq(
2464 &token::OpenDelim(token::Paren),
2465 &token::CloseDelim(token::Paren),
2466 SeqSep::trailing_allowed(token::Comma),
2467 |p| Ok(p.parse_expr()?)
2469 let hi = self.prev_span;
2471 es.insert(0, self_value);
2472 let seg = PathSegment {
2474 span: ident_span.to(ident_span),
2475 parameters: AngleBracketedParameterData { lifetimes, types, bindings }.into(),
2477 self.mk_expr(lo.to(hi), ExprKind::MethodCall(seg, es), ThinVec::new())
2481 if let Some(generic_arg_span) = lifetimes.get(0).map(|x| x.span).or_else(||
2482 types.get(0).map(|x| x.span)).or_else(||
2483 bindings.get(0).map(|x| x.span)) {
2484 self.span_err(generic_arg_span,
2485 "field expressions may not have generic arguments");
2488 let id = respan(ident_span.to(ident_span), ident);
2489 let field = self.mk_field(self_value, id);
2490 self.mk_expr(lo.to(ident_span), field, ThinVec::new())
2495 fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2500 while self.eat(&token::Question) {
2501 let hi = self.prev_span;
2502 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2506 if self.eat(&token::Dot) {
2508 token::Ident(i) => {
2509 let ident_span = self.span;
2511 e = self.parse_dot_suffix(i, ident_span, e, lo)?;
2513 token::Literal(token::Integer(n), suf) => {
2516 // A tuple index may not have a suffix
2517 self.expect_no_suffix(sp, "tuple index", suf);
2519 let dot_span = self.prev_span;
2523 let index = n.as_str().parse::<usize>().ok();
2526 let id = respan(dot_span.to(hi), n);
2527 let field = self.mk_tup_field(e, id);
2528 e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2531 let prev_span = self.prev_span;
2532 self.span_err(prev_span, "invalid tuple or tuple struct index");
2536 token::Literal(token::Float(n), _suf) => {
2538 let fstr = n.as_str();
2539 let mut err = self.diagnostic().struct_span_err(self.prev_span,
2540 &format!("unexpected token: `{}`", n));
2541 err.span_label(self.prev_span, "unexpected token");
2542 if fstr.chars().all(|x| "0123456789.".contains(x)) {
2543 let float = match fstr.parse::<f64>().ok() {
2547 let sugg = pprust::to_string(|s| {
2548 use print::pprust::PrintState;
2552 s.print_usize(float.trunc() as usize)?;
2555 s.s.word(fstr.splitn(2, ".").last().unwrap())
2557 err.span_suggestion(
2558 lo.to(self.prev_span),
2559 "try parenthesizing the first index",
2566 // FIXME Could factor this out into non_fatal_unexpected or something.
2567 let actual = self.this_token_to_string();
2568 self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2570 let dot_span = self.prev_span;
2571 e = self.parse_dot_suffix(keywords::Invalid.ident(), dot_span, e, lo)?;
2576 if self.expr_is_complete(&e) { break; }
2579 token::OpenDelim(token::Paren) => {
2580 let es = self.parse_unspanned_seq(
2581 &token::OpenDelim(token::Paren),
2582 &token::CloseDelim(token::Paren),
2583 SeqSep::trailing_allowed(token::Comma),
2584 |p| Ok(p.parse_expr()?)
2586 hi = self.prev_span;
2588 let nd = self.mk_call(e, es);
2589 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2593 // Could be either an index expression or a slicing expression.
2594 token::OpenDelim(token::Bracket) => {
2596 let ix = self.parse_expr()?;
2598 self.expect(&token::CloseDelim(token::Bracket))?;
2599 let index = self.mk_index(e, ix);
2600 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2608 pub fn process_potential_macro_variable(&mut self) {
2609 let ident = match self.token {
2610 token::Dollar if self.span.ctxt != syntax_pos::hygiene::SyntaxContext::empty() &&
2611 self.look_ahead(1, |t| t.is_ident()) => {
2613 let name = match self.token { token::Ident(ident) => ident, _ => unreachable!() };
2614 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2617 token::Interpolated(ref nt) => {
2618 self.meta_var_span = Some(self.span);
2620 token::NtIdent(ident) => ident,
2626 self.token = token::Ident(ident.node);
2627 self.span = ident.span;
2630 /// parse a single token tree from the input.
2631 pub fn parse_token_tree(&mut self) -> TokenTree {
2633 token::OpenDelim(..) => {
2634 let frame = mem::replace(&mut self.token_cursor.frame,
2635 self.token_cursor.stack.pop().unwrap());
2636 self.span = frame.span;
2638 TokenTree::Delimited(frame.span, Delimited {
2640 tts: frame.tree_cursor.original_stream().into(),
2643 token::CloseDelim(_) | token::Eof => unreachable!(),
2645 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2647 TokenTree::Token(span, token)
2652 // parse a stream of tokens into a list of TokenTree's,
2654 pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2655 let mut tts = Vec::new();
2656 while self.token != token::Eof {
2657 tts.push(self.parse_token_tree());
2662 pub fn parse_tokens(&mut self) -> TokenStream {
2663 let mut result = Vec::new();
2666 token::Eof | token::CloseDelim(..) => break,
2667 _ => result.push(self.parse_token_tree().into()),
2670 TokenStream::concat(result)
2673 /// Parse a prefix-unary-operator expr
2674 pub fn parse_prefix_expr(&mut self,
2675 already_parsed_attrs: Option<ThinVec<Attribute>>)
2676 -> PResult<'a, P<Expr>> {
2677 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2679 // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2680 let (hi, ex) = match self.token {
2683 let e = self.parse_prefix_expr(None);
2684 let (span, e) = self.interpolated_or_expr_span(e)?;
2685 (span, self.mk_unary(UnOp::Not, e))
2687 // Suggest `!` for bitwise negation when encountering a `~`
2690 let e = self.parse_prefix_expr(None);
2691 let (span, e) = self.interpolated_or_expr_span(e)?;
2692 let span_of_tilde = lo;
2693 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2694 "`~` can not be used as a unary operator");
2695 err.span_label(span_of_tilde, "did you mean `!`?");
2696 err.help("use `!` instead of `~` if you meant to perform bitwise negation");
2698 (span, self.mk_unary(UnOp::Not, e))
2700 token::BinOp(token::Minus) => {
2702 let e = self.parse_prefix_expr(None);
2703 let (span, e) = self.interpolated_or_expr_span(e)?;
2704 (span, self.mk_unary(UnOp::Neg, e))
2706 token::BinOp(token::Star) => {
2708 let e = self.parse_prefix_expr(None);
2709 let (span, e) = self.interpolated_or_expr_span(e)?;
2710 (span, self.mk_unary(UnOp::Deref, e))
2712 token::BinOp(token::And) | token::AndAnd => {
2714 let m = self.parse_mutability();
2715 let e = self.parse_prefix_expr(None);
2716 let (span, e) = self.interpolated_or_expr_span(e)?;
2717 (span, ExprKind::AddrOf(m, e))
2719 token::Ident(..) if self.token.is_keyword(keywords::In) => {
2721 let place = self.parse_expr_res(
2722 RESTRICTION_NO_STRUCT_LITERAL,
2725 let blk = self.parse_block()?;
2726 let span = blk.span;
2727 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2728 (span, ExprKind::InPlace(place, blk_expr))
2730 token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2732 let e = self.parse_prefix_expr(None);
2733 let (span, e) = self.interpolated_or_expr_span(e)?;
2734 (span, ExprKind::Box(e))
2736 _ => return self.parse_dot_or_call_expr(Some(attrs))
2738 return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2741 /// Parse an associative expression
2743 /// This parses an expression accounting for associativity and precedence of the operators in
2745 pub fn parse_assoc_expr(&mut self,
2746 already_parsed_attrs: Option<ThinVec<Attribute>>)
2747 -> PResult<'a, P<Expr>> {
2748 self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2751 /// Parse an associative expression with operators of at least `min_prec` precedence
2752 pub fn parse_assoc_expr_with(&mut self,
2755 -> PResult<'a, P<Expr>> {
2756 let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2759 let attrs = match lhs {
2760 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2763 if self.token == token::DotDot || self.token == token::DotDotDot {
2764 return self.parse_prefix_range_expr(attrs);
2766 self.parse_prefix_expr(attrs)?
2770 if self.expr_is_complete(&lhs) {
2771 // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2774 self.expected_tokens.push(TokenType::Operator);
2775 while let Some(op) = AssocOp::from_token(&self.token) {
2777 // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
2778 // it refers to. Interpolated identifiers are unwrapped early and never show up here
2779 // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
2780 // it as "interpolated", it doesn't change the answer for non-interpolated idents.
2781 let lhs_span = match (self.prev_token_kind, &lhs.node) {
2782 (PrevTokenKind::Interpolated, _) => self.prev_span,
2783 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
2784 if path.segments.len() == 1 => self.prev_span,
2788 let cur_op_span = self.span;
2789 let restrictions = if op.is_assign_like() {
2790 self.restrictions & RESTRICTION_NO_STRUCT_LITERAL
2794 if op.precedence() < min_prec {
2798 if op.is_comparison() {
2799 self.check_no_chained_comparison(&lhs, &op);
2802 if op == AssocOp::As {
2803 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
2805 } else if op == AssocOp::Colon {
2806 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
2809 err.span_label(self.span,
2810 "expecting a type here because of type ascription");
2811 let cm = self.sess.codemap();
2812 let cur_pos = cm.lookup_char_pos(self.span.lo);
2813 let op_pos = cm.lookup_char_pos(cur_op_span.hi);
2814 if cur_pos.line != op_pos.line {
2815 err.span_suggestion_short(cur_op_span,
2816 "did you mean to use `;` here?",
2823 } else if op == AssocOp::DotDot || op == AssocOp::DotDotDot {
2824 // If we didn’t have to handle `x..`/`x...`, it would be pretty easy to
2825 // generalise it to the Fixity::None code.
2827 // We have 2 alternatives here: `x..y`/`x...y` and `x..`/`x...` The other
2828 // two variants are handled with `parse_prefix_range_expr` call above.
2829 let rhs = if self.is_at_start_of_range_notation_rhs() {
2830 Some(self.parse_assoc_expr_with(op.precedence() + 1,
2831 LhsExpr::NotYetParsed)?)
2835 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2840 let limits = if op == AssocOp::DotDot {
2841 RangeLimits::HalfOpen
2846 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2847 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2851 let rhs = match op.fixity() {
2852 Fixity::Right => self.with_res(
2853 restrictions - RESTRICTION_STMT_EXPR,
2855 this.parse_assoc_expr_with(op.precedence(),
2856 LhsExpr::NotYetParsed)
2858 Fixity::Left => self.with_res(
2859 restrictions - RESTRICTION_STMT_EXPR,
2861 this.parse_assoc_expr_with(op.precedence() + 1,
2862 LhsExpr::NotYetParsed)
2864 // We currently have no non-associative operators that are not handled above by
2865 // the special cases. The code is here only for future convenience.
2866 Fixity::None => self.with_res(
2867 restrictions - RESTRICTION_STMT_EXPR,
2869 this.parse_assoc_expr_with(op.precedence() + 1,
2870 LhsExpr::NotYetParsed)
2874 let span = lhs_span.to(rhs.span);
2876 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2877 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2878 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2879 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2880 AssocOp::Greater | AssocOp::GreaterEqual => {
2881 let ast_op = op.to_ast_binop().unwrap();
2882 let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2883 self.mk_expr(span, binary, ThinVec::new())
2886 self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2888 self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
2889 AssocOp::AssignOp(k) => {
2891 token::Plus => BinOpKind::Add,
2892 token::Minus => BinOpKind::Sub,
2893 token::Star => BinOpKind::Mul,
2894 token::Slash => BinOpKind::Div,
2895 token::Percent => BinOpKind::Rem,
2896 token::Caret => BinOpKind::BitXor,
2897 token::And => BinOpKind::BitAnd,
2898 token::Or => BinOpKind::BitOr,
2899 token::Shl => BinOpKind::Shl,
2900 token::Shr => BinOpKind::Shr,
2902 let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2903 self.mk_expr(span, aopexpr, ThinVec::new())
2905 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotDot => {
2906 self.bug("As, Colon, DotDot or DotDotDot branch reached")
2910 if op.fixity() == Fixity::None { break }
2915 fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
2916 expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
2917 -> PResult<'a, P<Expr>> {
2918 let mk_expr = |this: &mut Self, rhs: P<Ty>| {
2919 this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
2922 // Save the state of the parser before parsing type normally, in case there is a
2923 // LessThan comparison after this cast.
2924 let parser_snapshot_before_type = self.clone();
2925 match self.parse_ty_no_plus() {
2927 Ok(mk_expr(self, rhs))
2929 Err(mut type_err) => {
2930 // Rewind to before attempting to parse the type with generics, to recover
2931 // from situations like `x as usize < y` in which we first tried to parse
2932 // `usize < y` as a type with generic arguments.
2933 let parser_snapshot_after_type = self.clone();
2934 mem::replace(self, parser_snapshot_before_type);
2936 match self.parse_path_without_generics(PathStyle::Type) {
2938 // Successfully parsed the type path leaving a `<` yet to parse.
2941 // Report non-fatal diagnostics, keep `x as usize` as an expression
2942 // in AST and continue parsing.
2943 let msg = format!("`<` is interpreted as a start of generic \
2944 arguments for `{}`, not a comparison", path);
2945 let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
2946 err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
2947 "interpreted as generic arguments");
2948 err.span_label(self.span, "not interpreted as comparison");
2950 let expr = mk_expr(self, P(Ty {
2952 node: TyKind::Path(None, path),
2953 id: ast::DUMMY_NODE_ID
2956 let expr_str = self.sess.codemap().span_to_snippet(expr.span)
2957 .unwrap_or(pprust::expr_to_string(&expr));
2958 err.span_suggestion(expr.span,
2959 "try comparing the casted value",
2960 format!("({})", expr_str));
2965 Err(mut path_err) => {
2966 // Couldn't parse as a path, return original error and parser state.
2968 mem::replace(self, parser_snapshot_after_type);
2976 /// Produce an error if comparison operators are chained (RFC #558).
2977 /// We only need to check lhs, not rhs, because all comparison ops
2978 /// have same precedence and are left-associative
2979 fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2980 debug_assert!(outer_op.is_comparison(),
2981 "check_no_chained_comparison: {:?} is not comparison",
2984 ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2985 // respan to include both operators
2986 let op_span = op.span.to(self.span);
2987 let mut err = self.diagnostic().struct_span_err(op_span,
2988 "chained comparison operators require parentheses");
2989 if op.node == BinOpKind::Lt &&
2990 *outer_op == AssocOp::Less || // Include `<` to provide this recommendation
2991 *outer_op == AssocOp::Greater // even in a case like the following:
2992 { // Foo<Bar<Baz<Qux, ()>>>
2994 "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3002 /// Parse prefix-forms of range notation: `..expr`, `..`, `...expr`
3003 fn parse_prefix_range_expr(&mut self,
3004 already_parsed_attrs: Option<ThinVec<Attribute>>)
3005 -> PResult<'a, P<Expr>> {
3006 debug_assert!(self.token == token::DotDot || self.token == token::DotDotDot,
3007 "parse_prefix_range_expr: token {:?} is not DotDot or DotDotDot",
3009 let tok = self.token.clone();
3010 let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3012 let mut hi = self.span;
3014 let opt_end = if self.is_at_start_of_range_notation_rhs() {
3015 // RHS must be parsed with more associativity than the dots.
3016 let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3017 Some(self.parse_assoc_expr_with(next_prec,
3018 LhsExpr::NotYetParsed)
3026 let limits = if tok == token::DotDot {
3027 RangeLimits::HalfOpen
3032 let r = try!(self.mk_range(None,
3035 Ok(self.mk_expr(lo.to(hi), r, attrs))
3038 fn is_at_start_of_range_notation_rhs(&self) -> bool {
3039 if self.token.can_begin_expr() {
3040 // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3041 if self.token == token::OpenDelim(token::Brace) {
3042 return !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL);
3050 /// Parse an 'if' or 'if let' expression ('if' token already eaten)
3051 pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3052 if self.check_keyword(keywords::Let) {
3053 return self.parse_if_let_expr(attrs);
3055 let lo = self.prev_span;
3056 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3057 let thn = self.parse_block()?;
3058 let mut els: Option<P<Expr>> = None;
3059 let mut hi = thn.span;
3060 if self.eat_keyword(keywords::Else) {
3061 let elexpr = self.parse_else_expr()?;
3065 Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3068 /// Parse an 'if let' expression ('if' token already eaten)
3069 pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3070 -> PResult<'a, P<Expr>> {
3071 let lo = self.prev_span;
3072 self.expect_keyword(keywords::Let)?;
3073 let pat = self.parse_pat()?;
3074 self.expect(&token::Eq)?;
3075 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3076 let thn = self.parse_block()?;
3077 let (hi, els) = if self.eat_keyword(keywords::Else) {
3078 let expr = self.parse_else_expr()?;
3079 (expr.span, Some(expr))
3083 Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
3086 // `move |args| expr`
3087 pub fn parse_lambda_expr(&mut self,
3089 capture_clause: CaptureBy,
3090 attrs: ThinVec<Attribute>)
3091 -> PResult<'a, P<Expr>>
3093 let decl = self.parse_fn_block_decl()?;
3094 let decl_hi = self.prev_span;
3095 let body = match decl.output {
3096 FunctionRetTy::Default(_) => self.parse_expr()?,
3098 // If an explicit return type is given, require a
3099 // block to appear (RFC 968).
3100 let body_lo = self.span;
3101 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3107 ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3111 // `else` token already eaten
3112 pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3113 if self.prev_token_kind == PrevTokenKind::DocComment {
3114 return Err(self.span_fatal_err(self.span, Error::UselessDocComment));
3116 if self.eat_keyword(keywords::If) {
3117 return self.parse_if_expr(ThinVec::new());
3119 let blk = self.parse_block()?;
3120 return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3124 /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3125 pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3127 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3128 // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3129 if let Some(doc) = attrs.iter().find(|x| x.is_sugared_doc) {
3130 self.span_fatal_err(doc.span, Error::UselessDocComment).emit();
3133 let pat = self.parse_pat()?;
3134 self.expect_keyword(keywords::In)?;
3135 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3136 let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3137 attrs.extend(iattrs);
3139 let hi = self.prev_span;
3140 Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3143 /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3144 pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3146 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3147 if let Some(doc) = attrs.iter().find(|x| x.is_sugared_doc) {
3148 self.span_fatal_err(doc.span, Error::UselessDocComment).emit();
3150 if self.token.is_keyword(keywords::Let) {
3151 return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3153 let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3154 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3155 attrs.extend(iattrs);
3156 let span = span_lo.to(body.span);
3157 return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3160 /// Parse a 'while let' expression ('while' token already eaten)
3161 pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3163 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3164 self.expect_keyword(keywords::Let)?;
3165 let pat = self.parse_pat()?;
3166 self.expect(&token::Eq)?;
3167 let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3168 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3169 attrs.extend(iattrs);
3170 let span = span_lo.to(body.span);
3171 return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3174 // parse `loop {...}`, `loop` token already eaten
3175 pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3177 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3178 if let Some(doc) = attrs.iter().find(|x| x.is_sugared_doc) {
3179 self.span_fatal_err(doc.span, Error::UselessDocComment).emit();
3181 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3182 attrs.extend(iattrs);
3183 let span = span_lo.to(body.span);
3184 Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3187 /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3188 pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3189 -> PResult<'a, P<Expr>>
3191 if let Some(doc) = attrs.iter().find(|x| x.is_sugared_doc) {
3192 self.span_fatal_err(doc.span, Error::UselessDocComment).emit();
3194 let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3195 attrs.extend(iattrs);
3196 Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3199 // `match` token already eaten
3200 fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3201 if let Some(doc) = attrs.iter().find(|x| x.is_sugared_doc) {
3202 self.span_fatal_err(doc.span, Error::UselessDocComment).emit();
3204 let match_span = self.prev_span;
3205 let lo = self.prev_span;
3206 let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL,
3208 if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3209 if self.token == token::Token::Semi {
3210 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3214 attrs.extend(self.parse_inner_attributes()?);
3216 let mut arms: Vec<Arm> = Vec::new();
3217 while self.token != token::CloseDelim(token::Brace) {
3218 match self.parse_arm() {
3219 Ok(arm) => arms.push(arm),
3221 // Recover by skipping to the end of the block.
3223 self.recover_stmt();
3224 let span = lo.to(self.span);
3225 if self.token == token::CloseDelim(token::Brace) {
3228 return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3234 return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3237 pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3238 maybe_whole!(self, NtArm, |x| x);
3240 let attrs = self.parse_outer_attributes()?;
3241 if let Some(doc) = attrs.iter().find(|x| x.is_sugared_doc) {
3242 self.span_fatal_err(doc.span, Error::UselessDocComment).emit();
3244 let pats = self.parse_pats()?;
3245 let guard = if self.eat_keyword(keywords::If) {
3246 Some(self.parse_expr()?)
3250 self.expect(&token::FatArrow)?;
3251 let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR, None)?;
3253 let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3254 && self.token != token::CloseDelim(token::Brace);
3257 self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3259 self.eat(&token::Comma);
3270 /// Parse an expression
3271 pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3272 self.parse_expr_res(Restrictions::empty(), None)
3275 /// Evaluate the closure with restrictions in place.
3277 /// After the closure is evaluated, restrictions are reset.
3278 pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3279 where F: FnOnce(&mut Self) -> T
3281 let old = self.restrictions;
3282 self.restrictions = r;
3284 self.restrictions = old;
3289 /// Parse an expression, subject to the given restrictions
3290 pub fn parse_expr_res(&mut self, r: Restrictions,
3291 already_parsed_attrs: Option<ThinVec<Attribute>>)
3292 -> PResult<'a, P<Expr>> {
3293 self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3296 /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3297 fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3298 if self.check(&token::Eq) {
3300 Ok(Some(self.parse_expr()?))
3306 /// Parse patterns, separated by '|' s
3307 fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3308 let mut pats = Vec::new();
3310 pats.push(self.parse_pat()?);
3311 if self.check(&token::BinOp(token::Or)) { self.bump();}
3312 else { return Ok(pats); }
3316 fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3317 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3318 let mut fields = vec![];
3319 let mut ddpos = None;
3321 while !self.check(&token::CloseDelim(token::Paren)) {
3322 if ddpos.is_none() && self.eat(&token::DotDot) {
3323 ddpos = Some(fields.len());
3324 if self.eat(&token::Comma) {
3325 // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3326 fields.push(self.parse_pat()?);
3328 } else if ddpos.is_some() && self.eat(&token::DotDot) {
3329 // Emit a friendly error, ignore `..` and continue parsing
3330 self.span_err(self.prev_span, "`..` can only be used once per \
3331 tuple or tuple struct pattern");
3333 fields.push(self.parse_pat()?);
3336 if !self.check(&token::CloseDelim(token::Paren)) ||
3337 (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3338 self.expect(&token::Comma)?;
3345 fn parse_pat_vec_elements(
3347 ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3348 let mut before = Vec::new();
3349 let mut slice = None;
3350 let mut after = Vec::new();
3351 let mut first = true;
3352 let mut before_slice = true;
3354 while self.token != token::CloseDelim(token::Bracket) {
3358 self.expect(&token::Comma)?;
3360 if self.token == token::CloseDelim(token::Bracket)
3361 && (before_slice || !after.is_empty()) {
3367 if self.eat(&token::DotDot) {
3369 if self.check(&token::Comma) ||
3370 self.check(&token::CloseDelim(token::Bracket)) {
3371 slice = Some(P(ast::Pat {
3372 id: ast::DUMMY_NODE_ID,
3373 node: PatKind::Wild,
3376 before_slice = false;
3382 let subpat = self.parse_pat()?;
3383 if before_slice && self.eat(&token::DotDot) {
3384 slice = Some(subpat);
3385 before_slice = false;
3386 } else if before_slice {
3387 before.push(subpat);
3393 Ok((before, slice, after))
3396 /// Parse the fields of a struct-like pattern
3397 fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3398 let mut fields = Vec::new();
3399 let mut etc = false;
3400 let mut first = true;
3401 while self.token != token::CloseDelim(token::Brace) {
3405 self.expect(&token::Comma)?;
3406 // accept trailing commas
3407 if self.check(&token::CloseDelim(token::Brace)) { break }
3410 let attrs = self.parse_outer_attributes()?;
3414 if self.check(&token::DotDot) {
3416 if self.token != token::CloseDelim(token::Brace) {
3417 let token_str = self.this_token_to_string();
3418 return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3425 // Check if a colon exists one ahead. This means we're parsing a fieldname.
3426 let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3427 // Parsing a pattern of the form "fieldname: pat"
3428 let fieldname = self.parse_field_name()?;
3430 let pat = self.parse_pat()?;
3432 (pat, fieldname, false)
3434 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3435 let is_box = self.eat_keyword(keywords::Box);
3436 let boxed_span = self.span;
3437 let is_ref = self.eat_keyword(keywords::Ref);
3438 let is_mut = self.eat_keyword(keywords::Mut);
3439 let fieldname = self.parse_ident()?;
3440 hi = self.prev_span;
3442 let bind_type = match (is_ref, is_mut) {
3443 (true, true) => BindingMode::ByRef(Mutability::Mutable),
3444 (true, false) => BindingMode::ByRef(Mutability::Immutable),
3445 (false, true) => BindingMode::ByValue(Mutability::Mutable),
3446 (false, false) => BindingMode::ByValue(Mutability::Immutable),
3448 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3449 let fieldpat = P(ast::Pat{
3450 id: ast::DUMMY_NODE_ID,
3451 node: PatKind::Ident(bind_type, fieldpath, None),
3452 span: boxed_span.to(hi),
3455 let subpat = if is_box {
3457 id: ast::DUMMY_NODE_ID,
3458 node: PatKind::Box(fieldpat),
3464 (subpat, fieldname, true)
3467 fields.push(codemap::Spanned { span: lo.to(hi),
3468 node: ast::FieldPat {
3471 is_shorthand: is_shorthand,
3472 attrs: attrs.into(),
3476 return Ok((fields, etc));
3479 fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3480 if self.token.is_path_start() {
3482 let (qself, path) = if self.eat_lt() {
3483 // Parse a qualified path
3485 self.parse_qualified_path(PathStyle::Expr)?;
3488 // Parse an unqualified path
3489 (None, self.parse_path(PathStyle::Expr)?)
3491 let hi = self.prev_span;
3492 Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3494 self.parse_pat_literal_maybe_minus()
3498 // helper function to decide whether to parse as ident binding or to try to do
3499 // something more complex like range patterns
3500 fn parse_as_ident(&mut self) -> bool {
3501 self.look_ahead(1, |t| match *t {
3502 token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3503 token::DotDotDot | token::ModSep | token::Not => Some(false),
3504 // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3505 // range pattern branch
3506 token::DotDot => None,
3508 }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3509 token::Comma | token::CloseDelim(token::Bracket) => true,
3514 /// Parse a pattern.
3515 pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3516 maybe_whole!(self, NtPat, |x| x);
3521 token::Underscore => {
3524 pat = PatKind::Wild;
3526 token::BinOp(token::And) | token::AndAnd => {
3527 // Parse &pat / &mut pat
3529 let mutbl = self.parse_mutability();
3530 if let token::Lifetime(ident) = self.token {
3531 return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3533 let subpat = self.parse_pat()?;
3534 pat = PatKind::Ref(subpat, mutbl);
3536 token::OpenDelim(token::Paren) => {
3537 // Parse (pat,pat,pat,...) as tuple pattern
3539 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3540 self.expect(&token::CloseDelim(token::Paren))?;
3541 pat = PatKind::Tuple(fields, ddpos);
3543 token::OpenDelim(token::Bracket) => {
3544 // Parse [pat,pat,...] as slice pattern
3546 let (before, slice, after) = self.parse_pat_vec_elements()?;
3547 self.expect(&token::CloseDelim(token::Bracket))?;
3548 pat = PatKind::Slice(before, slice, after);
3550 // At this point, token != _, &, &&, (, [
3551 _ => if self.eat_keyword(keywords::Mut) {
3552 // Parse mut ident @ pat / mut ref ident @ pat
3553 let mutref_span = self.prev_span.to(self.span);
3554 let binding_mode = if self.eat_keyword(keywords::Ref) {
3556 .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3557 .span_suggestion(mutref_span, "try switching the order", "ref mut".into())
3559 BindingMode::ByRef(Mutability::Mutable)
3561 BindingMode::ByValue(Mutability::Mutable)
3563 pat = self.parse_pat_ident(binding_mode)?;
3564 } else if self.eat_keyword(keywords::Ref) {
3565 // Parse ref ident @ pat / ref mut ident @ pat
3566 let mutbl = self.parse_mutability();
3567 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3568 } else if self.eat_keyword(keywords::Box) {
3570 let subpat = self.parse_pat()?;
3571 pat = PatKind::Box(subpat);
3572 } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3573 self.parse_as_ident() {
3574 // Parse ident @ pat
3575 // This can give false positives and parse nullary enums,
3576 // they are dealt with later in resolve
3577 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3578 pat = self.parse_pat_ident(binding_mode)?;
3579 } else if self.token.is_path_start() {
3580 // Parse pattern starting with a path
3581 let (qself, path) = if self.eat_lt() {
3582 // Parse a qualified path
3583 let (qself, path) = self.parse_qualified_path(PathStyle::Expr)?;
3586 // Parse an unqualified path
3587 (None, self.parse_path(PathStyle::Expr)?)
3590 token::Not if qself.is_none() => {
3591 // Parse macro invocation
3593 let (_, tts) = self.expect_delimited_token_tree()?;
3594 let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3595 pat = PatKind::Mac(mac);
3597 token::DotDotDot | token::DotDot => {
3598 let end_kind = match self.token {
3599 token::DotDot => RangeEnd::Excluded,
3600 token::DotDotDot => RangeEnd::Included,
3601 _ => panic!("can only parse `..` or `...` for ranges (checked above)"),
3604 let span = lo.to(self.prev_span);
3605 let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3607 let end = self.parse_pat_range_end()?;
3608 pat = PatKind::Range(begin, end, end_kind);
3610 token::OpenDelim(token::Brace) => {
3611 if qself.is_some() {
3612 return Err(self.fatal("unexpected `{` after qualified path"));
3614 // Parse struct pattern
3616 let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3618 self.recover_stmt();
3622 pat = PatKind::Struct(path, fields, etc);
3624 token::OpenDelim(token::Paren) => {
3625 if qself.is_some() {
3626 return Err(self.fatal("unexpected `(` after qualified path"));
3628 // Parse tuple struct or enum pattern
3630 let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3631 self.expect(&token::CloseDelim(token::Paren))?;
3632 pat = PatKind::TupleStruct(path, fields, ddpos)
3634 _ => pat = PatKind::Path(qself, path),
3637 // Try to parse everything else as literal with optional minus
3638 match self.parse_pat_literal_maybe_minus() {
3640 if self.eat(&token::DotDotDot) {
3641 let end = self.parse_pat_range_end()?;
3642 pat = PatKind::Range(begin, end, RangeEnd::Included);
3643 } else if self.eat(&token::DotDot) {
3644 let end = self.parse_pat_range_end()?;
3645 pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3647 pat = PatKind::Lit(begin);
3651 self.cancel(&mut err);
3652 let msg = format!("expected pattern, found {}", self.this_token_descr());
3653 return Err(self.fatal(&msg));
3660 id: ast::DUMMY_NODE_ID,
3662 span: lo.to(self.prev_span),
3666 /// Parse ident or ident @ pat
3667 /// used by the copy foo and ref foo patterns to give a good
3668 /// error message when parsing mistakes like ref foo(a,b)
3669 fn parse_pat_ident(&mut self,
3670 binding_mode: ast::BindingMode)
3671 -> PResult<'a, PatKind> {
3672 let ident_span = self.span;
3673 let ident = self.parse_ident()?;
3674 let name = codemap::Spanned{span: ident_span, node: ident};
3675 let sub = if self.eat(&token::At) {
3676 Some(self.parse_pat()?)
3681 // just to be friendly, if they write something like
3683 // we end up here with ( as the current token. This shortly
3684 // leads to a parse error. Note that if there is no explicit
3685 // binding mode then we do not end up here, because the lookahead
3686 // will direct us over to parse_enum_variant()
3687 if self.token == token::OpenDelim(token::Paren) {
3688 return Err(self.span_fatal(
3690 "expected identifier, found enum pattern"))
3693 Ok(PatKind::Ident(binding_mode, name, sub))
3696 /// Parse a local variable declaration
3697 fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3698 if let Some(doc) = attrs.iter().find(|x| x.is_sugared_doc) {
3699 self.span_fatal_err(doc.span, Error::UselessDocComment).emit();
3702 let pat = self.parse_pat()?;
3704 let ty = if self.eat(&token::Colon) {
3705 Some(self.parse_ty()?)
3709 let init = self.parse_initializer()?;
3714 id: ast::DUMMY_NODE_ID,
3715 span: lo.to(self.prev_span),
3720 /// Parse a structure field
3721 fn parse_name_and_ty(&mut self,
3724 attrs: Vec<Attribute>)
3725 -> PResult<'a, StructField> {
3726 let name = self.parse_ident()?;
3727 self.expect(&token::Colon)?;
3728 let ty = self.parse_ty()?;
3730 span: lo.to(self.prev_span),
3733 id: ast::DUMMY_NODE_ID,
3739 /// Emit an expected item after attributes error.
3740 fn expected_item_err(&self, attrs: &[Attribute]) {
3741 let message = match attrs.last() {
3742 Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3743 _ => "expected item after attributes",
3746 self.span_err(self.prev_span, message);
3749 /// Parse a statement. This stops just before trailing semicolons on everything but items.
3750 /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3751 pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3752 Ok(self.parse_stmt_(true))
3755 // Eat tokens until we can be relatively sure we reached the end of the
3756 // statement. This is something of a best-effort heuristic.
3758 // We terminate when we find an unmatched `}` (without consuming it).
3759 fn recover_stmt(&mut self) {
3760 self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
3763 // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3764 // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3765 // approximate - it can mean we break too early due to macros, but that
3766 // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3768 // If `break_on_block` is `Break`, then we will stop consuming tokens
3769 // after finding (and consuming) a brace-delimited block.
3770 fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
3771 let mut brace_depth = 0;
3772 let mut bracket_depth = 0;
3773 let mut in_block = false;
3774 debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
3775 break_on_semi, break_on_block);
3777 debug!("recover_stmt_ loop {:?}", self.token);
3779 token::OpenDelim(token::DelimToken::Brace) => {
3782 if break_on_block == BlockMode::Break &&
3784 bracket_depth == 0 {
3788 token::OpenDelim(token::DelimToken::Bracket) => {
3792 token::CloseDelim(token::DelimToken::Brace) => {
3793 if brace_depth == 0 {
3794 debug!("recover_stmt_ return - close delim {:?}", self.token);
3799 if in_block && bracket_depth == 0 && brace_depth == 0 {
3800 debug!("recover_stmt_ return - block end {:?}", self.token);
3804 token::CloseDelim(token::DelimToken::Bracket) => {
3806 if bracket_depth < 0 {
3812 debug!("recover_stmt_ return - Eof");
3817 if break_on_semi == SemiColonMode::Break &&
3819 bracket_depth == 0 {
3820 debug!("recover_stmt_ return - Semi");
3831 fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
3832 self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
3834 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
3839 fn is_catch_expr(&mut self) -> bool {
3840 self.token.is_keyword(keywords::Do) &&
3841 self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
3842 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
3844 // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3845 !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL)
3848 fn is_union_item(&self) -> bool {
3849 self.token.is_keyword(keywords::Union) &&
3850 self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
3853 fn is_defaultness(&self) -> bool {
3854 // `pub` is included for better error messages
3855 self.token.is_keyword(keywords::Default) &&
3856 self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
3857 t.is_keyword(keywords::Const) ||
3858 t.is_keyword(keywords::Fn) ||
3859 t.is_keyword(keywords::Unsafe) ||
3860 t.is_keyword(keywords::Extern) ||
3861 t.is_keyword(keywords::Type) ||
3862 t.is_keyword(keywords::Pub))
3865 fn eat_defaultness(&mut self) -> bool {
3866 let is_defaultness = self.is_defaultness();
3870 self.expected_tokens.push(TokenType::Keyword(keywords::Default));
3875 fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility)
3876 -> PResult<'a, Option<P<Item>>> {
3878 let (ident, def) = match self.token {
3879 token::Ident(ident) if ident.name == keywords::Macro.name() => {
3881 let ident = self.parse_ident()?;
3882 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
3883 match self.parse_token_tree() {
3884 TokenTree::Delimited(_, ref delimited) => delimited.stream(),
3885 _ => unreachable!(),
3887 } else if self.check(&token::OpenDelim(token::Paren)) {
3888 let args = self.parse_token_tree();
3889 let body = if self.check(&token::OpenDelim(token::Brace)) {
3890 self.parse_token_tree()
3895 TokenStream::concat(vec![
3897 TokenTree::Token(lo.to(self.prev_span), token::FatArrow).into(),
3905 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
3907 token::Ident(ident) if ident.name == "macro_rules" &&
3908 self.look_ahead(1, |t| *t == token::Not) => {
3909 let prev_span = self.prev_span;
3910 self.complain_if_pub_macro(vis, prev_span);
3914 let ident = self.parse_ident()?;
3915 let (delim, tokens) = self.expect_delimited_token_tree()?;
3916 if delim != token::Brace {
3917 if !self.eat(&token::Semi) {
3918 let msg = "macros that expand to items must either \
3919 be surrounded with braces or followed by a semicolon";
3920 self.span_err(self.prev_span, msg);
3924 (ident, ast::MacroDef { tokens: tokens, legacy: true })
3926 _ => return Ok(None),
3929 let span = lo.to(self.prev_span);
3930 Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
3933 fn parse_stmt_without_recovery(&mut self,
3934 macro_legacy_warnings: bool)
3935 -> PResult<'a, Option<Stmt>> {
3936 maybe_whole!(self, NtStmt, |x| Some(x));
3938 let attrs = self.parse_outer_attributes()?;
3941 Ok(Some(if self.eat_keyword(keywords::Let) {
3943 id: ast::DUMMY_NODE_ID,
3944 node: StmtKind::Local(self.parse_local(attrs.into())?),
3945 span: lo.to(self.prev_span),
3947 } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited)? {
3949 id: ast::DUMMY_NODE_ID,
3950 node: StmtKind::Item(macro_def),
3951 span: lo.to(self.prev_span),
3953 // Starts like a simple path, but not a union item.
3954 } else if self.token.is_path_start() &&
3955 !self.token.is_qpath_start() &&
3956 !self.is_union_item() {
3957 let pth = self.parse_path(PathStyle::Expr)?;
3959 if !self.eat(&token::Not) {
3960 let expr = if self.check(&token::OpenDelim(token::Brace)) {
3961 self.parse_struct_expr(lo, pth, ThinVec::new())?
3963 let hi = self.prev_span;
3964 self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
3967 let expr = self.with_res(RESTRICTION_STMT_EXPR, |this| {
3968 let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
3969 this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
3972 return Ok(Some(Stmt {
3973 id: ast::DUMMY_NODE_ID,
3974 node: StmtKind::Expr(expr),
3975 span: lo.to(self.prev_span),
3979 // it's a macro invocation
3980 let id = match self.token {
3981 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
3982 _ => self.parse_ident()?,
3985 // check that we're pointing at delimiters (need to check
3986 // again after the `if`, because of `parse_ident`
3987 // consuming more tokens).
3988 let delim = match self.token {
3989 token::OpenDelim(delim) => delim,
3991 // we only expect an ident if we didn't parse one
3993 let ident_str = if id.name == keywords::Invalid.name() {
3998 let tok_str = self.this_token_to_string();
3999 return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4005 let (_, tts) = self.expect_delimited_token_tree()?;
4006 let hi = self.prev_span;
4008 let style = if delim == token::Brace {
4009 MacStmtStyle::Braces
4011 MacStmtStyle::NoBraces
4014 if id.name == keywords::Invalid.name() {
4015 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
4016 let node = if delim == token::Brace ||
4017 self.token == token::Semi || self.token == token::Eof {
4018 StmtKind::Mac(P((mac, style, attrs.into())))
4020 // We used to incorrectly stop parsing macro-expanded statements here.
4021 // If the next token will be an error anyway but could have parsed with the
4022 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4023 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4024 // These can continue an expression, so we can't stop parsing and warn.
4025 token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4026 token::BinOp(token::Minus) | token::BinOp(token::Star) |
4027 token::BinOp(token::And) | token::BinOp(token::Or) |
4028 token::AndAnd | token::OrOr |
4029 token::DotDot | token::DotDotDot => false,
4032 self.warn_missing_semicolon();
4033 StmtKind::Mac(P((mac, style, attrs.into())))
4035 let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4036 let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4037 let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4041 id: ast::DUMMY_NODE_ID,
4046 // if it has a special ident, it's definitely an item
4048 // Require a semicolon or braces.
4049 if style != MacStmtStyle::Braces {
4050 if !self.eat(&token::Semi) {
4051 self.span_err(self.prev_span,
4052 "macros that expand to items must \
4053 either be surrounded with braces or \
4054 followed by a semicolon");
4057 let span = lo.to(hi);
4059 id: ast::DUMMY_NODE_ID,
4061 node: StmtKind::Item({
4063 span, id /*id is good here*/,
4064 ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
4065 Visibility::Inherited,
4071 // FIXME: Bad copy of attrs
4072 let old_directory_ownership =
4073 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4074 let item = self.parse_item_(attrs.clone(), false, true)?;
4075 self.directory.ownership = old_directory_ownership;
4079 id: ast::DUMMY_NODE_ID,
4080 span: lo.to(i.span),
4081 node: StmtKind::Item(i),
4084 let unused_attrs = |attrs: &[_], s: &mut Self| {
4085 if !attrs.is_empty() {
4086 if s.prev_token_kind == PrevTokenKind::DocComment {
4087 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4089 s.span_err(s.span, "expected statement after outer attribute");
4094 // Do not attempt to parse an expression if we're done here.
4095 if self.token == token::Semi {
4096 unused_attrs(&attrs, self);
4101 if self.token == token::CloseDelim(token::Brace) {
4102 unused_attrs(&attrs, self);
4106 // Remainder are line-expr stmts.
4107 let e = self.parse_expr_res(
4108 RESTRICTION_STMT_EXPR, Some(attrs.into()))?;
4110 id: ast::DUMMY_NODE_ID,
4111 span: lo.to(e.span),
4112 node: StmtKind::Expr(e),
4119 /// Is this expression a successfully-parsed statement?
4120 fn expr_is_complete(&mut self, e: &Expr) -> bool {
4121 self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
4122 !classify::expr_requires_semi_to_be_stmt(e)
4125 /// Parse a block. No inner attrs are allowed.
4126 pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4127 maybe_whole!(self, NtBlock, |x| x);
4131 if !self.eat(&token::OpenDelim(token::Brace)) {
4133 let tok = self.this_token_to_string();
4134 let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4136 // Check to see if the user has written something like
4141 // Which is valid in other languages, but not Rust.
4142 match self.parse_stmt_without_recovery(false) {
4144 let mut stmt_span = stmt.span;
4145 // expand the span to include the semicolon, if it exists
4146 if self.eat(&token::Semi) {
4147 stmt_span.hi = self.prev_span.hi;
4149 let sugg = pprust::to_string(|s| {
4150 use print::pprust::{PrintState, INDENT_UNIT};
4151 s.ibox(INDENT_UNIT)?;
4153 s.print_stmt(&stmt)?;
4154 s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4156 e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4159 self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4160 self.cancel(&mut e);
4167 self.parse_block_tail(lo, BlockCheckMode::Default)
4170 /// Parse a block. Inner attrs are allowed.
4171 fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4172 maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4175 self.expect(&token::OpenDelim(token::Brace))?;
4176 Ok((self.parse_inner_attributes()?,
4177 self.parse_block_tail(lo, BlockCheckMode::Default)?))
4180 /// Parse the rest of a block expression or function body
4181 /// Precondition: already parsed the '{'.
4182 fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4183 let mut stmts = vec![];
4185 while !self.eat(&token::CloseDelim(token::Brace)) {
4186 if let Some(stmt) = self.parse_full_stmt(false)? {
4188 } else if self.token == token::Eof {
4190 } else if let token::DocComment(_) = self.token {
4191 return Err(self.span_fatal_err(self.span, Error::UselessDocComment));
4193 // Found only `;` or `}`.
4200 id: ast::DUMMY_NODE_ID,
4202 span: lo.to(self.prev_span),
4206 /// Parse a statement, including the trailing semicolon.
4207 pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4208 let mut stmt = match self.parse_stmt_(macro_legacy_warnings) {
4210 None => return Ok(None),
4214 StmtKind::Expr(ref expr) if self.token != token::Eof => {
4215 // expression without semicolon
4216 if classify::expr_requires_semi_to_be_stmt(expr) {
4217 // Just check for errors and recover; do not eat semicolon yet.
4219 self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4222 self.recover_stmt();
4226 StmtKind::Local(..) => {
4227 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4228 if macro_legacy_warnings && self.token != token::Semi {
4229 self.warn_missing_semicolon();
4231 self.expect_one_of(&[token::Semi], &[])?;
4237 if self.eat(&token::Semi) {
4238 stmt = stmt.add_trailing_semicolon();
4241 stmt.span.hi = self.prev_span.hi;
4245 fn warn_missing_semicolon(&self) {
4246 self.diagnostic().struct_span_warn(self.span, {
4247 &format!("expected `;`, found `{}`", self.this_token_to_string())
4249 "This was erroneously allowed and will become a hard error in a future release"
4253 // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4254 // BOUND = TY_BOUND | LT_BOUND
4255 // LT_BOUND = LIFETIME (e.g. `'a`)
4256 // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4257 // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4258 fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4259 let mut bounds = Vec::new();
4261 let is_bound_start = self.check_path() || self.check_lifetime() ||
4262 self.check(&token::Question) ||
4263 self.check_keyword(keywords::For) ||
4264 self.check(&token::OpenDelim(token::Paren));
4266 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4267 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4268 if self.token.is_lifetime() {
4269 if let Some(question_span) = question {
4270 self.span_err(question_span,
4271 "`?` may only modify trait bounds, not lifetime bounds");
4273 bounds.push(RegionTyParamBound(self.expect_lifetime()));
4276 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4277 let path = self.parse_path(PathStyle::Type)?;
4278 let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4279 let modifier = if question.is_some() {
4280 TraitBoundModifier::Maybe
4282 TraitBoundModifier::None
4284 bounds.push(TraitTyParamBound(poly_trait, modifier));
4287 self.expect(&token::CloseDelim(token::Paren))?;
4288 if let Some(&RegionTyParamBound(..)) = bounds.last() {
4289 self.span_err(self.prev_span,
4290 "parenthesized lifetime bounds are not supported");
4297 if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4305 fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4306 self.parse_ty_param_bounds_common(true)
4309 // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4310 // BOUND = LT_BOUND (e.g. `'a`)
4311 fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4312 let mut lifetimes = Vec::new();
4313 while self.check_lifetime() {
4314 lifetimes.push(self.expect_lifetime());
4316 if !self.eat(&token::BinOp(token::Plus)) {
4323 /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4324 fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4325 let span = self.span;
4326 let ident = self.parse_ident()?;
4328 // Parse optional colon and param bounds.
4329 let bounds = if self.eat(&token::Colon) {
4330 self.parse_ty_param_bounds()?
4335 let default = if self.eat(&token::Eq) {
4336 Some(self.parse_ty()?)
4342 attrs: preceding_attrs.into(),
4344 id: ast::DUMMY_NODE_ID,
4351 /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4352 /// trailing comma and erroneous trailing attributes.
4353 pub fn parse_generic_params(&mut self) -> PResult<'a, (Vec<LifetimeDef>, Vec<TyParam>)> {
4354 let mut lifetime_defs = Vec::new();
4355 let mut ty_params = Vec::new();
4356 let mut seen_ty_param = false;
4358 let attrs = self.parse_outer_attributes()?;
4359 if self.check_lifetime() {
4360 let lifetime = self.expect_lifetime();
4361 // Parse lifetime parameter.
4362 let bounds = if self.eat(&token::Colon) {
4363 self.parse_lt_param_bounds()
4367 lifetime_defs.push(LifetimeDef {
4368 attrs: attrs.into(),
4373 self.span_err(self.prev_span,
4374 "lifetime parameters must be declared prior to type parameters");
4376 } else if self.check_ident() {
4377 // Parse type parameter.
4378 ty_params.push(self.parse_ty_param(attrs)?);
4379 seen_ty_param = true;
4381 // Check for trailing attributes and stop parsing.
4382 if !attrs.is_empty() {
4383 let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4384 self.span_err(attrs[0].span,
4385 &format!("trailing attribute after {} parameters", param_kind));
4390 if !self.eat(&token::Comma) {
4394 Ok((lifetime_defs, ty_params))
4397 /// Parse a set of optional generic type parameter declarations. Where
4398 /// clauses are not parsed here, and must be added later via
4399 /// `parse_where_clause()`.
4401 /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4402 /// | ( < lifetimes , typaramseq ( , )? > )
4403 /// where typaramseq = ( typaram ) | ( typaram , typaramseq )
4404 pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4405 maybe_whole!(self, NtGenerics, |x| x);
4407 let span_lo = self.span;
4409 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4412 lifetimes: lifetime_defs,
4413 ty_params: ty_params,
4414 where_clause: WhereClause {
4415 id: ast::DUMMY_NODE_ID,
4416 predicates: Vec::new(),
4418 span: span_lo.to(self.prev_span),
4421 Ok(ast::Generics::default())
4425 /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4426 /// possibly including trailing comma.
4427 fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4428 let mut lifetimes = Vec::new();
4429 let mut types = Vec::new();
4430 let mut bindings = Vec::new();
4431 let mut seen_type = false;
4432 let mut seen_binding = false;
4434 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4435 // Parse lifetime argument.
4436 lifetimes.push(self.expect_lifetime());
4437 if seen_type || seen_binding {
4438 self.span_err(self.prev_span,
4439 "lifetime parameters must be declared prior to type parameters");
4441 } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4442 // Parse associated type binding.
4444 let ident = self.parse_ident()?;
4446 let ty = self.parse_ty()?;
4447 bindings.push(TypeBinding {
4448 id: ast::DUMMY_NODE_ID,
4451 span: lo.to(self.prev_span),
4453 seen_binding = true;
4454 } else if self.check_type() {
4455 // Parse type argument.
4456 types.push(self.parse_ty()?);
4458 self.span_err(types[types.len() - 1].span,
4459 "type parameters must be declared prior to associated type bindings");
4466 if !self.eat(&token::Comma) {
4470 Ok((lifetimes, types, bindings))
4473 /// Parses an optional `where` clause and places it in `generics`.
4475 /// ```ignore (only-for-syntax-highlight)
4476 /// where T : Trait<U, V> + 'b, 'a : 'b
4478 pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4479 maybe_whole!(self, NtWhereClause, |x| x);
4481 let mut where_clause = WhereClause {
4482 id: ast::DUMMY_NODE_ID,
4483 predicates: Vec::new(),
4486 if !self.eat_keyword(keywords::Where) {
4487 return Ok(where_clause);
4490 // This is a temporary future proofing.
4492 // We are considering adding generics to the `where` keyword as an alternative higher-rank
4493 // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4494 // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4495 if token::Lt == self.token {
4496 let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4497 if ident_or_lifetime {
4498 let gt_comma_or_colon = self.look_ahead(2, |t| {
4499 *t == token::Gt || *t == token::Comma || *t == token::Colon
4501 if gt_comma_or_colon {
4502 self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4509 if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4510 let lifetime = self.expect_lifetime();
4511 // Bounds starting with a colon are mandatory, but possibly empty.
4512 self.expect(&token::Colon)?;
4513 let bounds = self.parse_lt_param_bounds();
4514 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4515 ast::WhereRegionPredicate {
4516 span: lo.to(self.prev_span),
4521 } else if self.check_type() {
4522 // Parse optional `for<'a, 'b>`.
4523 // This `for` is parsed greedily and applies to the whole predicate,
4524 // the bounded type can have its own `for` applying only to it.
4525 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4526 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4527 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4528 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4530 // Parse type with mandatory colon and (possibly empty) bounds,
4531 // or with mandatory equality sign and the second type.
4532 let ty = self.parse_ty()?;
4533 if self.eat(&token::Colon) {
4534 let bounds = self.parse_ty_param_bounds()?;
4535 where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4536 ast::WhereBoundPredicate {
4537 span: lo.to(self.prev_span),
4538 bound_lifetimes: lifetime_defs,
4543 // FIXME: Decide what should be used here, `=` or `==`.
4544 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4545 let rhs_ty = self.parse_ty()?;
4546 where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4547 ast::WhereEqPredicate {
4548 span: lo.to(self.prev_span),
4551 id: ast::DUMMY_NODE_ID,
4555 return self.unexpected();
4561 if !self.eat(&token::Comma) {
4569 fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4570 -> PResult<'a, (Vec<Arg> , bool)> {
4572 let mut variadic = false;
4573 let args: Vec<Option<Arg>> =
4574 self.parse_unspanned_seq(
4575 &token::OpenDelim(token::Paren),
4576 &token::CloseDelim(token::Paren),
4577 SeqSep::trailing_allowed(token::Comma),
4579 if p.token == token::DotDotDot {
4582 if p.token != token::CloseDelim(token::Paren) {
4585 "`...` must be last in argument list for variadic function");
4590 "only foreign functions are allowed to be variadic");
4595 match p.parse_arg_general(named_args) {
4596 Ok(arg) => Ok(Some(arg)),
4599 let lo = p.prev_span;
4600 // Skip every token until next possible arg or end.
4601 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4602 // Create a placeholder argument for proper arg count (#34264).
4603 let span = lo.to(p.prev_span);
4604 Ok(Some(dummy_arg(span)))
4611 let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4613 if variadic && args.is_empty() {
4615 "variadic function must be declared with at least one named argument");
4618 Ok((args, variadic))
4621 /// Parse the argument list and result type of a function declaration
4622 pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4624 let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4625 let ret_ty = self.parse_ret_ty()?;
4634 /// Returns the parsed optional self argument and whether a self shortcut was used.
4635 fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4636 let expect_ident = |this: &mut Self| match this.token {
4637 // Preserve hygienic context.
4638 token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4641 let isolated_self = |this: &mut Self, n| {
4642 this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4643 this.look_ahead(n + 1, |t| t != &token::ModSep)
4646 // Parse optional self parameter of a method.
4647 // Only a limited set of initial token sequences is considered self parameters, anything
4648 // else is parsed as a normal function parameter list, so some lookahead is required.
4649 let eself_lo = self.span;
4650 let (eself, eself_ident) = match self.token {
4651 token::BinOp(token::And) => {
4657 if isolated_self(self, 1) {
4659 (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4660 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4661 isolated_self(self, 2) {
4664 (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4665 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4666 isolated_self(self, 2) {
4668 let lt = self.expect_lifetime();
4669 (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4670 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4671 self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4672 isolated_self(self, 3) {
4674 let lt = self.expect_lifetime();
4676 (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4681 token::BinOp(token::Star) => {
4686 // Emit special error for `self` cases.
4687 if isolated_self(self, 1) {
4689 self.span_err(self.span, "cannot pass `self` by raw pointer");
4690 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4691 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4692 isolated_self(self, 2) {
4695 self.span_err(self.span, "cannot pass `self` by raw pointer");
4696 (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4701 token::Ident(..) => {
4702 if isolated_self(self, 0) {
4705 let eself_ident = expect_ident(self);
4706 if self.eat(&token::Colon) {
4707 let ty = self.parse_ty()?;
4708 (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4710 (SelfKind::Value(Mutability::Immutable), eself_ident)
4712 } else if self.token.is_keyword(keywords::Mut) &&
4713 isolated_self(self, 1) {
4717 let eself_ident = expect_ident(self);
4718 if self.eat(&token::Colon) {
4719 let ty = self.parse_ty()?;
4720 (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4722 (SelfKind::Value(Mutability::Mutable), eself_ident)
4728 _ => return Ok(None),
4731 let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
4732 Ok(Some(Arg::from_self(eself, eself_ident)))
4735 /// Parse the parameter list and result type of a function that may have a `self` parameter.
4736 fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
4737 where F: FnMut(&mut Parser<'a>) -> PResult<'a, Arg>,
4739 self.expect(&token::OpenDelim(token::Paren))?;
4741 // Parse optional self argument
4742 let self_arg = self.parse_self_arg()?;
4744 // Parse the rest of the function parameter list.
4745 let sep = SeqSep::trailing_allowed(token::Comma);
4746 let fn_inputs = if let Some(self_arg) = self_arg {
4747 if self.check(&token::CloseDelim(token::Paren)) {
4749 } else if self.eat(&token::Comma) {
4750 let mut fn_inputs = vec![self_arg];
4751 fn_inputs.append(&mut self.parse_seq_to_before_end(
4752 &token::CloseDelim(token::Paren), sep, parse_arg_fn)
4756 return self.unexpected();
4759 self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4762 // Parse closing paren and return type.
4763 self.expect(&token::CloseDelim(token::Paren))?;
4766 output: self.parse_ret_ty()?,
4771 // parse the |arg, arg| header on a lambda
4772 fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4773 let inputs_captures = {
4774 if self.eat(&token::OrOr) {
4777 self.expect(&token::BinOp(token::Or))?;
4778 let args = self.parse_seq_to_before_end(
4779 &token::BinOp(token::Or),
4780 SeqSep::trailing_allowed(token::Comma),
4781 |p| p.parse_fn_block_arg()
4787 let output = self.parse_ret_ty()?;
4790 inputs: inputs_captures,
4796 /// Parse the name and optional generic types of a function header.
4797 fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4798 let id = self.parse_ident()?;
4799 let generics = self.parse_generics()?;
4803 fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
4804 attrs: Vec<Attribute>) -> P<Item> {
4808 id: ast::DUMMY_NODE_ID,
4815 /// Parse an item-position function declaration.
4816 fn parse_item_fn(&mut self,
4818 constness: Spanned<Constness>,
4820 -> PResult<'a, ItemInfo> {
4821 let (ident, mut generics) = self.parse_fn_header()?;
4822 let decl = self.parse_fn_decl(false)?;
4823 generics.where_clause = self.parse_where_clause()?;
4824 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4825 Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4828 /// true if we are looking at `const ID`, false for things like `const fn` etc
4829 pub fn is_const_item(&mut self) -> bool {
4830 self.token.is_keyword(keywords::Const) &&
4831 !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4832 !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4835 /// parses all the "front matter" for a `fn` declaration, up to
4836 /// and including the `fn` keyword:
4840 /// - `const unsafe fn`
4843 pub fn parse_fn_front_matter(&mut self)
4844 -> PResult<'a, (Spanned<ast::Constness>,
4847 let is_const_fn = self.eat_keyword(keywords::Const);
4848 let const_span = self.prev_span;
4849 let unsafety = self.parse_unsafety()?;
4850 let (constness, unsafety, abi) = if is_const_fn {
4851 (respan(const_span, Constness::Const), unsafety, Abi::Rust)
4853 let abi = if self.eat_keyword(keywords::Extern) {
4854 self.parse_opt_abi()?.unwrap_or(Abi::C)
4858 (respan(self.prev_span, Constness::NotConst), unsafety, abi)
4860 self.expect_keyword(keywords::Fn)?;
4861 Ok((constness, unsafety, abi))
4864 /// Parse an impl item.
4865 pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
4866 maybe_whole!(self, NtImplItem, |x| x);
4868 let mut attrs = self.parse_outer_attributes()?;
4870 let vis = self.parse_visibility(false)?;
4871 let defaultness = self.parse_defaultness()?;
4872 let (name, node) = if self.eat_keyword(keywords::Type) {
4873 let name = self.parse_ident()?;
4874 self.expect(&token::Eq)?;
4875 let typ = self.parse_ty()?;
4876 self.expect(&token::Semi)?;
4877 (name, ast::ImplItemKind::Type(typ))
4878 } else if self.is_const_item() {
4879 self.expect_keyword(keywords::Const)?;
4880 let name = self.parse_ident()?;
4881 self.expect(&token::Colon)?;
4882 let typ = self.parse_ty()?;
4883 self.expect(&token::Eq)?;
4884 let expr = self.parse_expr()?;
4885 self.expect(&token::Semi)?;
4886 (name, ast::ImplItemKind::Const(typ, expr))
4888 let (name, inner_attrs, node) = self.parse_impl_method(&vis, at_end)?;
4889 attrs.extend(inner_attrs);
4894 id: ast::DUMMY_NODE_ID,
4895 span: lo.to(self.prev_span),
4898 defaultness: defaultness,
4904 fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
4905 if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
4910 fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
4912 Visibility::Inherited => Ok(()),
4914 let is_macro_rules: bool = match self.token {
4915 token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
4919 let mut err = self.diagnostic()
4920 .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
4921 err.help("did you mean #[macro_export]?");
4924 let mut err = self.diagnostic()
4925 .struct_span_err(sp, "can't qualify macro invocation with `pub`");
4926 err.help("try adjusting the macro to put `pub` inside the invocation");
4933 fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
4934 -> DiagnosticBuilder<'a>
4936 // Given this code `path(`, it seems like this is not
4937 // setting the visibility of a macro invocation, but rather
4938 // a mistyped method declaration.
4939 // Create a diagnostic pointing out that `fn` is missing.
4941 // x | pub path(&self) {
4942 // | ^ missing `fn`, `type`, or `const`
4944 // ^^ `sp` below will point to this
4945 let sp = prev_span.between(self.prev_span);
4946 let mut err = self.diagnostic().struct_span_err(
4948 &format!("missing `fn`, `type`, or `const` for {}-item declaration",
4950 err.span_label(sp, "missing `fn`, `type`, or `const`");
4954 /// Parse a method or a macro invocation in a trait impl.
4955 fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
4956 -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4957 // code copied from parse_macro_use_or_failure... abstraction!
4958 if self.token.is_path_start() {
4961 let prev_span = self.prev_span;
4964 let pth = self.parse_path(PathStyle::Mod)?;
4965 if pth.segments.len() == 1 {
4966 if !self.eat(&token::Not) {
4967 return Err(self.missing_assoc_item_kind_err("impl", prev_span));
4970 self.expect(&token::Not)?;
4973 self.complain_if_pub_macro(vis, prev_span);
4975 // eat a matched-delimiter token tree:
4977 let (delim, tts) = self.expect_delimited_token_tree()?;
4978 if delim != token::Brace {
4979 self.expect(&token::Semi)?
4982 let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
4983 Ok((keywords::Invalid.ident(), vec![], ast::ImplItemKind::Macro(mac)))
4985 let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
4986 let ident = self.parse_ident()?;
4987 let mut generics = self.parse_generics()?;
4988 let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
4989 generics.where_clause = self.parse_where_clause()?;
4991 let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4992 Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4996 constness: constness,
5002 /// Parse trait Foo { ... }
5003 fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5004 let ident = self.parse_ident()?;
5005 let mut tps = self.parse_generics()?;
5007 // Parse optional colon and supertrait bounds.
5008 let bounds = if self.eat(&token::Colon) {
5009 self.parse_ty_param_bounds()?
5014 tps.where_clause = self.parse_where_clause()?;
5016 self.expect(&token::OpenDelim(token::Brace))?;
5017 let mut trait_items = vec![];
5018 while !self.eat(&token::CloseDelim(token::Brace)) {
5019 let mut at_end = false;
5020 match self.parse_trait_item(&mut at_end) {
5021 Ok(item) => trait_items.push(item),
5025 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5030 Ok((ident, ItemKind::Trait(unsafety, tps, bounds, trait_items), None))
5033 /// Parses items implementations variants
5034 /// impl<T> Foo { ... }
5035 /// impl<T> ToString for &'static T { ... }
5036 /// impl Send for .. {}
5037 fn parse_item_impl(&mut self,
5038 unsafety: ast::Unsafety,
5039 defaultness: Defaultness) -> PResult<'a, ItemInfo> {
5040 let impl_span = self.span;
5042 // First, parse type parameters if necessary.
5043 let mut generics = self.parse_generics()?;
5045 // Special case: if the next identifier that follows is '(', don't
5046 // allow this to be parsed as a trait.
5047 let could_be_trait = self.token != token::OpenDelim(token::Paren);
5049 let neg_span = self.span;
5050 let polarity = if self.eat(&token::Not) {
5051 ast::ImplPolarity::Negative
5053 ast::ImplPolarity::Positive
5057 let mut ty = self.parse_ty()?;
5059 // Parse traits, if necessary.
5060 let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
5061 // New-style trait. Reinterpret the type as a trait.
5063 TyKind::Path(None, ref path) => {
5065 path: (*path).clone(),
5070 self.span_err(ty.span, "not a trait");
5075 if polarity == ast::ImplPolarity::Negative {
5076 // This is a negated type implementation
5077 // `impl !MyType {}`, which is not allowed.
5078 self.span_err(neg_span, "inherent implementation can't be negated");
5083 if opt_trait.is_some() && self.eat(&token::DotDot) {
5084 if generics.is_parameterized() {
5085 self.span_err(impl_span, "default trait implementations are not \
5086 allowed to have generics");
5089 if let ast::Defaultness::Default = defaultness {
5090 self.span_err(impl_span, "`default impl` is not allowed for \
5091 default trait implementations");
5094 self.expect(&token::OpenDelim(token::Brace))?;
5095 self.expect(&token::CloseDelim(token::Brace))?;
5096 Ok((keywords::Invalid.ident(),
5097 ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
5099 if opt_trait.is_some() {
5100 ty = self.parse_ty()?;
5102 generics.where_clause = self.parse_where_clause()?;
5104 self.expect(&token::OpenDelim(token::Brace))?;
5105 let attrs = self.parse_inner_attributes()?;
5107 let mut impl_items = vec![];
5108 while !self.eat(&token::CloseDelim(token::Brace)) {
5109 let mut at_end = false;
5110 match self.parse_impl_item(&mut at_end) {
5111 Ok(item) => impl_items.push(item),
5115 self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5121 Ok((keywords::Invalid.ident(),
5122 ItemKind::Impl(unsafety, polarity, defaultness, generics, opt_trait, ty, impl_items),
5127 fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<LifetimeDef>> {
5128 if self.eat_keyword(keywords::For) {
5130 let (lifetime_defs, ty_params) = self.parse_generic_params()?;
5132 if !ty_params.is_empty() {
5133 self.span_err(ty_params[0].span,
5134 "only lifetime parameters can be used in this context");
5142 /// Parse struct Foo { ... }
5143 fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5144 let class_name = self.parse_ident()?;
5146 let mut generics = self.parse_generics()?;
5148 // There is a special case worth noting here, as reported in issue #17904.
5149 // If we are parsing a tuple struct it is the case that the where clause
5150 // should follow the field list. Like so:
5152 // struct Foo<T>(T) where T: Copy;
5154 // If we are parsing a normal record-style struct it is the case
5155 // that the where clause comes before the body, and after the generics.
5156 // So if we look ahead and see a brace or a where-clause we begin
5157 // parsing a record style struct.
5159 // Otherwise if we look ahead and see a paren we parse a tuple-style
5162 let vdata = if self.token.is_keyword(keywords::Where) {
5163 generics.where_clause = self.parse_where_clause()?;
5164 if self.eat(&token::Semi) {
5165 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5166 VariantData::Unit(ast::DUMMY_NODE_ID)
5168 // If we see: `struct Foo<T> where T: Copy { ... }`
5169 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5171 // No `where` so: `struct Foo<T>;`
5172 } else if self.eat(&token::Semi) {
5173 VariantData::Unit(ast::DUMMY_NODE_ID)
5174 // Record-style struct definition
5175 } else if self.token == token::OpenDelim(token::Brace) {
5176 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5177 // Tuple-style struct definition with optional where-clause.
5178 } else if self.token == token::OpenDelim(token::Paren) {
5179 let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5180 generics.where_clause = self.parse_where_clause()?;
5181 self.expect(&token::Semi)?;
5184 let token_str = self.this_token_to_string();
5185 return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5186 name, found `{}`", token_str)))
5189 Ok((class_name, ItemKind::Struct(vdata, generics), None))
5192 /// Parse union Foo { ... }
5193 fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5194 let class_name = self.parse_ident()?;
5196 let mut generics = self.parse_generics()?;
5198 let vdata = if self.token.is_keyword(keywords::Where) {
5199 generics.where_clause = self.parse_where_clause()?;
5200 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5201 } else if self.token == token::OpenDelim(token::Brace) {
5202 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5204 let token_str = self.this_token_to_string();
5205 return Err(self.fatal(&format!("expected `where` or `{{` after union \
5206 name, found `{}`", token_str)))
5209 Ok((class_name, ItemKind::Union(vdata, generics), None))
5212 pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5213 let mut fields = Vec::new();
5214 if self.eat(&token::OpenDelim(token::Brace)) {
5215 while self.token != token::CloseDelim(token::Brace) {
5216 fields.push(self.parse_struct_decl_field().map_err(|e| {
5217 self.recover_stmt();
5218 self.eat(&token::CloseDelim(token::Brace));
5225 let token_str = self.this_token_to_string();
5226 return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5234 pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5235 // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5236 // Unit like structs are handled in parse_item_struct function
5237 let fields = self.parse_unspanned_seq(
5238 &token::OpenDelim(token::Paren),
5239 &token::CloseDelim(token::Paren),
5240 SeqSep::trailing_allowed(token::Comma),
5242 let attrs = p.parse_outer_attributes()?;
5244 let vis = p.parse_visibility(true)?;
5245 let ty = p.parse_ty()?;
5247 span: lo.to(p.span),
5250 id: ast::DUMMY_NODE_ID,
5259 /// Parse a structure field declaration
5260 pub fn parse_single_struct_field(&mut self,
5263 attrs: Vec<Attribute> )
5264 -> PResult<'a, StructField> {
5265 let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5270 token::CloseDelim(token::Brace) => {}
5271 token::DocComment(_) => return Err(self.span_fatal_err(self.span,
5272 Error::UselessDocComment)),
5273 _ => return Err(self.span_fatal_help(self.span,
5274 &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5275 "struct fields should be separated by commas")),
5280 /// Parse an element of a struct definition
5281 fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5282 let attrs = self.parse_outer_attributes()?;
5284 let vis = self.parse_visibility(false)?;
5285 self.parse_single_struct_field(lo, vis, attrs)
5288 /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5289 /// and `pub(super)` for `pub(in super)`. If the following element can't be a tuple (i.e. it's
5290 /// a function definition, it's not a tuple struct field) and the contents within the parens
5291 /// isn't valid, emit a proper diagnostic.
5292 pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5293 maybe_whole!(self, NtVis, |x| x);
5295 if !self.eat_keyword(keywords::Pub) {
5296 return Ok(Visibility::Inherited)
5299 if self.check(&token::OpenDelim(token::Paren)) {
5300 // We don't `self.bump()` the `(` yet because this might be a struct definition where
5301 // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5302 // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5303 // by the following tokens.
5304 if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5307 self.bump(); // `crate`
5308 let vis = Visibility::Crate(self.prev_span);
5309 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5311 } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5314 self.bump(); // `in`
5315 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5316 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5317 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5319 } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5320 self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5321 t.is_keyword(keywords::SelfValue)) {
5322 // `pub(self)` or `pub(super)`
5324 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5325 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5326 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5328 } else if !can_take_tuple { // Provide this diagnostic if this is not a tuple struct
5329 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5331 let msg = "incorrect visibility restriction";
5332 let suggestion = r##"some possible visibility restrictions are:
5333 `pub(crate)`: visible only on the current crate
5334 `pub(super)`: visible only in the current module's parent
5335 `pub(in path::to::module)`: visible only on the specified path"##;
5336 let path = self.parse_path(PathStyle::Mod)?;
5337 let path_span = self.prev_span;
5338 let help_msg = format!("make this visible only to module `{}` with `in`", path);
5339 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5340 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5341 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5342 err.emit(); // emit diagnostic, but continue with public visibility
5346 Ok(Visibility::Public)
5349 /// Parse defaultness: DEFAULT or nothing
5350 fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5351 if self.eat_defaultness() {
5352 Ok(Defaultness::Default)
5354 Ok(Defaultness::Final)
5358 /// Given a termination token, parse all of the items in a module
5359 fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5360 let mut items = vec![];
5361 while let Some(item) = self.parse_item()? {
5365 if !self.eat(term) {
5366 let token_str = self.this_token_to_string();
5367 return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5370 let hi = if self.span == syntax_pos::DUMMY_SP {
5377 inner: inner_lo.to(hi),
5382 fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5383 let id = self.parse_ident()?;
5384 self.expect(&token::Colon)?;
5385 let ty = self.parse_ty()?;
5386 self.expect(&token::Eq)?;
5387 let e = self.parse_expr()?;
5388 self.expect(&token::Semi)?;
5389 let item = match m {
5390 Some(m) => ItemKind::Static(ty, m, e),
5391 None => ItemKind::Const(ty, e),
5393 Ok((id, item, None))
5396 /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5397 fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5398 let (in_cfg, outer_attrs) = {
5399 let mut strip_unconfigured = ::config::StripUnconfigured {
5401 should_test: false, // irrelevant
5402 features: None, // don't perform gated feature checking
5404 let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5405 (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5408 let id_span = self.span;
5409 let id = self.parse_ident()?;
5410 if self.check(&token::Semi) {
5412 if in_cfg && self.recurse_into_file_modules {
5413 // This mod is in an external file. Let's go get it!
5414 let ModulePathSuccess { path, directory_ownership, warn } =
5415 self.submod_path(id, &outer_attrs, id_span)?;
5416 let (module, mut attrs) =
5417 self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5419 let attr = ast::Attribute {
5420 id: attr::mk_attr_id(),
5421 style: ast::AttrStyle::Outer,
5422 path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5423 Ident::from_str("warn_directory_ownership")),
5424 tokens: TokenStream::empty(),
5425 is_sugared_doc: false,
5426 span: syntax_pos::DUMMY_SP,
5428 attr::mark_known(&attr);
5431 Ok((id, module, Some(attrs)))
5433 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5434 Ok((id, ItemKind::Mod(placeholder), None))
5437 let old_directory = self.directory.clone();
5438 self.push_directory(id, &outer_attrs);
5440 self.expect(&token::OpenDelim(token::Brace))?;
5441 let mod_inner_lo = self.span;
5442 let attrs = self.parse_inner_attributes()?;
5443 let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5445 self.directory = old_directory;
5446 Ok((id, ItemKind::Mod(module), Some(attrs)))
5450 fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5451 if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5452 self.directory.path.push(&path.as_str());
5453 self.directory.ownership = DirectoryOwnership::Owned;
5455 self.directory.path.push(&id.name.as_str());
5459 pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5460 attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5463 /// Returns either a path to a module, or .
5464 pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5465 let mod_name = id.to_string();
5466 let default_path_str = format!("{}.rs", mod_name);
5467 let secondary_path_str = format!("{}{}mod.rs", mod_name, path::MAIN_SEPARATOR);
5468 let default_path = dir_path.join(&default_path_str);
5469 let secondary_path = dir_path.join(&secondary_path_str);
5470 let default_exists = codemap.file_exists(&default_path);
5471 let secondary_exists = codemap.file_exists(&secondary_path);
5473 let result = match (default_exists, secondary_exists) {
5474 (true, false) => Ok(ModulePathSuccess {
5476 directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5479 (false, true) => Ok(ModulePathSuccess {
5480 path: secondary_path,
5481 directory_ownership: DirectoryOwnership::Owned,
5484 (false, false) => Err(Error::FileNotFoundForModule {
5485 mod_name: mod_name.clone(),
5486 default_path: default_path_str,
5487 secondary_path: secondary_path_str,
5488 dir_path: format!("{}", dir_path.display()),
5490 (true, true) => Err(Error::DuplicatePaths {
5491 mod_name: mod_name.clone(),
5492 default_path: default_path_str,
5493 secondary_path: secondary_path_str,
5499 path_exists: default_exists || secondary_exists,
5504 fn submod_path(&mut self,
5506 outer_attrs: &[ast::Attribute],
5508 -> PResult<'a, ModulePathSuccess> {
5509 if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5510 return Ok(ModulePathSuccess {
5511 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5512 Some("mod.rs") => DirectoryOwnership::Owned,
5513 _ => DirectoryOwnership::UnownedViaMod(true),
5520 let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5522 if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5524 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5525 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5526 if paths.path_exists {
5527 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5529 err.span_note(id_sp, &msg);
5532 } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5534 if let Ok(result) = paths.result {
5535 return Ok(ModulePathSuccess { warn: true, ..result });
5538 let mut err = self.diagnostic().struct_span_err(id_sp,
5539 "cannot declare a new module at this location");
5540 if id_sp != syntax_pos::DUMMY_SP {
5541 let src_path = PathBuf::from(self.sess.codemap().span_to_filename(id_sp));
5542 if let Some(stem) = src_path.file_stem() {
5543 let mut dest_path = src_path.clone();
5544 dest_path.set_file_name(stem);
5545 dest_path.push("mod.rs");
5546 err.span_note(id_sp,
5547 &format!("maybe move this module `{}` to its own \
5548 directory via `{}`", src_path.to_string_lossy(),
5549 dest_path.to_string_lossy()));
5552 if paths.path_exists {
5553 err.span_note(id_sp,
5554 &format!("... or maybe `use` the module `{}` instead \
5555 of possibly redeclaring it",
5560 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5564 /// Read a module from a source file.
5565 fn eval_src_mod(&mut self,
5567 directory_ownership: DirectoryOwnership,
5570 -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5571 let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5572 if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5573 let mut err = String::from("circular modules: ");
5574 let len = included_mod_stack.len();
5575 for p in &included_mod_stack[i.. len] {
5576 err.push_str(&p.to_string_lossy());
5577 err.push_str(" -> ");
5579 err.push_str(&path.to_string_lossy());
5580 return Err(self.span_fatal(id_sp, &err[..]));
5582 included_mod_stack.push(path.clone());
5583 drop(included_mod_stack);
5586 new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5587 p0.cfg_mods = self.cfg_mods;
5588 let mod_inner_lo = p0.span;
5589 let mod_attrs = p0.parse_inner_attributes()?;
5590 let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5591 self.sess.included_mod_stack.borrow_mut().pop();
5592 Ok((ast::ItemKind::Mod(m0), mod_attrs))
5595 /// Parse a function declaration from a foreign module
5596 fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5597 -> PResult<'a, ForeignItem> {
5598 self.expect_keyword(keywords::Fn)?;
5600 let (ident, mut generics) = self.parse_fn_header()?;
5601 let decl = self.parse_fn_decl(true)?;
5602 generics.where_clause = self.parse_where_clause()?;
5604 self.expect(&token::Semi)?;
5605 Ok(ast::ForeignItem {
5608 node: ForeignItemKind::Fn(decl, generics),
5609 id: ast::DUMMY_NODE_ID,
5615 /// Parse a static item from a foreign module
5616 fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5617 -> PResult<'a, ForeignItem> {
5618 self.expect_keyword(keywords::Static)?;
5619 let mutbl = self.eat_keyword(keywords::Mut);
5621 let ident = self.parse_ident()?;
5622 self.expect(&token::Colon)?;
5623 let ty = self.parse_ty()?;
5625 self.expect(&token::Semi)?;
5629 node: ForeignItemKind::Static(ty, mutbl),
5630 id: ast::DUMMY_NODE_ID,
5636 /// Parse extern crate links
5640 /// extern crate foo;
5641 /// extern crate bar as foo;
5642 fn parse_item_extern_crate(&mut self,
5644 visibility: Visibility,
5645 attrs: Vec<Attribute>)
5646 -> PResult<'a, P<Item>> {
5648 let crate_name = self.parse_ident()?;
5649 let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
5650 (Some(crate_name.name), ident)
5654 self.expect(&token::Semi)?;
5656 let prev_span = self.prev_span;
5657 Ok(self.mk_item(lo.to(prev_span),
5659 ItemKind::ExternCrate(maybe_path),
5664 /// Parse `extern` for foreign ABIs
5667 /// `extern` is expected to have been
5668 /// consumed before calling this method
5674 fn parse_item_foreign_mod(&mut self,
5676 opt_abi: Option<abi::Abi>,
5677 visibility: Visibility,
5678 mut attrs: Vec<Attribute>)
5679 -> PResult<'a, P<Item>> {
5680 self.expect(&token::OpenDelim(token::Brace))?;
5682 let abi = opt_abi.unwrap_or(Abi::C);
5684 attrs.extend(self.parse_inner_attributes()?);
5686 let mut foreign_items = vec![];
5687 while let Some(item) = self.parse_foreign_item()? {
5688 foreign_items.push(item);
5690 self.expect(&token::CloseDelim(token::Brace))?;
5692 let prev_span = self.prev_span;
5693 let m = ast::ForeignMod {
5695 items: foreign_items
5697 let invalid = keywords::Invalid.ident();
5698 Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
5701 /// Parse type Foo = Bar;
5702 fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5703 let ident = self.parse_ident()?;
5704 let mut tps = self.parse_generics()?;
5705 tps.where_clause = self.parse_where_clause()?;
5706 self.expect(&token::Eq)?;
5707 let ty = self.parse_ty()?;
5708 self.expect(&token::Semi)?;
5709 Ok((ident, ItemKind::Ty(ty, tps), None))
5712 /// Parse the part of an "enum" decl following the '{'
5713 fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5714 let mut variants = Vec::new();
5715 let mut all_nullary = true;
5716 let mut any_disr = None;
5717 while self.token != token::CloseDelim(token::Brace) {
5718 let variant_attrs = self.parse_outer_attributes()?;
5719 let vlo = self.span;
5722 let mut disr_expr = None;
5723 let ident = self.parse_ident()?;
5724 if self.check(&token::OpenDelim(token::Brace)) {
5725 // Parse a struct variant.
5726 all_nullary = false;
5727 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
5728 ast::DUMMY_NODE_ID);
5729 } else if self.check(&token::OpenDelim(token::Paren)) {
5730 all_nullary = false;
5731 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
5732 ast::DUMMY_NODE_ID);
5733 } else if self.eat(&token::Eq) {
5734 disr_expr = Some(self.parse_expr()?);
5735 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5736 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5738 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5741 let vr = ast::Variant_ {
5743 attrs: variant_attrs,
5745 disr_expr: disr_expr,
5747 variants.push(respan(vlo.to(self.prev_span), vr));
5749 if !self.eat(&token::Comma) { break; }
5751 self.expect(&token::CloseDelim(token::Brace))?;
5753 Some(disr_span) if !all_nullary =>
5754 self.span_err(disr_span,
5755 "discriminator values can only be used with a c-like enum"),
5759 Ok(ast::EnumDef { variants: variants })
5762 /// Parse an "enum" declaration
5763 fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5764 let id = self.parse_ident()?;
5765 let mut generics = self.parse_generics()?;
5766 generics.where_clause = self.parse_where_clause()?;
5767 self.expect(&token::OpenDelim(token::Brace))?;
5769 let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
5770 self.recover_stmt();
5771 self.eat(&token::CloseDelim(token::Brace));
5774 Ok((id, ItemKind::Enum(enum_definition, generics), None))
5777 /// Parses a string as an ABI spec on an extern type or module. Consumes
5778 /// the `extern` keyword, if one is found.
5779 fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5781 token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5783 self.expect_no_suffix(sp, "ABI spec", suf);
5785 match abi::lookup(&s.as_str()) {
5786 Some(abi) => Ok(Some(abi)),
5788 let prev_span = self.prev_span;
5791 &format!("invalid ABI: expected one of [{}], \
5793 abi::all_names().join(", "),
5804 /// Parse one of the items allowed by the flags.
5805 /// NB: this function no longer parses the items inside an
5807 fn parse_item_(&mut self, attrs: Vec<Attribute>,
5808 macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5809 maybe_whole!(self, NtItem, |item| {
5810 let mut item = item.unwrap();
5811 let mut attrs = attrs;
5812 mem::swap(&mut item.attrs, &mut attrs);
5813 item.attrs.extend(attrs);
5819 let visibility = self.parse_visibility(false)?;
5821 if self.eat_keyword(keywords::Use) {
5823 let item_ = ItemKind::Use(self.parse_view_path()?);
5824 self.expect(&token::Semi)?;
5826 let prev_span = self.prev_span;
5827 let invalid = keywords::Invalid.ident();
5828 let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
5829 return Ok(Some(item));
5832 if self.eat_keyword(keywords::Extern) {
5833 if self.eat_keyword(keywords::Crate) {
5834 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
5837 let opt_abi = self.parse_opt_abi()?;
5839 if self.eat_keyword(keywords::Fn) {
5840 // EXTERN FUNCTION ITEM
5841 let fn_span = self.prev_span;
5842 let abi = opt_abi.unwrap_or(Abi::C);
5843 let (ident, item_, extra_attrs) =
5844 self.parse_item_fn(Unsafety::Normal,
5845 respan(fn_span, Constness::NotConst),
5847 let prev_span = self.prev_span;
5848 let item = self.mk_item(lo.to(prev_span),
5852 maybe_append(attrs, extra_attrs));
5853 return Ok(Some(item));
5854 } else if self.check(&token::OpenDelim(token::Brace)) {
5855 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
5861 if self.eat_keyword(keywords::Static) {
5863 let m = if self.eat_keyword(keywords::Mut) {
5866 Mutability::Immutable
5868 let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
5869 let prev_span = self.prev_span;
5870 let item = self.mk_item(lo.to(prev_span),
5874 maybe_append(attrs, extra_attrs));
5875 return Ok(Some(item));
5877 if self.eat_keyword(keywords::Const) {
5878 let const_span = self.prev_span;
5879 if self.check_keyword(keywords::Fn)
5880 || (self.check_keyword(keywords::Unsafe)
5881 && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5882 // CONST FUNCTION ITEM
5883 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5889 let (ident, item_, extra_attrs) =
5890 self.parse_item_fn(unsafety,
5891 respan(const_span, Constness::Const),
5893 let prev_span = self.prev_span;
5894 let item = self.mk_item(lo.to(prev_span),
5898 maybe_append(attrs, extra_attrs));
5899 return Ok(Some(item));
5903 if self.eat_keyword(keywords::Mut) {
5904 let prev_span = self.prev_span;
5905 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
5906 .help("did you mean to declare a static?")
5909 let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
5910 let prev_span = self.prev_span;
5911 let item = self.mk_item(lo.to(prev_span),
5915 maybe_append(attrs, extra_attrs));
5916 return Ok(Some(item));
5918 if self.check_keyword(keywords::Unsafe) &&
5919 self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5921 // UNSAFE TRAIT ITEM
5922 self.expect_keyword(keywords::Unsafe)?;
5923 self.expect_keyword(keywords::Trait)?;
5924 let (ident, item_, extra_attrs) =
5925 self.parse_item_trait(ast::Unsafety::Unsafe)?;
5926 let prev_span = self.prev_span;
5927 let item = self.mk_item(lo.to(prev_span),
5931 maybe_append(attrs, extra_attrs));
5932 return Ok(Some(item));
5934 if (self.check_keyword(keywords::Unsafe) &&
5935 self.look_ahead(1, |t| t.is_keyword(keywords::Impl))) ||
5936 (self.check_keyword(keywords::Default) &&
5937 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) &&
5938 self.look_ahead(2, |t| t.is_keyword(keywords::Impl)))
5941 let defaultness = self.parse_defaultness()?;
5942 self.expect_keyword(keywords::Unsafe)?;
5943 self.expect_keyword(keywords::Impl)?;
5946 extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe, defaultness)?;
5947 let prev_span = self.prev_span;
5948 let item = self.mk_item(lo.to(prev_span),
5952 maybe_append(attrs, extra_attrs));
5953 return Ok(Some(item));
5955 if self.check_keyword(keywords::Fn) {
5958 let fn_span = self.prev_span;
5959 let (ident, item_, extra_attrs) =
5960 self.parse_item_fn(Unsafety::Normal,
5961 respan(fn_span, Constness::NotConst),
5963 let prev_span = self.prev_span;
5964 let item = self.mk_item(lo.to(prev_span),
5968 maybe_append(attrs, extra_attrs));
5969 return Ok(Some(item));
5971 if self.check_keyword(keywords::Unsafe)
5972 && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5973 // UNSAFE FUNCTION ITEM
5975 let abi = if self.eat_keyword(keywords::Extern) {
5976 self.parse_opt_abi()?.unwrap_or(Abi::C)
5980 self.expect_keyword(keywords::Fn)?;
5981 let fn_span = self.prev_span;
5982 let (ident, item_, extra_attrs) =
5983 self.parse_item_fn(Unsafety::Unsafe,
5984 respan(fn_span, Constness::NotConst),
5986 let prev_span = self.prev_span;
5987 let item = self.mk_item(lo.to(prev_span),
5991 maybe_append(attrs, extra_attrs));
5992 return Ok(Some(item));
5994 if self.eat_keyword(keywords::Mod) {
5996 let (ident, item_, extra_attrs) =
5997 self.parse_item_mod(&attrs[..])?;
5998 let prev_span = self.prev_span;
5999 let item = self.mk_item(lo.to(prev_span),
6003 maybe_append(attrs, extra_attrs));
6004 return Ok(Some(item));
6006 if self.eat_keyword(keywords::Type) {
6008 let (ident, item_, extra_attrs) = self.parse_item_type()?;
6009 let prev_span = self.prev_span;
6010 let item = self.mk_item(lo.to(prev_span),
6014 maybe_append(attrs, extra_attrs));
6015 return Ok(Some(item));
6017 if self.eat_keyword(keywords::Enum) {
6019 let (ident, item_, extra_attrs) = self.parse_item_enum()?;
6020 let prev_span = self.prev_span;
6021 let item = self.mk_item(lo.to(prev_span),
6025 maybe_append(attrs, extra_attrs));
6026 return Ok(Some(item));
6028 if self.eat_keyword(keywords::Trait) {
6030 let (ident, item_, extra_attrs) =
6031 self.parse_item_trait(ast::Unsafety::Normal)?;
6032 let prev_span = self.prev_span;
6033 let item = self.mk_item(lo.to(prev_span),
6037 maybe_append(attrs, extra_attrs));
6038 return Ok(Some(item));
6040 if (self.check_keyword(keywords::Impl)) ||
6041 (self.check_keyword(keywords::Default) &&
6042 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)))
6045 let defaultness = self.parse_defaultness()?;
6046 self.expect_keyword(keywords::Impl)?;
6049 extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal, defaultness)?;
6050 let prev_span = self.prev_span;
6051 let item = self.mk_item(lo.to(prev_span),
6055 maybe_append(attrs, extra_attrs));
6056 return Ok(Some(item));
6058 if self.eat_keyword(keywords::Struct) {
6060 let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6061 let prev_span = self.prev_span;
6062 let item = self.mk_item(lo.to(prev_span),
6066 maybe_append(attrs, extra_attrs));
6067 return Ok(Some(item));
6069 if self.is_union_item() {
6072 let (ident, item_, extra_attrs) = self.parse_item_union()?;
6073 let prev_span = self.prev_span;
6074 let item = self.mk_item(lo.to(prev_span),
6078 maybe_append(attrs, extra_attrs));
6079 return Ok(Some(item));
6081 if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility)? {
6082 return Ok(Some(macro_def));
6085 self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
6088 /// Parse a foreign item.
6089 fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
6090 let attrs = self.parse_outer_attributes()?;
6092 let visibility = self.parse_visibility(false)?;
6094 if self.check_keyword(keywords::Static) {
6095 // FOREIGN STATIC ITEM
6096 return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6098 if self.check_keyword(keywords::Fn) {
6099 // FOREIGN FUNCTION ITEM
6100 return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6103 if self.check_keyword(keywords::Const) {
6104 return Err(self.span_fatal(self.span, "extern items cannot be `const`"));
6107 // FIXME #5668: this will occur for a macro invocation:
6108 match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
6110 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
6116 /// This is the fall-through for parsing items.
6117 fn parse_macro_use_or_failure(
6119 attrs: Vec<Attribute> ,
6120 macros_allowed: bool,
6121 attributes_allowed: bool,
6123 visibility: Visibility
6124 ) -> PResult<'a, Option<P<Item>>> {
6125 if macros_allowed && self.token.is_path_start() {
6126 // MACRO INVOCATION ITEM
6128 let prev_span = self.prev_span;
6129 self.complain_if_pub_macro(&visibility, prev_span);
6131 let mac_lo = self.span;
6134 let pth = self.parse_path(PathStyle::Mod)?;
6135 self.expect(&token::Not)?;
6137 // a 'special' identifier (like what `macro_rules!` uses)
6138 // is optional. We should eventually unify invoc syntax
6140 let id = if self.token.is_ident() {
6143 keywords::Invalid.ident() // no special identifier
6145 // eat a matched-delimiter token tree:
6146 let (delim, tts) = self.expect_delimited_token_tree()?;
6147 if delim != token::Brace {
6148 if !self.eat(&token::Semi) {
6149 self.span_err(self.prev_span,
6150 "macros that expand to items must either \
6151 be surrounded with braces or followed by \
6156 let hi = self.prev_span;
6157 let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6158 let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6159 return Ok(Some(item));
6162 // FAILURE TO PARSE ITEM
6164 Visibility::Inherited => {}
6166 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
6170 if !attributes_allowed && !attrs.is_empty() {
6171 self.expected_item_err(&attrs);
6176 pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6177 let attrs = self.parse_outer_attributes()?;
6178 self.parse_item_(attrs, true, false)
6181 fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> {
6182 self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
6183 &token::CloseDelim(token::Brace),
6184 SeqSep::trailing_allowed(token::Comma), |this| {
6186 let ident = if this.eat_keyword(keywords::SelfValue) {
6187 keywords::SelfValue.ident()
6191 let rename = this.parse_rename()?;
6192 let node = ast::PathListItem_ {
6195 id: ast::DUMMY_NODE_ID
6197 Ok(respan(lo.to(this.prev_span), node))
6202 fn is_import_coupler(&mut self) -> bool {
6203 self.check(&token::ModSep) &&
6204 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6205 *t == token::BinOp(token::Star))
6208 /// Matches ViewPath:
6209 /// MOD_SEP? non_global_path
6210 /// MOD_SEP? non_global_path as IDENT
6211 /// MOD_SEP? non_global_path MOD_SEP STAR
6212 /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE
6213 /// MOD_SEP? LBRACE item_seq RBRACE
6214 fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
6216 if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) ||
6217 self.is_import_coupler() {
6218 // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`.
6219 self.eat(&token::ModSep);
6220 let prefix = ast::Path {
6221 segments: vec![PathSegment::crate_root(lo)],
6222 span: lo.to(self.span),
6224 let view_path_kind = if self.eat(&token::BinOp(token::Star)) {
6225 ViewPathGlob(prefix)
6227 ViewPathList(prefix, self.parse_path_list_items()?)
6229 Ok(P(respan(lo.to(self.span), view_path_kind)))
6231 let prefix = self.parse_path(PathStyle::Mod)?.default_to_global();
6232 if self.is_import_coupler() {
6233 // `foo::bar::{a, b}` or `foo::bar::*`
6235 if self.check(&token::BinOp(token::Star)) {
6237 Ok(P(respan(lo.to(self.span), ViewPathGlob(prefix))))
6239 let items = self.parse_path_list_items()?;
6240 Ok(P(respan(lo.to(self.span), ViewPathList(prefix, items))))
6243 // `foo::bar` or `foo::bar as baz`
6244 let rename = self.parse_rename()?.
6245 unwrap_or(prefix.segments.last().unwrap().identifier);
6246 Ok(P(respan(lo.to(self.prev_span), ViewPathSimple(rename, prefix))))
6251 fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6252 if self.eat_keyword(keywords::As) {
6253 self.parse_ident().map(Some)
6259 /// Parses a source module as a crate. This is the main
6260 /// entry point for the parser.
6261 pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6264 attrs: self.parse_inner_attributes()?,
6265 module: self.parse_mod_items(&token::Eof, lo)?,
6266 span: lo.to(self.span),
6270 pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6271 let ret = match self.token {
6272 token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6273 token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6280 pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6281 match self.parse_optional_str() {
6282 Some((s, style, suf)) => {
6283 let sp = self.prev_span;
6284 self.expect_no_suffix(sp, "string literal", suf);
6287 _ => Err(self.fatal("expected string literal"))