]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/parser.rs
Rollup merge of #41910 - mersinvald:master, r=Mark-Simulacrum
[rust.git] / src / libsyntax / parse / parser.rs
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.
4 //
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.
10
11 use abi::{self, Abi};
12 use ast::{AttrStyle, BareFnTy};
13 use ast::{RegionTyParamBound, TraitTyParamBound, TraitBoundModifier};
14 use ast::Unsafety;
15 use ast::{Mod, Arg, Arm, Attribute, BindingMode, TraitItemKind};
16 use ast::Block;
17 use ast::{BlockCheckMode, CaptureBy};
18 use ast::{Constness, Crate};
19 use ast::Defaultness;
20 use ast::EnumDef;
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};
26 use ast::Local;
27 use ast::MacStmtStyle;
28 use ast::Mac_;
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};
34 use ast::StrStyle;
35 use ast::SelfKind;
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};
41 use ast::RangeEnd;
42 use {ast, attr};
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};
53 use print::pprust;
54 use ptr::P;
55 use parse::PResult;
56 use tokenstream::{self, Delimited, ThinTokenStream, TokenTree, TokenStream};
57 use symbol::{Symbol, keywords};
58 use util::ThinVec;
59
60 use std::cmp;
61 use std::collections::HashSet;
62 use std::mem;
63 use std::path::{self, Path, PathBuf};
64 use std::slice;
65
66 bitflags! {
67     pub flags Restrictions: u8 {
68         const RESTRICTION_STMT_EXPR         = 1 << 0,
69         const RESTRICTION_NO_STRUCT_LITERAL = 1 << 1,
70     }
71 }
72
73 type ItemInfo = (Ident, ItemKind, Option<Vec<Attribute> >);
74
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)]
78 pub enum PathStyle {
79     /// A path with no type parameters, e.g. `foo::bar::Baz`, used in imports or visibilities.
80     Mod,
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.
84     Type,
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.
87     Expr,
88 }
89
90 #[derive(Clone, Copy, Debug, PartialEq)]
91 pub enum SemiColonMode {
92     Break,
93     Ignore,
94 }
95
96 #[derive(Clone, Copy, Debug, PartialEq)]
97 pub enum BlockMode {
98     Break,
99     Ignore,
100 }
101
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 {
108     ($p:expr) => {
109         if let token::Interpolated(nt) = $p.token.clone() {
110             match *nt {
111                 token::NtExpr(ref e) => {
112                     $p.bump();
113                     return Ok((*e).clone());
114                 }
115                 token::NtPath(ref path) => {
116                     $p.bump();
117                     let span = $p.span;
118                     let kind = ExprKind::Path(None, (*path).clone());
119                     return Ok($p.mk_expr(span, kind, ThinVec::new()));
120                 }
121                 token::NtBlock(ref block) => {
122                     $p.bump();
123                     let span = $p.span;
124                     let kind = ExprKind::Block((*block).clone());
125                     return Ok($p.mk_expr(span, kind, ThinVec::new()));
126                 }
127                 _ => {},
128             };
129         }
130     }
131 }
132
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).clone() {
138                 $p.bump();
139                 return Ok($e);
140             }
141         }
142     };
143 }
144
145 fn maybe_append(mut lhs: Vec<Attribute>, rhs: Option<Vec<Attribute>>)
146                 -> Vec<Attribute> {
147     if let Some(ref attrs) = rhs {
148         lhs.extend(attrs.iter().cloned())
149     }
150     lhs
151 }
152
153 #[derive(PartialEq)]
154 enum PrevTokenKind {
155     DocComment,
156     Comma,
157     Plus,
158     Interpolated,
159     Eof,
160     Other,
161 }
162
163 /* ident is handled by common.rs */
164
165 pub struct Parser<'a> {
166     pub sess: &'a ParseSess,
167     /// the current token:
168     pub token: token::Token,
169     /// the span of the current token:
170     pub span: Span,
171     /// the span of the previous token:
172     pub meta_var_span: Option<Span>,
173     pub prev_span: Span,
174     /// the previous token kind
175     prev_token_kind: PrevTokenKind,
176     pub restrictions: Restrictions,
177     /// The set of seen errors about obsolete syntax. Used to suppress
178     /// extra detail when the same error is seen twice
179     pub obsolete_set: HashSet<ObsoleteSyntax>,
180     /// Used to determine the path to externally loaded source files
181     pub directory: Directory,
182     /// Name of the root module this parser originated from. If `None`, then the
183     /// name is not known. This does not change while the parser is descending
184     /// into modules, and sub-parsers have new values for this name.
185     pub root_module_name: Option<String>,
186     pub expected_tokens: Vec<TokenType>,
187     token_cursor: TokenCursor,
188     pub desugar_doc_comments: bool,
189     /// Whether we should configure out of line modules as we parse.
190     pub cfg_mods: bool,
191 }
192
193 struct TokenCursor {
194     frame: TokenCursorFrame,
195     stack: Vec<TokenCursorFrame>,
196 }
197
198 struct TokenCursorFrame {
199     delim: token::DelimToken,
200     span: Span,
201     open_delim: bool,
202     tree_cursor: tokenstream::Cursor,
203     close_delim: bool,
204 }
205
206 impl TokenCursorFrame {
207     fn new(sp: Span, delimited: &Delimited) -> Self {
208         TokenCursorFrame {
209             delim: delimited.delim,
210             span: sp,
211             open_delim: delimited.delim == token::NoDelim,
212             tree_cursor: delimited.stream().into_trees(),
213             close_delim: delimited.delim == token::NoDelim,
214         }
215     }
216 }
217
218 impl TokenCursor {
219     fn next(&mut self) -> TokenAndSpan {
220         loop {
221             let tree = if !self.frame.open_delim {
222                 self.frame.open_delim = true;
223                 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
224                     .open_tt(self.frame.span)
225             } else if let Some(tree) = self.frame.tree_cursor.next() {
226                 tree
227             } else if !self.frame.close_delim {
228                 self.frame.close_delim = true;
229                 Delimited { delim: self.frame.delim, tts: TokenStream::empty().into() }
230                     .close_tt(self.frame.span)
231             } else if let Some(frame) = self.stack.pop() {
232                 self.frame = frame;
233                 continue
234             } else {
235                 return TokenAndSpan { tok: token::Eof, sp: syntax_pos::DUMMY_SP }
236             };
237
238             match tree {
239                 TokenTree::Token(sp, tok) => return TokenAndSpan { tok: tok, sp: sp },
240                 TokenTree::Delimited(sp, ref delimited) => {
241                     let frame = TokenCursorFrame::new(sp, delimited);
242                     self.stack.push(mem::replace(&mut self.frame, frame));
243                 }
244             }
245         }
246     }
247
248     fn next_desugared(&mut self) -> TokenAndSpan {
249         let (sp, name) = match self.next() {
250             TokenAndSpan { sp, tok: token::DocComment(name) } => (sp, name),
251             tok => return tok,
252         };
253
254         let stripped = strip_doc_comment_decoration(&name.as_str());
255
256         // Searches for the occurrences of `"#*` and returns the minimum number of `#`s
257         // required to wrap the text.
258         let mut num_of_hashes = 0;
259         let mut count = 0;
260         for ch in stripped.chars() {
261             count = match ch {
262                 '"' => 1,
263                 '#' if count > 0 => count + 1,
264                 _ => 0,
265             };
266             num_of_hashes = cmp::max(num_of_hashes, count);
267         }
268
269         let body = TokenTree::Delimited(sp, Delimited {
270             delim: token::Bracket,
271             tts: [TokenTree::Token(sp, token::Ident(ast::Ident::from_str("doc"))),
272                   TokenTree::Token(sp, token::Eq),
273                   TokenTree::Token(sp, token::Literal(
274                       token::StrRaw(Symbol::intern(&stripped), num_of_hashes), None))]
275                 .iter().cloned().collect::<TokenStream>().into(),
276         });
277
278         self.stack.push(mem::replace(&mut self.frame, TokenCursorFrame::new(sp, &Delimited {
279             delim: token::NoDelim,
280             tts: if doc_comment_style(&name.as_str()) == AttrStyle::Inner {
281                 [TokenTree::Token(sp, token::Pound), TokenTree::Token(sp, token::Not), body]
282                     .iter().cloned().collect::<TokenStream>().into()
283             } else {
284                 [TokenTree::Token(sp, token::Pound), body]
285                     .iter().cloned().collect::<TokenStream>().into()
286             },
287         })));
288
289         self.next()
290     }
291 }
292
293 #[derive(PartialEq, Eq, Clone)]
294 pub enum TokenType {
295     Token(token::Token),
296     Keyword(keywords::Keyword),
297     Operator,
298     Lifetime,
299     Ident,
300     Path,
301     Type,
302 }
303
304 impl TokenType {
305     fn to_string(&self) -> String {
306         match *self {
307             TokenType::Token(ref t) => format!("`{}`", Parser::token_to_string(t)),
308             TokenType::Keyword(kw) => format!("`{}`", kw.name()),
309             TokenType::Operator => "an operator".to_string(),
310             TokenType::Lifetime => "lifetime".to_string(),
311             TokenType::Ident => "identifier".to_string(),
312             TokenType::Path => "path".to_string(),
313             TokenType::Type => "type".to_string(),
314         }
315     }
316 }
317
318 fn is_ident_or_underscore(t: &token::Token) -> bool {
319     t.is_ident() || *t == token::Underscore
320 }
321
322 /// Information about the path to a module.
323 pub struct ModulePath {
324     pub name: String,
325     pub path_exists: bool,
326     pub result: Result<ModulePathSuccess, Error>,
327 }
328
329 pub struct ModulePathSuccess {
330     pub path: PathBuf,
331     pub directory_ownership: DirectoryOwnership,
332     warn: bool,
333 }
334
335 pub struct ModulePathError {
336     pub err_msg: String,
337     pub help_msg: String,
338 }
339
340 pub enum Error {
341     FileNotFoundForModule {
342         mod_name: String,
343         default_path: String,
344         secondary_path: String,
345         dir_path: String,
346     },
347     DuplicatePaths {
348         mod_name: String,
349         default_path: String,
350         secondary_path: String,
351     },
352     UselessDocComment,
353     InclusiveRangeWithNoEnd,
354 }
355
356 impl Error {
357     pub fn span_err(self, sp: Span, handler: &errors::Handler) -> DiagnosticBuilder {
358         match self {
359             Error::FileNotFoundForModule { ref mod_name,
360                                            ref default_path,
361                                            ref secondary_path,
362                                            ref dir_path } => {
363                 let mut err = struct_span_err!(handler, sp, E0583,
364                                                "file not found for module `{}`", mod_name);
365                 err.help(&format!("name the file either {} or {} inside the directory {:?}",
366                                   default_path,
367                                   secondary_path,
368                                   dir_path));
369                 err
370             }
371             Error::DuplicatePaths { ref mod_name, ref default_path, ref secondary_path } => {
372                 let mut err = struct_span_err!(handler, sp, E0584,
373                                                "file for module `{}` found at both {} and {}",
374                                                mod_name,
375                                                default_path,
376                                                secondary_path);
377                 err.help("delete or rename one of them to remove the ambiguity");
378                 err
379             }
380             Error::UselessDocComment => {
381                 let mut err = struct_span_err!(handler, sp, E0585,
382                                   "found a documentation comment that doesn't document anything");
383                 err.help("doc comments must come before what they document, maybe a comment was \
384                           intended with `//`?");
385                 err
386             }
387             Error::InclusiveRangeWithNoEnd => {
388                 let mut err = struct_span_err!(handler, sp, E0586,
389                                                "inclusive range with no end");
390                 err.help("inclusive ranges must be bounded at the end (`...b` or `a...b`)");
391                 err
392             }
393         }
394     }
395 }
396
397 pub enum LhsExpr {
398     NotYetParsed,
399     AttributesParsed(ThinVec<Attribute>),
400     AlreadyParsed(P<Expr>),
401 }
402
403 impl From<Option<ThinVec<Attribute>>> for LhsExpr {
404     fn from(o: Option<ThinVec<Attribute>>) -> Self {
405         if let Some(attrs) = o {
406             LhsExpr::AttributesParsed(attrs)
407         } else {
408             LhsExpr::NotYetParsed
409         }
410     }
411 }
412
413 impl From<P<Expr>> for LhsExpr {
414     fn from(expr: P<Expr>) -> Self {
415         LhsExpr::AlreadyParsed(expr)
416     }
417 }
418
419 /// Create a placeholder argument.
420 fn dummy_arg(span: Span) -> Arg {
421     let spanned = Spanned {
422         span: span,
423         node: keywords::Invalid.ident()
424     };
425     let pat = P(Pat {
426         id: ast::DUMMY_NODE_ID,
427         node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable), spanned, None),
428         span: span
429     });
430     let ty = Ty {
431         node: TyKind::Err,
432         span: span,
433         id: ast::DUMMY_NODE_ID
434     };
435     Arg { ty: P(ty), pat: pat, id: ast::DUMMY_NODE_ID }
436 }
437
438 impl<'a> Parser<'a> {
439     pub fn new(sess: &'a ParseSess,
440                tokens: TokenStream,
441                directory: Option<Directory>,
442                desugar_doc_comments: bool)
443                -> Self {
444         let mut parser = Parser {
445             sess: sess,
446             token: token::Underscore,
447             span: syntax_pos::DUMMY_SP,
448             prev_span: syntax_pos::DUMMY_SP,
449             meta_var_span: None,
450             prev_token_kind: PrevTokenKind::Other,
451             restrictions: Restrictions::empty(),
452             obsolete_set: HashSet::new(),
453             directory: Directory { path: PathBuf::new(), ownership: DirectoryOwnership::Owned },
454             root_module_name: None,
455             expected_tokens: Vec::new(),
456             token_cursor: TokenCursor {
457                 frame: TokenCursorFrame::new(syntax_pos::DUMMY_SP, &Delimited {
458                     delim: token::NoDelim,
459                     tts: tokens.into(),
460                 }),
461                 stack: Vec::new(),
462             },
463             desugar_doc_comments: desugar_doc_comments,
464             cfg_mods: true,
465         };
466
467         let tok = parser.next_tok();
468         parser.token = tok.tok;
469         parser.span = tok.sp;
470         if let Some(directory) = directory {
471             parser.directory = directory;
472         } else if parser.span != syntax_pos::DUMMY_SP {
473             parser.directory.path = PathBuf::from(sess.codemap().span_to_filename(parser.span));
474             parser.directory.path.pop();
475         }
476         parser.process_potential_macro_variable();
477         parser
478     }
479
480     fn next_tok(&mut self) -> TokenAndSpan {
481         let mut next = if self.desugar_doc_comments {
482             self.token_cursor.next_desugared()
483         } else {
484             self.token_cursor.next()
485         };
486         if next.sp == syntax_pos::DUMMY_SP {
487             next.sp = self.prev_span;
488         }
489         next
490     }
491
492     /// Convert a token to a string using self's reader
493     pub fn token_to_string(token: &token::Token) -> String {
494         pprust::token_to_string(token)
495     }
496
497     /// Convert the current token to a string using self's reader
498     pub fn this_token_to_string(&self) -> String {
499         Parser::token_to_string(&self.token)
500     }
501
502     pub fn this_token_descr(&self) -> String {
503         let s = self.this_token_to_string();
504         if self.token.is_strict_keyword() {
505             format!("keyword `{}`", s)
506         } else if self.token.is_reserved_keyword() {
507             format!("reserved keyword `{}`", s)
508         } else {
509             format!("`{}`", s)
510         }
511     }
512
513     pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
514         let token_str = Parser::token_to_string(t);
515         Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
516     }
517
518     pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
519         match self.expect_one_of(&[], &[]) {
520             Err(e) => Err(e),
521             Ok(_) => unreachable!(),
522         }
523     }
524
525     /// Expect and consume the token t. Signal an error if
526     /// the next token is not t.
527     pub fn expect(&mut self, t: &token::Token) -> PResult<'a,  ()> {
528         if self.expected_tokens.is_empty() {
529             if self.token == *t {
530                 self.bump();
531                 Ok(())
532             } else {
533                 let token_str = Parser::token_to_string(t);
534                 let this_token_str = self.this_token_to_string();
535                 Err(self.fatal(&format!("expected `{}`, found `{}`",
536                                    token_str,
537                                    this_token_str)))
538             }
539         } else {
540             self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
541         }
542     }
543
544     /// Expect next token to be edible or inedible token.  If edible,
545     /// then consume it; if inedible, then return without consuming
546     /// anything.  Signal a fatal error if next token is unexpected.
547     pub fn expect_one_of(&mut self,
548                          edible: &[token::Token],
549                          inedible: &[token::Token]) -> PResult<'a,  ()>{
550         fn tokens_to_string(tokens: &[TokenType]) -> String {
551             let mut i = tokens.iter();
552             // This might be a sign we need a connect method on Iterator.
553             let b = i.next()
554                      .map_or("".to_string(), |t| t.to_string());
555             i.enumerate().fold(b, |mut b, (i, a)| {
556                 if tokens.len() > 2 && i == tokens.len() - 2 {
557                     b.push_str(", or ");
558                 } else if tokens.len() == 2 && i == tokens.len() - 2 {
559                     b.push_str(" or ");
560                 } else {
561                     b.push_str(", ");
562                 }
563                 b.push_str(&a.to_string());
564                 b
565             })
566         }
567         if edible.contains(&self.token) {
568             self.bump();
569             Ok(())
570         } else if inedible.contains(&self.token) {
571             // leave it in the input
572             Ok(())
573         } else {
574             let mut expected = edible.iter()
575                 .map(|x| TokenType::Token(x.clone()))
576                 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
577                 .chain(self.expected_tokens.iter().cloned())
578                 .collect::<Vec<_>>();
579             expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
580             expected.dedup();
581             let expect = tokens_to_string(&expected[..]);
582             let actual = self.this_token_to_string();
583             let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
584                 let short_expect = if expected.len() > 6 {
585                     format!("{} possible tokens", expected.len())
586                 } else {
587                     expect.clone()
588                 };
589                 (format!("expected one of {}, found `{}`", expect, actual),
590                  (self.prev_span.next_point(), format!("expected one of {} here", short_expect)))
591             } else if expected.is_empty() {
592                 (format!("unexpected token: `{}`", actual),
593                  (self.prev_span, "unexpected token after this".to_string()))
594             } else {
595                 (format!("expected {}, found `{}`", expect, actual),
596                  (self.prev_span.next_point(), format!("expected {} here", expect)))
597             };
598             let mut err = self.fatal(&msg_exp);
599             let sp = if self.token == token::Token::Eof {
600                 // This is EOF, don't want to point at the following char, but rather the last token
601                 self.prev_span
602             } else {
603                 label_sp
604             };
605             if self.span.contains(sp) {
606                 err.span_label(self.span, label_exp);
607             } else {
608                 err.span_label(sp, label_exp);
609                 err.span_label(self.span, "unexpected token");
610             }
611             Err(err)
612         }
613     }
614
615     /// returns the span of expr, if it was not interpolated or the span of the interpolated token
616     fn interpolated_or_expr_span(&self,
617                                  expr: PResult<'a, P<Expr>>)
618                                  -> PResult<'a, (Span, P<Expr>)> {
619         expr.map(|e| {
620             if self.prev_token_kind == PrevTokenKind::Interpolated {
621                 (self.prev_span, e)
622             } else {
623                 (e.span, e)
624             }
625         })
626     }
627
628     pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
629         self.check_strict_keywords();
630         self.check_reserved_keywords();
631         match self.token {
632             token::Ident(i) => {
633                 self.bump();
634                 Ok(i)
635             }
636             _ => {
637                 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
638                         self.span_fatal_err(self.prev_span, Error::UselessDocComment)
639                     } else {
640                         let mut err = self.fatal(&format!("expected identifier, found `{}`",
641                                                           self.this_token_to_string()));
642                         if self.token == token::Underscore {
643                             err.note("`_` is a wildcard pattern, not an identifier");
644                         }
645                         err
646                     })
647             }
648         }
649     }
650
651     /// Check if the next token is `tok`, and return `true` if so.
652     ///
653     /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
654     /// encountered.
655     pub fn check(&mut self, tok: &token::Token) -> bool {
656         let is_present = self.token == *tok;
657         if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
658         is_present
659     }
660
661     /// Consume token 'tok' if it exists. Returns true if the given
662     /// token was present, false otherwise.
663     pub fn eat(&mut self, tok: &token::Token) -> bool {
664         let is_present = self.check(tok);
665         if is_present { self.bump() }
666         is_present
667     }
668
669     pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
670         self.expected_tokens.push(TokenType::Keyword(kw));
671         self.token.is_keyword(kw)
672     }
673
674     /// If the next token is the given keyword, eat it and return
675     /// true. Otherwise, return false.
676     pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
677         if self.check_keyword(kw) {
678             self.bump();
679             true
680         } else {
681             false
682         }
683     }
684
685     pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
686         if self.token.is_keyword(kw) {
687             self.bump();
688             true
689         } else {
690             false
691         }
692     }
693
694     pub fn check_contextual_keyword(&mut self, ident: Ident) -> bool {
695         self.expected_tokens.push(TokenType::Token(token::Ident(ident)));
696         if let token::Ident(ref cur_ident) = self.token {
697             cur_ident.name == ident.name
698         } else {
699             false
700         }
701     }
702
703     pub fn eat_contextual_keyword(&mut self, ident: Ident) -> bool {
704         if self.check_contextual_keyword(ident) {
705             self.bump();
706             true
707         } else {
708             false
709         }
710     }
711
712     /// If the given word is not a keyword, signal an error.
713     /// If the next token is not the given word, signal an error.
714     /// Otherwise, eat it.
715     pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
716         if !self.eat_keyword(kw) {
717             self.unexpected()
718         } else {
719             Ok(())
720         }
721     }
722
723     /// Signal an error if the given string is a strict keyword
724     pub fn check_strict_keywords(&mut self) {
725         if self.token.is_strict_keyword() {
726             let token_str = self.this_token_to_string();
727             let span = self.span;
728             self.span_err(span,
729                           &format!("expected identifier, found keyword `{}`",
730                                   token_str));
731         }
732     }
733
734     /// Signal an error if the current token is a reserved keyword
735     pub fn check_reserved_keywords(&mut self) {
736         if self.token.is_reserved_keyword() {
737             let token_str = self.this_token_to_string();
738             self.fatal(&format!("`{}` is a reserved keyword", token_str)).emit()
739         }
740     }
741
742     fn check_ident(&mut self) -> bool {
743         if self.token.is_ident() {
744             true
745         } else {
746             self.expected_tokens.push(TokenType::Ident);
747             false
748         }
749     }
750
751     fn check_path(&mut self) -> bool {
752         if self.token.is_path_start() {
753             true
754         } else {
755             self.expected_tokens.push(TokenType::Path);
756             false
757         }
758     }
759
760     fn check_type(&mut self) -> bool {
761         if self.token.can_begin_type() {
762             true
763         } else {
764             self.expected_tokens.push(TokenType::Type);
765             false
766         }
767     }
768
769     /// Expect and consume an `&`. If `&&` is seen, replace it with a single
770     /// `&` and continue. If an `&` is not seen, signal an error.
771     fn expect_and(&mut self) -> PResult<'a, ()> {
772         self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
773         match self.token {
774             token::BinOp(token::And) => {
775                 self.bump();
776                 Ok(())
777             }
778             token::AndAnd => {
779                 let span = self.span;
780                 let lo = span.lo + BytePos(1);
781                 Ok(self.bump_with(token::BinOp(token::And), Span { lo: lo, ..span }))
782             }
783             _ => self.unexpected()
784         }
785     }
786
787     pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
788         match suffix {
789             None => {/* everything ok */}
790             Some(suf) => {
791                 let text = suf.as_str();
792                 if text.is_empty() {
793                     self.span_bug(sp, "found empty literal suffix in Some")
794                 }
795                 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
796             }
797         }
798     }
799
800     /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
801     /// `<` and continue. If a `<` is not seen, return false.
802     ///
803     /// This is meant to be used when parsing generics on a path to get the
804     /// starting token.
805     fn eat_lt(&mut self) -> bool {
806         self.expected_tokens.push(TokenType::Token(token::Lt));
807         match self.token {
808             token::Lt => {
809                 self.bump();
810                 true
811             }
812             token::BinOp(token::Shl) => {
813                 let span = self.span;
814                 let lo = span.lo + BytePos(1);
815                 self.bump_with(token::Lt, Span { lo: lo, ..span });
816                 true
817             }
818             _ => false,
819         }
820     }
821
822     fn expect_lt(&mut self) -> PResult<'a, ()> {
823         if !self.eat_lt() {
824             self.unexpected()
825         } else {
826             Ok(())
827         }
828     }
829
830     /// Expect and consume a GT. if a >> is seen, replace it
831     /// with a single > and continue. If a GT is not seen,
832     /// signal an error.
833     pub fn expect_gt(&mut self) -> PResult<'a, ()> {
834         self.expected_tokens.push(TokenType::Token(token::Gt));
835         match self.token {
836             token::Gt => {
837                 self.bump();
838                 Ok(())
839             }
840             token::BinOp(token::Shr) => {
841                 let span = self.span;
842                 let lo = span.lo + BytePos(1);
843                 Ok(self.bump_with(token::Gt, Span { lo: lo, ..span }))
844             }
845             token::BinOpEq(token::Shr) => {
846                 let span = self.span;
847                 let lo = span.lo + BytePos(1);
848                 Ok(self.bump_with(token::Ge, Span { lo: lo, ..span }))
849             }
850             token::Ge => {
851                 let span = self.span;
852                 let lo = span.lo + BytePos(1);
853                 Ok(self.bump_with(token::Eq, Span { lo: lo, ..span }))
854             }
855             _ => self.unexpected()
856         }
857     }
858
859     pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
860                                                   sep: Option<token::Token>,
861                                                   mut f: F)
862                                                   -> PResult<'a, (Vec<T>, bool)>
863         where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
864     {
865         let mut v = Vec::new();
866         // This loop works by alternating back and forth between parsing types
867         // and commas.  For example, given a string `A, B,>`, the parser would
868         // first parse `A`, then a comma, then `B`, then a comma. After that it
869         // would encounter a `>` and stop. This lets the parser handle trailing
870         // commas in generic parameters, because it can stop either after
871         // parsing a type or after parsing a comma.
872         for i in 0.. {
873             if self.check(&token::Gt)
874                 || self.token == token::BinOp(token::Shr)
875                 || self.token == token::Ge
876                 || self.token == token::BinOpEq(token::Shr) {
877                 break;
878             }
879
880             if i % 2 == 0 {
881                 match f(self)? {
882                     Some(result) => v.push(result),
883                     None => return Ok((v, true))
884                 }
885             } else {
886                 if let Some(t) = sep.as_ref() {
887                     self.expect(t)?;
888                 }
889
890             }
891         }
892         return Ok((v, false));
893     }
894
895     /// Parse a sequence bracketed by '<' and '>', stopping
896     /// before the '>'.
897     pub fn parse_seq_to_before_gt<T, F>(&mut self,
898                                         sep: Option<token::Token>,
899                                         mut f: F)
900                                         -> PResult<'a, Vec<T>> where
901         F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
902     {
903         let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
904                                                                        |p| Ok(Some(f(p)?)))?;
905         assert!(!returned);
906         return Ok(result);
907     }
908
909     pub fn parse_seq_to_gt<T, F>(&mut self,
910                                  sep: Option<token::Token>,
911                                  f: F)
912                                  -> PResult<'a, Vec<T>> where
913         F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
914     {
915         let v = self.parse_seq_to_before_gt(sep, f)?;
916         self.expect_gt()?;
917         return Ok(v);
918     }
919
920     pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
921                                            sep: Option<token::Token>,
922                                            f: F)
923                                            -> PResult<'a, (Vec<T>, bool)> where
924         F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
925     {
926         let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
927         if !returned {
928             self.expect_gt()?;
929         }
930         return Ok((v, returned));
931     }
932
933     /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
934     /// passes through any errors encountered. Used for error recovery.
935     pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
936         let handler = self.diagnostic();
937
938         self.parse_seq_to_before_tokens(kets,
939                                         SeqSep::none(),
940                                         |p| Ok(p.parse_token_tree()),
941                                         |mut e| handler.cancel(&mut e));
942     }
943
944     /// Parse a sequence, including the closing delimiter. The function
945     /// f must consume tokens until reaching the next separator or
946     /// closing bracket.
947     pub fn parse_seq_to_end<T, F>(&mut self,
948                                   ket: &token::Token,
949                                   sep: SeqSep,
950                                   f: F)
951                                   -> PResult<'a, Vec<T>> where
952         F: FnMut(&mut Parser<'a>) -> PResult<'a,  T>,
953     {
954         let val = self.parse_seq_to_before_end(ket, sep, f);
955         self.bump();
956         Ok(val)
957     }
958
959     /// Parse a sequence, not including the closing delimiter. The function
960     /// f must consume tokens until reaching the next separator or
961     /// closing bracket.
962     pub fn parse_seq_to_before_end<T, F>(&mut self,
963                                          ket: &token::Token,
964                                          sep: SeqSep,
965                                          f: F)
966                                          -> Vec<T>
967         where F: FnMut(&mut Parser<'a>) -> PResult<'a,  T>
968     {
969         self.parse_seq_to_before_tokens(&[ket], sep, f, |mut e| e.emit())
970     }
971
972     // `fe` is an error handler.
973     fn parse_seq_to_before_tokens<T, F, Fe>(&mut self,
974                                             kets: &[&token::Token],
975                                             sep: SeqSep,
976                                             mut f: F,
977                                             mut fe: Fe)
978                                             -> Vec<T>
979         where F: FnMut(&mut Parser<'a>) -> PResult<'a,  T>,
980               Fe: FnMut(DiagnosticBuilder)
981     {
982         let mut first: bool = true;
983         let mut v = vec![];
984         while !kets.contains(&&self.token) {
985             match self.token {
986                 token::CloseDelim(..) | token::Eof => break,
987                 _ => {}
988             };
989             if let Some(ref t) = sep.sep {
990                 if first {
991                     first = false;
992                 } else {
993                     if let Err(e) = self.expect(t) {
994                         fe(e);
995                         break;
996                     }
997                 }
998             }
999             if sep.trailing_sep_allowed && kets.iter().any(|k| self.check(k)) {
1000                 break;
1001             }
1002
1003             match f(self) {
1004                 Ok(t) => v.push(t),
1005                 Err(e) => {
1006                     fe(e);
1007                     break;
1008                 }
1009             }
1010         }
1011
1012         v
1013     }
1014
1015     /// Parse a sequence, including the closing delimiter. The function
1016     /// f must consume tokens until reaching the next separator or
1017     /// closing bracket.
1018     pub fn parse_unspanned_seq<T, F>(&mut self,
1019                                      bra: &token::Token,
1020                                      ket: &token::Token,
1021                                      sep: SeqSep,
1022                                      f: F)
1023                                      -> PResult<'a, Vec<T>> where
1024         F: FnMut(&mut Parser<'a>) -> PResult<'a,  T>,
1025     {
1026         self.expect(bra)?;
1027         let result = self.parse_seq_to_before_end(ket, sep, f);
1028         if self.token == *ket {
1029             self.bump();
1030         }
1031         Ok(result)
1032     }
1033
1034     // NB: Do not use this function unless you actually plan to place the
1035     // spanned list in the AST.
1036     pub fn parse_seq<T, F>(&mut self,
1037                            bra: &token::Token,
1038                            ket: &token::Token,
1039                            sep: SeqSep,
1040                            f: F)
1041                            -> PResult<'a, Spanned<Vec<T>>> where
1042         F: FnMut(&mut Parser<'a>) -> PResult<'a,  T>,
1043     {
1044         let lo = self.span;
1045         self.expect(bra)?;
1046         let result = self.parse_seq_to_before_end(ket, sep, f);
1047         let hi = self.span;
1048         self.bump();
1049         Ok(respan(lo.to(hi), result))
1050     }
1051
1052     /// Advance the parser by one token
1053     pub fn bump(&mut self) {
1054         if self.prev_token_kind == PrevTokenKind::Eof {
1055             // Bumping after EOF is a bad sign, usually an infinite loop.
1056             self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1057         }
1058
1059         self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1060
1061         // Record last token kind for possible error recovery.
1062         self.prev_token_kind = match self.token {
1063             token::DocComment(..) => PrevTokenKind::DocComment,
1064             token::Comma => PrevTokenKind::Comma,
1065             token::BinOp(token::Plus) => PrevTokenKind::Plus,
1066             token::Interpolated(..) => PrevTokenKind::Interpolated,
1067             token::Eof => PrevTokenKind::Eof,
1068             _ => PrevTokenKind::Other,
1069         };
1070
1071         let next = self.next_tok();
1072         self.span = next.sp;
1073         self.token = next.tok;
1074         self.expected_tokens.clear();
1075         // check after each token
1076         self.process_potential_macro_variable();
1077     }
1078
1079     /// Advance the parser using provided token as a next one. Use this when
1080     /// consuming a part of a token. For example a single `<` from `<<`.
1081     pub fn bump_with(&mut self, next: token::Token, span: Span) {
1082         self.prev_span = Span { hi: span.lo, ..self.span };
1083         // It would be incorrect to record the kind of the current token, but
1084         // fortunately for tokens currently using `bump_with`, the
1085         // prev_token_kind will be of no use anyway.
1086         self.prev_token_kind = PrevTokenKind::Other;
1087         self.span = span;
1088         self.token = next;
1089         self.expected_tokens.clear();
1090     }
1091
1092     pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1093         F: FnOnce(&token::Token) -> R,
1094     {
1095         if dist == 0 {
1096             return f(&self.token)
1097         }
1098
1099         f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1100             Some(tree) => match tree {
1101                 TokenTree::Token(_, tok) => tok,
1102                 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1103             },
1104             None => token::CloseDelim(self.token_cursor.frame.delim),
1105         })
1106     }
1107     pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1108         self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1109     }
1110     pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1111         self.sess.span_diagnostic.struct_span_fatal(sp, m)
1112     }
1113     pub fn span_fatal_err(&self, sp: Span, err: Error) -> DiagnosticBuilder<'a> {
1114         err.span_err(sp, self.diagnostic())
1115     }
1116     pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1117         let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1118         err.help(help);
1119         err
1120     }
1121     pub fn bug(&self, m: &str) -> ! {
1122         self.sess.span_diagnostic.span_bug(self.span, m)
1123     }
1124     pub fn warn(&self, m: &str) {
1125         self.sess.span_diagnostic.span_warn(self.span, m)
1126     }
1127     pub fn span_warn(&self, sp: Span, m: &str) {
1128         self.sess.span_diagnostic.span_warn(sp, m)
1129     }
1130     pub fn span_err(&self, sp: Span, m: &str) {
1131         self.sess.span_diagnostic.span_err(sp, m)
1132     }
1133     pub fn span_err_help(&self, sp: Span, m: &str, h: &str) {
1134         let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1135         err.help(h);
1136         err.emit();
1137     }
1138     pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1139         self.sess.span_diagnostic.span_bug(sp, m)
1140     }
1141     pub fn abort_if_errors(&self) {
1142         self.sess.span_diagnostic.abort_if_errors();
1143     }
1144
1145     fn cancel(&self, err: &mut DiagnosticBuilder) {
1146         self.sess.span_diagnostic.cancel(err)
1147     }
1148
1149     pub fn diagnostic(&self) -> &'a errors::Handler {
1150         &self.sess.span_diagnostic
1151     }
1152
1153     /// Is the current token one of the keywords that signals a bare function
1154     /// type?
1155     pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1156         self.check_keyword(keywords::Fn) ||
1157             self.check_keyword(keywords::Unsafe) ||
1158             self.check_keyword(keywords::Extern)
1159     }
1160
1161     fn get_label(&mut self) -> ast::Ident {
1162         match self.token {
1163             token::Lifetime(ref ident) => *ident,
1164             _ => self.bug("not a lifetime"),
1165         }
1166     }
1167
1168     /// parse a TyKind::BareFn type:
1169     pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<LifetimeDef>)
1170                             -> PResult<'a, TyKind> {
1171         /*
1172
1173         [unsafe] [extern "ABI"] fn (S) -> T
1174          ^~~~^           ^~~~^     ^~^    ^
1175            |               |        |     |
1176            |               |        |   Return type
1177            |               |      Argument types
1178            |               |
1179            |              ABI
1180         Function Style
1181         */
1182
1183         let unsafety = self.parse_unsafety()?;
1184         let abi = if self.eat_keyword(keywords::Extern) {
1185             self.parse_opt_abi()?.unwrap_or(Abi::C)
1186         } else {
1187             Abi::Rust
1188         };
1189
1190         self.expect_keyword(keywords::Fn)?;
1191         let (inputs, variadic) = self.parse_fn_args(false, true)?;
1192         let ret_ty = self.parse_ret_ty()?;
1193         let decl = P(FnDecl {
1194             inputs: inputs,
1195             output: ret_ty,
1196             variadic: variadic
1197         });
1198         Ok(TyKind::BareFn(P(BareFnTy {
1199             abi: abi,
1200             unsafety: unsafety,
1201             lifetimes: lifetime_defs,
1202             decl: decl
1203         })))
1204     }
1205
1206     pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1207         if self.eat_keyword(keywords::Unsafe) {
1208             return Ok(Unsafety::Unsafe);
1209         } else {
1210             return Ok(Unsafety::Normal);
1211         }
1212     }
1213
1214     /// Parse the items in a trait declaration
1215     pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1216         maybe_whole!(self, NtTraitItem, |x| x);
1217         let mut attrs = self.parse_outer_attributes()?;
1218         let lo = self.span;
1219
1220         let (name, node) = if self.eat_keyword(keywords::Type) {
1221             let TyParam {ident, bounds, default, ..} = self.parse_ty_param(vec![])?;
1222             self.expect(&token::Semi)?;
1223             (ident, TraitItemKind::Type(bounds, default))
1224         } else if self.is_const_item() {
1225             self.expect_keyword(keywords::Const)?;
1226             let ident = self.parse_ident()?;
1227             self.expect(&token::Colon)?;
1228             let ty = self.parse_ty()?;
1229             let default = if self.check(&token::Eq) {
1230                 self.bump();
1231                 let expr = self.parse_expr()?;
1232                 self.expect(&token::Semi)?;
1233                 Some(expr)
1234             } else {
1235                 self.expect(&token::Semi)?;
1236                 None
1237             };
1238             (ident, TraitItemKind::Const(ty, default))
1239         } else if self.token.is_path_start() {
1240             // trait item macro.
1241             // code copied from parse_macro_use_or_failure... abstraction!
1242             let prev_span = self.prev_span;
1243             let lo = self.span;
1244             let pth = self.parse_path(PathStyle::Mod)?;
1245
1246             if pth.segments.len() == 1 {
1247                 if !self.eat(&token::Not) {
1248                     return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1249                 }
1250             } else {
1251                 self.expect(&token::Not)?;
1252             }
1253
1254             // eat a matched-delimiter token tree:
1255             let (delim, tts) = self.expect_delimited_token_tree()?;
1256             if delim != token::Brace {
1257                 self.expect(&token::Semi)?
1258             }
1259
1260             let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1261             (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac))
1262         } else {
1263             let (constness, unsafety, abi) = match self.parse_fn_front_matter() {
1264                 Ok(cua) => cua,
1265                 Err(e) => return Err(e),
1266             };
1267
1268             let ident = self.parse_ident()?;
1269             let mut generics = self.parse_generics()?;
1270
1271             let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1272                 // This is somewhat dubious; We don't want to allow
1273                 // argument names to be left off if there is a
1274                 // definition...
1275                 p.parse_arg_general(false)
1276             })?;
1277
1278             generics.where_clause = self.parse_where_clause()?;
1279             let sig = ast::MethodSig {
1280                 unsafety: unsafety,
1281                 constness: constness,
1282                 decl: d,
1283                 generics: generics,
1284                 abi: abi,
1285             };
1286
1287             let body = match self.token {
1288                 token::Semi => {
1289                     self.bump();
1290                     *at_end = true;
1291                     debug!("parse_trait_methods(): parsing required method");
1292                     None
1293                 }
1294                 token::OpenDelim(token::Brace) => {
1295                     debug!("parse_trait_methods(): parsing provided method");
1296                     *at_end = true;
1297                     let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1298                     attrs.extend(inner_attrs.iter().cloned());
1299                     Some(body)
1300                 }
1301                 _ => {
1302                     let token_str = self.this_token_to_string();
1303                     return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1304                 }
1305             };
1306             (ident, ast::TraitItemKind::Method(sig, body))
1307         };
1308
1309         Ok(TraitItem {
1310             id: ast::DUMMY_NODE_ID,
1311             ident: name,
1312             attrs: attrs,
1313             node: node,
1314             span: lo.to(self.prev_span),
1315         })
1316     }
1317
1318     /// Parse optional return type [ -> TY ] in function decl
1319     pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1320         if self.eat(&token::RArrow) {
1321             Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
1322         } else {
1323             Ok(FunctionRetTy::Default(Span { hi: self.span.lo, ..self.span }))
1324         }
1325     }
1326
1327     // Parse a type
1328     pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1329         self.parse_ty_common(true)
1330     }
1331
1332     /// Parse a type in restricted contexts where `+` is not permitted.
1333     /// Example 1: `&'a TYPE`
1334     ///     `+` is prohibited to maintain operator priority (P(+) < P(&)).
1335     /// Example 2: `value1 as TYPE + value2`
1336     ///     `+` is prohibited to avoid interactions with expression grammar.
1337     fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1338         self.parse_ty_common(false)
1339     }
1340
1341     fn parse_ty_common(&mut self, allow_plus: bool) -> PResult<'a, P<Ty>> {
1342         maybe_whole!(self, NtTy, |x| x);
1343
1344         let lo = self.span;
1345         let node = if self.eat(&token::OpenDelim(token::Paren)) {
1346             // `(TYPE)` is a parenthesized type.
1347             // `(TYPE,)` is a tuple with a single field of type TYPE.
1348             let mut ts = vec![];
1349             let mut last_comma = false;
1350             while self.token != token::CloseDelim(token::Paren) {
1351                 ts.push(self.parse_ty()?);
1352                 if self.eat(&token::Comma) {
1353                     last_comma = true;
1354                 } else {
1355                     last_comma = false;
1356                     break;
1357                 }
1358             }
1359             let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1360             self.expect(&token::CloseDelim(token::Paren))?;
1361
1362             if ts.len() == 1 && !last_comma {
1363                 let ty = ts.into_iter().nth(0).unwrap().unwrap();
1364                 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1365                 match ty.node {
1366                     // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1367                     TyKind::Path(None, ref path) if maybe_bounds => {
1368                         self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1369                     }
1370                     TyKind::TraitObject(ref bounds)
1371                             if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1372                         let path = match bounds[0] {
1373                             TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1374                             _ => self.bug("unexpected lifetime bound"),
1375                         };
1376                         self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1377                     }
1378                     // `(TYPE)`
1379                     _ => TyKind::Paren(P(ty))
1380                 }
1381             } else {
1382                 TyKind::Tup(ts)
1383             }
1384         } else if self.eat(&token::Not) {
1385             // Never type `!`
1386             TyKind::Never
1387         } else if self.eat(&token::BinOp(token::Star)) {
1388             // Raw pointer
1389             TyKind::Ptr(self.parse_ptr()?)
1390         } else if self.eat(&token::OpenDelim(token::Bracket)) {
1391             // Array or slice
1392             let t = self.parse_ty()?;
1393             // Parse optional `; EXPR` in `[TYPE; EXPR]`
1394             let t = match self.maybe_parse_fixed_length_of_vec()? {
1395                 None => TyKind::Slice(t),
1396                 Some(suffix) => TyKind::Array(t, suffix),
1397             };
1398             self.expect(&token::CloseDelim(token::Bracket))?;
1399             t
1400         } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1401             // Reference
1402             self.expect_and()?;
1403             self.parse_borrowed_pointee()?
1404         } else if self.eat_keyword_noexpect(keywords::Typeof) {
1405             // `typeof(EXPR)`
1406             // In order to not be ambiguous, the type must be surrounded by parens.
1407             self.expect(&token::OpenDelim(token::Paren))?;
1408             let e = self.parse_expr()?;
1409             self.expect(&token::CloseDelim(token::Paren))?;
1410             TyKind::Typeof(e)
1411         } else if self.eat(&token::Underscore) {
1412             // A type to be inferred `_`
1413             TyKind::Infer
1414         } else if self.eat_lt() {
1415             // Qualified path
1416             let (qself, path) = self.parse_qualified_path(PathStyle::Type)?;
1417             TyKind::Path(Some(qself), path)
1418         } else if self.token.is_path_start() {
1419             // Simple path
1420             let path = self.parse_path(PathStyle::Type)?;
1421             if self.eat(&token::Not) {
1422                 // Macro invocation in type position
1423                 let (_, tts) = self.expect_delimited_token_tree()?;
1424                 TyKind::Mac(respan(lo.to(self.span), Mac_ { path: path, tts: tts }))
1425             } else {
1426                 // Just a type path or bound list (trait object type) starting with a trait.
1427                 //   `Type`
1428                 //   `Trait1 + Trait2 + 'a`
1429                 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1430                     self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1431                 } else {
1432                     TyKind::Path(None, path)
1433                 }
1434             }
1435         } else if self.token_is_bare_fn_keyword() {
1436             // Function pointer type
1437             self.parse_ty_bare_fn(Vec::new())?
1438         } else if self.check_keyword(keywords::For) {
1439             // Function pointer type or bound list (trait object type) starting with a poly-trait.
1440             //   `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1441             //   `for<'lt> Trait1<'lt> + Trait2 + 'a`
1442             let lo = self.span;
1443             let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1444             if self.token_is_bare_fn_keyword() {
1445                 self.parse_ty_bare_fn(lifetime_defs)?
1446             } else {
1447                 let path = self.parse_path(PathStyle::Type)?;
1448                 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1449                 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1450             }
1451         } else if self.eat_keyword(keywords::Impl) {
1452             // FIXME: figure out priority of `+` in `impl Trait1 + Trait2` (#34511).
1453             TyKind::ImplTrait(self.parse_ty_param_bounds()?)
1454         } else if self.check(&token::Question) ||
1455                   self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)){
1456             // Bound list (trait object type)
1457             TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?)
1458         } else {
1459             let msg = format!("expected type, found {}", self.this_token_descr());
1460             return Err(self.fatal(&msg));
1461         };
1462
1463         let span = lo.to(self.prev_span);
1464         let ty = Ty { node: node, span: span, id: ast::DUMMY_NODE_ID };
1465
1466         // Try to recover from use of `+` with incorrect priority.
1467         self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1468
1469         Ok(P(ty))
1470     }
1471
1472     fn parse_remaining_bounds(&mut self, lifetime_defs: Vec<LifetimeDef>, path: ast::Path,
1473                               lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1474         let poly_trait_ref = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
1475         let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1476         if parse_plus {
1477             self.bump(); // `+`
1478             bounds.append(&mut self.parse_ty_param_bounds()?);
1479         }
1480         Ok(TyKind::TraitObject(bounds))
1481     }
1482
1483     fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1484         // Do not add `+` to expected tokens.
1485         if !allow_plus || self.token != token::BinOp(token::Plus) {
1486             return Ok(())
1487         }
1488
1489         self.bump(); // `+`
1490         let bounds = self.parse_ty_param_bounds()?;
1491         let sum_span = ty.span.to(self.prev_span);
1492
1493         let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1494             "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(ty));
1495
1496         match ty.node {
1497             TyKind::Rptr(ref lifetime, ref mut_ty) => {
1498                 let sum_with_parens = pprust::to_string(|s| {
1499                     use print::pp::word;
1500                     use print::pprust::PrintState;
1501
1502                     word(&mut s.s, "&")?;
1503                     s.print_opt_lifetime(lifetime)?;
1504                     s.print_mutability(mut_ty.mutbl)?;
1505                     s.popen()?;
1506                     s.print_type(&mut_ty.ty)?;
1507                     s.print_bounds(" +", &bounds)?;
1508                     s.pclose()
1509                 });
1510                 err.span_suggestion(sum_span, "try adding parentheses:", sum_with_parens);
1511             }
1512             TyKind::Ptr(..) | TyKind::BareFn(..) => {
1513                 err.span_label(sum_span, "perhaps you forgot parentheses?");
1514             }
1515             _ => {
1516                 err.span_label(sum_span, "expected a path");
1517             },
1518         }
1519         err.emit();
1520         Ok(())
1521     }
1522
1523     fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1524         let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1525         let mutbl = self.parse_mutability();
1526         let ty = self.parse_ty_no_plus()?;
1527         return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1528     }
1529
1530     pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1531         let mutbl = if self.eat_keyword(keywords::Mut) {
1532             Mutability::Mutable
1533         } else if self.eat_keyword(keywords::Const) {
1534             Mutability::Immutable
1535         } else {
1536             let span = self.prev_span;
1537             self.span_err(span,
1538                           "expected mut or const in raw pointer type (use \
1539                            `*mut T` or `*const T` as appropriate)");
1540             Mutability::Immutable
1541         };
1542         let t = self.parse_ty_no_plus()?;
1543         Ok(MutTy { ty: t, mutbl: mutbl })
1544     }
1545
1546     pub fn is_named_argument(&mut self) -> bool {
1547         let offset = match self.token {
1548             token::BinOp(token::And) |
1549             token::AndAnd => 1,
1550             _ if self.token.is_keyword(keywords::Mut) => 1,
1551             _ => 0
1552         };
1553
1554         debug!("parser is_named_argument offset:{}", offset);
1555
1556         if offset == 0 {
1557             is_ident_or_underscore(&self.token)
1558                 && self.look_ahead(1, |t| *t == token::Colon)
1559         } else {
1560             self.look_ahead(offset, |t| is_ident_or_underscore(t))
1561                 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1562         }
1563     }
1564
1565     /// This version of parse arg doesn't necessarily require
1566     /// identifier names.
1567     pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1568         maybe_whole!(self, NtArg, |x| x);
1569
1570         let pat = if require_name || self.is_named_argument() {
1571             debug!("parse_arg_general parse_pat (require_name:{})",
1572                    require_name);
1573             let pat = self.parse_pat()?;
1574
1575             self.expect(&token::Colon)?;
1576             pat
1577         } else {
1578             debug!("parse_arg_general ident_to_pat");
1579             let sp = self.prev_span;
1580             let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1581             P(Pat {
1582                 id: ast::DUMMY_NODE_ID,
1583                 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1584                                      spanned, None),
1585                 span: sp
1586             })
1587         };
1588
1589         let t = self.parse_ty()?;
1590
1591         Ok(Arg {
1592             ty: t,
1593             pat: pat,
1594             id: ast::DUMMY_NODE_ID,
1595         })
1596     }
1597
1598     /// Parse a single function argument
1599     pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1600         self.parse_arg_general(true)
1601     }
1602
1603     /// Parse an argument in a lambda header e.g. |arg, arg|
1604     pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1605         let pat = self.parse_pat()?;
1606         let t = if self.eat(&token::Colon) {
1607             self.parse_ty()?
1608         } else {
1609             P(Ty {
1610                 id: ast::DUMMY_NODE_ID,
1611                 node: TyKind::Infer,
1612                 span: self.span,
1613             })
1614         };
1615         Ok(Arg {
1616             ty: t,
1617             pat: pat,
1618             id: ast::DUMMY_NODE_ID
1619         })
1620     }
1621
1622     pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1623         if self.eat(&token::Semi) {
1624             Ok(Some(self.parse_expr()?))
1625         } else {
1626             Ok(None)
1627         }
1628     }
1629
1630     /// Matches token_lit = LIT_INTEGER | ...
1631     pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1632         let out = match self.token {
1633             token::Interpolated(ref nt) => match **nt {
1634                 token::NtExpr(ref v) => match v.node {
1635                     ExprKind::Lit(ref lit) => { lit.node.clone() }
1636                     _ => { return self.unexpected_last(&self.token); }
1637                 },
1638                 _ => { return self.unexpected_last(&self.token); }
1639             },
1640             token::Literal(lit, suf) => {
1641                 let diag = Some((self.span, &self.sess.span_diagnostic));
1642                 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1643
1644                 if suffix_illegal {
1645                     let sp = self.span;
1646                     self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1647                 }
1648
1649                 result.unwrap()
1650             }
1651             _ => { return self.unexpected_last(&self.token); }
1652         };
1653
1654         self.bump();
1655         Ok(out)
1656     }
1657
1658     /// Matches lit = true | false | token_lit
1659     pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1660         let lo = self.span;
1661         let lit = if self.eat_keyword(keywords::True) {
1662             LitKind::Bool(true)
1663         } else if self.eat_keyword(keywords::False) {
1664             LitKind::Bool(false)
1665         } else {
1666             let lit = self.parse_lit_token()?;
1667             lit
1668         };
1669         Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1670     }
1671
1672     /// matches '-' lit | lit
1673     pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1674         let minus_lo = self.span;
1675         let minus_present = self.eat(&token::BinOp(token::Minus));
1676         let lo = self.span;
1677         let literal = P(self.parse_lit()?);
1678         let hi = self.prev_span;
1679         let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1680
1681         if minus_present {
1682             let minus_hi = self.prev_span;
1683             let unary = self.mk_unary(UnOp::Neg, expr);
1684             Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1685         } else {
1686             Ok(expr)
1687         }
1688     }
1689
1690     pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1691         match self.token {
1692             token::Ident(sid) if self.token.is_path_segment_keyword() => {
1693                 self.bump();
1694                 Ok(sid)
1695             }
1696             _ => self.parse_ident(),
1697          }
1698      }
1699
1700     /// Parses qualified path.
1701     ///
1702     /// Assumes that the leading `<` has been parsed already.
1703     ///
1704     /// Qualifed paths are a part of the universal function call
1705     /// syntax (UFCS).
1706     ///
1707     /// `qualified_path = <type [as trait_ref]>::path`
1708     ///
1709     /// See `parse_path` for `mode` meaning.
1710     ///
1711     /// # Examples:
1712     ///
1713     /// `<T as U>::a`
1714     /// `<T as U>::F::a::<S>`
1715     pub fn parse_qualified_path(&mut self, mode: PathStyle)
1716                                 -> PResult<'a, (QSelf, ast::Path)> {
1717         let span = self.prev_span;
1718         let self_type = self.parse_ty()?;
1719         let mut path = if self.eat_keyword(keywords::As) {
1720             self.parse_path(PathStyle::Type)?
1721         } else {
1722             ast::Path {
1723                 span: span,
1724                 segments: vec![]
1725             }
1726         };
1727
1728         let qself = QSelf {
1729             ty: self_type,
1730             position: path.segments.len()
1731         };
1732
1733         self.expect(&token::Gt)?;
1734         self.expect(&token::ModSep)?;
1735
1736         let segments = match mode {
1737             PathStyle::Type => {
1738                 self.parse_path_segments_without_colons()?
1739             }
1740             PathStyle::Expr => {
1741                 self.parse_path_segments_with_colons()?
1742             }
1743             PathStyle::Mod => {
1744                 self.parse_path_segments_without_types()?
1745             }
1746         };
1747         path.segments.extend(segments);
1748
1749         path.span.hi = self.prev_span.hi;
1750
1751         Ok((qself, path))
1752     }
1753
1754     /// Parses a path and optional type parameter bounds, depending on the
1755     /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1756     /// bounds are permitted and whether `::` must precede type parameter
1757     /// groups.
1758     pub fn parse_path(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1759         maybe_whole!(self, NtPath, |x| x);
1760
1761         let lo = self.meta_var_span.unwrap_or(self.span);
1762         let is_global = self.eat(&token::ModSep);
1763
1764         // Parse any number of segments and bound sets. A segment is an
1765         // identifier followed by an optional lifetime and a set of types.
1766         // A bound set is a set of type parameter bounds.
1767         let mut segments = match mode {
1768             PathStyle::Type => {
1769                 self.parse_path_segments_without_colons()?
1770             }
1771             PathStyle::Expr => {
1772                 self.parse_path_segments_with_colons()?
1773             }
1774             PathStyle::Mod => {
1775                 self.parse_path_segments_without_types()?
1776             }
1777         };
1778
1779         if is_global {
1780             segments.insert(0, PathSegment::crate_root());
1781         }
1782
1783         // Assemble the result.
1784         Ok(ast::Path {
1785             span: lo.to(self.prev_span),
1786             segments: segments,
1787         })
1788     }
1789
1790     /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1791     /// This is used when parsing derive macro paths in `#[derive]` attributes.
1792     pub fn parse_path_allowing_meta(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1793         let meta_ident = match self.token {
1794             token::Interpolated(ref nt) => match **nt {
1795                 token::NtMeta(ref meta) => match meta.node {
1796                     ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
1797                     _ => None,
1798                 },
1799                 _ => None,
1800             },
1801             _ => None,
1802         };
1803         if let Some(ident) = meta_ident {
1804             self.bump();
1805             return Ok(ast::Path::from_ident(self.prev_span, ident));
1806         }
1807         self.parse_path(mode)
1808     }
1809
1810     /// Examples:
1811     /// - `a::b<T,U>::c<V,W>`
1812     /// - `a::b<T,U>::c(V) -> W`
1813     /// - `a::b<T,U>::c(V)`
1814     pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1815         let mut segments = Vec::new();
1816         loop {
1817             // First, parse an identifier.
1818             let ident_span = self.span;
1819             let identifier = self.parse_path_segment_ident()?;
1820
1821             if self.check(&token::ModSep) && self.look_ahead(1, |t| *t == token::Lt) {
1822                 self.bump();
1823                 let prev_span = self.prev_span;
1824
1825                 let mut err = self.diagnostic().struct_span_err(prev_span,
1826                     "unexpected token: `::`");
1827                 err.help(
1828                     "use `<...>` instead of `::<...>` if you meant to specify type arguments");
1829                 err.emit();
1830             }
1831
1832             // Parse types, optionally.
1833             let parameters = if self.eat_lt() {
1834                 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1835                 self.expect_gt()?;
1836                 ast::AngleBracketedParameterData {
1837                     lifetimes: lifetimes,
1838                     types: types,
1839                     bindings: bindings,
1840                 }.into()
1841             } else if self.eat(&token::OpenDelim(token::Paren)) {
1842                 let lo = self.prev_span;
1843
1844                 let inputs = self.parse_seq_to_end(
1845                     &token::CloseDelim(token::Paren),
1846                     SeqSep::trailing_allowed(token::Comma),
1847                     |p| p.parse_ty())?;
1848
1849                 let output_ty = if self.eat(&token::RArrow) {
1850                     Some(self.parse_ty_no_plus()?)
1851                 } else {
1852                     None
1853                 };
1854
1855                 let hi = self.prev_span;
1856
1857                 Some(P(ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData {
1858                     span: lo.to(hi),
1859                     inputs: inputs,
1860                     output: output_ty,
1861                 })))
1862             } else {
1863                 None
1864             };
1865
1866             // Assemble and push the result.
1867             segments.push(PathSegment {
1868                 identifier: identifier,
1869                 span: ident_span,
1870                 parameters: parameters
1871             });
1872
1873             // Continue only if we see a `::`
1874             if !self.eat(&token::ModSep) {
1875                 return Ok(segments);
1876             }
1877         }
1878     }
1879
1880     /// Examples:
1881     /// - `a::b::<T,U>::c`
1882     pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1883         let mut segments = Vec::new();
1884         loop {
1885             // First, parse an identifier.
1886             let ident_span = self.span;
1887             let identifier = self.parse_path_segment_ident()?;
1888
1889             // If we do not see a `::`, stop.
1890             if !self.eat(&token::ModSep) {
1891                 segments.push(PathSegment::from_ident(identifier, ident_span));
1892                 return Ok(segments);
1893             }
1894
1895             // Check for a type segment.
1896             if self.eat_lt() {
1897                 // Consumed `a::b::<`, go look for types
1898                 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1899                 self.expect_gt()?;
1900                 segments.push(PathSegment {
1901                     identifier: identifier,
1902                     span: ident_span,
1903                     parameters: ast::AngleBracketedParameterData {
1904                         lifetimes: lifetimes,
1905                         types: types,
1906                         bindings: bindings,
1907                     }.into(),
1908                 });
1909
1910                 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1911                 if !self.eat(&token::ModSep) {
1912                     return Ok(segments);
1913                 }
1914             } else {
1915                 // Consumed `a::`, go look for `b`
1916                 segments.push(PathSegment::from_ident(identifier, ident_span));
1917             }
1918         }
1919     }
1920
1921     /// Examples:
1922     /// - `a::b::c`
1923     pub fn parse_path_segments_without_types(&mut self)
1924                                              -> PResult<'a, Vec<PathSegment>> {
1925         let mut segments = Vec::new();
1926         loop {
1927             // First, parse an identifier.
1928             let ident_span = self.span;
1929             let identifier = self.parse_path_segment_ident()?;
1930
1931             // Assemble and push the result.
1932             segments.push(PathSegment::from_ident(identifier, ident_span));
1933
1934             // If we do not see a `::` or see `::{`/`::*`, stop.
1935             if !self.check(&token::ModSep) || self.is_import_coupler() {
1936                 return Ok(segments);
1937             } else {
1938                 self.bump();
1939             }
1940         }
1941     }
1942
1943     fn check_lifetime(&mut self) -> bool {
1944         self.expected_tokens.push(TokenType::Lifetime);
1945         self.token.is_lifetime()
1946     }
1947
1948     /// Parse single lifetime 'a or panic.
1949     fn expect_lifetime(&mut self) -> Lifetime {
1950         match self.token {
1951             token::Lifetime(ident) => {
1952                 let ident_span = self.span;
1953                 self.bump();
1954                 Lifetime { name: ident.name, span: ident_span, id: ast::DUMMY_NODE_ID }
1955             }
1956             _ => self.span_bug(self.span, "not a lifetime")
1957         }
1958     }
1959
1960     /// Parse mutability (`mut` or nothing).
1961     fn parse_mutability(&mut self) -> Mutability {
1962         if self.eat_keyword(keywords::Mut) {
1963             Mutability::Mutable
1964         } else {
1965             Mutability::Immutable
1966         }
1967     }
1968
1969     pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1970         if let token::Literal(token::Integer(name), None) = self.token {
1971             self.bump();
1972             Ok(Ident::with_empty_ctxt(name))
1973         } else {
1974             self.parse_ident()
1975         }
1976     }
1977
1978     /// Parse ident (COLON expr)?
1979     pub fn parse_field(&mut self) -> PResult<'a, Field> {
1980         let attrs = self.parse_outer_attributes()?;
1981         let lo = self.span;
1982         let hi;
1983
1984         // Check if a colon exists one ahead. This means we're parsing a fieldname.
1985         let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1986             let fieldname = self.parse_field_name()?;
1987             self.bump();
1988             hi = self.prev_span;
1989             (fieldname, self.parse_expr()?, false)
1990         } else {
1991             let fieldname = self.parse_ident()?;
1992             hi = self.prev_span;
1993
1994             // Mimic `x: x` for the `x` field shorthand.
1995             let path = ast::Path::from_ident(lo.to(hi), fieldname);
1996             (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
1997         };
1998         Ok(ast::Field {
1999             ident: respan(lo.to(hi), fieldname),
2000             span: lo.to(expr.span),
2001             expr: expr,
2002             is_shorthand: is_shorthand,
2003             attrs: attrs.into(),
2004         })
2005     }
2006
2007     pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2008         P(Expr {
2009             id: ast::DUMMY_NODE_ID,
2010             node: node,
2011             span: span,
2012             attrs: attrs.into(),
2013         })
2014     }
2015
2016     pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2017         ExprKind::Unary(unop, expr)
2018     }
2019
2020     pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2021         ExprKind::Binary(binop, lhs, rhs)
2022     }
2023
2024     pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2025         ExprKind::Call(f, args)
2026     }
2027
2028     fn mk_method_call(&mut self,
2029                       ident: ast::SpannedIdent,
2030                       tps: Vec<P<Ty>>,
2031                       args: Vec<P<Expr>>)
2032                       -> ast::ExprKind {
2033         ExprKind::MethodCall(ident, tps, args)
2034     }
2035
2036     pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2037         ExprKind::Index(expr, idx)
2038     }
2039
2040     pub fn mk_range(&mut self,
2041                     start: Option<P<Expr>>,
2042                     end: Option<P<Expr>>,
2043                     limits: RangeLimits)
2044                     -> PResult<'a, ast::ExprKind> {
2045         if end.is_none() && limits == RangeLimits::Closed {
2046             Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2047         } else {
2048             Ok(ExprKind::Range(start, end, limits))
2049         }
2050     }
2051
2052     pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::ExprKind {
2053         ExprKind::Field(expr, ident)
2054     }
2055
2056     pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2057         ExprKind::TupField(expr, idx)
2058     }
2059
2060     pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2061                         lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2062         ExprKind::AssignOp(binop, lhs, rhs)
2063     }
2064
2065     pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2066         P(Expr {
2067             id: ast::DUMMY_NODE_ID,
2068             node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2069             span: span,
2070             attrs: attrs,
2071         })
2072     }
2073
2074     pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2075         let span = &self.span;
2076         let lv_lit = P(codemap::Spanned {
2077             node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2078             span: *span
2079         });
2080
2081         P(Expr {
2082             id: ast::DUMMY_NODE_ID,
2083             node: ExprKind::Lit(lv_lit),
2084             span: *span,
2085             attrs: attrs,
2086         })
2087     }
2088
2089     fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2090         match self.token {
2091             token::OpenDelim(delim) => match self.parse_token_tree() {
2092                 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2093                 _ => unreachable!(),
2094             },
2095             _ => Err(self.fatal("expected open delimiter")),
2096         }
2097     }
2098
2099     /// At the bottom (top?) of the precedence hierarchy,
2100     /// parse things like parenthesized exprs,
2101     /// macros, return, etc.
2102     ///
2103     /// NB: This does not parse outer attributes,
2104     ///     and is private because it only works
2105     ///     correctly if called from parse_dot_or_call_expr().
2106     fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2107         maybe_whole_expr!(self);
2108
2109         // Outer attributes are already parsed and will be
2110         // added to the return value after the fact.
2111         //
2112         // Therefore, prevent sub-parser from parsing
2113         // attributes by giving them a empty "already parsed" list.
2114         let mut attrs = ThinVec::new();
2115
2116         let lo = self.span;
2117         let mut hi = self.span;
2118
2119         let ex: ExprKind;
2120
2121         // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2122         match self.token {
2123             token::OpenDelim(token::Paren) => {
2124                 self.bump();
2125
2126                 attrs.extend(self.parse_inner_attributes()?);
2127
2128                 // (e) is parenthesized e
2129                 // (e,) is a tuple with only one field, e
2130                 let mut es = vec![];
2131                 let mut trailing_comma = false;
2132                 while self.token != token::CloseDelim(token::Paren) {
2133                     es.push(self.parse_expr()?);
2134                     self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2135                     if self.check(&token::Comma) {
2136                         trailing_comma = true;
2137
2138                         self.bump();
2139                     } else {
2140                         trailing_comma = false;
2141                         break;
2142                     }
2143                 }
2144                 self.bump();
2145
2146                 hi = self.prev_span;
2147                 let span = lo.to(hi);
2148                 return if es.len() == 1 && !trailing_comma {
2149                     Ok(self.mk_expr(span, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2150                 } else {
2151                     Ok(self.mk_expr(span, ExprKind::Tup(es), attrs))
2152                 }
2153             },
2154             token::OpenDelim(token::Brace) => {
2155                 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2156             },
2157             token::BinOp(token::Or) |  token::OrOr => {
2158                 let lo = self.span;
2159                 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2160             },
2161             token::OpenDelim(token::Bracket) => {
2162                 self.bump();
2163
2164                 attrs.extend(self.parse_inner_attributes()?);
2165
2166                 if self.check(&token::CloseDelim(token::Bracket)) {
2167                     // Empty vector.
2168                     self.bump();
2169                     ex = ExprKind::Array(Vec::new());
2170                 } else {
2171                     // Nonempty vector.
2172                     let first_expr = self.parse_expr()?;
2173                     if self.check(&token::Semi) {
2174                         // Repeating array syntax: [ 0; 512 ]
2175                         self.bump();
2176                         let count = self.parse_expr()?;
2177                         self.expect(&token::CloseDelim(token::Bracket))?;
2178                         ex = ExprKind::Repeat(first_expr, count);
2179                     } else if self.check(&token::Comma) {
2180                         // Vector with two or more elements.
2181                         self.bump();
2182                         let remaining_exprs = self.parse_seq_to_end(
2183                             &token::CloseDelim(token::Bracket),
2184                             SeqSep::trailing_allowed(token::Comma),
2185                             |p| Ok(p.parse_expr()?)
2186                         )?;
2187                         let mut exprs = vec![first_expr];
2188                         exprs.extend(remaining_exprs);
2189                         ex = ExprKind::Array(exprs);
2190                     } else {
2191                         // Vector with one element.
2192                         self.expect(&token::CloseDelim(token::Bracket))?;
2193                         ex = ExprKind::Array(vec![first_expr]);
2194                     }
2195                 }
2196                 hi = self.prev_span;
2197             }
2198             _ => {
2199                 if self.eat_lt() {
2200                     let (qself, path) =
2201                         self.parse_qualified_path(PathStyle::Expr)?;
2202                     hi = path.span;
2203                     return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2204                 }
2205                 if self.eat_keyword(keywords::Move) {
2206                     let lo = self.prev_span;
2207                     return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2208                 }
2209                 if self.eat_keyword(keywords::If) {
2210                     return self.parse_if_expr(attrs);
2211                 }
2212                 if self.eat_keyword(keywords::For) {
2213                     let lo = self.prev_span;
2214                     return self.parse_for_expr(None, lo, attrs);
2215                 }
2216                 if self.eat_keyword(keywords::While) {
2217                     let lo = self.prev_span;
2218                     return self.parse_while_expr(None, lo, attrs);
2219                 }
2220                 if self.token.is_lifetime() {
2221                     let label = Spanned { node: self.get_label(),
2222                                           span: self.span };
2223                     let lo = self.span;
2224                     self.bump();
2225                     self.expect(&token::Colon)?;
2226                     if self.eat_keyword(keywords::While) {
2227                         return self.parse_while_expr(Some(label), lo, attrs)
2228                     }
2229                     if self.eat_keyword(keywords::For) {
2230                         return self.parse_for_expr(Some(label), lo, attrs)
2231                     }
2232                     if self.eat_keyword(keywords::Loop) {
2233                         return self.parse_loop_expr(Some(label), lo, attrs)
2234                     }
2235                     return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2236                 }
2237                 if self.eat_keyword(keywords::Loop) {
2238                     let lo = self.prev_span;
2239                     return self.parse_loop_expr(None, lo, attrs);
2240                 }
2241                 if self.eat_keyword(keywords::Continue) {
2242                     let ex = if self.token.is_lifetime() {
2243                         let ex = ExprKind::Continue(Some(Spanned{
2244                             node: self.get_label(),
2245                             span: self.span
2246                         }));
2247                         self.bump();
2248                         ex
2249                     } else {
2250                         ExprKind::Continue(None)
2251                     };
2252                     let hi = self.prev_span;
2253                     return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2254                 }
2255                 if self.eat_keyword(keywords::Match) {
2256                     return self.parse_match_expr(attrs);
2257                 }
2258                 if self.eat_keyword(keywords::Unsafe) {
2259                     return self.parse_block_expr(
2260                         lo,
2261                         BlockCheckMode::Unsafe(ast::UserProvided),
2262                         attrs);
2263                 }
2264                 if self.is_catch_expr() {
2265                     assert!(self.eat_keyword(keywords::Do));
2266                     assert!(self.eat_keyword(keywords::Catch));
2267                     let lo = self.prev_span;
2268                     return self.parse_catch_expr(lo, attrs);
2269                 }
2270                 if self.eat_keyword(keywords::Return) {
2271                     if self.token.can_begin_expr() {
2272                         let e = self.parse_expr()?;
2273                         hi = e.span;
2274                         ex = ExprKind::Ret(Some(e));
2275                     } else {
2276                         ex = ExprKind::Ret(None);
2277                     }
2278                 } else if self.eat_keyword(keywords::Break) {
2279                     let lt = if self.token.is_lifetime() {
2280                         let spanned_lt = Spanned {
2281                             node: self.get_label(),
2282                             span: self.span
2283                         };
2284                         self.bump();
2285                         Some(spanned_lt)
2286                     } else {
2287                         None
2288                     };
2289                     let e = if self.token.can_begin_expr()
2290                                && !(self.token == token::OpenDelim(token::Brace)
2291                                     && self.restrictions.contains(
2292                                            RESTRICTION_NO_STRUCT_LITERAL)) {
2293                         Some(self.parse_expr()?)
2294                     } else {
2295                         None
2296                     };
2297                     ex = ExprKind::Break(lt, e);
2298                     hi = self.prev_span;
2299                 } else if self.token.is_keyword(keywords::Let) {
2300                     // Catch this syntax error here, instead of in `check_strict_keywords`, so
2301                     // that we can explicitly mention that let is not to be used as an expression
2302                     let mut db = self.fatal("expected expression, found statement (`let`)");
2303                     db.note("variable declaration using `let` is a statement");
2304                     return Err(db);
2305                 } else if self.token.is_path_start() {
2306                     let pth = self.parse_path(PathStyle::Expr)?;
2307
2308                     // `!`, as an operator, is prefix, so we know this isn't that
2309                     if self.eat(&token::Not) {
2310                         // MACRO INVOCATION expression
2311                         let (_, tts) = self.expect_delimited_token_tree()?;
2312                         let hi = self.prev_span;
2313                         return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2314                     }
2315                     if self.check(&token::OpenDelim(token::Brace)) {
2316                         // This is a struct literal, unless we're prohibited
2317                         // from parsing struct literals here.
2318                         let prohibited = self.restrictions.contains(
2319                             RESTRICTION_NO_STRUCT_LITERAL
2320                         );
2321                         if !prohibited {
2322                             return self.parse_struct_expr(lo, pth, attrs);
2323                         }
2324                     }
2325
2326                     hi = pth.span;
2327                     ex = ExprKind::Path(None, pth);
2328                 } else {
2329                     match self.parse_lit() {
2330                         Ok(lit) => {
2331                             hi = lit.span;
2332                             ex = ExprKind::Lit(P(lit));
2333                         }
2334                         Err(mut err) => {
2335                             self.cancel(&mut err);
2336                             let msg = format!("expected expression, found {}",
2337                                               self.this_token_descr());
2338                             return Err(self.fatal(&msg));
2339                         }
2340                     }
2341                 }
2342             }
2343         }
2344
2345         return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2346     }
2347
2348     fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2349                          -> PResult<'a, P<Expr>> {
2350         self.bump();
2351         let mut fields = Vec::new();
2352         let mut base = None;
2353
2354         attrs.extend(self.parse_inner_attributes()?);
2355
2356         while self.token != token::CloseDelim(token::Brace) {
2357             if self.eat(&token::DotDot) {
2358                 match self.parse_expr() {
2359                     Ok(e) => {
2360                         base = Some(e);
2361                     }
2362                     Err(mut e) => {
2363                         e.emit();
2364                         self.recover_stmt();
2365                     }
2366                 }
2367                 break;
2368             }
2369
2370             match self.parse_field() {
2371                 Ok(f) => fields.push(f),
2372                 Err(mut e) => {
2373                     e.emit();
2374                     self.recover_stmt();
2375                     break;
2376                 }
2377             }
2378
2379             match self.expect_one_of(&[token::Comma],
2380                                      &[token::CloseDelim(token::Brace)]) {
2381                 Ok(()) => {}
2382                 Err(mut e) => {
2383                     e.emit();
2384                     self.recover_stmt();
2385                     break;
2386                 }
2387             }
2388         }
2389
2390         let span = lo.to(self.span);
2391         self.expect(&token::CloseDelim(token::Brace))?;
2392         return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2393     }
2394
2395     fn parse_or_use_outer_attributes(&mut self,
2396                                      already_parsed_attrs: Option<ThinVec<Attribute>>)
2397                                      -> PResult<'a, ThinVec<Attribute>> {
2398         if let Some(attrs) = already_parsed_attrs {
2399             Ok(attrs)
2400         } else {
2401             self.parse_outer_attributes().map(|a| a.into())
2402         }
2403     }
2404
2405     /// Parse a block or unsafe block
2406     pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2407                             outer_attrs: ThinVec<Attribute>)
2408                             -> PResult<'a, P<Expr>> {
2409
2410         self.expect(&token::OpenDelim(token::Brace))?;
2411
2412         let mut attrs = outer_attrs;
2413         attrs.extend(self.parse_inner_attributes()?);
2414
2415         let blk = self.parse_block_tail(lo, blk_mode)?;
2416         return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2417     }
2418
2419     /// parse a.b or a(13) or a[4] or just a
2420     pub fn parse_dot_or_call_expr(&mut self,
2421                                   already_parsed_attrs: Option<ThinVec<Attribute>>)
2422                                   -> PResult<'a, P<Expr>> {
2423         let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2424
2425         let b = self.parse_bottom_expr();
2426         let (span, b) = self.interpolated_or_expr_span(b)?;
2427         self.parse_dot_or_call_expr_with(b, span, attrs)
2428     }
2429
2430     pub fn parse_dot_or_call_expr_with(&mut self,
2431                                        e0: P<Expr>,
2432                                        lo: Span,
2433                                        mut attrs: ThinVec<Attribute>)
2434                                        -> PResult<'a, P<Expr>> {
2435         // Stitch the list of outer attributes onto the return value.
2436         // A little bit ugly, but the best way given the current code
2437         // structure
2438         self.parse_dot_or_call_expr_with_(e0, lo)
2439         .map(|expr|
2440             expr.map(|mut expr| {
2441                 attrs.extend::<Vec<_>>(expr.attrs.into());
2442                 expr.attrs = attrs;
2443                 match expr.node {
2444                     ExprKind::If(..) | ExprKind::IfLet(..) => {
2445                         if !expr.attrs.is_empty() {
2446                             // Just point to the first attribute in there...
2447                             let span = expr.attrs[0].span;
2448
2449                             self.span_err(span,
2450                                 "attributes are not yet allowed on `if` \
2451                                 expressions");
2452                         }
2453                     }
2454                     _ => {}
2455                 }
2456                 expr
2457             })
2458         )
2459     }
2460
2461     // Assuming we have just parsed `.foo` (i.e., a dot and an ident), continue
2462     // parsing into an expression.
2463     fn parse_dot_suffix(&mut self, ident: Ident, ident_span: Span, self_value: P<Expr>, lo: Span)
2464                         -> PResult<'a, P<Expr>> {
2465         let (_, tys, bindings) = if self.eat(&token::ModSep) {
2466             self.expect_lt()?;
2467             let args = self.parse_generic_args()?;
2468             self.expect_gt()?;
2469             args
2470         } else {
2471             (Vec::new(), Vec::new(), Vec::new())
2472         };
2473
2474         if !bindings.is_empty() {
2475             let prev_span = self.prev_span;
2476             self.span_err(prev_span, "type bindings are only permitted on trait paths");
2477         }
2478
2479         Ok(match self.token {
2480             // expr.f() method call.
2481             token::OpenDelim(token::Paren) => {
2482                 let mut es = self.parse_unspanned_seq(
2483                     &token::OpenDelim(token::Paren),
2484                     &token::CloseDelim(token::Paren),
2485                     SeqSep::trailing_allowed(token::Comma),
2486                     |p| Ok(p.parse_expr()?)
2487                 )?;
2488                 let hi = self.prev_span;
2489
2490                 es.insert(0, self_value);
2491                 let id = respan(ident_span.to(ident_span), ident);
2492                 let nd = self.mk_method_call(id, tys, es);
2493                 self.mk_expr(lo.to(hi), nd, ThinVec::new())
2494             }
2495             // Field access.
2496             _ => {
2497                 if !tys.is_empty() {
2498                     let prev_span = self.prev_span;
2499                     self.span_err(prev_span,
2500                                   "field expressions may not \
2501                                    have type parameters");
2502                 }
2503
2504                 let id = respan(ident_span.to(ident_span), ident);
2505                 let field = self.mk_field(self_value, id);
2506                 self.mk_expr(lo.to(ident_span), field, ThinVec::new())
2507             }
2508         })
2509     }
2510
2511     fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2512         let mut e = e0;
2513         let mut hi;
2514         loop {
2515             // expr?
2516             while self.eat(&token::Question) {
2517                 let hi = self.prev_span;
2518                 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2519             }
2520
2521             // expr.f
2522             if self.eat(&token::Dot) {
2523                 match self.token {
2524                   token::Ident(i) => {
2525                     let ident_span = self.span;
2526                     self.bump();
2527                     e = self.parse_dot_suffix(i, ident_span, e, lo)?;
2528                   }
2529                   token::Literal(token::Integer(n), suf) => {
2530                     let sp = self.span;
2531
2532                     // A tuple index may not have a suffix
2533                     self.expect_no_suffix(sp, "tuple index", suf);
2534
2535                     let dot_span = self.prev_span;
2536                     hi = self.span;
2537                     self.bump();
2538
2539                     let index = n.as_str().parse::<usize>().ok();
2540                     match index {
2541                         Some(n) => {
2542                             let id = respan(dot_span.to(hi), n);
2543                             let field = self.mk_tup_field(e, id);
2544                             e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2545                         }
2546                         None => {
2547                             let prev_span = self.prev_span;
2548                             self.span_err(prev_span, "invalid tuple or tuple struct index");
2549                         }
2550                     }
2551                   }
2552                   token::Literal(token::Float(n), _suf) => {
2553                     self.bump();
2554                     let fstr = n.as_str();
2555                     let mut err = self.diagnostic().struct_span_err(self.prev_span,
2556                         &format!("unexpected token: `{}`", n));
2557                     err.span_label(self.prev_span, "unexpected token");
2558                     if fstr.chars().all(|x| "0123456789.".contains(x)) {
2559                         let float = match fstr.parse::<f64>().ok() {
2560                             Some(f) => f,
2561                             None => continue,
2562                         };
2563                         let sugg = pprust::to_string(|s| {
2564                             use print::pprust::PrintState;
2565                             use print::pp::word;
2566                             s.popen()?;
2567                             s.print_expr(&e)?;
2568                             word(&mut s.s, ".")?;
2569                             s.print_usize(float.trunc() as usize)?;
2570                             s.pclose()?;
2571                             word(&mut s.s, ".")?;
2572                             word(&mut s.s, fstr.splitn(2, ".").last().unwrap())
2573                         });
2574                         err.span_suggestion(
2575                             lo.to(self.prev_span),
2576                             "try parenthesizing the first index",
2577                             sugg);
2578                     }
2579                     return Err(err);
2580
2581                   }
2582                   _ => {
2583                     // FIXME Could factor this out into non_fatal_unexpected or something.
2584                     let actual = self.this_token_to_string();
2585                     self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2586
2587                     let dot_span = self.prev_span;
2588                     e = self.parse_dot_suffix(keywords::Invalid.ident(), dot_span, e, lo)?;
2589                   }
2590                 }
2591                 continue;
2592             }
2593             if self.expr_is_complete(&e) { break; }
2594             match self.token {
2595               // expr(...)
2596               token::OpenDelim(token::Paren) => {
2597                 let es = self.parse_unspanned_seq(
2598                     &token::OpenDelim(token::Paren),
2599                     &token::CloseDelim(token::Paren),
2600                     SeqSep::trailing_allowed(token::Comma),
2601                     |p| Ok(p.parse_expr()?)
2602                 )?;
2603                 hi = self.prev_span;
2604
2605                 let nd = self.mk_call(e, es);
2606                 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2607               }
2608
2609               // expr[...]
2610               // Could be either an index expression or a slicing expression.
2611               token::OpenDelim(token::Bracket) => {
2612                 self.bump();
2613                 let ix = self.parse_expr()?;
2614                 hi = self.span;
2615                 self.expect(&token::CloseDelim(token::Bracket))?;
2616                 let index = self.mk_index(e, ix);
2617                 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2618               }
2619               _ => return Ok(e)
2620             }
2621         }
2622         return Ok(e);
2623     }
2624
2625     pub fn process_potential_macro_variable(&mut self) {
2626         let ident = match self.token {
2627             token::SubstNt(name) => {
2628                 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2629                 return
2630             }
2631             token::Interpolated(ref nt) => {
2632                 self.meta_var_span = Some(self.span);
2633                 match **nt {
2634                     token::NtIdent(ident) => ident,
2635                     _ => return,
2636                 }
2637             }
2638             _ => return,
2639         };
2640         self.token = token::Ident(ident.node);
2641         self.span = ident.span;
2642     }
2643
2644     /// parse a single token tree from the input.
2645     pub fn parse_token_tree(&mut self) -> TokenTree {
2646         match self.token {
2647             token::OpenDelim(..) => {
2648                 let frame = mem::replace(&mut self.token_cursor.frame,
2649                                          self.token_cursor.stack.pop().unwrap());
2650                 self.span = frame.span;
2651                 self.bump();
2652                 TokenTree::Delimited(frame.span, Delimited {
2653                     delim: frame.delim,
2654                     tts: frame.tree_cursor.original_stream().into(),
2655                 })
2656             },
2657             token::CloseDelim(_) | token::Eof => unreachable!(),
2658             _ => {
2659                 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2660                 self.bump();
2661                 TokenTree::Token(span, token)
2662             }
2663         }
2664     }
2665
2666     // parse a stream of tokens into a list of TokenTree's,
2667     // up to EOF.
2668     pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2669         let mut tts = Vec::new();
2670         while self.token != token::Eof {
2671             tts.push(self.parse_token_tree());
2672         }
2673         Ok(tts)
2674     }
2675
2676     pub fn parse_tokens(&mut self) -> TokenStream {
2677         let mut result = Vec::new();
2678         loop {
2679             match self.token {
2680                 token::Eof | token::CloseDelim(..) => break,
2681                 _ => result.push(self.parse_token_tree().into()),
2682             }
2683         }
2684         TokenStream::concat(result)
2685     }
2686
2687     /// Parse a prefix-unary-operator expr
2688     pub fn parse_prefix_expr(&mut self,
2689                              already_parsed_attrs: Option<ThinVec<Attribute>>)
2690                              -> PResult<'a, P<Expr>> {
2691         let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2692         let lo = self.span;
2693         // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2694         let (hi, ex) = match self.token {
2695             token::Not => {
2696                 self.bump();
2697                 let e = self.parse_prefix_expr(None);
2698                 let (span, e) = self.interpolated_or_expr_span(e)?;
2699                 (span, self.mk_unary(UnOp::Not, e))
2700             }
2701             // Suggest `!` for bitwise negation when encountering a `~`
2702             token::Tilde => {
2703                 self.bump();
2704                 let e = self.parse_prefix_expr(None);
2705                 let (span, e) = self.interpolated_or_expr_span(e)?;
2706                 let span_of_tilde = lo;
2707                 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2708                         "`~` can not be used as a unary operator");
2709                 err.span_label(span_of_tilde, "did you mean `!`?");
2710                 err.help("use `!` instead of `~` if you meant to perform bitwise negation");
2711                 err.emit();
2712                 (span, self.mk_unary(UnOp::Not, e))
2713             }
2714             token::BinOp(token::Minus) => {
2715                 self.bump();
2716                 let e = self.parse_prefix_expr(None);
2717                 let (span, e) = self.interpolated_or_expr_span(e)?;
2718                 (span, self.mk_unary(UnOp::Neg, e))
2719             }
2720             token::BinOp(token::Star) => {
2721                 self.bump();
2722                 let e = self.parse_prefix_expr(None);
2723                 let (span, e) = self.interpolated_or_expr_span(e)?;
2724                 (span, self.mk_unary(UnOp::Deref, e))
2725             }
2726             token::BinOp(token::And) | token::AndAnd => {
2727                 self.expect_and()?;
2728                 let m = self.parse_mutability();
2729                 let e = self.parse_prefix_expr(None);
2730                 let (span, e) = self.interpolated_or_expr_span(e)?;
2731                 (span, ExprKind::AddrOf(m, e))
2732             }
2733             token::Ident(..) if self.token.is_keyword(keywords::In) => {
2734                 self.bump();
2735                 let place = self.parse_expr_res(
2736                     RESTRICTION_NO_STRUCT_LITERAL,
2737                     None,
2738                 )?;
2739                 let blk = self.parse_block()?;
2740                 let span = blk.span;
2741                 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2742                 (span, ExprKind::InPlace(place, blk_expr))
2743             }
2744             token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2745                 self.bump();
2746                 let e = self.parse_prefix_expr(None);
2747                 let (span, e) = self.interpolated_or_expr_span(e)?;
2748                 (span, ExprKind::Box(e))
2749             }
2750             _ => return self.parse_dot_or_call_expr(Some(attrs))
2751         };
2752         return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2753     }
2754
2755     /// Parse an associative expression
2756     ///
2757     /// This parses an expression accounting for associativity and precedence of the operators in
2758     /// the expression.
2759     pub fn parse_assoc_expr(&mut self,
2760                             already_parsed_attrs: Option<ThinVec<Attribute>>)
2761                             -> PResult<'a, P<Expr>> {
2762         self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2763     }
2764
2765     /// Parse an associative expression with operators of at least `min_prec` precedence
2766     pub fn parse_assoc_expr_with(&mut self,
2767                                  min_prec: usize,
2768                                  lhs: LhsExpr)
2769                                  -> PResult<'a, P<Expr>> {
2770         let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2771             expr
2772         } else {
2773             let attrs = match lhs {
2774                 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2775                 _ => None,
2776             };
2777             if self.token == token::DotDot || self.token == token::DotDotDot {
2778                 return self.parse_prefix_range_expr(attrs);
2779             } else {
2780                 self.parse_prefix_expr(attrs)?
2781             }
2782         };
2783
2784         if self.expr_is_complete(&lhs) {
2785             // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2786             return Ok(lhs);
2787         }
2788         self.expected_tokens.push(TokenType::Operator);
2789         while let Some(op) = AssocOp::from_token(&self.token) {
2790
2791             let lhs_span = if self.prev_token_kind == PrevTokenKind::Interpolated {
2792                 self.prev_span
2793             } else {
2794                 lhs.span
2795             };
2796
2797             let cur_op_span = self.span;
2798             let restrictions = if op.is_assign_like() {
2799                 self.restrictions & RESTRICTION_NO_STRUCT_LITERAL
2800             } else {
2801                 self.restrictions
2802             };
2803             if op.precedence() < min_prec {
2804                 break;
2805             }
2806             self.bump();
2807             if op.is_comparison() {
2808                 self.check_no_chained_comparison(&lhs, &op);
2809             }
2810             // Special cases:
2811             if op == AssocOp::As {
2812                 let rhs = self.parse_ty_no_plus()?;
2813                 lhs = self.mk_expr(lhs_span.to(rhs.span), ExprKind::Cast(lhs, rhs), ThinVec::new());
2814                 continue
2815             } else if op == AssocOp::Colon {
2816                 let rhs = self.parse_ty_no_plus()?;
2817                 lhs = self.mk_expr(lhs_span.to(rhs.span), ExprKind::Type(lhs, rhs), ThinVec::new());
2818                 continue
2819             } else if op == AssocOp::DotDot || op == AssocOp::DotDotDot {
2820                 // If we didn’t have to handle `x..`/`x...`, it would be pretty easy to
2821                 // generalise it to the Fixity::None code.
2822                 //
2823                 // We have 2 alternatives here: `x..y`/`x...y` and `x..`/`x...` The other
2824                 // two variants are handled with `parse_prefix_range_expr` call above.
2825                 let rhs = if self.is_at_start_of_range_notation_rhs() {
2826                     Some(self.parse_assoc_expr_with(op.precedence() + 1,
2827                                                     LhsExpr::NotYetParsed)?)
2828                 } else {
2829                     None
2830                 };
2831                 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2832                     x.span
2833                 } else {
2834                     cur_op_span
2835                 });
2836                 let limits = if op == AssocOp::DotDot {
2837                     RangeLimits::HalfOpen
2838                 } else {
2839                     RangeLimits::Closed
2840                 };
2841
2842                 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2843                 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2844                 break
2845             }
2846
2847             let rhs = match op.fixity() {
2848                 Fixity::Right => self.with_res(
2849                     restrictions - RESTRICTION_STMT_EXPR,
2850                     |this| {
2851                         this.parse_assoc_expr_with(op.precedence(),
2852                             LhsExpr::NotYetParsed)
2853                 }),
2854                 Fixity::Left => self.with_res(
2855                     restrictions - RESTRICTION_STMT_EXPR,
2856                     |this| {
2857                         this.parse_assoc_expr_with(op.precedence() + 1,
2858                             LhsExpr::NotYetParsed)
2859                 }),
2860                 // We currently have no non-associative operators that are not handled above by
2861                 // the special cases. The code is here only for future convenience.
2862                 Fixity::None => self.with_res(
2863                     restrictions - RESTRICTION_STMT_EXPR,
2864                     |this| {
2865                         this.parse_assoc_expr_with(op.precedence() + 1,
2866                             LhsExpr::NotYetParsed)
2867                 }),
2868             }?;
2869
2870             let span = lhs_span.to(rhs.span);
2871             lhs = match op {
2872                 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2873                 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2874                 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2875                 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2876                 AssocOp::Greater | AssocOp::GreaterEqual => {
2877                     let ast_op = op.to_ast_binop().unwrap();
2878                     let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2879                     self.mk_expr(span, binary, ThinVec::new())
2880                 }
2881                 AssocOp::Assign =>
2882                     self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2883                 AssocOp::Inplace =>
2884                     self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
2885                 AssocOp::AssignOp(k) => {
2886                     let aop = match k {
2887                         token::Plus =>    BinOpKind::Add,
2888                         token::Minus =>   BinOpKind::Sub,
2889                         token::Star =>    BinOpKind::Mul,
2890                         token::Slash =>   BinOpKind::Div,
2891                         token::Percent => BinOpKind::Rem,
2892                         token::Caret =>   BinOpKind::BitXor,
2893                         token::And =>     BinOpKind::BitAnd,
2894                         token::Or =>      BinOpKind::BitOr,
2895                         token::Shl =>     BinOpKind::Shl,
2896                         token::Shr =>     BinOpKind::Shr,
2897                     };
2898                     let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2899                     self.mk_expr(span, aopexpr, ThinVec::new())
2900                 }
2901                 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotDot => {
2902                     self.bug("As, Colon, DotDot or DotDotDot branch reached")
2903                 }
2904             };
2905
2906             if op.fixity() == Fixity::None { break }
2907         }
2908         Ok(lhs)
2909     }
2910
2911     /// Produce an error if comparison operators are chained (RFC #558).
2912     /// We only need to check lhs, not rhs, because all comparison ops
2913     /// have same precedence and are left-associative
2914     fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2915         debug_assert!(outer_op.is_comparison());
2916         match lhs.node {
2917             ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2918                 // respan to include both operators
2919                 let op_span = op.span.to(self.span);
2920                 let mut err = self.diagnostic().struct_span_err(op_span,
2921                     "chained comparison operators require parentheses");
2922                 if op.node == BinOpKind::Lt &&
2923                     *outer_op == AssocOp::Less ||  // Include `<` to provide this recommendation
2924                     *outer_op == AssocOp::Greater  // even in a case like the following:
2925                 {                                  //     Foo<Bar<Baz<Qux, ()>>>
2926                     err.help(
2927                         "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2928                 }
2929                 err.emit();
2930             }
2931             _ => {}
2932         }
2933     }
2934
2935     /// Parse prefix-forms of range notation: `..expr`, `..`, `...expr`
2936     fn parse_prefix_range_expr(&mut self,
2937                                already_parsed_attrs: Option<ThinVec<Attribute>>)
2938                                -> PResult<'a, P<Expr>> {
2939         debug_assert!(self.token == token::DotDot || self.token == token::DotDotDot);
2940         let tok = self.token.clone();
2941         let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2942         let lo = self.span;
2943         let mut hi = self.span;
2944         self.bump();
2945         let opt_end = if self.is_at_start_of_range_notation_rhs() {
2946             // RHS must be parsed with more associativity than the dots.
2947             let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
2948             Some(self.parse_assoc_expr_with(next_prec,
2949                                             LhsExpr::NotYetParsed)
2950                 .map(|x|{
2951                     hi = x.span;
2952                     x
2953                 })?)
2954          } else {
2955             None
2956         };
2957         let limits = if tok == token::DotDot {
2958             RangeLimits::HalfOpen
2959         } else {
2960             RangeLimits::Closed
2961         };
2962
2963         let r = try!(self.mk_range(None,
2964                                    opt_end,
2965                                    limits));
2966         Ok(self.mk_expr(lo.to(hi), r, attrs))
2967     }
2968
2969     fn is_at_start_of_range_notation_rhs(&self) -> bool {
2970         if self.token.can_begin_expr() {
2971             // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2972             if self.token == token::OpenDelim(token::Brace) {
2973                 return !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL);
2974             }
2975             true
2976         } else {
2977             false
2978         }
2979     }
2980
2981     /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2982     pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
2983         if self.check_keyword(keywords::Let) {
2984             return self.parse_if_let_expr(attrs);
2985         }
2986         let lo = self.prev_span;
2987         let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
2988         let thn = self.parse_block()?;
2989         let mut els: Option<P<Expr>> = None;
2990         let mut hi = thn.span;
2991         if self.eat_keyword(keywords::Else) {
2992             let elexpr = self.parse_else_expr()?;
2993             hi = elexpr.span;
2994             els = Some(elexpr);
2995         }
2996         Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
2997     }
2998
2999     /// Parse an 'if let' expression ('if' token already eaten)
3000     pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3001                              -> PResult<'a, P<Expr>> {
3002         let lo = self.prev_span;
3003         self.expect_keyword(keywords::Let)?;
3004         let pat = self.parse_pat()?;
3005         self.expect(&token::Eq)?;
3006         let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3007         let thn = self.parse_block()?;
3008         let (hi, els) = if self.eat_keyword(keywords::Else) {
3009             let expr = self.parse_else_expr()?;
3010             (expr.span, Some(expr))
3011         } else {
3012             (thn.span, None)
3013         };
3014         Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
3015     }
3016
3017     // `move |args| expr`
3018     pub fn parse_lambda_expr(&mut self,
3019                              lo: Span,
3020                              capture_clause: CaptureBy,
3021                              attrs: ThinVec<Attribute>)
3022                              -> PResult<'a, P<Expr>>
3023     {
3024         let decl = self.parse_fn_block_decl()?;
3025         let decl_hi = self.prev_span;
3026         let body = match decl.output {
3027             FunctionRetTy::Default(_) => self.parse_expr()?,
3028             _ => {
3029                 // If an explicit return type is given, require a
3030                 // block to appear (RFC 968).
3031                 let body_lo = self.span;
3032                 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3033             }
3034         };
3035
3036         Ok(self.mk_expr(
3037             lo.to(body.span),
3038             ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3039             attrs))
3040     }
3041
3042     // `else` token already eaten
3043     pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3044         if self.eat_keyword(keywords::If) {
3045             return self.parse_if_expr(ThinVec::new());
3046         } else {
3047             let blk = self.parse_block()?;
3048             return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3049         }
3050     }
3051
3052     /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3053     pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3054                           span_lo: Span,
3055                           mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3056         // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3057
3058         let pat = self.parse_pat()?;
3059         self.expect_keyword(keywords::In)?;
3060         let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3061         let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3062         attrs.extend(iattrs);
3063
3064         let hi = self.prev_span;
3065         Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3066     }
3067
3068     /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3069     pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3070                             span_lo: Span,
3071                             mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3072         if self.token.is_keyword(keywords::Let) {
3073             return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3074         }
3075         let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3076         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3077         attrs.extend(iattrs);
3078         let span = span_lo.to(body.span);
3079         return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3080     }
3081
3082     /// Parse a 'while let' expression ('while' token already eaten)
3083     pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3084                                 span_lo: Span,
3085                                 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3086         self.expect_keyword(keywords::Let)?;
3087         let pat = self.parse_pat()?;
3088         self.expect(&token::Eq)?;
3089         let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3090         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3091         attrs.extend(iattrs);
3092         let span = span_lo.to(body.span);
3093         return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3094     }
3095
3096     // parse `loop {...}`, `loop` token already eaten
3097     pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3098                            span_lo: Span,
3099                            mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3100         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3101         attrs.extend(iattrs);
3102         let span = span_lo.to(body.span);
3103         Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3104     }
3105
3106     /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3107     pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3108         -> PResult<'a, P<Expr>>
3109     {
3110         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3111         attrs.extend(iattrs);
3112         Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3113     }
3114
3115     // `match` token already eaten
3116     fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3117         let match_span = self.prev_span;
3118         let lo = self.prev_span;
3119         let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL,
3120                                                None)?;
3121         if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3122             if self.token == token::Token::Semi {
3123                 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3124             }
3125             return Err(e)
3126         }
3127         attrs.extend(self.parse_inner_attributes()?);
3128
3129         let mut arms: Vec<Arm> = Vec::new();
3130         while self.token != token::CloseDelim(token::Brace) {
3131             match self.parse_arm() {
3132                 Ok(arm) => arms.push(arm),
3133                 Err(mut e) => {
3134                     // Recover by skipping to the end of the block.
3135                     e.emit();
3136                     self.recover_stmt();
3137                     let span = lo.to(self.span);
3138                     if self.token == token::CloseDelim(token::Brace) {
3139                         self.bump();
3140                     }
3141                     return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3142                 }
3143             }
3144         }
3145         let hi = self.span;
3146         self.bump();
3147         return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3148     }
3149
3150     pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3151         maybe_whole!(self, NtArm, |x| x);
3152
3153         let attrs = self.parse_outer_attributes()?;
3154         let pats = self.parse_pats()?;
3155         let guard = if self.eat_keyword(keywords::If) {
3156             Some(self.parse_expr()?)
3157         } else {
3158             None
3159         };
3160         self.expect(&token::FatArrow)?;
3161         let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR, None)?;
3162
3163         let require_comma =
3164             !classify::expr_is_simple_block(&expr)
3165             && self.token != token::CloseDelim(token::Brace);
3166
3167         if require_comma {
3168             self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3169         } else {
3170             self.eat(&token::Comma);
3171         }
3172
3173         Ok(ast::Arm {
3174             attrs: attrs,
3175             pats: pats,
3176             guard: guard,
3177             body: expr,
3178         })
3179     }
3180
3181     /// Parse an expression
3182     pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3183         self.parse_expr_res(Restrictions::empty(), None)
3184     }
3185
3186     /// Evaluate the closure with restrictions in place.
3187     ///
3188     /// After the closure is evaluated, restrictions are reset.
3189     pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3190         where F: FnOnce(&mut Self) -> T
3191     {
3192         let old = self.restrictions;
3193         self.restrictions = r;
3194         let r = f(self);
3195         self.restrictions = old;
3196         return r;
3197
3198     }
3199
3200     /// Parse an expression, subject to the given restrictions
3201     pub fn parse_expr_res(&mut self, r: Restrictions,
3202                           already_parsed_attrs: Option<ThinVec<Attribute>>)
3203                           -> PResult<'a, P<Expr>> {
3204         self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3205     }
3206
3207     /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3208     fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3209         if self.check(&token::Eq) {
3210             self.bump();
3211             Ok(Some(self.parse_expr()?))
3212         } else {
3213             Ok(None)
3214         }
3215     }
3216
3217     /// Parse patterns, separated by '|' s
3218     fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3219         let mut pats = Vec::new();
3220         loop {
3221             pats.push(self.parse_pat()?);
3222             if self.check(&token::BinOp(token::Or)) { self.bump();}
3223             else { return Ok(pats); }
3224         };
3225     }
3226
3227     fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3228                                 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3229         let mut fields = vec![];
3230         let mut ddpos = None;
3231
3232         while !self.check(&token::CloseDelim(token::Paren)) {
3233             if ddpos.is_none() && self.eat(&token::DotDot) {
3234                 ddpos = Some(fields.len());
3235                 if self.eat(&token::Comma) {
3236                     // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3237                     fields.push(self.parse_pat()?);
3238                 }
3239             } else if ddpos.is_some() && self.eat(&token::DotDot) {
3240                 // Emit a friendly error, ignore `..` and continue parsing
3241                 self.span_err(self.prev_span, "`..` can only be used once per \
3242                                                tuple or tuple struct pattern");
3243             } else {
3244                 fields.push(self.parse_pat()?);
3245             }
3246
3247             if !self.check(&token::CloseDelim(token::Paren)) ||
3248                     (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3249                 self.expect(&token::Comma)?;
3250             }
3251         }
3252
3253         Ok((fields, ddpos))
3254     }
3255
3256     fn parse_pat_vec_elements(
3257         &mut self,
3258     ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3259         let mut before = Vec::new();
3260         let mut slice = None;
3261         let mut after = Vec::new();
3262         let mut first = true;
3263         let mut before_slice = true;
3264
3265         while self.token != token::CloseDelim(token::Bracket) {
3266             if first {
3267                 first = false;
3268             } else {
3269                 self.expect(&token::Comma)?;
3270
3271                 if self.token == token::CloseDelim(token::Bracket)
3272                         && (before_slice || !after.is_empty()) {
3273                     break
3274                 }
3275             }
3276
3277             if before_slice {
3278                 if self.eat(&token::DotDot) {
3279
3280                     if self.check(&token::Comma) ||
3281                             self.check(&token::CloseDelim(token::Bracket)) {
3282                         slice = Some(P(ast::Pat {
3283                             id: ast::DUMMY_NODE_ID,
3284                             node: PatKind::Wild,
3285                             span: self.span,
3286                         }));
3287                         before_slice = false;
3288                     }
3289                     continue
3290                 }
3291             }
3292
3293             let subpat = self.parse_pat()?;
3294             if before_slice && self.eat(&token::DotDot) {
3295                 slice = Some(subpat);
3296                 before_slice = false;
3297             } else if before_slice {
3298                 before.push(subpat);
3299             } else {
3300                 after.push(subpat);
3301             }
3302         }
3303
3304         Ok((before, slice, after))
3305     }
3306
3307     /// Parse the fields of a struct-like pattern
3308     fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3309         let mut fields = Vec::new();
3310         let mut etc = false;
3311         let mut first = true;
3312         while self.token != token::CloseDelim(token::Brace) {
3313             if first {
3314                 first = false;
3315             } else {
3316                 self.expect(&token::Comma)?;
3317                 // accept trailing commas
3318                 if self.check(&token::CloseDelim(token::Brace)) { break }
3319             }
3320
3321             let attrs = self.parse_outer_attributes()?;
3322             let lo = self.span;
3323             let hi;
3324
3325             if self.check(&token::DotDot) {
3326                 self.bump();
3327                 if self.token != token::CloseDelim(token::Brace) {
3328                     let token_str = self.this_token_to_string();
3329                     return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3330                                        token_str)))
3331                 }
3332                 etc = true;
3333                 break;
3334             }
3335
3336             // Check if a colon exists one ahead. This means we're parsing a fieldname.
3337             let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3338                 // Parsing a pattern of the form "fieldname: pat"
3339                 let fieldname = self.parse_field_name()?;
3340                 self.bump();
3341                 let pat = self.parse_pat()?;
3342                 hi = pat.span;
3343                 (pat, fieldname, false)
3344             } else {
3345                 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3346                 let is_box = self.eat_keyword(keywords::Box);
3347                 let boxed_span = self.span;
3348                 let is_ref = self.eat_keyword(keywords::Ref);
3349                 let is_mut = self.eat_keyword(keywords::Mut);
3350                 let fieldname = self.parse_ident()?;
3351                 hi = self.prev_span;
3352
3353                 let bind_type = match (is_ref, is_mut) {
3354                     (true, true) => BindingMode::ByRef(Mutability::Mutable),
3355                     (true, false) => BindingMode::ByRef(Mutability::Immutable),
3356                     (false, true) => BindingMode::ByValue(Mutability::Mutable),
3357                     (false, false) => BindingMode::ByValue(Mutability::Immutable),
3358                 };
3359                 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3360                 let fieldpat = P(ast::Pat{
3361                     id: ast::DUMMY_NODE_ID,
3362                     node: PatKind::Ident(bind_type, fieldpath, None),
3363                     span: boxed_span.to(hi),
3364                 });
3365
3366                 let subpat = if is_box {
3367                     P(ast::Pat{
3368                         id: ast::DUMMY_NODE_ID,
3369                         node: PatKind::Box(fieldpat),
3370                         span: lo.to(hi),
3371                     })
3372                 } else {
3373                     fieldpat
3374                 };
3375                 (subpat, fieldname, true)
3376             };
3377
3378             fields.push(codemap::Spanned { span: lo.to(hi),
3379                                            node: ast::FieldPat {
3380                                                ident: fieldname,
3381                                                pat: subpat,
3382                                                is_shorthand: is_shorthand,
3383                                                attrs: attrs.into(),
3384                                            }
3385             });
3386         }
3387         return Ok((fields, etc));
3388     }
3389
3390     fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3391         if self.token.is_path_start() {
3392             let lo = self.span;
3393             let (qself, path) = if self.eat_lt() {
3394                 // Parse a qualified path
3395                 let (qself, path) =
3396                     self.parse_qualified_path(PathStyle::Expr)?;
3397                 (Some(qself), path)
3398             } else {
3399                 // Parse an unqualified path
3400                 (None, self.parse_path(PathStyle::Expr)?)
3401             };
3402             let hi = self.prev_span;
3403             Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3404         } else {
3405             self.parse_pat_literal_maybe_minus()
3406         }
3407     }
3408
3409     // helper function to decide whether to parse as ident binding or to try to do
3410     // something more complex like range patterns
3411     fn parse_as_ident(&mut self) -> bool {
3412         self.look_ahead(1, |t| match *t {
3413             token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3414             token::DotDotDot | token::ModSep | token::Not => Some(false),
3415             // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3416             // range pattern branch
3417             token::DotDot => None,
3418             _ => Some(true),
3419         }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3420             token::Comma | token::CloseDelim(token::Bracket) => true,
3421             _ => false,
3422         }))
3423     }
3424
3425     /// Parse a pattern.
3426     pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3427         maybe_whole!(self, NtPat, |x| x);
3428
3429         let lo = self.span;
3430         let pat;
3431         match self.token {
3432             token::Underscore => {
3433                 // Parse _
3434                 self.bump();
3435                 pat = PatKind::Wild;
3436             }
3437             token::BinOp(token::And) | token::AndAnd => {
3438                 // Parse &pat / &mut pat
3439                 self.expect_and()?;
3440                 let mutbl = self.parse_mutability();
3441                 if let token::Lifetime(ident) = self.token {
3442                     return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3443                 }
3444                 let subpat = self.parse_pat()?;
3445                 pat = PatKind::Ref(subpat, mutbl);
3446             }
3447             token::OpenDelim(token::Paren) => {
3448                 // Parse (pat,pat,pat,...) as tuple pattern
3449                 self.bump();
3450                 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3451                 self.expect(&token::CloseDelim(token::Paren))?;
3452                 pat = PatKind::Tuple(fields, ddpos);
3453             }
3454             token::OpenDelim(token::Bracket) => {
3455                 // Parse [pat,pat,...] as slice pattern
3456                 self.bump();
3457                 let (before, slice, after) = self.parse_pat_vec_elements()?;
3458                 self.expect(&token::CloseDelim(token::Bracket))?;
3459                 pat = PatKind::Slice(before, slice, after);
3460             }
3461             // At this point, token != _, &, &&, (, [
3462             _ => if self.eat_keyword(keywords::Mut) {
3463                 // Parse mut ident @ pat
3464                 pat = self.parse_pat_ident(BindingMode::ByValue(Mutability::Mutable))?;
3465             } else if self.eat_keyword(keywords::Ref) {
3466                 // Parse ref ident @ pat / ref mut ident @ pat
3467                 let mutbl = self.parse_mutability();
3468                 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3469             } else if self.eat_keyword(keywords::Box) {
3470                 // Parse box pat
3471                 let subpat = self.parse_pat()?;
3472                 pat = PatKind::Box(subpat);
3473             } else if self.token.is_ident() && !self.token.is_any_keyword() &&
3474                       self.parse_as_ident() {
3475                 // Parse ident @ pat
3476                 // This can give false positives and parse nullary enums,
3477                 // they are dealt with later in resolve
3478                 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3479                 pat = self.parse_pat_ident(binding_mode)?;
3480             } else if self.token.is_path_start() {
3481                 // Parse pattern starting with a path
3482                 let (qself, path) = if self.eat_lt() {
3483                     // Parse a qualified path
3484                     let (qself, path) = self.parse_qualified_path(PathStyle::Expr)?;
3485                     (Some(qself), path)
3486                 } else {
3487                     // Parse an unqualified path
3488                     (None, self.parse_path(PathStyle::Expr)?)
3489                 };
3490                 match self.token {
3491                     token::Not if qself.is_none() => {
3492                         // Parse macro invocation
3493                         self.bump();
3494                         let (_, tts) = self.expect_delimited_token_tree()?;
3495                         let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3496                         pat = PatKind::Mac(mac);
3497                     }
3498                     token::DotDotDot | token::DotDot => {
3499                         let end_kind = match self.token {
3500                             token::DotDot => RangeEnd::Excluded,
3501                             token::DotDotDot => RangeEnd::Included,
3502                             _ => panic!("can only parse `..` or `...` for ranges (checked above)"),
3503                         };
3504                         // Parse range
3505                         let span = lo.to(self.prev_span);
3506                         let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3507                         self.bump();
3508                         let end = self.parse_pat_range_end()?;
3509                         pat = PatKind::Range(begin, end, end_kind);
3510                     }
3511                     token::OpenDelim(token::Brace) => {
3512                         if qself.is_some() {
3513                             return Err(self.fatal("unexpected `{` after qualified path"));
3514                         }
3515                         // Parse struct pattern
3516                         self.bump();
3517                         let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3518                             e.emit();
3519                             self.recover_stmt();
3520                             (vec![], false)
3521                         });
3522                         self.bump();
3523                         pat = PatKind::Struct(path, fields, etc);
3524                     }
3525                     token::OpenDelim(token::Paren) => {
3526                         if qself.is_some() {
3527                             return Err(self.fatal("unexpected `(` after qualified path"));
3528                         }
3529                         // Parse tuple struct or enum pattern
3530                         self.bump();
3531                         let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3532                         self.expect(&token::CloseDelim(token::Paren))?;
3533                         pat = PatKind::TupleStruct(path, fields, ddpos)
3534                     }
3535                     _ => pat = PatKind::Path(qself, path),
3536                 }
3537             } else {
3538                 // Try to parse everything else as literal with optional minus
3539                 match self.parse_pat_literal_maybe_minus() {
3540                     Ok(begin) => {
3541                         if self.eat(&token::DotDotDot) {
3542                             let end = self.parse_pat_range_end()?;
3543                             pat = PatKind::Range(begin, end, RangeEnd::Included);
3544                         } else if self.eat(&token::DotDot) {
3545                             let end = self.parse_pat_range_end()?;
3546                             pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3547                         } else {
3548                             pat = PatKind::Lit(begin);
3549                         }
3550                     }
3551                     Err(mut err) => {
3552                         self.cancel(&mut err);
3553                         let msg = format!("expected pattern, found {}", self.this_token_descr());
3554                         return Err(self.fatal(&msg));
3555                     }
3556                 }
3557             }
3558         }
3559
3560         Ok(P(ast::Pat {
3561             id: ast::DUMMY_NODE_ID,
3562             node: pat,
3563             span: lo.to(self.prev_span),
3564         }))
3565     }
3566
3567     /// Parse ident or ident @ pat
3568     /// used by the copy foo and ref foo patterns to give a good
3569     /// error message when parsing mistakes like ref foo(a,b)
3570     fn parse_pat_ident(&mut self,
3571                        binding_mode: ast::BindingMode)
3572                        -> PResult<'a, PatKind> {
3573         let ident_span = self.span;
3574         let ident = self.parse_ident()?;
3575         let name = codemap::Spanned{span: ident_span, node: ident};
3576         let sub = if self.eat(&token::At) {
3577             Some(self.parse_pat()?)
3578         } else {
3579             None
3580         };
3581
3582         // just to be friendly, if they write something like
3583         //   ref Some(i)
3584         // we end up here with ( as the current token.  This shortly
3585         // leads to a parse error.  Note that if there is no explicit
3586         // binding mode then we do not end up here, because the lookahead
3587         // will direct us over to parse_enum_variant()
3588         if self.token == token::OpenDelim(token::Paren) {
3589             return Err(self.span_fatal(
3590                 self.prev_span,
3591                 "expected identifier, found enum pattern"))
3592         }
3593
3594         Ok(PatKind::Ident(binding_mode, name, sub))
3595     }
3596
3597     /// Parse a local variable declaration
3598     fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3599         let lo = self.span;
3600         let pat = self.parse_pat()?;
3601
3602         let ty = if self.eat(&token::Colon) {
3603             Some(self.parse_ty()?)
3604         } else {
3605             None
3606         };
3607         let init = self.parse_initializer()?;
3608         Ok(P(ast::Local {
3609             ty: ty,
3610             pat: pat,
3611             init: init,
3612             id: ast::DUMMY_NODE_ID,
3613             span: lo.to(self.prev_span),
3614             attrs: attrs,
3615         }))
3616     }
3617
3618     /// Parse a structure field
3619     fn parse_name_and_ty(&mut self,
3620                          lo: Span,
3621                          vis: Visibility,
3622                          attrs: Vec<Attribute>)
3623                          -> PResult<'a, StructField> {
3624         let name = self.parse_ident()?;
3625         self.expect(&token::Colon)?;
3626         let ty = self.parse_ty()?;
3627         Ok(StructField {
3628             span: lo.to(self.prev_span),
3629             ident: Some(name),
3630             vis: vis,
3631             id: ast::DUMMY_NODE_ID,
3632             ty: ty,
3633             attrs: attrs,
3634         })
3635     }
3636
3637     /// Emit an expected item after attributes error.
3638     fn expected_item_err(&self, attrs: &[Attribute]) {
3639         let message = match attrs.last() {
3640             Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3641             _ => "expected item after attributes",
3642         };
3643
3644         self.span_err(self.prev_span, message);
3645     }
3646
3647     /// Parse a statement. This stops just before trailing semicolons on everything but items.
3648     /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3649     pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3650         Ok(self.parse_stmt_(true))
3651     }
3652
3653     // Eat tokens until we can be relatively sure we reached the end of the
3654     // statement. This is something of a best-effort heuristic.
3655     //
3656     // We terminate when we find an unmatched `}` (without consuming it).
3657     fn recover_stmt(&mut self) {
3658         self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
3659     }
3660
3661     // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3662     // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3663     // approximate - it can mean we break too early due to macros, but that
3664     // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3665     //
3666     // If `break_on_block` is `Break`, then we will stop consuming tokens
3667     // after finding (and consuming) a brace-delimited block.
3668     fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
3669         let mut brace_depth = 0;
3670         let mut bracket_depth = 0;
3671         let mut in_block = false;
3672         debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
3673                break_on_semi, break_on_block);
3674         loop {
3675             debug!("recover_stmt_ loop {:?}", self.token);
3676             match self.token {
3677                 token::OpenDelim(token::DelimToken::Brace) => {
3678                     brace_depth += 1;
3679                     self.bump();
3680                     if break_on_block == BlockMode::Break &&
3681                        brace_depth == 1 &&
3682                        bracket_depth == 0 {
3683                         in_block = true;
3684                     }
3685                 }
3686                 token::OpenDelim(token::DelimToken::Bracket) => {
3687                     bracket_depth += 1;
3688                     self.bump();
3689                 }
3690                 token::CloseDelim(token::DelimToken::Brace) => {
3691                     if brace_depth == 0 {
3692                         debug!("recover_stmt_ return - close delim {:?}", self.token);
3693                         return;
3694                     }
3695                     brace_depth -= 1;
3696                     self.bump();
3697                     if in_block && bracket_depth == 0 && brace_depth == 0 {
3698                         debug!("recover_stmt_ return - block end {:?}", self.token);
3699                         return;
3700                     }
3701                 }
3702                 token::CloseDelim(token::DelimToken::Bracket) => {
3703                     bracket_depth -= 1;
3704                     if bracket_depth < 0 {
3705                         bracket_depth = 0;
3706                     }
3707                     self.bump();
3708                 }
3709                 token::Eof => {
3710                     debug!("recover_stmt_ return - Eof");
3711                     return;
3712                 }
3713                 token::Semi => {
3714                     self.bump();
3715                     if break_on_semi == SemiColonMode::Break &&
3716                        brace_depth == 0 &&
3717                        bracket_depth == 0 {
3718                         debug!("recover_stmt_ return - Semi");
3719                         return;
3720                     }
3721                 }
3722                 _ => {
3723                     self.bump()
3724                 }
3725             }
3726         }
3727     }
3728
3729     fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
3730         self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
3731             e.emit();
3732             self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
3733             None
3734         })
3735     }
3736
3737     fn is_catch_expr(&mut self) -> bool {
3738         self.token.is_keyword(keywords::Do) &&
3739         self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
3740         self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
3741
3742         // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3743         !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL)
3744     }
3745
3746     fn is_union_item(&self) -> bool {
3747         self.token.is_keyword(keywords::Union) &&
3748         self.look_ahead(1, |t| t.is_ident() && !t.is_any_keyword())
3749     }
3750
3751     fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility)
3752                      -> PResult<'a, Option<P<Item>>> {
3753         let lo = self.span;
3754         match self.token {
3755             token::Ident(ident) if ident.name == "macro_rules" => {
3756                 if self.look_ahead(1, |t| *t == token::Not) {
3757                     let prev_span = self.prev_span;
3758                     self.complain_if_pub_macro(vis, prev_span);
3759                     self.bump();
3760                     self.bump();
3761                 }
3762             }
3763             _ => return Ok(None),
3764         };
3765
3766         let id = self.parse_ident()?;
3767         let (delim, tts) = self.expect_delimited_token_tree()?;
3768         if delim != token::Brace {
3769             if !self.eat(&token::Semi) {
3770                 let msg = "macros that expand to items must either be surrounded with braces \
3771                            or followed by a semicolon";
3772                 self.span_err(self.prev_span, msg);
3773             }
3774         }
3775
3776         let span = lo.to(self.prev_span);
3777         let kind = ItemKind::MacroDef(tts);
3778         Ok(Some(self.mk_item(span, id, kind, Visibility::Inherited, attrs.to_owned())))
3779     }
3780
3781     fn parse_stmt_without_recovery(&mut self,
3782                                    macro_legacy_warnings: bool)
3783                                    -> PResult<'a, Option<Stmt>> {
3784         maybe_whole!(self, NtStmt, |x| Some(x));
3785
3786         let attrs = self.parse_outer_attributes()?;
3787         let lo = self.span;
3788
3789         Ok(Some(if self.eat_keyword(keywords::Let) {
3790             Stmt {
3791                 id: ast::DUMMY_NODE_ID,
3792                 node: StmtKind::Local(self.parse_local(attrs.into())?),
3793                 span: lo.to(self.prev_span),
3794             }
3795         } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited)? {
3796             Stmt {
3797                 id: ast::DUMMY_NODE_ID,
3798                 node: StmtKind::Item(macro_def),
3799                 span: lo.to(self.prev_span),
3800             }
3801         // Starts like a simple path, but not a union item.
3802         } else if self.token.is_path_start() &&
3803                   !self.token.is_qpath_start() &&
3804                   !self.is_union_item() {
3805             let pth = self.parse_path(PathStyle::Expr)?;
3806
3807             if !self.eat(&token::Not) {
3808                 let expr = if self.check(&token::OpenDelim(token::Brace)) {
3809                     self.parse_struct_expr(lo, pth, ThinVec::new())?
3810                 } else {
3811                     let hi = self.prev_span;
3812                     self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
3813                 };
3814
3815                 let expr = self.with_res(RESTRICTION_STMT_EXPR, |this| {
3816                     let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
3817                     this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
3818                 })?;
3819
3820                 return Ok(Some(Stmt {
3821                     id: ast::DUMMY_NODE_ID,
3822                     node: StmtKind::Expr(expr),
3823                     span: lo.to(self.prev_span),
3824                 }));
3825             }
3826
3827             // it's a macro invocation
3828             let id = match self.token {
3829                 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
3830                 _ => self.parse_ident()?,
3831             };
3832
3833             // check that we're pointing at delimiters (need to check
3834             // again after the `if`, because of `parse_ident`
3835             // consuming more tokens).
3836             let delim = match self.token {
3837                 token::OpenDelim(delim) => delim,
3838                 _ => {
3839                     // we only expect an ident if we didn't parse one
3840                     // above.
3841                     let ident_str = if id.name == keywords::Invalid.name() {
3842                         "identifier, "
3843                     } else {
3844                         ""
3845                     };
3846                     let tok_str = self.this_token_to_string();
3847                     return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3848                                        ident_str,
3849                                        tok_str)))
3850                 },
3851             };
3852
3853             let (_, tts) = self.expect_delimited_token_tree()?;
3854             let hi = self.prev_span;
3855
3856             let style = if delim == token::Brace {
3857                 MacStmtStyle::Braces
3858             } else {
3859                 MacStmtStyle::NoBraces
3860             };
3861
3862             if id.name == keywords::Invalid.name() {
3863                 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
3864                 let node = if delim == token::Brace ||
3865                               self.token == token::Semi || self.token == token::Eof {
3866                     StmtKind::Mac(P((mac, style, attrs.into())))
3867                 }
3868                 // We used to incorrectly stop parsing macro-expanded statements here.
3869                 // If the next token will be an error anyway but could have parsed with the
3870                 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
3871                 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
3872                     // These can continue an expression, so we can't stop parsing and warn.
3873                     token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
3874                     token::BinOp(token::Minus) | token::BinOp(token::Star) |
3875                     token::BinOp(token::And) | token::BinOp(token::Or) |
3876                     token::AndAnd | token::OrOr |
3877                     token::DotDot | token::DotDotDot => false,
3878                     _ => true,
3879                 } {
3880                     self.warn_missing_semicolon();
3881                     StmtKind::Mac(P((mac, style, attrs.into())))
3882                 } else {
3883                     let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
3884                     let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
3885                     let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
3886                     StmtKind::Expr(e)
3887                 };
3888                 Stmt {
3889                     id: ast::DUMMY_NODE_ID,
3890                     span: lo.to(hi),
3891                     node: node,
3892                 }
3893             } else {
3894                 // if it has a special ident, it's definitely an item
3895                 //
3896                 // Require a semicolon or braces.
3897                 if style != MacStmtStyle::Braces {
3898                     if !self.eat(&token::Semi) {
3899                         self.span_err(self.prev_span,
3900                                       "macros that expand to items must \
3901                                        either be surrounded with braces or \
3902                                        followed by a semicolon");
3903                     }
3904                 }
3905                 let span = lo.to(hi);
3906                 Stmt {
3907                     id: ast::DUMMY_NODE_ID,
3908                     span: span,
3909                     node: StmtKind::Item({
3910                         self.mk_item(
3911                             span, id /*id is good here*/,
3912                             ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
3913                             Visibility::Inherited,
3914                             attrs)
3915                     }),
3916                 }
3917             }
3918         } else {
3919             // FIXME: Bad copy of attrs
3920             let old_directory_ownership =
3921                 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
3922             let item = self.parse_item_(attrs.clone(), false, true)?;
3923             self.directory.ownership = old_directory_ownership;
3924             match item {
3925                 Some(i) => Stmt {
3926                     id: ast::DUMMY_NODE_ID,
3927                     span: lo.to(i.span),
3928                     node: StmtKind::Item(i),
3929                 },
3930                 None => {
3931                     let unused_attrs = |attrs: &[_], s: &mut Self| {
3932                         if !attrs.is_empty() {
3933                             if s.prev_token_kind == PrevTokenKind::DocComment {
3934                                 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
3935                             } else {
3936                                 s.span_err(s.span, "expected statement after outer attribute");
3937                             }
3938                         }
3939                     };
3940
3941                     // Do not attempt to parse an expression if we're done here.
3942                     if self.token == token::Semi {
3943                         unused_attrs(&attrs, self);
3944                         self.bump();
3945                         return Ok(None);
3946                     }
3947
3948                     if self.token == token::CloseDelim(token::Brace) {
3949                         unused_attrs(&attrs, self);
3950                         return Ok(None);
3951                     }
3952
3953                     // Remainder are line-expr stmts.
3954                     let e = self.parse_expr_res(
3955                         RESTRICTION_STMT_EXPR, Some(attrs.into()))?;
3956                     Stmt {
3957                         id: ast::DUMMY_NODE_ID,
3958                         span: lo.to(e.span),
3959                         node: StmtKind::Expr(e),
3960                     }
3961                 }
3962             }
3963         }))
3964     }
3965
3966     /// Is this expression a successfully-parsed statement?
3967     fn expr_is_complete(&mut self, e: &Expr) -> bool {
3968         self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
3969             !classify::expr_requires_semi_to_be_stmt(e)
3970     }
3971
3972     /// Parse a block. No inner attrs are allowed.
3973     pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
3974         maybe_whole!(self, NtBlock, |x| x);
3975
3976         let lo = self.span;
3977
3978         if !self.eat(&token::OpenDelim(token::Brace)) {
3979             let sp = self.span;
3980             let tok = self.this_token_to_string();
3981             let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
3982
3983             // Check to see if the user has written something like
3984             //
3985             //    if (cond)
3986             //      bar;
3987             //
3988             // Which is valid in other languages, but not Rust.
3989             match self.parse_stmt_without_recovery(false) {
3990                 Ok(Some(stmt)) => {
3991                     let mut stmt_span = stmt.span;
3992                     // expand the span to include the semicolon, if it exists
3993                     if self.eat(&token::Semi) {
3994                         stmt_span.hi = self.prev_span.hi;
3995                     }
3996                     let sugg = pprust::to_string(|s| {
3997                         use print::pprust::{PrintState, INDENT_UNIT};
3998                         s.ibox(INDENT_UNIT)?;
3999                         s.bopen()?;
4000                         s.print_stmt(&stmt)?;
4001                         s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4002                     });
4003                     e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4004                 }
4005                 Err(mut e) => {
4006                     self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4007                     self.cancel(&mut e);
4008                 }
4009                 _ => ()
4010             }
4011             return Err(e);
4012         }
4013
4014         self.parse_block_tail(lo, BlockCheckMode::Default)
4015     }
4016
4017     /// Parse a block. Inner attrs are allowed.
4018     fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4019         maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4020
4021         let lo = self.span;
4022         self.expect(&token::OpenDelim(token::Brace))?;
4023         Ok((self.parse_inner_attributes()?,
4024             self.parse_block_tail(lo, BlockCheckMode::Default)?))
4025     }
4026
4027     /// Parse the rest of a block expression or function body
4028     /// Precondition: already parsed the '{'.
4029     fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4030         let mut stmts = vec![];
4031
4032         while !self.eat(&token::CloseDelim(token::Brace)) {
4033             if let Some(stmt) = self.parse_full_stmt(false)? {
4034                 stmts.push(stmt);
4035             } else if self.token == token::Eof {
4036                 break;
4037             } else {
4038                 // Found only `;` or `}`.
4039                 continue;
4040             };
4041         }
4042
4043         Ok(P(ast::Block {
4044             stmts: stmts,
4045             id: ast::DUMMY_NODE_ID,
4046             rules: s,
4047             span: lo.to(self.prev_span),
4048         }))
4049     }
4050
4051     /// Parse a statement, including the trailing semicolon.
4052     pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4053         let mut stmt = match self.parse_stmt_(macro_legacy_warnings) {
4054             Some(stmt) => stmt,
4055             None => return Ok(None),
4056         };
4057
4058         match stmt.node {
4059             StmtKind::Expr(ref expr) if self.token != token::Eof => {
4060                 // expression without semicolon
4061                 if classify::expr_requires_semi_to_be_stmt(expr) {
4062                     // Just check for errors and recover; do not eat semicolon yet.
4063                     if let Err(mut e) =
4064                         self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4065                     {
4066                         e.emit();
4067                         self.recover_stmt();
4068                     }
4069                 }
4070             }
4071             StmtKind::Local(..) => {
4072                 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4073                 if macro_legacy_warnings && self.token != token::Semi {
4074                     self.warn_missing_semicolon();
4075                 } else {
4076                     self.expect_one_of(&[token::Semi], &[])?;
4077                 }
4078             }
4079             _ => {}
4080         }
4081
4082         if self.eat(&token::Semi) {
4083             stmt = stmt.add_trailing_semicolon();
4084         }
4085
4086         stmt.span.hi = self.prev_span.hi;
4087         Ok(Some(stmt))
4088     }
4089
4090     fn warn_missing_semicolon(&self) {
4091         self.diagnostic().struct_span_warn(self.span, {
4092             &format!("expected `;`, found `{}`", self.this_token_to_string())
4093         }).note({
4094             "This was erroneously allowed and will become a hard error in a future release"
4095         }).emit();
4096     }
4097
4098     // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4099     // BOUND = TY_BOUND | LT_BOUND
4100     // LT_BOUND = LIFETIME (e.g. `'a`)
4101     // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4102     // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4103     fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4104         let mut bounds = Vec::new();
4105         loop {
4106             let is_bound_start = self.check_path() || self.check_lifetime() ||
4107                                  self.check(&token::Question) ||
4108                                  self.check_keyword(keywords::For) ||
4109                                  self.check(&token::OpenDelim(token::Paren));
4110             if is_bound_start {
4111                 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4112                 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4113                 if self.token.is_lifetime() {
4114                     if let Some(question_span) = question {
4115                         self.span_err(question_span,
4116                                       "`?` may only modify trait bounds, not lifetime bounds");
4117                     }
4118                     bounds.push(RegionTyParamBound(self.expect_lifetime()));
4119                 } else {
4120                     let lo = self.span;
4121                     let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4122                     let path = self.parse_path(PathStyle::Type)?;
4123                     let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4124                     let modifier = if question.is_some() {
4125                         TraitBoundModifier::Maybe
4126                     } else {
4127                         TraitBoundModifier::None
4128                     };
4129                     bounds.push(TraitTyParamBound(poly_trait, modifier));
4130                 }
4131                 if has_parens {
4132                     self.expect(&token::CloseDelim(token::Paren))?;
4133                     if let Some(&RegionTyParamBound(..)) = bounds.last() {
4134                         self.span_err(self.prev_span,
4135                                       "parenthesized lifetime bounds are not supported");
4136                     }
4137                 }
4138             } else {
4139                 break
4140             }
4141
4142             if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4143                 break
4144             }
4145         }
4146
4147         return Ok(bounds);
4148     }
4149
4150     fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4151         self.parse_ty_param_bounds_common(true)
4152     }
4153
4154     // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4155     // BOUND = LT_BOUND (e.g. `'a`)
4156     fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4157         let mut lifetimes = Vec::new();
4158         while self.check_lifetime() {
4159             lifetimes.push(self.expect_lifetime());
4160
4161             if !self.eat(&token::BinOp(token::Plus)) {
4162                 break
4163             }
4164         }
4165         lifetimes
4166     }
4167
4168     /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4169     fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4170         let span = self.span;
4171         let ident = self.parse_ident()?;
4172
4173         // Parse optional colon and param bounds.
4174         let bounds = if self.eat(&token::Colon) {
4175             self.parse_ty_param_bounds()?
4176         } else {
4177             Vec::new()
4178         };
4179
4180         let default = if self.eat(&token::Eq) {
4181             Some(self.parse_ty()?)
4182         } else {
4183             None
4184         };
4185
4186         Ok(TyParam {
4187             attrs: preceding_attrs.into(),
4188             ident: ident,
4189             id: ast::DUMMY_NODE_ID,
4190             bounds: bounds,
4191             default: default,
4192             span: span,
4193         })
4194     }
4195
4196     /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4197     /// trailing comma and erroneous trailing attributes.
4198     pub fn parse_generic_params(&mut self) -> PResult<'a, (Vec<LifetimeDef>, Vec<TyParam>)> {
4199         let mut lifetime_defs = Vec::new();
4200         let mut ty_params = Vec::new();
4201         let mut seen_ty_param = false;
4202         loop {
4203             let attrs = self.parse_outer_attributes()?;
4204             if self.check_lifetime() {
4205                 let lifetime = self.expect_lifetime();
4206                 // Parse lifetime parameter.
4207                 let bounds = if self.eat(&token::Colon) {
4208                     self.parse_lt_param_bounds()
4209                 } else {
4210                     Vec::new()
4211                 };
4212                 lifetime_defs.push(LifetimeDef {
4213                     attrs: attrs.into(),
4214                     lifetime: lifetime,
4215                     bounds: bounds,
4216                 });
4217                 if seen_ty_param {
4218                     self.span_err(self.prev_span,
4219                         "lifetime parameters must be declared prior to type parameters");
4220                 }
4221             } else if self.check_ident() {
4222                 // Parse type parameter.
4223                 ty_params.push(self.parse_ty_param(attrs)?);
4224                 seen_ty_param = true;
4225             } else {
4226                 // Check for trailing attributes and stop parsing.
4227                 if !attrs.is_empty() {
4228                     let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4229                     self.span_err(attrs[0].span,
4230                         &format!("trailing attribute after {} parameters", param_kind));
4231                 }
4232                 break
4233             }
4234
4235             if !self.eat(&token::Comma) {
4236                 break
4237             }
4238         }
4239         Ok((lifetime_defs, ty_params))
4240     }
4241
4242     /// Parse a set of optional generic type parameter declarations. Where
4243     /// clauses are not parsed here, and must be added later via
4244     /// `parse_where_clause()`.
4245     ///
4246     /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4247     ///                  | ( < lifetimes , typaramseq ( , )? > )
4248     /// where   typaramseq = ( typaram ) | ( typaram , typaramseq )
4249     pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4250         maybe_whole!(self, NtGenerics, |x| x);
4251
4252         let span_lo = self.span;
4253         if self.eat_lt() {
4254             let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4255             self.expect_gt()?;
4256             Ok(ast::Generics {
4257                 lifetimes: lifetime_defs,
4258                 ty_params: ty_params,
4259                 where_clause: WhereClause {
4260                     id: ast::DUMMY_NODE_ID,
4261                     predicates: Vec::new(),
4262                 },
4263                 span: span_lo.to(self.prev_span),
4264             })
4265         } else {
4266             Ok(ast::Generics::default())
4267         }
4268     }
4269
4270     /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4271     /// possibly including trailing comma.
4272     fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4273         let mut lifetimes = Vec::new();
4274         let mut types = Vec::new();
4275         let mut bindings = Vec::new();
4276         let mut seen_type = false;
4277         let mut seen_binding = false;
4278         loop {
4279             if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4280                 // Parse lifetime argument.
4281                 lifetimes.push(self.expect_lifetime());
4282                 if seen_type || seen_binding {
4283                     self.span_err(self.prev_span,
4284                         "lifetime parameters must be declared prior to type parameters");
4285                 }
4286             } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4287                 // Parse associated type binding.
4288                 let lo = self.span;
4289                 let ident = self.parse_ident()?;
4290                 self.bump();
4291                 let ty = self.parse_ty()?;
4292                 bindings.push(TypeBinding {
4293                     id: ast::DUMMY_NODE_ID,
4294                     ident: ident,
4295                     ty: ty,
4296                     span: lo.to(self.prev_span),
4297                 });
4298                 seen_binding = true;
4299             } else if self.check_type() {
4300                 // Parse type argument.
4301                 types.push(self.parse_ty()?);
4302                 if seen_binding {
4303                     self.span_err(types[types.len() - 1].span,
4304                         "type parameters must be declared prior to associated type bindings");
4305                 }
4306                 seen_type = true;
4307             } else {
4308                 break
4309             }
4310
4311             if !self.eat(&token::Comma) {
4312                 break
4313             }
4314         }
4315         Ok((lifetimes, types, bindings))
4316     }
4317
4318     /// Parses an optional `where` clause and places it in `generics`.
4319     ///
4320     /// ```ignore
4321     /// where T : Trait<U, V> + 'b, 'a : 'b
4322     /// ```
4323     pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4324         maybe_whole!(self, NtWhereClause, |x| x);
4325
4326         let mut where_clause = WhereClause {
4327             id: ast::DUMMY_NODE_ID,
4328             predicates: Vec::new(),
4329         };
4330
4331         if !self.eat_keyword(keywords::Where) {
4332             return Ok(where_clause);
4333         }
4334
4335         // This is a temporary future proofing.
4336         //
4337         // We are considering adding generics to the `where` keyword as an alternative higher-rank
4338         // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4339         // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4340         if token::Lt == self.token {
4341             let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4342             if ident_or_lifetime {
4343                 let gt_comma_or_colon = self.look_ahead(2, |t| {
4344                     *t == token::Gt || *t == token::Comma || *t == token::Colon
4345                 });
4346                 if gt_comma_or_colon {
4347                     self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4348                 }
4349             }
4350         }
4351
4352         loop {
4353             let lo = self.span;
4354             if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4355                 let lifetime = self.expect_lifetime();
4356                 // Bounds starting with a colon are mandatory, but possibly empty.
4357                 self.expect(&token::Colon)?;
4358                 let bounds = self.parse_lt_param_bounds();
4359                 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4360                     ast::WhereRegionPredicate {
4361                         span: lo.to(self.prev_span),
4362                         lifetime: lifetime,
4363                         bounds: bounds,
4364                     }
4365                 ));
4366             } else if self.check_type() {
4367                 // Parse optional `for<'a, 'b>`.
4368                 // This `for` is parsed greedily and applies to the whole predicate,
4369                 // the bounded type can have its own `for` applying only to it.
4370                 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4371                 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4372                 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4373                 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4374
4375                 // Parse type with mandatory colon and (possibly empty) bounds,
4376                 // or with mandatory equality sign and the second type.
4377                 let ty = self.parse_ty()?;
4378                 if self.eat(&token::Colon) {
4379                     let bounds = self.parse_ty_param_bounds()?;
4380                     where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4381                         ast::WhereBoundPredicate {
4382                             span: lo.to(self.prev_span),
4383                             bound_lifetimes: lifetime_defs,
4384                             bounded_ty: ty,
4385                             bounds: bounds,
4386                         }
4387                     ));
4388                 // FIXME: Decide what should be used here, `=` or `==`.
4389                 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4390                     let rhs_ty = self.parse_ty()?;
4391                     where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4392                         ast::WhereEqPredicate {
4393                             span: lo.to(self.prev_span),
4394                             lhs_ty: ty,
4395                             rhs_ty: rhs_ty,
4396                             id: ast::DUMMY_NODE_ID,
4397                         }
4398                     ));
4399                 } else {
4400                     return self.unexpected();
4401                 }
4402             } else {
4403                 break
4404             }
4405
4406             if !self.eat(&token::Comma) {
4407                 break
4408             }
4409         }
4410
4411         Ok(where_clause)
4412     }
4413
4414     fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4415                      -> PResult<'a, (Vec<Arg> , bool)> {
4416         let sp = self.span;
4417         let mut variadic = false;
4418         let args: Vec<Option<Arg>> =
4419             self.parse_unspanned_seq(
4420                 &token::OpenDelim(token::Paren),
4421                 &token::CloseDelim(token::Paren),
4422                 SeqSep::trailing_allowed(token::Comma),
4423                 |p| {
4424                     if p.token == token::DotDotDot {
4425                         p.bump();
4426                         if allow_variadic {
4427                             if p.token != token::CloseDelim(token::Paren) {
4428                                 let span = p.span;
4429                                 p.span_err(span,
4430                                     "`...` must be last in argument list for variadic function");
4431                             }
4432                         } else {
4433                             let span = p.span;
4434                             p.span_err(span,
4435                                        "only foreign functions are allowed to be variadic");
4436                         }
4437                         variadic = true;
4438                         Ok(None)
4439                     } else {
4440                         match p.parse_arg_general(named_args) {
4441                             Ok(arg) => Ok(Some(arg)),
4442                             Err(mut e) => {
4443                                 e.emit();
4444                                 let lo = p.prev_span;
4445                                 // Skip every token until next possible arg or end.
4446                                 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4447                                 // Create a placeholder argument for proper arg count (#34264).
4448                                 let span = lo.to(p.prev_span);
4449                                 Ok(Some(dummy_arg(span)))
4450                             }
4451                         }
4452                     }
4453                 }
4454             )?;
4455
4456         let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4457
4458         if variadic && args.is_empty() {
4459             self.span_err(sp,
4460                           "variadic function must be declared with at least one named argument");
4461         }
4462
4463         Ok((args, variadic))
4464     }
4465
4466     /// Parse the argument list and result type of a function declaration
4467     pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4468
4469         let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4470         let ret_ty = self.parse_ret_ty()?;
4471
4472         Ok(P(FnDecl {
4473             inputs: args,
4474             output: ret_ty,
4475             variadic: variadic
4476         }))
4477     }
4478
4479     /// Returns the parsed optional self argument and whether a self shortcut was used.
4480     fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4481         let expect_ident = |this: &mut Self| match this.token {
4482             // Preserve hygienic context.
4483             token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4484             _ => unreachable!()
4485         };
4486         let isolated_self = |this: &mut Self, n| {
4487             this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4488             this.look_ahead(n + 1, |t| t != &token::ModSep)
4489         };
4490
4491         // Parse optional self parameter of a method.
4492         // Only a limited set of initial token sequences is considered self parameters, anything
4493         // else is parsed as a normal function parameter list, so some lookahead is required.
4494         let eself_lo = self.span;
4495         let (eself, eself_ident) = match self.token {
4496             token::BinOp(token::And) => {
4497                 // &self
4498                 // &mut self
4499                 // &'lt self
4500                 // &'lt mut self
4501                 // &not_self
4502                 if isolated_self(self, 1) {
4503                     self.bump();
4504                     (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4505                 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4506                           isolated_self(self, 2) {
4507                     self.bump();
4508                     self.bump();
4509                     (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4510                 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4511                           isolated_self(self, 2) {
4512                     self.bump();
4513                     let lt = self.expect_lifetime();
4514                     (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4515                 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4516                           self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4517                           isolated_self(self, 3) {
4518                     self.bump();
4519                     let lt = self.expect_lifetime();
4520                     self.bump();
4521                     (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4522                 } else {
4523                     return Ok(None);
4524                 }
4525             }
4526             token::BinOp(token::Star) => {
4527                 // *self
4528                 // *const self
4529                 // *mut self
4530                 // *not_self
4531                 // Emit special error for `self` cases.
4532                 if isolated_self(self, 1) {
4533                     self.bump();
4534                     self.span_err(self.span, "cannot pass `self` by raw pointer");
4535                     (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4536                 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4537                           isolated_self(self, 2) {
4538                     self.bump();
4539                     self.bump();
4540                     self.span_err(self.span, "cannot pass `self` by raw pointer");
4541                     (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4542                 } else {
4543                     return Ok(None);
4544                 }
4545             }
4546             token::Ident(..) => {
4547                 if isolated_self(self, 0) {
4548                     // self
4549                     // self: TYPE
4550                     let eself_ident = expect_ident(self);
4551                     if self.eat(&token::Colon) {
4552                         let ty = self.parse_ty()?;
4553                         (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4554                     } else {
4555                         (SelfKind::Value(Mutability::Immutable), eself_ident)
4556                     }
4557                 } else if self.token.is_keyword(keywords::Mut) &&
4558                           isolated_self(self, 1) {
4559                     // mut self
4560                     // mut self: TYPE
4561                     self.bump();
4562                     let eself_ident = expect_ident(self);
4563                     if self.eat(&token::Colon) {
4564                         let ty = self.parse_ty()?;
4565                         (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4566                     } else {
4567                         (SelfKind::Value(Mutability::Mutable), eself_ident)
4568                     }
4569                 } else {
4570                     return Ok(None);
4571                 }
4572             }
4573             _ => return Ok(None),
4574         };
4575
4576         let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
4577         Ok(Some(Arg::from_self(eself, eself_ident)))
4578     }
4579
4580     /// Parse the parameter list and result type of a function that may have a `self` parameter.
4581     fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
4582         where F: FnMut(&mut Parser<'a>) -> PResult<'a,  Arg>,
4583     {
4584         self.expect(&token::OpenDelim(token::Paren))?;
4585
4586         // Parse optional self argument
4587         let self_arg = self.parse_self_arg()?;
4588
4589         // Parse the rest of the function parameter list.
4590         let sep = SeqSep::trailing_allowed(token::Comma);
4591         let fn_inputs = if let Some(self_arg) = self_arg {
4592             if self.check(&token::CloseDelim(token::Paren)) {
4593                 vec![self_arg]
4594             } else if self.eat(&token::Comma) {
4595                 let mut fn_inputs = vec![self_arg];
4596                 fn_inputs.append(&mut self.parse_seq_to_before_end(
4597                     &token::CloseDelim(token::Paren), sep, parse_arg_fn)
4598                 );
4599                 fn_inputs
4600             } else {
4601                 return self.unexpected();
4602             }
4603         } else {
4604             self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4605         };
4606
4607         // Parse closing paren and return type.
4608         self.expect(&token::CloseDelim(token::Paren))?;
4609         Ok(P(FnDecl {
4610             inputs: fn_inputs,
4611             output: self.parse_ret_ty()?,
4612             variadic: false
4613         }))
4614     }
4615
4616     // parse the |arg, arg| header on a lambda
4617     fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4618         let inputs_captures = {
4619             if self.eat(&token::OrOr) {
4620                 Vec::new()
4621             } else {
4622                 self.expect(&token::BinOp(token::Or))?;
4623                 let args = self.parse_seq_to_before_end(
4624                     &token::BinOp(token::Or),
4625                     SeqSep::trailing_allowed(token::Comma),
4626                     |p| p.parse_fn_block_arg()
4627                 );
4628                 self.bump();
4629                 args
4630             }
4631         };
4632         let output = self.parse_ret_ty()?;
4633
4634         Ok(P(FnDecl {
4635             inputs: inputs_captures,
4636             output: output,
4637             variadic: false
4638         }))
4639     }
4640
4641     /// Parse the name and optional generic types of a function header.
4642     fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4643         let id = self.parse_ident()?;
4644         let generics = self.parse_generics()?;
4645         Ok((id, generics))
4646     }
4647
4648     fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
4649                attrs: Vec<Attribute>) -> P<Item> {
4650         P(Item {
4651             ident: ident,
4652             attrs: attrs,
4653             id: ast::DUMMY_NODE_ID,
4654             node: node,
4655             vis: vis,
4656             span: span,
4657         })
4658     }
4659
4660     /// Parse an item-position function declaration.
4661     fn parse_item_fn(&mut self,
4662                      unsafety: Unsafety,
4663                      constness: Spanned<Constness>,
4664                      abi: abi::Abi)
4665                      -> PResult<'a, ItemInfo> {
4666         let (ident, mut generics) = self.parse_fn_header()?;
4667         let decl = self.parse_fn_decl(false)?;
4668         generics.where_clause = self.parse_where_clause()?;
4669         let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4670         Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4671     }
4672
4673     /// true if we are looking at `const ID`, false for things like `const fn` etc
4674     pub fn is_const_item(&mut self) -> bool {
4675         self.token.is_keyword(keywords::Const) &&
4676             !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4677             !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4678     }
4679
4680     /// parses all the "front matter" for a `fn` declaration, up to
4681     /// and including the `fn` keyword:
4682     ///
4683     /// - `const fn`
4684     /// - `unsafe fn`
4685     /// - `const unsafe fn`
4686     /// - `extern fn`
4687     /// - etc
4688     pub fn parse_fn_front_matter(&mut self)
4689                                  -> PResult<'a, (Spanned<ast::Constness>,
4690                                                 ast::Unsafety,
4691                                                 abi::Abi)> {
4692         let is_const_fn = self.eat_keyword(keywords::Const);
4693         let const_span = self.prev_span;
4694         let unsafety = self.parse_unsafety()?;
4695         let (constness, unsafety, abi) = if is_const_fn {
4696             (respan(const_span, Constness::Const), unsafety, Abi::Rust)
4697         } else {
4698             let abi = if self.eat_keyword(keywords::Extern) {
4699                 self.parse_opt_abi()?.unwrap_or(Abi::C)
4700             } else {
4701                 Abi::Rust
4702             };
4703             (respan(self.prev_span, Constness::NotConst), unsafety, abi)
4704         };
4705         self.expect_keyword(keywords::Fn)?;
4706         Ok((constness, unsafety, abi))
4707     }
4708
4709     /// Parse an impl item.
4710     pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
4711         maybe_whole!(self, NtImplItem, |x| x);
4712
4713         let mut attrs = self.parse_outer_attributes()?;
4714         let lo = self.span;
4715         let vis = self.parse_visibility(false)?;
4716         let defaultness = self.parse_defaultness()?;
4717         let (name, node) = if self.eat_keyword(keywords::Type) {
4718             let name = self.parse_ident()?;
4719             self.expect(&token::Eq)?;
4720             let typ = self.parse_ty()?;
4721             self.expect(&token::Semi)?;
4722             (name, ast::ImplItemKind::Type(typ))
4723         } else if self.is_const_item() {
4724             self.expect_keyword(keywords::Const)?;
4725             let name = self.parse_ident()?;
4726             self.expect(&token::Colon)?;
4727             let typ = self.parse_ty()?;
4728             self.expect(&token::Eq)?;
4729             let expr = self.parse_expr()?;
4730             self.expect(&token::Semi)?;
4731             (name, ast::ImplItemKind::Const(typ, expr))
4732         } else {
4733             let (name, inner_attrs, node) = self.parse_impl_method(&vis, at_end)?;
4734             attrs.extend(inner_attrs);
4735             (name, node)
4736         };
4737
4738         Ok(ImplItem {
4739             id: ast::DUMMY_NODE_ID,
4740             span: lo.to(self.prev_span),
4741             ident: name,
4742             vis: vis,
4743             defaultness: defaultness,
4744             attrs: attrs,
4745             node: node
4746         })
4747     }
4748
4749     fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
4750         if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
4751             err.emit();
4752         }
4753     }
4754
4755     fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
4756         match *vis {
4757             Visibility::Inherited => Ok(()),
4758             _ => {
4759                 let is_macro_rules: bool = match self.token {
4760                     token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
4761                     _ => false,
4762                 };
4763                 if is_macro_rules {
4764                     let mut err = self.diagnostic()
4765                         .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
4766                     err.help("did you mean #[macro_export]?");
4767                     Err(err)
4768                 } else {
4769                     let mut err = self.diagnostic()
4770                         .struct_span_err(sp, "can't qualify macro invocation with `pub`");
4771                     err.help("try adjusting the macro to put `pub` inside the invocation");
4772                     Err(err)
4773                 }
4774             }
4775         }
4776     }
4777
4778     fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
4779                                    -> DiagnosticBuilder<'a>
4780     {
4781         // Given this code `path(`, it seems like this is not
4782         // setting the visibility of a macro invocation, but rather
4783         // a mistyped method declaration.
4784         // Create a diagnostic pointing out that `fn` is missing.
4785         //
4786         // x |     pub path(&self) {
4787         //   |        ^ missing `fn`, `type`, or `const`
4788         //     pub  path(
4789         //        ^^ `sp` below will point to this
4790         let sp = prev_span.between(self.prev_span);
4791         let mut err = self.diagnostic().struct_span_err(
4792             sp,
4793             &format!("missing `fn`, `type`, or `const` for {}-item declaration",
4794                      item_type));
4795         err.span_label(sp, "missing `fn`, `type`, or `const`");
4796         err
4797     }
4798
4799     /// Parse a method or a macro invocation in a trait impl.
4800     fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
4801                          -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4802         // code copied from parse_macro_use_or_failure... abstraction!
4803         if self.token.is_path_start() {
4804             // Method macro.
4805
4806             let prev_span = self.prev_span;
4807
4808             let lo = self.span;
4809             let pth = self.parse_path(PathStyle::Mod)?;
4810             if pth.segments.len() == 1 {
4811                 if !self.eat(&token::Not) {
4812                     return Err(self.missing_assoc_item_kind_err("impl", prev_span));
4813                 }
4814             } else {
4815                 self.expect(&token::Not)?;
4816             }
4817
4818             self.complain_if_pub_macro(vis, prev_span);
4819
4820             // eat a matched-delimiter token tree:
4821             *at_end = true;
4822             let (delim, tts) = self.expect_delimited_token_tree()?;
4823             if delim != token::Brace {
4824                 self.expect(&token::Semi)?
4825             }
4826
4827             let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
4828             Ok((keywords::Invalid.ident(), vec![], ast::ImplItemKind::Macro(mac)))
4829         } else {
4830             let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
4831             let ident = self.parse_ident()?;
4832             let mut generics = self.parse_generics()?;
4833             let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
4834             generics.where_clause = self.parse_where_clause()?;
4835             *at_end = true;
4836             let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4837             Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4838                 generics: generics,
4839                 abi: abi,
4840                 unsafety: unsafety,
4841                 constness: constness,
4842                 decl: decl
4843              }, body)))
4844         }
4845     }
4846
4847     /// Parse trait Foo { ... }
4848     fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4849         let ident = self.parse_ident()?;
4850         let mut tps = self.parse_generics()?;
4851
4852         // Parse optional colon and supertrait bounds.
4853         let bounds = if self.eat(&token::Colon) {
4854             self.parse_ty_param_bounds()?
4855         } else {
4856             Vec::new()
4857         };
4858
4859         tps.where_clause = self.parse_where_clause()?;
4860
4861         self.expect(&token::OpenDelim(token::Brace))?;
4862         let mut trait_items = vec![];
4863         while !self.eat(&token::CloseDelim(token::Brace)) {
4864             let mut at_end = false;
4865             match self.parse_trait_item(&mut at_end) {
4866                 Ok(item) => trait_items.push(item),
4867                 Err(mut e) => {
4868                     e.emit();
4869                     if !at_end {
4870                         self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
4871                     }
4872                 }
4873             }
4874         }
4875         Ok((ident, ItemKind::Trait(unsafety, tps, bounds, trait_items), None))
4876     }
4877
4878     /// Parses items implementations variants
4879     ///    impl<T> Foo { ... }
4880     ///    impl<T> ToString for &'static T { ... }
4881     ///    impl Send for .. {}
4882     fn parse_item_impl(&mut self,
4883                        unsafety: ast::Unsafety,
4884                        defaultness: Defaultness) -> PResult<'a, ItemInfo> {
4885         let impl_span = self.span;
4886
4887         // First, parse type parameters if necessary.
4888         let mut generics = self.parse_generics()?;
4889
4890         // Special case: if the next identifier that follows is '(', don't
4891         // allow this to be parsed as a trait.
4892         let could_be_trait = self.token != token::OpenDelim(token::Paren);
4893
4894         let neg_span = self.span;
4895         let polarity = if self.eat(&token::Not) {
4896             ast::ImplPolarity::Negative
4897         } else {
4898             ast::ImplPolarity::Positive
4899         };
4900
4901         // Parse the trait.
4902         let mut ty = self.parse_ty()?;
4903
4904         // Parse traits, if necessary.
4905         let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4906             // New-style trait. Reinterpret the type as a trait.
4907             match ty.node {
4908                 TyKind::Path(None, ref path) => {
4909                     Some(TraitRef {
4910                         path: (*path).clone(),
4911                         ref_id: ty.id,
4912                     })
4913                 }
4914                 _ => {
4915                     self.span_err(ty.span, "not a trait");
4916                     None
4917                 }
4918             }
4919         } else {
4920             if polarity == ast::ImplPolarity::Negative {
4921                 // This is a negated type implementation
4922                 // `impl !MyType {}`, which is not allowed.
4923                 self.span_err(neg_span, "inherent implementation can't be negated");
4924             }
4925             None
4926         };
4927
4928         if opt_trait.is_some() && self.eat(&token::DotDot) {
4929             if generics.is_parameterized() {
4930                 self.span_err(impl_span, "default trait implementations are not \
4931                                           allowed to have generics");
4932             }
4933
4934             if let ast::Defaultness::Default = defaultness {
4935                 self.span_err(impl_span, "`default impl` is not allowed for \
4936                                          default trait implementations");
4937             }
4938
4939             self.expect(&token::OpenDelim(token::Brace))?;
4940             self.expect(&token::CloseDelim(token::Brace))?;
4941             Ok((keywords::Invalid.ident(),
4942              ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
4943         } else {
4944             if opt_trait.is_some() {
4945                 ty = self.parse_ty()?;
4946             }
4947             generics.where_clause = self.parse_where_clause()?;
4948
4949             self.expect(&token::OpenDelim(token::Brace))?;
4950             let attrs = self.parse_inner_attributes()?;
4951
4952             let mut impl_items = vec![];
4953             while !self.eat(&token::CloseDelim(token::Brace)) {
4954                 let mut at_end = false;
4955                 match self.parse_impl_item(&mut at_end) {
4956                     Ok(item) => impl_items.push(item),
4957                     Err(mut e) => {
4958                         e.emit();
4959                         if !at_end {
4960                             self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
4961                         }
4962                     }
4963                 }
4964             }
4965
4966             Ok((keywords::Invalid.ident(),
4967              ItemKind::Impl(unsafety, polarity, defaultness, generics, opt_trait, ty, impl_items),
4968              Some(attrs)))
4969         }
4970     }
4971
4972     fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<LifetimeDef>> {
4973         if self.eat_keyword(keywords::For) {
4974             self.expect_lt()?;
4975             let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4976             self.expect_gt()?;
4977             if !ty_params.is_empty() {
4978                 self.span_err(ty_params[0].span,
4979                               "only lifetime parameters can be used in this context");
4980             }
4981             Ok(lifetime_defs)
4982         } else {
4983             Ok(Vec::new())
4984         }
4985     }
4986
4987     /// Parse struct Foo { ... }
4988     fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
4989         let class_name = self.parse_ident()?;
4990
4991         let mut generics = self.parse_generics()?;
4992
4993         // There is a special case worth noting here, as reported in issue #17904.
4994         // If we are parsing a tuple struct it is the case that the where clause
4995         // should follow the field list. Like so:
4996         //
4997         // struct Foo<T>(T) where T: Copy;
4998         //
4999         // If we are parsing a normal record-style struct it is the case
5000         // that the where clause comes before the body, and after the generics.
5001         // So if we look ahead and see a brace or a where-clause we begin
5002         // parsing a record style struct.
5003         //
5004         // Otherwise if we look ahead and see a paren we parse a tuple-style
5005         // struct.
5006
5007         let vdata = if self.token.is_keyword(keywords::Where) {
5008             generics.where_clause = self.parse_where_clause()?;
5009             if self.eat(&token::Semi) {
5010                 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5011                 VariantData::Unit(ast::DUMMY_NODE_ID)
5012             } else {
5013                 // If we see: `struct Foo<T> where T: Copy { ... }`
5014                 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5015             }
5016         // No `where` so: `struct Foo<T>;`
5017         } else if self.eat(&token::Semi) {
5018             VariantData::Unit(ast::DUMMY_NODE_ID)
5019         // Record-style struct definition
5020         } else if self.token == token::OpenDelim(token::Brace) {
5021             VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5022         // Tuple-style struct definition with optional where-clause.
5023         } else if self.token == token::OpenDelim(token::Paren) {
5024             let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5025             generics.where_clause = self.parse_where_clause()?;
5026             self.expect(&token::Semi)?;
5027             body
5028         } else {
5029             let token_str = self.this_token_to_string();
5030             return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5031                                             name, found `{}`", token_str)))
5032         };
5033
5034         Ok((class_name, ItemKind::Struct(vdata, generics), None))
5035     }
5036
5037     /// Parse union Foo { ... }
5038     fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5039         let class_name = self.parse_ident()?;
5040
5041         let mut generics = self.parse_generics()?;
5042
5043         let vdata = if self.token.is_keyword(keywords::Where) {
5044             generics.where_clause = self.parse_where_clause()?;
5045             VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5046         } else if self.token == token::OpenDelim(token::Brace) {
5047             VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5048         } else {
5049             let token_str = self.this_token_to_string();
5050             return Err(self.fatal(&format!("expected `where` or `{{` after union \
5051                                             name, found `{}`", token_str)))
5052         };
5053
5054         Ok((class_name, ItemKind::Union(vdata, generics), None))
5055     }
5056
5057     pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5058         let mut fields = Vec::new();
5059         if self.eat(&token::OpenDelim(token::Brace)) {
5060             while self.token != token::CloseDelim(token::Brace) {
5061                 fields.push(self.parse_struct_decl_field().map_err(|e| {
5062                     self.recover_stmt();
5063                     self.eat(&token::CloseDelim(token::Brace));
5064                     e
5065                 })?);
5066             }
5067
5068             self.bump();
5069         } else {
5070             let token_str = self.this_token_to_string();
5071             return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5072                                 name, found `{}`",
5073                                 token_str)));
5074         }
5075
5076         Ok(fields)
5077     }
5078
5079     pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5080         // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5081         // Unit like structs are handled in parse_item_struct function
5082         let fields = self.parse_unspanned_seq(
5083             &token::OpenDelim(token::Paren),
5084             &token::CloseDelim(token::Paren),
5085             SeqSep::trailing_allowed(token::Comma),
5086             |p| {
5087                 let attrs = p.parse_outer_attributes()?;
5088                 let lo = p.span;
5089                 let vis = p.parse_visibility(true)?;
5090                 let ty = p.parse_ty()?;
5091                 Ok(StructField {
5092                     span: lo.to(p.span),
5093                     vis: vis,
5094                     ident: None,
5095                     id: ast::DUMMY_NODE_ID,
5096                     ty: ty,
5097                     attrs: attrs,
5098                 })
5099             })?;
5100
5101         Ok(fields)
5102     }
5103
5104     /// Parse a structure field declaration
5105     pub fn parse_single_struct_field(&mut self,
5106                                      lo: Span,
5107                                      vis: Visibility,
5108                                      attrs: Vec<Attribute> )
5109                                      -> PResult<'a, StructField> {
5110         let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5111         match self.token {
5112             token::Comma => {
5113                 self.bump();
5114             }
5115             token::CloseDelim(token::Brace) => {}
5116             token::DocComment(_) => return Err(self.span_fatal_err(self.span,
5117                                                                    Error::UselessDocComment)),
5118             _ => return Err(self.span_fatal_help(self.span,
5119                     &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5120                     "struct fields should be separated by commas")),
5121         }
5122         Ok(a_var)
5123     }
5124
5125     /// Parse an element of a struct definition
5126     fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5127         let attrs = self.parse_outer_attributes()?;
5128         let lo = self.span;
5129         let vis = self.parse_visibility(false)?;
5130         self.parse_single_struct_field(lo, vis, attrs)
5131     }
5132
5133     /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5134     /// and `pub(super)` for `pub(in super)`.  If the following element can't be a tuple (i.e. it's
5135     /// a function definition, it's not a tuple struct field) and the contents within the parens
5136     /// isn't valid, emit a proper diagnostic.
5137     pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5138         maybe_whole!(self, NtVis, |x| x);
5139
5140         if !self.eat_keyword(keywords::Pub) {
5141             return Ok(Visibility::Inherited)
5142         }
5143
5144         if self.check(&token::OpenDelim(token::Paren)) {
5145             // We don't `self.bump()` the `(` yet because this might be a struct definition where
5146             // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5147             // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5148             // by the following tokens.
5149             if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5150                 // `pub(crate)`
5151                 self.bump(); // `(`
5152                 self.bump(); // `crate`
5153                 let vis = Visibility::Crate(self.prev_span);
5154                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5155                 return Ok(vis)
5156             } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5157                 // `pub(in path)`
5158                 self.bump(); // `(`
5159                 self.bump(); // `in`
5160                 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5161                 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5162                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5163                 return Ok(vis)
5164             } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5165                       self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5166                                              t.is_keyword(keywords::SelfValue)) {
5167                 // `pub(self)` or `pub(super)`
5168                 self.bump(); // `(`
5169                 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5170                 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5171                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5172                 return Ok(vis)
5173             } else if !can_take_tuple {  // Provide this diagnostic if this is not a tuple struct
5174                 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5175                 self.bump(); // `(`
5176                 let msg = "incorrect visibility restriction";
5177                 let suggestion = r##"some possible visibility restrictions are:
5178 `pub(crate)`: visible only on the current crate
5179 `pub(super)`: visible only in the current module's parent
5180 `pub(in path::to::module)`: visible only on the specified path"##;
5181                 let path = self.parse_path(PathStyle::Mod)?;
5182                 let path_span = self.prev_span;
5183                 let help_msg = format!("make this visible only to module `{}` with `in`:", path);
5184                 self.expect(&token::CloseDelim(token::Paren))?;  // `)`
5185                 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5186                 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5187                 err.emit();  // emit diagnostic, but continue with public visibility
5188             }
5189         }
5190
5191         Ok(Visibility::Public)
5192     }
5193
5194     /// Parse defaultness: DEFAULT or nothing
5195     fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5196         if self.eat_contextual_keyword(keywords::Default.ident()) {
5197             Ok(Defaultness::Default)
5198         } else {
5199             Ok(Defaultness::Final)
5200         }
5201     }
5202
5203     /// Given a termination token, parse all of the items in a module
5204     fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5205         let mut items = vec![];
5206         while let Some(item) = self.parse_item()? {
5207             items.push(item);
5208         }
5209
5210         if !self.eat(term) {
5211             let token_str = self.this_token_to_string();
5212             return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5213         }
5214
5215         let hi = if self.span == syntax_pos::DUMMY_SP {
5216             inner_lo
5217         } else {
5218             self.prev_span
5219         };
5220
5221         Ok(ast::Mod {
5222             inner: inner_lo.to(hi),
5223             items: items
5224         })
5225     }
5226
5227     fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5228         let id = self.parse_ident()?;
5229         self.expect(&token::Colon)?;
5230         let ty = self.parse_ty()?;
5231         self.expect(&token::Eq)?;
5232         let e = self.parse_expr()?;
5233         self.expect(&token::Semi)?;
5234         let item = match m {
5235             Some(m) => ItemKind::Static(ty, m, e),
5236             None => ItemKind::Const(ty, e),
5237         };
5238         Ok((id, item, None))
5239     }
5240
5241     /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5242     fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5243         let (in_cfg, outer_attrs) = {
5244             let mut strip_unconfigured = ::config::StripUnconfigured {
5245                 sess: self.sess,
5246                 should_test: false, // irrelevant
5247                 features: None, // don't perform gated feature checking
5248             };
5249             let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5250             (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5251         };
5252
5253         let id_span = self.span;
5254         let id = self.parse_ident()?;
5255         if self.check(&token::Semi) {
5256             self.bump();
5257             if in_cfg {
5258                 // This mod is in an external file. Let's go get it!
5259                 let ModulePathSuccess { path, directory_ownership, warn } =
5260                     self.submod_path(id, &outer_attrs, id_span)?;
5261                 let (module, mut attrs) =
5262                     self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5263                 if warn {
5264                     let attr = ast::Attribute {
5265                         id: attr::mk_attr_id(),
5266                         style: ast::AttrStyle::Outer,
5267                         path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5268                                                     Ident::from_str("warn_directory_ownership")),
5269                         tokens: TokenStream::empty(),
5270                         is_sugared_doc: false,
5271                         span: syntax_pos::DUMMY_SP,
5272                     };
5273                     attr::mark_known(&attr);
5274                     attrs.push(attr);
5275                 }
5276                 Ok((id, module, Some(attrs)))
5277             } else {
5278                 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5279                 Ok((id, ItemKind::Mod(placeholder), None))
5280             }
5281         } else {
5282             let old_directory = self.directory.clone();
5283             self.push_directory(id, &outer_attrs);
5284             self.expect(&token::OpenDelim(token::Brace))?;
5285             let mod_inner_lo = self.span;
5286             let attrs = self.parse_inner_attributes()?;
5287             let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5288             self.directory = old_directory;
5289             Ok((id, ItemKind::Mod(module), Some(attrs)))
5290         }
5291     }
5292
5293     fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5294         if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5295             self.directory.path.push(&path.as_str());
5296             self.directory.ownership = DirectoryOwnership::Owned;
5297         } else {
5298             self.directory.path.push(&id.name.as_str());
5299         }
5300     }
5301
5302     pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5303         attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5304     }
5305
5306     /// Returns either a path to a module, or .
5307     pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5308         let mod_name = id.to_string();
5309         let default_path_str = format!("{}.rs", mod_name);
5310         let secondary_path_str = format!("{}{}mod.rs", mod_name, path::MAIN_SEPARATOR);
5311         let default_path = dir_path.join(&default_path_str);
5312         let secondary_path = dir_path.join(&secondary_path_str);
5313         let default_exists = codemap.file_exists(&default_path);
5314         let secondary_exists = codemap.file_exists(&secondary_path);
5315
5316         let result = match (default_exists, secondary_exists) {
5317             (true, false) => Ok(ModulePathSuccess {
5318                 path: default_path,
5319                 directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5320                 warn: false,
5321             }),
5322             (false, true) => Ok(ModulePathSuccess {
5323                 path: secondary_path,
5324                 directory_ownership: DirectoryOwnership::Owned,
5325                 warn: false,
5326             }),
5327             (false, false) => Err(Error::FileNotFoundForModule {
5328                 mod_name: mod_name.clone(),
5329                 default_path: default_path_str,
5330                 secondary_path: secondary_path_str,
5331                 dir_path: format!("{}", dir_path.display()),
5332             }),
5333             (true, true) => Err(Error::DuplicatePaths {
5334                 mod_name: mod_name.clone(),
5335                 default_path: default_path_str,
5336                 secondary_path: secondary_path_str,
5337             }),
5338         };
5339
5340         ModulePath {
5341             name: mod_name,
5342             path_exists: default_exists || secondary_exists,
5343             result: result,
5344         }
5345     }
5346
5347     fn submod_path(&mut self,
5348                    id: ast::Ident,
5349                    outer_attrs: &[ast::Attribute],
5350                    id_sp: Span) -> PResult<'a, ModulePathSuccess> {
5351         if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5352             return Ok(ModulePathSuccess {
5353                 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5354                     Some("mod.rs") => DirectoryOwnership::Owned,
5355                     _ => DirectoryOwnership::UnownedViaMod(true),
5356                 },
5357                 path: path,
5358                 warn: false,
5359             });
5360         }
5361
5362         let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5363
5364         if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5365             let msg =
5366                 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5367             let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5368             if paths.path_exists {
5369                 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5370                                   paths.name);
5371                 err.span_note(id_sp, &msg);
5372             }
5373             Err(err)
5374         } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5375             if warn {
5376                 if let Ok(result) = paths.result {
5377                     return Ok(ModulePathSuccess { warn: true, ..result });
5378                 }
5379             }
5380             let mut err = self.diagnostic().struct_span_err(id_sp,
5381                 "cannot declare a new module at this location");
5382             if id_sp != syntax_pos::DUMMY_SP {
5383                 let src_path = PathBuf::from(self.sess.codemap().span_to_filename(id_sp));
5384                 if let Some(stem) = src_path.file_stem() {
5385                     let mut dest_path = src_path.clone();
5386                     dest_path.set_file_name(stem);
5387                     dest_path.push("mod.rs");
5388                     err.span_note(id_sp,
5389                                   &format!("maybe move this module `{}` to its own \
5390                                             directory via `{}`", src_path.to_string_lossy(),
5391                                            dest_path.to_string_lossy()));
5392                 }
5393             }
5394             if paths.path_exists {
5395                 err.span_note(id_sp,
5396                               &format!("... or maybe `use` the module `{}` instead \
5397                                         of possibly redeclaring it",
5398                                        paths.name));
5399             }
5400             Err(err)
5401         } else {
5402             paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5403         }
5404     }
5405
5406     /// Read a module from a source file.
5407     fn eval_src_mod(&mut self,
5408                     path: PathBuf,
5409                     directory_ownership: DirectoryOwnership,
5410                     name: String,
5411                     id_sp: Span)
5412                     -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5413         let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5414         if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5415             let mut err = String::from("circular modules: ");
5416             let len = included_mod_stack.len();
5417             for p in &included_mod_stack[i.. len] {
5418                 err.push_str(&p.to_string_lossy());
5419                 err.push_str(" -> ");
5420             }
5421             err.push_str(&path.to_string_lossy());
5422             return Err(self.span_fatal(id_sp, &err[..]));
5423         }
5424         included_mod_stack.push(path.clone());
5425         drop(included_mod_stack);
5426
5427         let mut p0 =
5428             new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5429         p0.cfg_mods = self.cfg_mods;
5430         let mod_inner_lo = p0.span;
5431         let mod_attrs = p0.parse_inner_attributes()?;
5432         let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5433         self.sess.included_mod_stack.borrow_mut().pop();
5434         Ok((ast::ItemKind::Mod(m0), mod_attrs))
5435     }
5436
5437     /// Parse a function declaration from a foreign module
5438     fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5439                              -> PResult<'a, ForeignItem> {
5440         self.expect_keyword(keywords::Fn)?;
5441
5442         let (ident, mut generics) = self.parse_fn_header()?;
5443         let decl = self.parse_fn_decl(true)?;
5444         generics.where_clause = self.parse_where_clause()?;
5445         let hi = self.span;
5446         self.expect(&token::Semi)?;
5447         Ok(ast::ForeignItem {
5448             ident: ident,
5449             attrs: attrs,
5450             node: ForeignItemKind::Fn(decl, generics),
5451             id: ast::DUMMY_NODE_ID,
5452             span: lo.to(hi),
5453             vis: vis
5454         })
5455     }
5456
5457     /// Parse a static item from a foreign module
5458     fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5459                                  -> PResult<'a, ForeignItem> {
5460         self.expect_keyword(keywords::Static)?;
5461         let mutbl = self.eat_keyword(keywords::Mut);
5462
5463         let ident = self.parse_ident()?;
5464         self.expect(&token::Colon)?;
5465         let ty = self.parse_ty()?;
5466         let hi = self.span;
5467         self.expect(&token::Semi)?;
5468         Ok(ForeignItem {
5469             ident: ident,
5470             attrs: attrs,
5471             node: ForeignItemKind::Static(ty, mutbl),
5472             id: ast::DUMMY_NODE_ID,
5473             span: lo.to(hi),
5474             vis: vis
5475         })
5476     }
5477
5478     /// Parse extern crate links
5479     ///
5480     /// # Examples
5481     ///
5482     /// extern crate foo;
5483     /// extern crate bar as foo;
5484     fn parse_item_extern_crate(&mut self,
5485                                lo: Span,
5486                                visibility: Visibility,
5487                                attrs: Vec<Attribute>)
5488                                 -> PResult<'a, P<Item>> {
5489
5490         let crate_name = self.parse_ident()?;
5491         let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
5492             (Some(crate_name.name), ident)
5493         } else {
5494             (None, crate_name)
5495         };
5496         self.expect(&token::Semi)?;
5497
5498         let prev_span = self.prev_span;
5499         Ok(self.mk_item(lo.to(prev_span),
5500                         ident,
5501                         ItemKind::ExternCrate(maybe_path),
5502                         visibility,
5503                         attrs))
5504     }
5505
5506     /// Parse `extern` for foreign ABIs
5507     /// modules.
5508     ///
5509     /// `extern` is expected to have been
5510     /// consumed before calling this method
5511     ///
5512     /// # Examples:
5513     ///
5514     /// extern "C" {}
5515     /// extern {}
5516     fn parse_item_foreign_mod(&mut self,
5517                               lo: Span,
5518                               opt_abi: Option<abi::Abi>,
5519                               visibility: Visibility,
5520                               mut attrs: Vec<Attribute>)
5521                               -> PResult<'a, P<Item>> {
5522         self.expect(&token::OpenDelim(token::Brace))?;
5523
5524         let abi = opt_abi.unwrap_or(Abi::C);
5525
5526         attrs.extend(self.parse_inner_attributes()?);
5527
5528         let mut foreign_items = vec![];
5529         while let Some(item) = self.parse_foreign_item()? {
5530             foreign_items.push(item);
5531         }
5532         self.expect(&token::CloseDelim(token::Brace))?;
5533
5534         let prev_span = self.prev_span;
5535         let m = ast::ForeignMod {
5536             abi: abi,
5537             items: foreign_items
5538         };
5539         let invalid = keywords::Invalid.ident();
5540         Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
5541     }
5542
5543     /// Parse type Foo = Bar;
5544     fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5545         let ident = self.parse_ident()?;
5546         let mut tps = self.parse_generics()?;
5547         tps.where_clause = self.parse_where_clause()?;
5548         self.expect(&token::Eq)?;
5549         let ty = self.parse_ty()?;
5550         self.expect(&token::Semi)?;
5551         Ok((ident, ItemKind::Ty(ty, tps), None))
5552     }
5553
5554     /// Parse the part of an "enum" decl following the '{'
5555     fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5556         let mut variants = Vec::new();
5557         let mut all_nullary = true;
5558         let mut any_disr = None;
5559         while self.token != token::CloseDelim(token::Brace) {
5560             let variant_attrs = self.parse_outer_attributes()?;
5561             let vlo = self.span;
5562
5563             let struct_def;
5564             let mut disr_expr = None;
5565             let ident = self.parse_ident()?;
5566             if self.check(&token::OpenDelim(token::Brace)) {
5567                 // Parse a struct variant.
5568                 all_nullary = false;
5569                 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
5570                                                  ast::DUMMY_NODE_ID);
5571             } else if self.check(&token::OpenDelim(token::Paren)) {
5572                 all_nullary = false;
5573                 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
5574                                                 ast::DUMMY_NODE_ID);
5575             } else if self.eat(&token::Eq) {
5576                 disr_expr = Some(self.parse_expr()?);
5577                 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5578                 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5579             } else {
5580                 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5581             }
5582
5583             let vr = ast::Variant_ {
5584                 name: ident,
5585                 attrs: variant_attrs,
5586                 data: struct_def,
5587                 disr_expr: disr_expr,
5588             };
5589             variants.push(respan(vlo.to(self.prev_span), vr));
5590
5591             if !self.eat(&token::Comma) { break; }
5592         }
5593         self.expect(&token::CloseDelim(token::Brace))?;
5594         match any_disr {
5595             Some(disr_span) if !all_nullary =>
5596                 self.span_err(disr_span,
5597                     "discriminator values can only be used with a c-like enum"),
5598             _ => ()
5599         }
5600
5601         Ok(ast::EnumDef { variants: variants })
5602     }
5603
5604     /// Parse an "enum" declaration
5605     fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5606         let id = self.parse_ident()?;
5607         let mut generics = self.parse_generics()?;
5608         generics.where_clause = self.parse_where_clause()?;
5609         self.expect(&token::OpenDelim(token::Brace))?;
5610
5611         let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
5612             self.recover_stmt();
5613             self.eat(&token::CloseDelim(token::Brace));
5614             e
5615         })?;
5616         Ok((id, ItemKind::Enum(enum_definition, generics), None))
5617     }
5618
5619     /// Parses a string as an ABI spec on an extern type or module. Consumes
5620     /// the `extern` keyword, if one is found.
5621     fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5622         match self.token {
5623             token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5624                 let sp = self.span;
5625                 self.expect_no_suffix(sp, "ABI spec", suf);
5626                 self.bump();
5627                 match abi::lookup(&s.as_str()) {
5628                     Some(abi) => Ok(Some(abi)),
5629                     None => {
5630                         let prev_span = self.prev_span;
5631                         self.span_err(
5632                             prev_span,
5633                             &format!("invalid ABI: expected one of [{}], \
5634                                      found `{}`",
5635                                     abi::all_names().join(", "),
5636                                     s));
5637                         Ok(None)
5638                     }
5639                 }
5640             }
5641
5642             _ => Ok(None),
5643         }
5644     }
5645
5646     /// Parse one of the items allowed by the flags.
5647     /// NB: this function no longer parses the items inside an
5648     /// extern crate.
5649     fn parse_item_(&mut self, attrs: Vec<Attribute>,
5650                    macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5651         maybe_whole!(self, NtItem, |item| {
5652             let mut item = item.unwrap();
5653             let mut attrs = attrs;
5654             mem::swap(&mut item.attrs, &mut attrs);
5655             item.attrs.extend(attrs);
5656             Some(P(item))
5657         });
5658
5659         let lo = self.span;
5660
5661         let visibility = self.parse_visibility(false)?;
5662
5663         if self.eat_keyword(keywords::Use) {
5664             // USE ITEM
5665             let item_ = ItemKind::Use(self.parse_view_path()?);
5666             self.expect(&token::Semi)?;
5667
5668             let prev_span = self.prev_span;
5669             let invalid = keywords::Invalid.ident();
5670             let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
5671             return Ok(Some(item));
5672         }
5673
5674         if self.eat_keyword(keywords::Extern) {
5675             if self.eat_keyword(keywords::Crate) {
5676                 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
5677             }
5678
5679             let opt_abi = self.parse_opt_abi()?;
5680
5681             if self.eat_keyword(keywords::Fn) {
5682                 // EXTERN FUNCTION ITEM
5683                 let fn_span = self.prev_span;
5684                 let abi = opt_abi.unwrap_or(Abi::C);
5685                 let (ident, item_, extra_attrs) =
5686                     self.parse_item_fn(Unsafety::Normal,
5687                                        respan(fn_span, Constness::NotConst),
5688                                        abi)?;
5689                 let prev_span = self.prev_span;
5690                 let item = self.mk_item(lo.to(prev_span),
5691                                         ident,
5692                                         item_,
5693                                         visibility,
5694                                         maybe_append(attrs, extra_attrs));
5695                 return Ok(Some(item));
5696             } else if self.check(&token::OpenDelim(token::Brace)) {
5697                 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
5698             }
5699
5700             self.unexpected()?;
5701         }
5702
5703         if self.eat_keyword(keywords::Static) {
5704             // STATIC ITEM
5705             let m = if self.eat_keyword(keywords::Mut) {
5706                 Mutability::Mutable
5707             } else {
5708                 Mutability::Immutable
5709             };
5710             let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
5711             let prev_span = self.prev_span;
5712             let item = self.mk_item(lo.to(prev_span),
5713                                     ident,
5714                                     item_,
5715                                     visibility,
5716                                     maybe_append(attrs, extra_attrs));
5717             return Ok(Some(item));
5718         }
5719         if self.eat_keyword(keywords::Const) {
5720             let const_span = self.prev_span;
5721             if self.check_keyword(keywords::Fn)
5722                 || (self.check_keyword(keywords::Unsafe)
5723                     && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5724                 // CONST FUNCTION ITEM
5725                 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5726                     Unsafety::Unsafe
5727                 } else {
5728                     Unsafety::Normal
5729                 };
5730                 self.bump();
5731                 let (ident, item_, extra_attrs) =
5732                     self.parse_item_fn(unsafety,
5733                                        respan(const_span, Constness::Const),
5734                                        Abi::Rust)?;
5735                 let prev_span = self.prev_span;
5736                 let item = self.mk_item(lo.to(prev_span),
5737                                         ident,
5738                                         item_,
5739                                         visibility,
5740                                         maybe_append(attrs, extra_attrs));
5741                 return Ok(Some(item));
5742             }
5743
5744             // CONST ITEM
5745             if self.eat_keyword(keywords::Mut) {
5746                 let prev_span = self.prev_span;
5747                 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
5748                                  .help("did you mean to declare a static?")
5749                                  .emit();
5750             }
5751             let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
5752             let prev_span = self.prev_span;
5753             let item = self.mk_item(lo.to(prev_span),
5754                                     ident,
5755                                     item_,
5756                                     visibility,
5757                                     maybe_append(attrs, extra_attrs));
5758             return Ok(Some(item));
5759         }
5760         if self.check_keyword(keywords::Unsafe) &&
5761             self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5762         {
5763             // UNSAFE TRAIT ITEM
5764             self.expect_keyword(keywords::Unsafe)?;
5765             self.expect_keyword(keywords::Trait)?;
5766             let (ident, item_, extra_attrs) =
5767                 self.parse_item_trait(ast::Unsafety::Unsafe)?;
5768             let prev_span = self.prev_span;
5769             let item = self.mk_item(lo.to(prev_span),
5770                                     ident,
5771                                     item_,
5772                                     visibility,
5773                                     maybe_append(attrs, extra_attrs));
5774             return Ok(Some(item));
5775         }
5776         if (self.check_keyword(keywords::Unsafe) &&
5777             self.look_ahead(1, |t| t.is_keyword(keywords::Impl))) ||
5778            (self.check_keyword(keywords::Default) &&
5779             self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) &&
5780             self.look_ahead(2, |t| t.is_keyword(keywords::Impl)))
5781         {
5782             // IMPL ITEM
5783             let defaultness = self.parse_defaultness()?;
5784             self.expect_keyword(keywords::Unsafe)?;
5785             self.expect_keyword(keywords::Impl)?;
5786             let (ident,
5787                  item_,
5788                  extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe, defaultness)?;
5789             let prev_span = self.prev_span;
5790             let item = self.mk_item(lo.to(prev_span),
5791                                     ident,
5792                                     item_,
5793                                     visibility,
5794                                     maybe_append(attrs, extra_attrs));
5795             return Ok(Some(item));
5796         }
5797         if self.check_keyword(keywords::Fn) {
5798             // FUNCTION ITEM
5799             self.bump();
5800             let fn_span = self.prev_span;
5801             let (ident, item_, extra_attrs) =
5802                 self.parse_item_fn(Unsafety::Normal,
5803                                    respan(fn_span, Constness::NotConst),
5804                                    Abi::Rust)?;
5805             let prev_span = self.prev_span;
5806             let item = self.mk_item(lo.to(prev_span),
5807                                     ident,
5808                                     item_,
5809                                     visibility,
5810                                     maybe_append(attrs, extra_attrs));
5811             return Ok(Some(item));
5812         }
5813         if self.check_keyword(keywords::Unsafe)
5814             && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5815             // UNSAFE FUNCTION ITEM
5816             self.bump();
5817             let abi = if self.eat_keyword(keywords::Extern) {
5818                 self.parse_opt_abi()?.unwrap_or(Abi::C)
5819             } else {
5820                 Abi::Rust
5821             };
5822             self.expect_keyword(keywords::Fn)?;
5823             let fn_span = self.prev_span;
5824             let (ident, item_, extra_attrs) =
5825                 self.parse_item_fn(Unsafety::Unsafe,
5826                                    respan(fn_span, Constness::NotConst),
5827                                    abi)?;
5828             let prev_span = self.prev_span;
5829             let item = self.mk_item(lo.to(prev_span),
5830                                     ident,
5831                                     item_,
5832                                     visibility,
5833                                     maybe_append(attrs, extra_attrs));
5834             return Ok(Some(item));
5835         }
5836         if self.eat_keyword(keywords::Mod) {
5837             // MODULE ITEM
5838             let (ident, item_, extra_attrs) =
5839                 self.parse_item_mod(&attrs[..])?;
5840             let prev_span = self.prev_span;
5841             let item = self.mk_item(lo.to(prev_span),
5842                                     ident,
5843                                     item_,
5844                                     visibility,
5845                                     maybe_append(attrs, extra_attrs));
5846             return Ok(Some(item));
5847         }
5848         if self.eat_keyword(keywords::Type) {
5849             // TYPE ITEM
5850             let (ident, item_, extra_attrs) = self.parse_item_type()?;
5851             let prev_span = self.prev_span;
5852             let item = self.mk_item(lo.to(prev_span),
5853                                     ident,
5854                                     item_,
5855                                     visibility,
5856                                     maybe_append(attrs, extra_attrs));
5857             return Ok(Some(item));
5858         }
5859         if self.eat_keyword(keywords::Enum) {
5860             // ENUM ITEM
5861             let (ident, item_, extra_attrs) = self.parse_item_enum()?;
5862             let prev_span = self.prev_span;
5863             let item = self.mk_item(lo.to(prev_span),
5864                                     ident,
5865                                     item_,
5866                                     visibility,
5867                                     maybe_append(attrs, extra_attrs));
5868             return Ok(Some(item));
5869         }
5870         if self.eat_keyword(keywords::Trait) {
5871             // TRAIT ITEM
5872             let (ident, item_, extra_attrs) =
5873                 self.parse_item_trait(ast::Unsafety::Normal)?;
5874             let prev_span = self.prev_span;
5875             let item = self.mk_item(lo.to(prev_span),
5876                                     ident,
5877                                     item_,
5878                                     visibility,
5879                                     maybe_append(attrs, extra_attrs));
5880             return Ok(Some(item));
5881         }
5882         if (self.check_keyword(keywords::Impl)) ||
5883            (self.check_keyword(keywords::Default) &&
5884             self.look_ahead(1, |t| t.is_keyword(keywords::Impl)))
5885         {
5886             // IMPL ITEM
5887             let defaultness = self.parse_defaultness()?;
5888             self.expect_keyword(keywords::Impl)?;
5889             let (ident,
5890                  item_,
5891                  extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal, defaultness)?;
5892             let prev_span = self.prev_span;
5893             let item = self.mk_item(lo.to(prev_span),
5894                                     ident,
5895                                     item_,
5896                                     visibility,
5897                                     maybe_append(attrs, extra_attrs));
5898             return Ok(Some(item));
5899         }
5900         if self.eat_keyword(keywords::Struct) {
5901             // STRUCT ITEM
5902             let (ident, item_, extra_attrs) = self.parse_item_struct()?;
5903             let prev_span = self.prev_span;
5904             let item = self.mk_item(lo.to(prev_span),
5905                                     ident,
5906                                     item_,
5907                                     visibility,
5908                                     maybe_append(attrs, extra_attrs));
5909             return Ok(Some(item));
5910         }
5911         if self.is_union_item() {
5912             // UNION ITEM
5913             self.bump();
5914             let (ident, item_, extra_attrs) = self.parse_item_union()?;
5915             let prev_span = self.prev_span;
5916             let item = self.mk_item(lo.to(prev_span),
5917                                     ident,
5918                                     item_,
5919                                     visibility,
5920                                     maybe_append(attrs, extra_attrs));
5921             return Ok(Some(item));
5922         }
5923         if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility)? {
5924             return Ok(Some(macro_def));
5925         }
5926
5927         self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5928     }
5929
5930     /// Parse a foreign item.
5931     fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
5932         let attrs = self.parse_outer_attributes()?;
5933         let lo = self.span;
5934         let visibility = self.parse_visibility(false)?;
5935
5936         if self.check_keyword(keywords::Static) {
5937             // FOREIGN STATIC ITEM
5938             return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
5939         }
5940         if self.check_keyword(keywords::Fn) {
5941             // FOREIGN FUNCTION ITEM
5942             return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
5943         }
5944
5945         // FIXME #5668: this will occur for a macro invocation:
5946         match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
5947             Some(item) => {
5948                 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5949             }
5950             None => Ok(None)
5951         }
5952     }
5953
5954     /// This is the fall-through for parsing items.
5955     fn parse_macro_use_or_failure(
5956         &mut self,
5957         attrs: Vec<Attribute> ,
5958         macros_allowed: bool,
5959         attributes_allowed: bool,
5960         lo: Span,
5961         visibility: Visibility
5962     ) -> PResult<'a, Option<P<Item>>> {
5963         if macros_allowed && self.token.is_path_start() {
5964             // MACRO INVOCATION ITEM
5965
5966             let prev_span = self.prev_span;
5967             self.complain_if_pub_macro(&visibility, prev_span);
5968
5969             let mac_lo = self.span;
5970
5971             // item macro.
5972             let pth = self.parse_path(PathStyle::Mod)?;
5973             self.expect(&token::Not)?;
5974
5975             // a 'special' identifier (like what `macro_rules!` uses)
5976             // is optional. We should eventually unify invoc syntax
5977             // and remove this.
5978             let id = if self.token.is_ident() {
5979                 self.parse_ident()?
5980             } else {
5981                 keywords::Invalid.ident() // no special identifier
5982             };
5983             // eat a matched-delimiter token tree:
5984             let (delim, tts) = self.expect_delimited_token_tree()?;
5985             if delim != token::Brace {
5986                 if !self.eat(&token::Semi) {
5987                     let prev_span = self.prev_span;
5988                     self.span_err(prev_span,
5989                                   "macros that expand to items must either \
5990                                    be surrounded with braces or followed by \
5991                                    a semicolon");
5992                 }
5993             }
5994
5995             let hi = self.prev_span;
5996             let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
5997             let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
5998             return Ok(Some(item));
5999         }
6000
6001         // FAILURE TO PARSE ITEM
6002         match visibility {
6003             Visibility::Inherited => {}
6004             _ => {
6005                 let prev_span = self.prev_span;
6006                 return Err(self.span_fatal(prev_span, "unmatched visibility `pub`"));
6007             }
6008         }
6009
6010         if !attributes_allowed && !attrs.is_empty() {
6011             self.expected_item_err(&attrs);
6012         }
6013         Ok(None)
6014     }
6015
6016     pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6017         let attrs = self.parse_outer_attributes()?;
6018         self.parse_item_(attrs, true, false)
6019     }
6020
6021     fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> {
6022         self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
6023                                  &token::CloseDelim(token::Brace),
6024                                  SeqSep::trailing_allowed(token::Comma), |this| {
6025             let lo = this.span;
6026             let ident = if this.eat_keyword(keywords::SelfValue) {
6027                 keywords::SelfValue.ident()
6028             } else {
6029                 this.parse_ident()?
6030             };
6031             let rename = this.parse_rename()?;
6032             let node = ast::PathListItem_ {
6033                 name: ident,
6034                 rename: rename,
6035                 id: ast::DUMMY_NODE_ID
6036             };
6037             Ok(respan(lo.to(this.prev_span), node))
6038         })
6039     }
6040
6041     /// `::{` or `::*`
6042     fn is_import_coupler(&mut self) -> bool {
6043         self.check(&token::ModSep) &&
6044             self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6045                                    *t == token::BinOp(token::Star))
6046     }
6047
6048     /// Matches ViewPath:
6049     /// MOD_SEP? non_global_path
6050     /// MOD_SEP? non_global_path as IDENT
6051     /// MOD_SEP? non_global_path MOD_SEP STAR
6052     /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE
6053     /// MOD_SEP? LBRACE item_seq RBRACE
6054     fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
6055         let lo = self.span;
6056         if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) ||
6057            self.is_import_coupler() {
6058             // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`.
6059             self.eat(&token::ModSep);
6060             let prefix = ast::Path {
6061                 segments: vec![PathSegment::crate_root()],
6062                 span: lo.to(self.span),
6063             };
6064             let view_path_kind = if self.eat(&token::BinOp(token::Star)) {
6065                 ViewPathGlob(prefix)
6066             } else {
6067                 ViewPathList(prefix, self.parse_path_list_items()?)
6068             };
6069             Ok(P(respan(lo.to(self.span), view_path_kind)))
6070         } else {
6071             let prefix = self.parse_path(PathStyle::Mod)?.default_to_global();
6072             if self.is_import_coupler() {
6073                 // `foo::bar::{a, b}` or `foo::bar::*`
6074                 self.bump();
6075                 if self.check(&token::BinOp(token::Star)) {
6076                     self.bump();
6077                     Ok(P(respan(lo.to(self.span), ViewPathGlob(prefix))))
6078                 } else {
6079                     let items = self.parse_path_list_items()?;
6080                     Ok(P(respan(lo.to(self.span), ViewPathList(prefix, items))))
6081                 }
6082             } else {
6083                 // `foo::bar` or `foo::bar as baz`
6084                 let rename = self.parse_rename()?.
6085                                   unwrap_or(prefix.segments.last().unwrap().identifier);
6086                 Ok(P(respan(lo.to(self.prev_span), ViewPathSimple(rename, prefix))))
6087             }
6088         }
6089     }
6090
6091     fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6092         if self.eat_keyword(keywords::As) {
6093             self.parse_ident().map(Some)
6094         } else {
6095             Ok(None)
6096         }
6097     }
6098
6099     /// Parses a source module as a crate. This is the main
6100     /// entry point for the parser.
6101     pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6102         let lo = self.span;
6103         Ok(ast::Crate {
6104             attrs: self.parse_inner_attributes()?,
6105             module: self.parse_mod_items(&token::Eof, lo)?,
6106             span: lo.to(self.span),
6107         })
6108     }
6109
6110     pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6111         let ret = match self.token {
6112             token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6113             token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6114             _ => return None
6115         };
6116         self.bump();
6117         Some(ret)
6118     }
6119
6120     pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6121         match self.parse_optional_str() {
6122             Some((s, style, suf)) => {
6123                 let sp = self.prev_span;
6124                 self.expect_no_suffix(sp, "string literal", suf);
6125                 Ok((s, style))
6126             }
6127             _ =>  Err(self.fatal("expected string literal"))
6128         }
6129     }
6130 }