]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/parser.rs
c09ddb4d1c9e039a9cc98654183867fe6667cef1
[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<'a>(self, sp: Span, handler: &'a errors::Handler) -> DiagnosticBuilder<'a> {
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 = match self.desugar_doc_comments {
482             true => self.token_cursor.next_desugared(),
483             false => self.token_cursor.next(),
484         };
485         if next.sp == syntax_pos::DUMMY_SP {
486             next.sp = self.prev_span;
487         }
488         next
489     }
490
491     /// Convert a token to a string using self's reader
492     pub fn token_to_string(token: &token::Token) -> String {
493         pprust::token_to_string(token)
494     }
495
496     /// Convert the current token to a string using self's reader
497     pub fn this_token_to_string(&self) -> String {
498         Parser::token_to_string(&self.token)
499     }
500
501     pub fn this_token_descr(&self) -> String {
502         let s = self.this_token_to_string();
503         if self.token.is_strict_keyword() {
504             format!("keyword `{}`", s)
505         } else if self.token.is_reserved_keyword() {
506             format!("reserved keyword `{}`", s)
507         } else {
508             format!("`{}`", s)
509         }
510     }
511
512     pub fn unexpected_last<T>(&self, t: &token::Token) -> PResult<'a, T> {
513         let token_str = Parser::token_to_string(t);
514         Err(self.span_fatal(self.prev_span, &format!("unexpected token: `{}`", token_str)))
515     }
516
517     pub fn unexpected<T>(&mut self) -> PResult<'a, T> {
518         match self.expect_one_of(&[], &[]) {
519             Err(e) => Err(e),
520             Ok(_) => unreachable!(),
521         }
522     }
523
524     /// Expect and consume the token t. Signal an error if
525     /// the next token is not t.
526     pub fn expect(&mut self, t: &token::Token) -> PResult<'a,  ()> {
527         if self.expected_tokens.is_empty() {
528             if self.token == *t {
529                 self.bump();
530                 Ok(())
531             } else {
532                 let token_str = Parser::token_to_string(t);
533                 let this_token_str = self.this_token_to_string();
534                 Err(self.fatal(&format!("expected `{}`, found `{}`",
535                                    token_str,
536                                    this_token_str)))
537             }
538         } else {
539             self.expect_one_of(unsafe { slice::from_raw_parts(t, 1) }, &[])
540         }
541     }
542
543     /// Expect next token to be edible or inedible token.  If edible,
544     /// then consume it; if inedible, then return without consuming
545     /// anything.  Signal a fatal error if next token is unexpected.
546     pub fn expect_one_of(&mut self,
547                          edible: &[token::Token],
548                          inedible: &[token::Token]) -> PResult<'a,  ()>{
549         fn tokens_to_string(tokens: &[TokenType]) -> String {
550             let mut i = tokens.iter();
551             // This might be a sign we need a connect method on Iterator.
552             let b = i.next()
553                      .map_or("".to_string(), |t| t.to_string());
554             i.enumerate().fold(b, |mut b, (i, ref a)| {
555                 if tokens.len() > 2 && i == tokens.len() - 2 {
556                     b.push_str(", or ");
557                 } else if tokens.len() == 2 && i == tokens.len() - 2 {
558                     b.push_str(" or ");
559                 } else {
560                     b.push_str(", ");
561                 }
562                 b.push_str(&a.to_string());
563                 b
564             })
565         }
566         if edible.contains(&self.token) {
567             self.bump();
568             Ok(())
569         } else if inedible.contains(&self.token) {
570             // leave it in the input
571             Ok(())
572         } else {
573             let mut expected = edible.iter()
574                 .map(|x| TokenType::Token(x.clone()))
575                 .chain(inedible.iter().map(|x| TokenType::Token(x.clone())))
576                 .chain(self.expected_tokens.iter().cloned())
577                 .collect::<Vec<_>>();
578             expected.sort_by(|a, b| a.to_string().cmp(&b.to_string()));
579             expected.dedup();
580             let expect = tokens_to_string(&expected[..]);
581             let actual = self.this_token_to_string();
582             let (msg_exp, (label_sp, label_exp)) = if expected.len() > 1 {
583                 let short_expect = if expected.len() > 6 {
584                     format!("{} possible tokens", expected.len())
585                 } else {
586                     expect.clone()
587                 };
588                 (format!("expected one of {}, found `{}`", expect, actual),
589                  (self.prev_span.next_point(), format!("expected one of {} here", short_expect)))
590             } else if expected.is_empty() {
591                 (format!("unexpected token: `{}`", actual),
592                  (self.prev_span, "unexpected token after this".to_string()))
593             } else {
594                 (format!("expected {}, found `{}`", expect, actual),
595                  (self.prev_span.next_point(), format!("expected {} here", expect)))
596             };
597             let mut err = self.fatal(&msg_exp);
598             let sp = if self.token == token::Token::Eof {
599                 // This is EOF, don't want to point at the following char, but rather the last token
600                 self.prev_span
601             } else {
602                 label_sp
603             };
604             if self.span.contains(sp) {
605                 err.span_label(self.span, &label_exp);
606             } else {
607                 err.span_label(sp, &label_exp);
608                 err.span_label(self.span, &"unexpected token");
609             }
610             Err(err)
611         }
612     }
613
614     /// returns the span of expr, if it was not interpolated or the span of the interpolated token
615     fn interpolated_or_expr_span(&self,
616                                  expr: PResult<'a, P<Expr>>)
617                                  -> PResult<'a, (Span, P<Expr>)> {
618         expr.map(|e| {
619             if self.prev_token_kind == PrevTokenKind::Interpolated {
620                 (self.prev_span, e)
621             } else {
622                 (e.span, e)
623             }
624         })
625     }
626
627     pub fn parse_ident(&mut self) -> PResult<'a, ast::Ident> {
628         self.check_strict_keywords();
629         self.check_reserved_keywords();
630         match self.token {
631             token::Ident(i) => {
632                 self.bump();
633                 Ok(i)
634             }
635             _ => {
636                 Err(if self.prev_token_kind == PrevTokenKind::DocComment {
637                         self.span_fatal_err(self.prev_span, Error::UselessDocComment)
638                     } else {
639                         let mut err = self.fatal(&format!("expected identifier, found `{}`",
640                                                           self.this_token_to_string()));
641                         if self.token == token::Underscore {
642                             err.note("`_` is a wildcard pattern, not an identifier");
643                         }
644                         err
645                     })
646             }
647         }
648     }
649
650     /// Check if the next token is `tok`, and return `true` if so.
651     ///
652     /// This method will automatically add `tok` to `expected_tokens` if `tok` is not
653     /// encountered.
654     pub fn check(&mut self, tok: &token::Token) -> bool {
655         let is_present = self.token == *tok;
656         if !is_present { self.expected_tokens.push(TokenType::Token(tok.clone())); }
657         is_present
658     }
659
660     /// Consume token 'tok' if it exists. Returns true if the given
661     /// token was present, false otherwise.
662     pub fn eat(&mut self, tok: &token::Token) -> bool {
663         let is_present = self.check(tok);
664         if is_present { self.bump() }
665         is_present
666     }
667
668     pub fn check_keyword(&mut self, kw: keywords::Keyword) -> bool {
669         self.expected_tokens.push(TokenType::Keyword(kw));
670         self.token.is_keyword(kw)
671     }
672
673     /// If the next token is the given keyword, eat it and return
674     /// true. Otherwise, return false.
675     pub fn eat_keyword(&mut self, kw: keywords::Keyword) -> bool {
676         if self.check_keyword(kw) {
677             self.bump();
678             true
679         } else {
680             false
681         }
682     }
683
684     pub fn eat_keyword_noexpect(&mut self, kw: keywords::Keyword) -> bool {
685         if self.token.is_keyword(kw) {
686             self.bump();
687             true
688         } else {
689             false
690         }
691     }
692
693     pub fn check_contextual_keyword(&mut self, ident: Ident) -> bool {
694         self.expected_tokens.push(TokenType::Token(token::Ident(ident)));
695         if let token::Ident(ref cur_ident) = self.token {
696             cur_ident.name == ident.name
697         } else {
698             false
699         }
700     }
701
702     pub fn eat_contextual_keyword(&mut self, ident: Ident) -> bool {
703         if self.check_contextual_keyword(ident) {
704             self.bump();
705             true
706         } else {
707             false
708         }
709     }
710
711     /// If the given word is not a keyword, signal an error.
712     /// If the next token is not the given word, signal an error.
713     /// Otherwise, eat it.
714     pub fn expect_keyword(&mut self, kw: keywords::Keyword) -> PResult<'a, ()> {
715         if !self.eat_keyword(kw) {
716             self.unexpected()
717         } else {
718             Ok(())
719         }
720     }
721
722     /// Signal an error if the given string is a strict keyword
723     pub fn check_strict_keywords(&mut self) {
724         if self.token.is_strict_keyword() {
725             let token_str = self.this_token_to_string();
726             let span = self.span;
727             self.span_err(span,
728                           &format!("expected identifier, found keyword `{}`",
729                                   token_str));
730         }
731     }
732
733     /// Signal an error if the current token is a reserved keyword
734     pub fn check_reserved_keywords(&mut self) {
735         if self.token.is_reserved_keyword() {
736             let token_str = self.this_token_to_string();
737             self.fatal(&format!("`{}` is a reserved keyword", token_str)).emit()
738         }
739     }
740
741     fn check_ident(&mut self) -> bool {
742         if self.token.is_ident() {
743             true
744         } else {
745             self.expected_tokens.push(TokenType::Ident);
746             false
747         }
748     }
749
750     fn check_path(&mut self) -> bool {
751         if self.token.is_path_start() {
752             true
753         } else {
754             self.expected_tokens.push(TokenType::Path);
755             false
756         }
757     }
758
759     fn check_type(&mut self) -> bool {
760         if self.token.can_begin_type() {
761             true
762         } else {
763             self.expected_tokens.push(TokenType::Type);
764             false
765         }
766     }
767
768     /// Expect and consume an `&`. If `&&` is seen, replace it with a single
769     /// `&` and continue. If an `&` is not seen, signal an error.
770     fn expect_and(&mut self) -> PResult<'a, ()> {
771         self.expected_tokens.push(TokenType::Token(token::BinOp(token::And)));
772         match self.token {
773             token::BinOp(token::And) => {
774                 self.bump();
775                 Ok(())
776             }
777             token::AndAnd => {
778                 let span = self.span;
779                 let lo = span.lo + BytePos(1);
780                 Ok(self.bump_with(token::BinOp(token::And), Span { lo: lo, ..span }))
781             }
782             _ => self.unexpected()
783         }
784     }
785
786     pub fn expect_no_suffix(&self, sp: Span, kind: &str, suffix: Option<ast::Name>) {
787         match suffix {
788             None => {/* everything ok */}
789             Some(suf) => {
790                 let text = suf.as_str();
791                 if text.is_empty() {
792                     self.span_bug(sp, "found empty literal suffix in Some")
793                 }
794                 self.span_err(sp, &format!("{} with a suffix is invalid", kind));
795             }
796         }
797     }
798
799     /// Attempt to consume a `<`. If `<<` is seen, replace it with a single
800     /// `<` and continue. If a `<` is not seen, return false.
801     ///
802     /// This is meant to be used when parsing generics on a path to get the
803     /// starting token.
804     fn eat_lt(&mut self) -> bool {
805         self.expected_tokens.push(TokenType::Token(token::Lt));
806         match self.token {
807             token::Lt => {
808                 self.bump();
809                 true
810             }
811             token::BinOp(token::Shl) => {
812                 let span = self.span;
813                 let lo = span.lo + BytePos(1);
814                 self.bump_with(token::Lt, Span { lo: lo, ..span });
815                 true
816             }
817             _ => false,
818         }
819     }
820
821     fn expect_lt(&mut self) -> PResult<'a, ()> {
822         if !self.eat_lt() {
823             self.unexpected()
824         } else {
825             Ok(())
826         }
827     }
828
829     /// Expect and consume a GT. if a >> is seen, replace it
830     /// with a single > and continue. If a GT is not seen,
831     /// signal an error.
832     pub fn expect_gt(&mut self) -> PResult<'a, ()> {
833         self.expected_tokens.push(TokenType::Token(token::Gt));
834         match self.token {
835             token::Gt => {
836                 self.bump();
837                 Ok(())
838             }
839             token::BinOp(token::Shr) => {
840                 let span = self.span;
841                 let lo = span.lo + BytePos(1);
842                 Ok(self.bump_with(token::Gt, Span { lo: lo, ..span }))
843             }
844             token::BinOpEq(token::Shr) => {
845                 let span = self.span;
846                 let lo = span.lo + BytePos(1);
847                 Ok(self.bump_with(token::Ge, Span { lo: lo, ..span }))
848             }
849             token::Ge => {
850                 let span = self.span;
851                 let lo = span.lo + BytePos(1);
852                 Ok(self.bump_with(token::Eq, Span { lo: lo, ..span }))
853             }
854             _ => self.unexpected()
855         }
856     }
857
858     pub fn parse_seq_to_before_gt_or_return<T, F>(&mut self,
859                                                   sep: Option<token::Token>,
860                                                   mut f: F)
861                                                   -> PResult<'a, (Vec<T>, bool)>
862         where F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
863     {
864         let mut v = Vec::new();
865         // This loop works by alternating back and forth between parsing types
866         // and commas.  For example, given a string `A, B,>`, the parser would
867         // first parse `A`, then a comma, then `B`, then a comma. After that it
868         // would encounter a `>` and stop. This lets the parser handle trailing
869         // commas in generic parameters, because it can stop either after
870         // parsing a type or after parsing a comma.
871         for i in 0.. {
872             if self.check(&token::Gt)
873                 || self.token == token::BinOp(token::Shr)
874                 || self.token == token::Ge
875                 || self.token == token::BinOpEq(token::Shr) {
876                 break;
877             }
878
879             if i % 2 == 0 {
880                 match f(self)? {
881                     Some(result) => v.push(result),
882                     None => return Ok((v, true))
883                 }
884             } else {
885                 if let Some(t) = sep.as_ref() {
886                     self.expect(t)?;
887                 }
888
889             }
890         }
891         return Ok((v, false));
892     }
893
894     /// Parse a sequence bracketed by '<' and '>', stopping
895     /// before the '>'.
896     pub fn parse_seq_to_before_gt<T, F>(&mut self,
897                                         sep: Option<token::Token>,
898                                         mut f: F)
899                                         -> PResult<'a, Vec<T>> where
900         F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
901     {
902         let (result, returned) = self.parse_seq_to_before_gt_or_return(sep,
903                                                                        |p| Ok(Some(f(p)?)))?;
904         assert!(!returned);
905         return Ok(result);
906     }
907
908     pub fn parse_seq_to_gt<T, F>(&mut self,
909                                  sep: Option<token::Token>,
910                                  f: F)
911                                  -> PResult<'a, Vec<T>> where
912         F: FnMut(&mut Parser<'a>) -> PResult<'a, T>,
913     {
914         let v = self.parse_seq_to_before_gt(sep, f)?;
915         self.expect_gt()?;
916         return Ok(v);
917     }
918
919     pub fn parse_seq_to_gt_or_return<T, F>(&mut self,
920                                            sep: Option<token::Token>,
921                                            f: F)
922                                            -> PResult<'a, (Vec<T>, bool)> where
923         F: FnMut(&mut Parser<'a>) -> PResult<'a, Option<T>>,
924     {
925         let (v, returned) = self.parse_seq_to_before_gt_or_return(sep, f)?;
926         if !returned {
927             self.expect_gt()?;
928         }
929         return Ok((v, returned));
930     }
931
932     /// Eat and discard tokens until one of `kets` is encountered. Respects token trees,
933     /// passes through any errors encountered. Used for error recovery.
934     pub fn eat_to_tokens(&mut self, kets: &[&token::Token]) {
935         let handler = self.diagnostic();
936
937         self.parse_seq_to_before_tokens(kets,
938                                         SeqSep::none(),
939                                         |p| Ok(p.parse_token_tree()),
940                                         |mut e| handler.cancel(&mut e));
941     }
942
943     /// Parse a sequence, including the closing delimiter. The function
944     /// f must consume tokens until reaching the next separator or
945     /// closing bracket.
946     pub fn parse_seq_to_end<T, F>(&mut self,
947                                   ket: &token::Token,
948                                   sep: SeqSep,
949                                   f: F)
950                                   -> PResult<'a, Vec<T>> where
951         F: FnMut(&mut Parser<'a>) -> PResult<'a,  T>,
952     {
953         let val = self.parse_seq_to_before_end(ket, sep, f);
954         self.bump();
955         Ok(val)
956     }
957
958     /// Parse a sequence, not including the closing delimiter. The function
959     /// f must consume tokens until reaching the next separator or
960     /// closing bracket.
961     pub fn parse_seq_to_before_end<T, F>(&mut self,
962                                          ket: &token::Token,
963                                          sep: SeqSep,
964                                          f: F)
965                                          -> Vec<T>
966         where F: FnMut(&mut Parser<'a>) -> PResult<'a,  T>
967     {
968         self.parse_seq_to_before_tokens(&[ket], sep, f, |mut e| e.emit())
969     }
970
971     // `fe` is an error handler.
972     fn parse_seq_to_before_tokens<T, F, Fe>(&mut self,
973                                             kets: &[&token::Token],
974                                             sep: SeqSep,
975                                             mut f: F,
976                                             mut fe: Fe)
977                                             -> Vec<T>
978         where F: FnMut(&mut Parser<'a>) -> PResult<'a,  T>,
979               Fe: FnMut(DiagnosticBuilder)
980     {
981         let mut first: bool = true;
982         let mut v = vec![];
983         while !kets.contains(&&self.token) {
984             match self.token {
985                 token::CloseDelim(..) | token::Eof => break,
986                 _ => {}
987             };
988             match sep.sep {
989                 Some(ref t) => {
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                 _ => ()
1000             }
1001             if sep.trailing_sep_allowed && kets.iter().any(|k| self.check(k)) {
1002                 break;
1003             }
1004
1005             match f(self) {
1006                 Ok(t) => v.push(t),
1007                 Err(e) => {
1008                     fe(e);
1009                     break;
1010                 }
1011             }
1012         }
1013
1014         v
1015     }
1016
1017     /// Parse a sequence, including the closing delimiter. The function
1018     /// f must consume tokens until reaching the next separator or
1019     /// closing bracket.
1020     pub fn parse_unspanned_seq<T, F>(&mut self,
1021                                      bra: &token::Token,
1022                                      ket: &token::Token,
1023                                      sep: SeqSep,
1024                                      f: F)
1025                                      -> PResult<'a, Vec<T>> where
1026         F: FnMut(&mut Parser<'a>) -> PResult<'a,  T>,
1027     {
1028         self.expect(bra)?;
1029         let result = self.parse_seq_to_before_end(ket, sep, f);
1030         if self.token == *ket {
1031             self.bump();
1032         }
1033         Ok(result)
1034     }
1035
1036     // NB: Do not use this function unless you actually plan to place the
1037     // spanned list in the AST.
1038     pub fn parse_seq<T, F>(&mut self,
1039                            bra: &token::Token,
1040                            ket: &token::Token,
1041                            sep: SeqSep,
1042                            f: F)
1043                            -> PResult<'a, Spanned<Vec<T>>> where
1044         F: FnMut(&mut Parser<'a>) -> PResult<'a,  T>,
1045     {
1046         let lo = self.span;
1047         self.expect(bra)?;
1048         let result = self.parse_seq_to_before_end(ket, sep, f);
1049         let hi = self.span;
1050         self.bump();
1051         Ok(respan(lo.to(hi), result))
1052     }
1053
1054     /// Advance the parser by one token
1055     pub fn bump(&mut self) {
1056         if self.prev_token_kind == PrevTokenKind::Eof {
1057             // Bumping after EOF is a bad sign, usually an infinite loop.
1058             self.bug("attempted to bump the parser past EOF (may be stuck in a loop)");
1059         }
1060
1061         self.prev_span = self.meta_var_span.take().unwrap_or(self.span);
1062
1063         // Record last token kind for possible error recovery.
1064         self.prev_token_kind = match self.token {
1065             token::DocComment(..) => PrevTokenKind::DocComment,
1066             token::Comma => PrevTokenKind::Comma,
1067             token::BinOp(token::Plus) => PrevTokenKind::Plus,
1068             token::Interpolated(..) => PrevTokenKind::Interpolated,
1069             token::Eof => PrevTokenKind::Eof,
1070             _ => PrevTokenKind::Other,
1071         };
1072
1073         let next = self.next_tok();
1074         self.span = next.sp;
1075         self.token = next.tok;
1076         self.expected_tokens.clear();
1077         // check after each token
1078         self.process_potential_macro_variable();
1079     }
1080
1081     /// Advance the parser using provided token as a next one. Use this when
1082     /// consuming a part of a token. For example a single `<` from `<<`.
1083     pub fn bump_with(&mut self, next: token::Token, span: Span) {
1084         self.prev_span = Span { hi: span.lo, ..self.span };
1085         // It would be incorrect to record the kind of the current token, but
1086         // fortunately for tokens currently using `bump_with`, the
1087         // prev_token_kind will be of no use anyway.
1088         self.prev_token_kind = PrevTokenKind::Other;
1089         self.span = span;
1090         self.token = next;
1091         self.expected_tokens.clear();
1092     }
1093
1094     pub fn look_ahead<R, F>(&self, dist: usize, f: F) -> R where
1095         F: FnOnce(&token::Token) -> R,
1096     {
1097         if dist == 0 {
1098             return f(&self.token)
1099         }
1100
1101         f(&match self.token_cursor.frame.tree_cursor.look_ahead(dist - 1) {
1102             Some(tree) => match tree {
1103                 TokenTree::Token(_, tok) => tok,
1104                 TokenTree::Delimited(_, delimited) => token::OpenDelim(delimited.delim),
1105             },
1106             None => token::CloseDelim(self.token_cursor.frame.delim),
1107         })
1108     }
1109     pub fn fatal(&self, m: &str) -> DiagnosticBuilder<'a> {
1110         self.sess.span_diagnostic.struct_span_fatal(self.span, m)
1111     }
1112     pub fn span_fatal(&self, sp: Span, m: &str) -> DiagnosticBuilder<'a> {
1113         self.sess.span_diagnostic.struct_span_fatal(sp, m)
1114     }
1115     pub fn span_fatal_err(&self, sp: Span, err: Error) -> DiagnosticBuilder<'a> {
1116         err.span_err(sp, self.diagnostic())
1117     }
1118     pub fn span_fatal_help(&self, sp: Span, m: &str, help: &str) -> DiagnosticBuilder<'a> {
1119         let mut err = self.sess.span_diagnostic.struct_span_fatal(sp, m);
1120         err.help(help);
1121         err
1122     }
1123     pub fn bug(&self, m: &str) -> ! {
1124         self.sess.span_diagnostic.span_bug(self.span, m)
1125     }
1126     pub fn warn(&self, m: &str) {
1127         self.sess.span_diagnostic.span_warn(self.span, m)
1128     }
1129     pub fn span_warn(&self, sp: Span, m: &str) {
1130         self.sess.span_diagnostic.span_warn(sp, m)
1131     }
1132     pub fn span_err(&self, sp: Span, m: &str) {
1133         self.sess.span_diagnostic.span_err(sp, m)
1134     }
1135     pub fn span_err_help(&self, sp: Span, m: &str, h: &str) {
1136         let mut err = self.sess.span_diagnostic.mut_span_err(sp, m);
1137         err.help(h);
1138         err.emit();
1139     }
1140     pub fn span_bug(&self, sp: Span, m: &str) -> ! {
1141         self.sess.span_diagnostic.span_bug(sp, m)
1142     }
1143     pub fn abort_if_errors(&self) {
1144         self.sess.span_diagnostic.abort_if_errors();
1145     }
1146
1147     fn cancel(&self, err: &mut DiagnosticBuilder) {
1148         self.sess.span_diagnostic.cancel(err)
1149     }
1150
1151     pub fn diagnostic(&self) -> &'a errors::Handler {
1152         &self.sess.span_diagnostic
1153     }
1154
1155     /// Is the current token one of the keywords that signals a bare function
1156     /// type?
1157     pub fn token_is_bare_fn_keyword(&mut self) -> bool {
1158         self.check_keyword(keywords::Fn) ||
1159             self.check_keyword(keywords::Unsafe) ||
1160             self.check_keyword(keywords::Extern)
1161     }
1162
1163     fn get_label(&mut self) -> ast::Ident {
1164         match self.token {
1165             token::Lifetime(ref ident) => *ident,
1166             _ => self.bug("not a lifetime"),
1167         }
1168     }
1169
1170     /// parse a TyKind::BareFn type:
1171     pub fn parse_ty_bare_fn(&mut self, lifetime_defs: Vec<LifetimeDef>)
1172                             -> PResult<'a, TyKind> {
1173         /*
1174
1175         [unsafe] [extern "ABI"] fn (S) -> T
1176          ^~~~^           ^~~~^     ^~^    ^
1177            |               |        |     |
1178            |               |        |   Return type
1179            |               |      Argument types
1180            |               |
1181            |              ABI
1182         Function Style
1183         */
1184
1185         let unsafety = self.parse_unsafety()?;
1186         let abi = if self.eat_keyword(keywords::Extern) {
1187             self.parse_opt_abi()?.unwrap_or(Abi::C)
1188         } else {
1189             Abi::Rust
1190         };
1191
1192         self.expect_keyword(keywords::Fn)?;
1193         let (inputs, variadic) = self.parse_fn_args(false, true)?;
1194         let ret_ty = self.parse_ret_ty()?;
1195         let decl = P(FnDecl {
1196             inputs: inputs,
1197             output: ret_ty,
1198             variadic: variadic
1199         });
1200         Ok(TyKind::BareFn(P(BareFnTy {
1201             abi: abi,
1202             unsafety: unsafety,
1203             lifetimes: lifetime_defs,
1204             decl: decl
1205         })))
1206     }
1207
1208     pub fn parse_unsafety(&mut self) -> PResult<'a, Unsafety> {
1209         if self.eat_keyword(keywords::Unsafe) {
1210             return Ok(Unsafety::Unsafe);
1211         } else {
1212             return Ok(Unsafety::Normal);
1213         }
1214     }
1215
1216     /// Parse the items in a trait declaration
1217     pub fn parse_trait_item(&mut self, at_end: &mut bool) -> PResult<'a, TraitItem> {
1218         maybe_whole!(self, NtTraitItem, |x| x);
1219         let mut attrs = self.parse_outer_attributes()?;
1220         let lo = self.span;
1221
1222         let (name, node) = if self.eat_keyword(keywords::Type) {
1223             let TyParam {ident, bounds, default, ..} = self.parse_ty_param(vec![])?;
1224             self.expect(&token::Semi)?;
1225             (ident, TraitItemKind::Type(bounds, default))
1226         } else if self.is_const_item() {
1227             self.expect_keyword(keywords::Const)?;
1228             let ident = self.parse_ident()?;
1229             self.expect(&token::Colon)?;
1230             let ty = self.parse_ty()?;
1231             let default = if self.check(&token::Eq) {
1232                 self.bump();
1233                 let expr = self.parse_expr()?;
1234                 self.expect(&token::Semi)?;
1235                 Some(expr)
1236             } else {
1237                 self.expect(&token::Semi)?;
1238                 None
1239             };
1240             (ident, TraitItemKind::Const(ty, default))
1241         } else if self.token.is_path_start() {
1242             // trait item macro.
1243             // code copied from parse_macro_use_or_failure... abstraction!
1244             let prev_span = self.prev_span;
1245             let lo = self.span;
1246             let pth = self.parse_path(PathStyle::Mod)?;
1247
1248             if pth.segments.len() == 1 {
1249                 if !self.eat(&token::Not) {
1250                     return Err(self.missing_assoc_item_kind_err("trait", prev_span));
1251                 }
1252             } else {
1253                 self.expect(&token::Not)?;
1254             }
1255
1256             // eat a matched-delimiter token tree:
1257             let (delim, tts) = self.expect_delimited_token_tree()?;
1258             if delim != token::Brace {
1259                 self.expect(&token::Semi)?
1260             }
1261
1262             let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
1263             (keywords::Invalid.ident(), ast::TraitItemKind::Macro(mac))
1264         } else {
1265             let (constness, unsafety, abi) = match self.parse_fn_front_matter() {
1266                 Ok(cua) => cua,
1267                 Err(e) => return Err(e),
1268             };
1269
1270             let ident = self.parse_ident()?;
1271             let mut generics = self.parse_generics()?;
1272
1273             let d = self.parse_fn_decl_with_self(|p: &mut Parser<'a>|{
1274                 // This is somewhat dubious; We don't want to allow
1275                 // argument names to be left off if there is a
1276                 // definition...
1277                 p.parse_arg_general(false)
1278             })?;
1279
1280             generics.where_clause = self.parse_where_clause()?;
1281             let sig = ast::MethodSig {
1282                 unsafety: unsafety,
1283                 constness: constness,
1284                 decl: d,
1285                 generics: generics,
1286                 abi: abi,
1287             };
1288
1289             let body = match self.token {
1290                 token::Semi => {
1291                     self.bump();
1292                     *at_end = true;
1293                     debug!("parse_trait_methods(): parsing required method");
1294                     None
1295                 }
1296                 token::OpenDelim(token::Brace) => {
1297                     debug!("parse_trait_methods(): parsing provided method");
1298                     *at_end = true;
1299                     let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
1300                     attrs.extend(inner_attrs.iter().cloned());
1301                     Some(body)
1302                 }
1303                 _ => {
1304                     let token_str = self.this_token_to_string();
1305                     return Err(self.fatal(&format!("expected `;` or `{{`, found `{}`", token_str)));
1306                 }
1307             };
1308             (ident, ast::TraitItemKind::Method(sig, body))
1309         };
1310
1311         Ok(TraitItem {
1312             id: ast::DUMMY_NODE_ID,
1313             ident: name,
1314             attrs: attrs,
1315             node: node,
1316             span: lo.to(self.prev_span),
1317         })
1318     }
1319
1320     /// Parse optional return type [ -> TY ] in function decl
1321     pub fn parse_ret_ty(&mut self) -> PResult<'a, FunctionRetTy> {
1322         if self.eat(&token::RArrow) {
1323             Ok(FunctionRetTy::Ty(self.parse_ty_no_plus()?))
1324         } else {
1325             Ok(FunctionRetTy::Default(Span { hi: self.span.lo, ..self.span }))
1326         }
1327     }
1328
1329     // Parse a type
1330     pub fn parse_ty(&mut self) -> PResult<'a, P<Ty>> {
1331         self.parse_ty_common(true)
1332     }
1333
1334     /// Parse a type in restricted contexts where `+` is not permitted.
1335     /// Example 1: `&'a TYPE`
1336     ///     `+` is prohibited to maintain operator priority (P(+) < P(&)).
1337     /// Example 2: `value1 as TYPE + value2`
1338     ///     `+` is prohibited to avoid interactions with expression grammar.
1339     fn parse_ty_no_plus(&mut self) -> PResult<'a, P<Ty>> {
1340         self.parse_ty_common(false)
1341     }
1342
1343     fn parse_ty_common(&mut self, allow_plus: bool) -> PResult<'a, P<Ty>> {
1344         maybe_whole!(self, NtTy, |x| x);
1345
1346         let lo = self.span;
1347         let node = if self.eat(&token::OpenDelim(token::Paren)) {
1348             // `(TYPE)` is a parenthesized type.
1349             // `(TYPE,)` is a tuple with a single field of type TYPE.
1350             let mut ts = vec![];
1351             let mut last_comma = false;
1352             while self.token != token::CloseDelim(token::Paren) {
1353                 ts.push(self.parse_ty()?);
1354                 if self.eat(&token::Comma) {
1355                     last_comma = true;
1356                 } else {
1357                     last_comma = false;
1358                     break;
1359                 }
1360             }
1361             let trailing_plus = self.prev_token_kind == PrevTokenKind::Plus;
1362             self.expect(&token::CloseDelim(token::Paren))?;
1363
1364             if ts.len() == 1 && !last_comma {
1365                 let ty = ts.into_iter().nth(0).unwrap().unwrap();
1366                 let maybe_bounds = allow_plus && self.token == token::BinOp(token::Plus);
1367                 match ty.node {
1368                     // `(TY_BOUND_NOPAREN) + BOUND + ...`.
1369                     TyKind::Path(None, ref path) if maybe_bounds => {
1370                         self.parse_remaining_bounds(Vec::new(), path.clone(), lo, true)?
1371                     }
1372                     TyKind::TraitObject(ref bounds)
1373                             if maybe_bounds && bounds.len() == 1 && !trailing_plus => {
1374                         let path = match bounds[0] {
1375                             TraitTyParamBound(ref pt, ..) => pt.trait_ref.path.clone(),
1376                             _ => self.bug("unexpected lifetime bound"),
1377                         };
1378                         self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1379                     }
1380                     // `(TYPE)`
1381                     _ => TyKind::Paren(P(ty))
1382                 }
1383             } else {
1384                 TyKind::Tup(ts)
1385             }
1386         } else if self.eat(&token::Not) {
1387             // Never type `!`
1388             TyKind::Never
1389         } else if self.eat(&token::BinOp(token::Star)) {
1390             // Raw pointer
1391             TyKind::Ptr(self.parse_ptr()?)
1392         } else if self.eat(&token::OpenDelim(token::Bracket)) {
1393             // Array or slice
1394             let t = self.parse_ty()?;
1395             // Parse optional `; EXPR` in `[TYPE; EXPR]`
1396             let t = match self.maybe_parse_fixed_length_of_vec()? {
1397                 None => TyKind::Slice(t),
1398                 Some(suffix) => TyKind::Array(t, suffix),
1399             };
1400             self.expect(&token::CloseDelim(token::Bracket))?;
1401             t
1402         } else if self.check(&token::BinOp(token::And)) || self.check(&token::AndAnd) {
1403             // Reference
1404             self.expect_and()?;
1405             self.parse_borrowed_pointee()?
1406         } else if self.eat_keyword_noexpect(keywords::Typeof) {
1407             // `typeof(EXPR)`
1408             // In order to not be ambiguous, the type must be surrounded by parens.
1409             self.expect(&token::OpenDelim(token::Paren))?;
1410             let e = self.parse_expr()?;
1411             self.expect(&token::CloseDelim(token::Paren))?;
1412             TyKind::Typeof(e)
1413         } else if self.eat(&token::Underscore) {
1414             // A type to be inferred `_`
1415             TyKind::Infer
1416         } else if self.eat_lt() {
1417             // Qualified path
1418             let (qself, path) = self.parse_qualified_path(PathStyle::Type)?;
1419             TyKind::Path(Some(qself), path)
1420         } else if self.token.is_path_start() {
1421             // Simple path
1422             let path = self.parse_path(PathStyle::Type)?;
1423             if self.eat(&token::Not) {
1424                 // Macro invocation in type position
1425                 let (_, tts) = self.expect_delimited_token_tree()?;
1426                 TyKind::Mac(respan(lo.to(self.span), Mac_ { path: path, tts: tts }))
1427             } else {
1428                 // Just a type path or bound list (trait object type) starting with a trait.
1429                 //   `Type`
1430                 //   `Trait1 + Trait2 + 'a`
1431                 if allow_plus && self.check(&token::BinOp(token::Plus)) {
1432                     self.parse_remaining_bounds(Vec::new(), path, lo, true)?
1433                 } else {
1434                     TyKind::Path(None, path)
1435                 }
1436             }
1437         } else if self.token_is_bare_fn_keyword() {
1438             // Function pointer type
1439             self.parse_ty_bare_fn(Vec::new())?
1440         } else if self.check_keyword(keywords::For) {
1441             // Function pointer type or bound list (trait object type) starting with a poly-trait.
1442             //   `for<'lt> [unsafe] [extern "ABI"] fn (&'lt S) -> T`
1443             //   `for<'lt> Trait1<'lt> + Trait2 + 'a`
1444             let lo = self.span;
1445             let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
1446             if self.token_is_bare_fn_keyword() {
1447                 self.parse_ty_bare_fn(lifetime_defs)?
1448             } else {
1449                 let path = self.parse_path(PathStyle::Type)?;
1450                 let parse_plus = allow_plus && self.check(&token::BinOp(token::Plus));
1451                 self.parse_remaining_bounds(lifetime_defs, path, lo, parse_plus)?
1452             }
1453         } else if self.eat_keyword(keywords::Impl) {
1454             // FIXME: figure out priority of `+` in `impl Trait1 + Trait2` (#34511).
1455             TyKind::ImplTrait(self.parse_ty_param_bounds()?)
1456         } else if self.check(&token::Question) ||
1457                   self.check_lifetime() && self.look_ahead(1, |t| t == &token::BinOp(token::Plus)){
1458             // Bound list (trait object type)
1459             TyKind::TraitObject(self.parse_ty_param_bounds_common(allow_plus)?)
1460         } else {
1461             let msg = format!("expected type, found {}", self.this_token_descr());
1462             return Err(self.fatal(&msg));
1463         };
1464
1465         let span = lo.to(self.prev_span);
1466         let ty = Ty { node: node, span: span, id: ast::DUMMY_NODE_ID };
1467
1468         // Try to recover from use of `+` with incorrect priority.
1469         self.maybe_recover_from_bad_type_plus(allow_plus, &ty)?;
1470
1471         Ok(P(ty))
1472     }
1473
1474     fn parse_remaining_bounds(&mut self, lifetime_defs: Vec<LifetimeDef>, path: ast::Path,
1475                               lo: Span, parse_plus: bool) -> PResult<'a, TyKind> {
1476         let poly_trait_ref = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
1477         let mut bounds = vec![TraitTyParamBound(poly_trait_ref, TraitBoundModifier::None)];
1478         if parse_plus {
1479             self.bump(); // `+`
1480             bounds.append(&mut self.parse_ty_param_bounds()?);
1481         }
1482         Ok(TyKind::TraitObject(bounds))
1483     }
1484
1485     fn maybe_recover_from_bad_type_plus(&mut self, allow_plus: bool, ty: &Ty) -> PResult<'a, ()> {
1486         // Do not add `+` to expected tokens.
1487         if !allow_plus || self.token != token::BinOp(token::Plus) {
1488             return Ok(())
1489         }
1490
1491         self.bump(); // `+`
1492         let bounds = self.parse_ty_param_bounds()?;
1493         let sum_span = ty.span.to(self.prev_span);
1494
1495         let mut err = struct_span_err!(self.sess.span_diagnostic, sum_span, E0178,
1496             "expected a path on the left-hand side of `+`, not `{}`", pprust::ty_to_string(&ty));
1497
1498         match ty.node {
1499             TyKind::Rptr(ref lifetime, ref mut_ty) => {
1500                 let sum_with_parens = pprust::to_string(|s| {
1501                     use print::pp::word;
1502                     use print::pprust::PrintState;
1503
1504                     word(&mut s.s, "&")?;
1505                     s.print_opt_lifetime(lifetime)?;
1506                     s.print_mutability(mut_ty.mutbl)?;
1507                     s.popen()?;
1508                     s.print_type(&mut_ty.ty)?;
1509                     s.print_bounds(" +", &bounds)?;
1510                     s.pclose()
1511                 });
1512                 err.span_suggestion(sum_span, "try adding parentheses:", sum_with_parens);
1513             }
1514             TyKind::Ptr(..) | TyKind::BareFn(..) => {
1515                 err.span_label(sum_span, &"perhaps you forgot parentheses?");
1516             }
1517             _ => {
1518                 err.span_label(sum_span, &"expected a path");
1519             },
1520         }
1521         err.emit();
1522         Ok(())
1523     }
1524
1525     fn parse_borrowed_pointee(&mut self) -> PResult<'a, TyKind> {
1526         let opt_lifetime = if self.check_lifetime() { Some(self.expect_lifetime()) } else { None };
1527         let mutbl = self.parse_mutability();
1528         let ty = self.parse_ty_no_plus()?;
1529         return Ok(TyKind::Rptr(opt_lifetime, MutTy { ty: ty, mutbl: mutbl }));
1530     }
1531
1532     pub fn parse_ptr(&mut self) -> PResult<'a, MutTy> {
1533         let mutbl = if self.eat_keyword(keywords::Mut) {
1534             Mutability::Mutable
1535         } else if self.eat_keyword(keywords::Const) {
1536             Mutability::Immutable
1537         } else {
1538             let span = self.prev_span;
1539             self.span_err(span,
1540                           "expected mut or const in raw pointer type (use \
1541                            `*mut T` or `*const T` as appropriate)");
1542             Mutability::Immutable
1543         };
1544         let t = self.parse_ty_no_plus()?;
1545         Ok(MutTy { ty: t, mutbl: mutbl })
1546     }
1547
1548     pub fn is_named_argument(&mut self) -> bool {
1549         let offset = match self.token {
1550             token::BinOp(token::And) => 1,
1551             token::AndAnd => 1,
1552             _ if self.token.is_keyword(keywords::Mut) => 1,
1553             _ => 0
1554         };
1555
1556         debug!("parser is_named_argument offset:{}", offset);
1557
1558         if offset == 0 {
1559             is_ident_or_underscore(&self.token)
1560                 && self.look_ahead(1, |t| *t == token::Colon)
1561         } else {
1562             self.look_ahead(offset, |t| is_ident_or_underscore(t))
1563                 && self.look_ahead(offset + 1, |t| *t == token::Colon)
1564         }
1565     }
1566
1567     /// This version of parse arg doesn't necessarily require
1568     /// identifier names.
1569     pub fn parse_arg_general(&mut self, require_name: bool) -> PResult<'a, Arg> {
1570         maybe_whole!(self, NtArg, |x| x);
1571
1572         let pat = if require_name || self.is_named_argument() {
1573             debug!("parse_arg_general parse_pat (require_name:{})",
1574                    require_name);
1575             let pat = self.parse_pat()?;
1576
1577             self.expect(&token::Colon)?;
1578             pat
1579         } else {
1580             debug!("parse_arg_general ident_to_pat");
1581             let sp = self.prev_span;
1582             let spanned = Spanned { span: sp, node: keywords::Invalid.ident() };
1583             P(Pat {
1584                 id: ast::DUMMY_NODE_ID,
1585                 node: PatKind::Ident(BindingMode::ByValue(Mutability::Immutable),
1586                                      spanned, None),
1587                 span: sp
1588             })
1589         };
1590
1591         let t = self.parse_ty()?;
1592
1593         Ok(Arg {
1594             ty: t,
1595             pat: pat,
1596             id: ast::DUMMY_NODE_ID,
1597         })
1598     }
1599
1600     /// Parse a single function argument
1601     pub fn parse_arg(&mut self) -> PResult<'a, Arg> {
1602         self.parse_arg_general(true)
1603     }
1604
1605     /// Parse an argument in a lambda header e.g. |arg, arg|
1606     pub fn parse_fn_block_arg(&mut self) -> PResult<'a, Arg> {
1607         let pat = self.parse_pat()?;
1608         let t = if self.eat(&token::Colon) {
1609             self.parse_ty()?
1610         } else {
1611             P(Ty {
1612                 id: ast::DUMMY_NODE_ID,
1613                 node: TyKind::Infer,
1614                 span: self.span,
1615             })
1616         };
1617         Ok(Arg {
1618             ty: t,
1619             pat: pat,
1620             id: ast::DUMMY_NODE_ID
1621         })
1622     }
1623
1624     pub fn maybe_parse_fixed_length_of_vec(&mut self) -> PResult<'a, Option<P<ast::Expr>>> {
1625         if self.eat(&token::Semi) {
1626             Ok(Some(self.parse_expr()?))
1627         } else {
1628             Ok(None)
1629         }
1630     }
1631
1632     /// Matches token_lit = LIT_INTEGER | ...
1633     pub fn parse_lit_token(&mut self) -> PResult<'a, LitKind> {
1634         let out = match self.token {
1635             token::Interpolated(ref nt) => match **nt {
1636                 token::NtExpr(ref v) => match v.node {
1637                     ExprKind::Lit(ref lit) => { lit.node.clone() }
1638                     _ => { return self.unexpected_last(&self.token); }
1639                 },
1640                 _ => { return self.unexpected_last(&self.token); }
1641             },
1642             token::Literal(lit, suf) => {
1643                 let diag = Some((self.span, &self.sess.span_diagnostic));
1644                 let (suffix_illegal, result) = parse::lit_token(lit, suf, diag);
1645
1646                 if suffix_illegal {
1647                     let sp = self.span;
1648                     self.expect_no_suffix(sp, &format!("{} literal", lit.short_name()), suf)
1649                 }
1650
1651                 result.unwrap()
1652             }
1653             _ => { return self.unexpected_last(&self.token); }
1654         };
1655
1656         self.bump();
1657         Ok(out)
1658     }
1659
1660     /// Matches lit = true | false | token_lit
1661     pub fn parse_lit(&mut self) -> PResult<'a, Lit> {
1662         let lo = self.span;
1663         let lit = if self.eat_keyword(keywords::True) {
1664             LitKind::Bool(true)
1665         } else if self.eat_keyword(keywords::False) {
1666             LitKind::Bool(false)
1667         } else {
1668             let lit = self.parse_lit_token()?;
1669             lit
1670         };
1671         Ok(codemap::Spanned { node: lit, span: lo.to(self.prev_span) })
1672     }
1673
1674     /// matches '-' lit | lit
1675     pub fn parse_pat_literal_maybe_minus(&mut self) -> PResult<'a, P<Expr>> {
1676         let minus_lo = self.span;
1677         let minus_present = self.eat(&token::BinOp(token::Minus));
1678         let lo = self.span;
1679         let literal = P(self.parse_lit()?);
1680         let hi = self.prev_span;
1681         let expr = self.mk_expr(lo.to(hi), ExprKind::Lit(literal), ThinVec::new());
1682
1683         if minus_present {
1684             let minus_hi = self.prev_span;
1685             let unary = self.mk_unary(UnOp::Neg, expr);
1686             Ok(self.mk_expr(minus_lo.to(minus_hi), unary, ThinVec::new()))
1687         } else {
1688             Ok(expr)
1689         }
1690     }
1691
1692     pub fn parse_path_segment_ident(&mut self) -> PResult<'a, ast::Ident> {
1693         match self.token {
1694             token::Ident(sid) if self.token.is_path_segment_keyword() => {
1695                 self.bump();
1696                 Ok(sid)
1697             }
1698             _ => self.parse_ident(),
1699          }
1700      }
1701
1702     /// Parses qualified path.
1703     ///
1704     /// Assumes that the leading `<` has been parsed already.
1705     ///
1706     /// Qualifed paths are a part of the universal function call
1707     /// syntax (UFCS).
1708     ///
1709     /// `qualified_path = <type [as trait_ref]>::path`
1710     ///
1711     /// See `parse_path` for `mode` meaning.
1712     ///
1713     /// # Examples:
1714     ///
1715     /// `<T as U>::a`
1716     /// `<T as U>::F::a::<S>`
1717     pub fn parse_qualified_path(&mut self, mode: PathStyle)
1718                                 -> PResult<'a, (QSelf, ast::Path)> {
1719         let span = self.prev_span;
1720         let self_type = self.parse_ty()?;
1721         let mut path = if self.eat_keyword(keywords::As) {
1722             self.parse_path(PathStyle::Type)?
1723         } else {
1724             ast::Path {
1725                 span: span,
1726                 segments: vec![]
1727             }
1728         };
1729
1730         let qself = QSelf {
1731             ty: self_type,
1732             position: path.segments.len()
1733         };
1734
1735         self.expect(&token::Gt)?;
1736         self.expect(&token::ModSep)?;
1737
1738         let segments = match mode {
1739             PathStyle::Type => {
1740                 self.parse_path_segments_without_colons()?
1741             }
1742             PathStyle::Expr => {
1743                 self.parse_path_segments_with_colons()?
1744             }
1745             PathStyle::Mod => {
1746                 self.parse_path_segments_without_types()?
1747             }
1748         };
1749         path.segments.extend(segments);
1750
1751         path.span.hi = self.prev_span.hi;
1752
1753         Ok((qself, path))
1754     }
1755
1756     /// Parses a path and optional type parameter bounds, depending on the
1757     /// mode. The `mode` parameter determines whether lifetimes, types, and/or
1758     /// bounds are permitted and whether `::` must precede type parameter
1759     /// groups.
1760     pub fn parse_path(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1761         maybe_whole!(self, NtPath, |x| x);
1762
1763         let lo = self.meta_var_span.unwrap_or(self.span);
1764         let is_global = self.eat(&token::ModSep);
1765
1766         // Parse any number of segments and bound sets. A segment is an
1767         // identifier followed by an optional lifetime and a set of types.
1768         // A bound set is a set of type parameter bounds.
1769         let mut segments = match mode {
1770             PathStyle::Type => {
1771                 self.parse_path_segments_without_colons()?
1772             }
1773             PathStyle::Expr => {
1774                 self.parse_path_segments_with_colons()?
1775             }
1776             PathStyle::Mod => {
1777                 self.parse_path_segments_without_types()?
1778             }
1779         };
1780
1781         if is_global {
1782             segments.insert(0, PathSegment::crate_root());
1783         }
1784
1785         // Assemble the result.
1786         Ok(ast::Path {
1787             span: lo.to(self.prev_span),
1788             segments: segments,
1789         })
1790     }
1791
1792     /// Like `parse_path`, but also supports parsing `Word` meta items into paths for back-compat.
1793     /// This is used when parsing derive macro paths in `#[derive]` attributes.
1794     pub fn parse_path_allowing_meta(&mut self, mode: PathStyle) -> PResult<'a, ast::Path> {
1795         let meta_ident = match self.token {
1796             token::Interpolated(ref nt) => match **nt {
1797                 token::NtMeta(ref meta) => match meta.node {
1798                     ast::MetaItemKind::Word => Some(ast::Ident::with_empty_ctxt(meta.name)),
1799                     _ => None,
1800                 },
1801                 _ => None,
1802             },
1803             _ => None,
1804         };
1805         if let Some(ident) = meta_ident {
1806             self.bump();
1807             return Ok(ast::Path::from_ident(self.prev_span, ident));
1808         }
1809         self.parse_path(mode)
1810     }
1811
1812     /// Examples:
1813     /// - `a::b<T,U>::c<V,W>`
1814     /// - `a::b<T,U>::c(V) -> W`
1815     /// - `a::b<T,U>::c(V)`
1816     pub fn parse_path_segments_without_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1817         let mut segments = Vec::new();
1818         loop {
1819             // First, parse an identifier.
1820             let ident_span = self.span;
1821             let identifier = self.parse_path_segment_ident()?;
1822
1823             if self.check(&token::ModSep) && self.look_ahead(1, |t| *t == token::Lt) {
1824                 self.bump();
1825                 let prev_span = self.prev_span;
1826
1827                 let mut err = self.diagnostic().struct_span_err(prev_span,
1828                     "unexpected token: `::`");
1829                 err.help(
1830                     "use `<...>` instead of `::<...>` if you meant to specify type arguments");
1831                 err.emit();
1832             }
1833
1834             // Parse types, optionally.
1835             let parameters = if self.eat_lt() {
1836                 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1837                 self.expect_gt()?;
1838                 ast::AngleBracketedParameterData {
1839                     lifetimes: lifetimes,
1840                     types: types,
1841                     bindings: bindings,
1842                 }.into()
1843             } else if self.eat(&token::OpenDelim(token::Paren)) {
1844                 let lo = self.prev_span;
1845
1846                 let inputs = self.parse_seq_to_end(
1847                     &token::CloseDelim(token::Paren),
1848                     SeqSep::trailing_allowed(token::Comma),
1849                     |p| p.parse_ty())?;
1850
1851                 let output_ty = if self.eat(&token::RArrow) {
1852                     Some(self.parse_ty_no_plus()?)
1853                 } else {
1854                     None
1855                 };
1856
1857                 let hi = self.prev_span;
1858
1859                 Some(P(ast::PathParameters::Parenthesized(ast::ParenthesizedParameterData {
1860                     span: lo.to(hi),
1861                     inputs: inputs,
1862                     output: output_ty,
1863                 })))
1864             } else {
1865                 None
1866             };
1867
1868             // Assemble and push the result.
1869             segments.push(PathSegment {
1870                 identifier: identifier,
1871                 span: ident_span,
1872                 parameters: parameters
1873             });
1874
1875             // Continue only if we see a `::`
1876             if !self.eat(&token::ModSep) {
1877                 return Ok(segments);
1878             }
1879         }
1880     }
1881
1882     /// Examples:
1883     /// - `a::b::<T,U>::c`
1884     pub fn parse_path_segments_with_colons(&mut self) -> PResult<'a, Vec<PathSegment>> {
1885         let mut segments = Vec::new();
1886         loop {
1887             // First, parse an identifier.
1888             let ident_span = self.span;
1889             let identifier = self.parse_path_segment_ident()?;
1890
1891             // If we do not see a `::`, stop.
1892             if !self.eat(&token::ModSep) {
1893                 segments.push(PathSegment::from_ident(identifier, ident_span));
1894                 return Ok(segments);
1895             }
1896
1897             // Check for a type segment.
1898             if self.eat_lt() {
1899                 // Consumed `a::b::<`, go look for types
1900                 let (lifetimes, types, bindings) = self.parse_generic_args()?;
1901                 self.expect_gt()?;
1902                 segments.push(PathSegment {
1903                     identifier: identifier,
1904                     span: ident_span,
1905                     parameters: ast::AngleBracketedParameterData {
1906                         lifetimes: lifetimes,
1907                         types: types,
1908                         bindings: bindings,
1909                     }.into(),
1910                 });
1911
1912                 // Consumed `a::b::<T,U>`, check for `::` before proceeding
1913                 if !self.eat(&token::ModSep) {
1914                     return Ok(segments);
1915                 }
1916             } else {
1917                 // Consumed `a::`, go look for `b`
1918                 segments.push(PathSegment::from_ident(identifier, ident_span));
1919             }
1920         }
1921     }
1922
1923     /// Examples:
1924     /// - `a::b::c`
1925     pub fn parse_path_segments_without_types(&mut self)
1926                                              -> PResult<'a, Vec<PathSegment>> {
1927         let mut segments = Vec::new();
1928         loop {
1929             // First, parse an identifier.
1930             let ident_span = self.span;
1931             let identifier = self.parse_path_segment_ident()?;
1932
1933             // Assemble and push the result.
1934             segments.push(PathSegment::from_ident(identifier, ident_span));
1935
1936             // If we do not see a `::` or see `::{`/`::*`, stop.
1937             if !self.check(&token::ModSep) || self.is_import_coupler() {
1938                 return Ok(segments);
1939             } else {
1940                 self.bump();
1941             }
1942         }
1943     }
1944
1945     fn check_lifetime(&mut self) -> bool {
1946         self.expected_tokens.push(TokenType::Lifetime);
1947         self.token.is_lifetime()
1948     }
1949
1950     /// Parse single lifetime 'a or panic.
1951     fn expect_lifetime(&mut self) -> Lifetime {
1952         match self.token {
1953             token::Lifetime(ident) => {
1954                 let ident_span = self.span;
1955                 self.bump();
1956                 Lifetime { name: ident.name, span: ident_span, id: ast::DUMMY_NODE_ID }
1957             }
1958             _ => self.span_bug(self.span, "not a lifetime")
1959         }
1960     }
1961
1962     /// Parse mutability (`mut` or nothing).
1963     fn parse_mutability(&mut self) -> Mutability {
1964         if self.eat_keyword(keywords::Mut) {
1965             Mutability::Mutable
1966         } else {
1967             Mutability::Immutable
1968         }
1969     }
1970
1971     pub fn parse_field_name(&mut self) -> PResult<'a, Ident> {
1972         if let token::Literal(token::Integer(name), None) = self.token {
1973             self.bump();
1974             Ok(Ident::with_empty_ctxt(name))
1975         } else {
1976             self.parse_ident()
1977         }
1978     }
1979
1980     /// Parse ident (COLON expr)?
1981     pub fn parse_field(&mut self) -> PResult<'a, Field> {
1982         let attrs = self.parse_outer_attributes()?;
1983         let lo = self.span;
1984         let hi;
1985
1986         // Check if a colon exists one ahead. This means we're parsing a fieldname.
1987         let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
1988             let fieldname = self.parse_field_name()?;
1989             self.bump();
1990             hi = self.prev_span;
1991             (fieldname, self.parse_expr()?, false)
1992         } else {
1993             let fieldname = self.parse_ident()?;
1994             hi = self.prev_span;
1995
1996             // Mimic `x: x` for the `x` field shorthand.
1997             let path = ast::Path::from_ident(lo.to(hi), fieldname);
1998             (fieldname, self.mk_expr(lo.to(hi), ExprKind::Path(None, path), ThinVec::new()), true)
1999         };
2000         Ok(ast::Field {
2001             ident: respan(lo.to(hi), fieldname),
2002             span: lo.to(expr.span),
2003             expr: expr,
2004             is_shorthand: is_shorthand,
2005             attrs: attrs.into(),
2006         })
2007     }
2008
2009     pub fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2010         P(Expr {
2011             id: ast::DUMMY_NODE_ID,
2012             node: node,
2013             span: span,
2014             attrs: attrs.into(),
2015         })
2016     }
2017
2018     pub fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2019         ExprKind::Unary(unop, expr)
2020     }
2021
2022     pub fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2023         ExprKind::Binary(binop, lhs, rhs)
2024     }
2025
2026     pub fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2027         ExprKind::Call(f, args)
2028     }
2029
2030     fn mk_method_call(&mut self,
2031                       ident: ast::SpannedIdent,
2032                       tps: Vec<P<Ty>>,
2033                       args: Vec<P<Expr>>)
2034                       -> ast::ExprKind {
2035         ExprKind::MethodCall(ident, tps, args)
2036     }
2037
2038     pub fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2039         ExprKind::Index(expr, idx)
2040     }
2041
2042     pub fn mk_range(&mut self,
2043                     start: Option<P<Expr>>,
2044                     end: Option<P<Expr>>,
2045                     limits: RangeLimits)
2046                     -> PResult<'a, ast::ExprKind> {
2047         if end.is_none() && limits == RangeLimits::Closed {
2048             Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2049         } else {
2050             Ok(ExprKind::Range(start, end, limits))
2051         }
2052     }
2053
2054     pub fn mk_field(&mut self, expr: P<Expr>, ident: ast::SpannedIdent) -> ast::ExprKind {
2055         ExprKind::Field(expr, ident)
2056     }
2057
2058     pub fn mk_tup_field(&mut self, expr: P<Expr>, idx: codemap::Spanned<usize>) -> ast::ExprKind {
2059         ExprKind::TupField(expr, idx)
2060     }
2061
2062     pub fn mk_assign_op(&mut self, binop: ast::BinOp,
2063                         lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2064         ExprKind::AssignOp(binop, lhs, rhs)
2065     }
2066
2067     pub fn mk_mac_expr(&mut self, span: Span, m: Mac_, attrs: ThinVec<Attribute>) -> P<Expr> {
2068         P(Expr {
2069             id: ast::DUMMY_NODE_ID,
2070             node: ExprKind::Mac(codemap::Spanned {node: m, span: span}),
2071             span: span,
2072             attrs: attrs,
2073         })
2074     }
2075
2076     pub fn mk_lit_u32(&mut self, i: u32, attrs: ThinVec<Attribute>) -> P<Expr> {
2077         let span = &self.span;
2078         let lv_lit = P(codemap::Spanned {
2079             node: LitKind::Int(i as u128, ast::LitIntType::Unsigned(UintTy::U32)),
2080             span: *span
2081         });
2082
2083         P(Expr {
2084             id: ast::DUMMY_NODE_ID,
2085             node: ExprKind::Lit(lv_lit),
2086             span: *span,
2087             attrs: attrs,
2088         })
2089     }
2090
2091     fn expect_delimited_token_tree(&mut self) -> PResult<'a, (token::DelimToken, ThinTokenStream)> {
2092         match self.token {
2093             token::OpenDelim(delim) => match self.parse_token_tree() {
2094                 TokenTree::Delimited(_, delimited) => Ok((delim, delimited.stream().into())),
2095                 _ => unreachable!(),
2096             },
2097             _ => Err(self.fatal("expected open delimiter")),
2098         }
2099     }
2100
2101     /// At the bottom (top?) of the precedence hierarchy,
2102     /// parse things like parenthesized exprs,
2103     /// macros, return, etc.
2104     ///
2105     /// NB: This does not parse outer attributes,
2106     ///     and is private because it only works
2107     ///     correctly if called from parse_dot_or_call_expr().
2108     fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2109         maybe_whole_expr!(self);
2110
2111         // Outer attributes are already parsed and will be
2112         // added to the return value after the fact.
2113         //
2114         // Therefore, prevent sub-parser from parsing
2115         // attributes by giving them a empty "already parsed" list.
2116         let mut attrs = ThinVec::new();
2117
2118         let lo = self.span;
2119         let mut hi = self.span;
2120
2121         let ex: ExprKind;
2122
2123         // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2124         match self.token {
2125             token::OpenDelim(token::Paren) => {
2126                 self.bump();
2127
2128                 attrs.extend(self.parse_inner_attributes()?);
2129
2130                 // (e) is parenthesized e
2131                 // (e,) is a tuple with only one field, e
2132                 let mut es = vec![];
2133                 let mut trailing_comma = false;
2134                 while self.token != token::CloseDelim(token::Paren) {
2135                     es.push(self.parse_expr()?);
2136                     self.expect_one_of(&[], &[token::Comma, token::CloseDelim(token::Paren)])?;
2137                     if self.check(&token::Comma) {
2138                         trailing_comma = true;
2139
2140                         self.bump();
2141                     } else {
2142                         trailing_comma = false;
2143                         break;
2144                     }
2145                 }
2146                 self.bump();
2147
2148                 hi = self.prev_span;
2149                 let span = lo.to(hi);
2150                 return if es.len() == 1 && !trailing_comma {
2151                     Ok(self.mk_expr(span, ExprKind::Paren(es.into_iter().nth(0).unwrap()), attrs))
2152                 } else {
2153                     Ok(self.mk_expr(span, ExprKind::Tup(es), attrs))
2154                 }
2155             },
2156             token::OpenDelim(token::Brace) => {
2157                 return self.parse_block_expr(lo, BlockCheckMode::Default, attrs);
2158             },
2159             token::BinOp(token::Or) |  token::OrOr => {
2160                 let lo = self.span;
2161                 return self.parse_lambda_expr(lo, CaptureBy::Ref, attrs);
2162             },
2163             token::OpenDelim(token::Bracket) => {
2164                 self.bump();
2165
2166                 attrs.extend(self.parse_inner_attributes()?);
2167
2168                 if self.check(&token::CloseDelim(token::Bracket)) {
2169                     // Empty vector.
2170                     self.bump();
2171                     ex = ExprKind::Array(Vec::new());
2172                 } else {
2173                     // Nonempty vector.
2174                     let first_expr = self.parse_expr()?;
2175                     if self.check(&token::Semi) {
2176                         // Repeating array syntax: [ 0; 512 ]
2177                         self.bump();
2178                         let count = self.parse_expr()?;
2179                         self.expect(&token::CloseDelim(token::Bracket))?;
2180                         ex = ExprKind::Repeat(first_expr, count);
2181                     } else if self.check(&token::Comma) {
2182                         // Vector with two or more elements.
2183                         self.bump();
2184                         let remaining_exprs = self.parse_seq_to_end(
2185                             &token::CloseDelim(token::Bracket),
2186                             SeqSep::trailing_allowed(token::Comma),
2187                             |p| Ok(p.parse_expr()?)
2188                         )?;
2189                         let mut exprs = vec![first_expr];
2190                         exprs.extend(remaining_exprs);
2191                         ex = ExprKind::Array(exprs);
2192                     } else {
2193                         // Vector with one element.
2194                         self.expect(&token::CloseDelim(token::Bracket))?;
2195                         ex = ExprKind::Array(vec![first_expr]);
2196                     }
2197                 }
2198                 hi = self.prev_span;
2199             }
2200             _ => {
2201                 if self.eat_lt() {
2202                     let (qself, path) =
2203                         self.parse_qualified_path(PathStyle::Expr)?;
2204                     hi = path.span;
2205                     return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2206                 }
2207                 if self.eat_keyword(keywords::Move) {
2208                     let lo = self.prev_span;
2209                     return self.parse_lambda_expr(lo, CaptureBy::Value, attrs);
2210                 }
2211                 if self.eat_keyword(keywords::If) {
2212                     return self.parse_if_expr(attrs);
2213                 }
2214                 if self.eat_keyword(keywords::For) {
2215                     let lo = self.prev_span;
2216                     return self.parse_for_expr(None, lo, attrs);
2217                 }
2218                 if self.eat_keyword(keywords::While) {
2219                     let lo = self.prev_span;
2220                     return self.parse_while_expr(None, lo, attrs);
2221                 }
2222                 if self.token.is_lifetime() {
2223                     let label = Spanned { node: self.get_label(),
2224                                           span: self.span };
2225                     let lo = self.span;
2226                     self.bump();
2227                     self.expect(&token::Colon)?;
2228                     if self.eat_keyword(keywords::While) {
2229                         return self.parse_while_expr(Some(label), lo, attrs)
2230                     }
2231                     if self.eat_keyword(keywords::For) {
2232                         return self.parse_for_expr(Some(label), lo, attrs)
2233                     }
2234                     if self.eat_keyword(keywords::Loop) {
2235                         return self.parse_loop_expr(Some(label), lo, attrs)
2236                     }
2237                     return Err(self.fatal("expected `while`, `for`, or `loop` after a label"))
2238                 }
2239                 if self.eat_keyword(keywords::Loop) {
2240                     let lo = self.prev_span;
2241                     return self.parse_loop_expr(None, lo, attrs);
2242                 }
2243                 if self.eat_keyword(keywords::Continue) {
2244                     let ex = if self.token.is_lifetime() {
2245                         let ex = ExprKind::Continue(Some(Spanned{
2246                             node: self.get_label(),
2247                             span: self.span
2248                         }));
2249                         self.bump();
2250                         ex
2251                     } else {
2252                         ExprKind::Continue(None)
2253                     };
2254                     let hi = self.prev_span;
2255                     return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2256                 }
2257                 if self.eat_keyword(keywords::Match) {
2258                     return self.parse_match_expr(attrs);
2259                 }
2260                 if self.eat_keyword(keywords::Unsafe) {
2261                     return self.parse_block_expr(
2262                         lo,
2263                         BlockCheckMode::Unsafe(ast::UserProvided),
2264                         attrs);
2265                 }
2266                 if self.is_catch_expr() {
2267                     assert!(self.eat_keyword(keywords::Do));
2268                     assert!(self.eat_keyword(keywords::Catch));
2269                     let lo = self.prev_span;
2270                     return self.parse_catch_expr(lo, attrs);
2271                 }
2272                 if self.eat_keyword(keywords::Return) {
2273                     if self.token.can_begin_expr() {
2274                         let e = self.parse_expr()?;
2275                         hi = e.span;
2276                         ex = ExprKind::Ret(Some(e));
2277                     } else {
2278                         ex = ExprKind::Ret(None);
2279                     }
2280                 } else if self.eat_keyword(keywords::Break) {
2281                     let lt = if self.token.is_lifetime() {
2282                         let spanned_lt = Spanned {
2283                             node: self.get_label(),
2284                             span: self.span
2285                         };
2286                         self.bump();
2287                         Some(spanned_lt)
2288                     } else {
2289                         None
2290                     };
2291                     let e = if self.token.can_begin_expr()
2292                                && !(self.token == token::OpenDelim(token::Brace)
2293                                     && self.restrictions.contains(
2294                                            RESTRICTION_NO_STRUCT_LITERAL)) {
2295                         Some(self.parse_expr()?)
2296                     } else {
2297                         None
2298                     };
2299                     ex = ExprKind::Break(lt, e);
2300                     hi = self.prev_span;
2301                 } else if self.token.is_keyword(keywords::Let) {
2302                     // Catch this syntax error here, instead of in `check_strict_keywords`, so
2303                     // that we can explicitly mention that let is not to be used as an expression
2304                     let mut db = self.fatal("expected expression, found statement (`let`)");
2305                     db.note("variable declaration using `let` is a statement");
2306                     return Err(db);
2307                 } else if self.token.is_path_start() {
2308                     let pth = self.parse_path(PathStyle::Expr)?;
2309
2310                     // `!`, as an operator, is prefix, so we know this isn't that
2311                     if self.eat(&token::Not) {
2312                         // MACRO INVOCATION expression
2313                         let (_, tts) = self.expect_delimited_token_tree()?;
2314                         let hi = self.prev_span;
2315                         return Ok(self.mk_mac_expr(lo.to(hi), Mac_ { path: pth, tts: tts }, attrs));
2316                     }
2317                     if self.check(&token::OpenDelim(token::Brace)) {
2318                         // This is a struct literal, unless we're prohibited
2319                         // from parsing struct literals here.
2320                         let prohibited = self.restrictions.contains(
2321                             RESTRICTION_NO_STRUCT_LITERAL
2322                         );
2323                         if !prohibited {
2324                             return self.parse_struct_expr(lo, pth, attrs);
2325                         }
2326                     }
2327
2328                     hi = pth.span;
2329                     ex = ExprKind::Path(None, pth);
2330                 } else {
2331                     match self.parse_lit() {
2332                         Ok(lit) => {
2333                             hi = lit.span;
2334                             ex = ExprKind::Lit(P(lit));
2335                         }
2336                         Err(mut err) => {
2337                             self.cancel(&mut err);
2338                             let msg = format!("expected expression, found {}",
2339                                               self.this_token_descr());
2340                             return Err(self.fatal(&msg));
2341                         }
2342                     }
2343                 }
2344             }
2345         }
2346
2347         return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2348     }
2349
2350     fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2351                          -> PResult<'a, P<Expr>> {
2352         self.bump();
2353         let mut fields = Vec::new();
2354         let mut base = None;
2355
2356         attrs.extend(self.parse_inner_attributes()?);
2357
2358         while self.token != token::CloseDelim(token::Brace) {
2359             if self.eat(&token::DotDot) {
2360                 match self.parse_expr() {
2361                     Ok(e) => {
2362                         base = Some(e);
2363                     }
2364                     Err(mut e) => {
2365                         e.emit();
2366                         self.recover_stmt();
2367                     }
2368                 }
2369                 break;
2370             }
2371
2372             match self.parse_field() {
2373                 Ok(f) => fields.push(f),
2374                 Err(mut e) => {
2375                     e.emit();
2376                     self.recover_stmt();
2377                     break;
2378                 }
2379             }
2380
2381             match self.expect_one_of(&[token::Comma],
2382                                      &[token::CloseDelim(token::Brace)]) {
2383                 Ok(()) => {}
2384                 Err(mut e) => {
2385                     e.emit();
2386                     self.recover_stmt();
2387                     break;
2388                 }
2389             }
2390         }
2391
2392         let span = lo.to(self.span);
2393         self.expect(&token::CloseDelim(token::Brace))?;
2394         return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2395     }
2396
2397     fn parse_or_use_outer_attributes(&mut self,
2398                                      already_parsed_attrs: Option<ThinVec<Attribute>>)
2399                                      -> PResult<'a, ThinVec<Attribute>> {
2400         if let Some(attrs) = already_parsed_attrs {
2401             Ok(attrs)
2402         } else {
2403             self.parse_outer_attributes().map(|a| a.into())
2404         }
2405     }
2406
2407     /// Parse a block or unsafe block
2408     pub fn parse_block_expr(&mut self, lo: Span, blk_mode: BlockCheckMode,
2409                             outer_attrs: ThinVec<Attribute>)
2410                             -> PResult<'a, P<Expr>> {
2411
2412         self.expect(&token::OpenDelim(token::Brace))?;
2413
2414         let mut attrs = outer_attrs;
2415         attrs.extend(self.parse_inner_attributes()?);
2416
2417         let blk = self.parse_block_tail(lo, blk_mode)?;
2418         return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), attrs));
2419     }
2420
2421     /// parse a.b or a(13) or a[4] or just a
2422     pub fn parse_dot_or_call_expr(&mut self,
2423                                   already_parsed_attrs: Option<ThinVec<Attribute>>)
2424                                   -> PResult<'a, P<Expr>> {
2425         let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2426
2427         let b = self.parse_bottom_expr();
2428         let (span, b) = self.interpolated_or_expr_span(b)?;
2429         self.parse_dot_or_call_expr_with(b, span, attrs)
2430     }
2431
2432     pub fn parse_dot_or_call_expr_with(&mut self,
2433                                        e0: P<Expr>,
2434                                        lo: Span,
2435                                        mut attrs: ThinVec<Attribute>)
2436                                        -> PResult<'a, P<Expr>> {
2437         // Stitch the list of outer attributes onto the return value.
2438         // A little bit ugly, but the best way given the current code
2439         // structure
2440         self.parse_dot_or_call_expr_with_(e0, lo)
2441         .map(|expr|
2442             expr.map(|mut expr| {
2443                 attrs.extend::<Vec<_>>(expr.attrs.into());
2444                 expr.attrs = attrs;
2445                 match expr.node {
2446                     ExprKind::If(..) | ExprKind::IfLet(..) => {
2447                         if !expr.attrs.is_empty() {
2448                             // Just point to the first attribute in there...
2449                             let span = expr.attrs[0].span;
2450
2451                             self.span_err(span,
2452                                 "attributes are not yet allowed on `if` \
2453                                 expressions");
2454                         }
2455                     }
2456                     _ => {}
2457                 }
2458                 expr
2459             })
2460         )
2461     }
2462
2463     // Assuming we have just parsed `.foo` (i.e., a dot and an ident), continue
2464     // parsing into an expression.
2465     fn parse_dot_suffix(&mut self, ident: Ident, ident_span: Span, self_value: P<Expr>, lo: Span)
2466                         -> PResult<'a, P<Expr>> {
2467         let (_, tys, bindings) = if self.eat(&token::ModSep) {
2468             self.expect_lt()?;
2469             let args = self.parse_generic_args()?;
2470             self.expect_gt()?;
2471             args
2472         } else {
2473             (Vec::new(), Vec::new(), Vec::new())
2474         };
2475
2476         if !bindings.is_empty() {
2477             let prev_span = self.prev_span;
2478             self.span_err(prev_span, "type bindings are only permitted on trait paths");
2479         }
2480
2481         Ok(match self.token {
2482             // expr.f() method call.
2483             token::OpenDelim(token::Paren) => {
2484                 let mut es = self.parse_unspanned_seq(
2485                     &token::OpenDelim(token::Paren),
2486                     &token::CloseDelim(token::Paren),
2487                     SeqSep::trailing_allowed(token::Comma),
2488                     |p| Ok(p.parse_expr()?)
2489                 )?;
2490                 let hi = self.prev_span;
2491
2492                 es.insert(0, self_value);
2493                 let id = respan(ident_span.to(ident_span), ident);
2494                 let nd = self.mk_method_call(id, tys, es);
2495                 self.mk_expr(lo.to(hi), nd, ThinVec::new())
2496             }
2497             // Field access.
2498             _ => {
2499                 if !tys.is_empty() {
2500                     let prev_span = self.prev_span;
2501                     self.span_err(prev_span,
2502                                   "field expressions may not \
2503                                    have type parameters");
2504                 }
2505
2506                 let id = respan(ident_span.to(ident_span), ident);
2507                 let field = self.mk_field(self_value, id);
2508                 self.mk_expr(lo.to(ident_span), field, ThinVec::new())
2509             }
2510         })
2511     }
2512
2513     fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
2514         let mut e = e0;
2515         let mut hi;
2516         loop {
2517             // expr?
2518             while self.eat(&token::Question) {
2519                 let hi = self.prev_span;
2520                 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
2521             }
2522
2523             // expr.f
2524             if self.eat(&token::Dot) {
2525                 match self.token {
2526                   token::Ident(i) => {
2527                     let ident_span = self.span;
2528                     self.bump();
2529                     e = self.parse_dot_suffix(i, ident_span, e, lo)?;
2530                   }
2531                   token::Literal(token::Integer(n), suf) => {
2532                     let sp = self.span;
2533
2534                     // A tuple index may not have a suffix
2535                     self.expect_no_suffix(sp, "tuple index", suf);
2536
2537                     let dot_span = self.prev_span;
2538                     hi = self.span;
2539                     self.bump();
2540
2541                     let index = n.as_str().parse::<usize>().ok();
2542                     match index {
2543                         Some(n) => {
2544                             let id = respan(dot_span.to(hi), n);
2545                             let field = self.mk_tup_field(e, id);
2546                             e = self.mk_expr(lo.to(hi), field, ThinVec::new());
2547                         }
2548                         None => {
2549                             let prev_span = self.prev_span;
2550                             self.span_err(prev_span, "invalid tuple or tuple struct index");
2551                         }
2552                     }
2553                   }
2554                   token::Literal(token::Float(n), _suf) => {
2555                     self.bump();
2556                     let fstr = n.as_str();
2557                     let mut err = self.diagnostic().struct_span_err(self.prev_span,
2558                         &format!("unexpected token: `{}`", n));
2559                     err.span_label(self.prev_span, &"unexpected token");
2560                     if fstr.chars().all(|x| "0123456789.".contains(x)) {
2561                         let float = match fstr.parse::<f64>().ok() {
2562                             Some(f) => f,
2563                             None => continue,
2564                         };
2565                         let sugg = pprust::to_string(|s| {
2566                             use print::pprust::PrintState;
2567                             use print::pp::word;
2568                             s.popen()?;
2569                             s.print_expr(&e)?;
2570                             word(&mut s.s, ".")?;
2571                             s.print_usize(float.trunc() as usize)?;
2572                             s.pclose()?;
2573                             word(&mut s.s, ".")?;
2574                             word(&mut s.s, fstr.splitn(2, ".").last().unwrap())
2575                         });
2576                         err.span_suggestion(
2577                             lo.to(self.prev_span),
2578                             "try parenthesizing the first index",
2579                             sugg);
2580                     }
2581                     return Err(err);
2582
2583                   }
2584                   _ => {
2585                     // FIXME Could factor this out into non_fatal_unexpected or something.
2586                     let actual = self.this_token_to_string();
2587                     self.span_err(self.span, &format!("unexpected token: `{}`", actual));
2588
2589                     let dot_span = self.prev_span;
2590                     e = self.parse_dot_suffix(keywords::Invalid.ident(), dot_span, e, lo)?;
2591                   }
2592                 }
2593                 continue;
2594             }
2595             if self.expr_is_complete(&e) { break; }
2596             match self.token {
2597               // expr(...)
2598               token::OpenDelim(token::Paren) => {
2599                 let es = self.parse_unspanned_seq(
2600                     &token::OpenDelim(token::Paren),
2601                     &token::CloseDelim(token::Paren),
2602                     SeqSep::trailing_allowed(token::Comma),
2603                     |p| Ok(p.parse_expr()?)
2604                 )?;
2605                 hi = self.prev_span;
2606
2607                 let nd = self.mk_call(e, es);
2608                 e = self.mk_expr(lo.to(hi), nd, ThinVec::new());
2609               }
2610
2611               // expr[...]
2612               // Could be either an index expression or a slicing expression.
2613               token::OpenDelim(token::Bracket) => {
2614                 self.bump();
2615                 let ix = self.parse_expr()?;
2616                 hi = self.span;
2617                 self.expect(&token::CloseDelim(token::Bracket))?;
2618                 let index = self.mk_index(e, ix);
2619                 e = self.mk_expr(lo.to(hi), index, ThinVec::new())
2620               }
2621               _ => return Ok(e)
2622             }
2623         }
2624         return Ok(e);
2625     }
2626
2627     pub fn process_potential_macro_variable(&mut self) {
2628         let ident = match self.token {
2629             token::SubstNt(name) => {
2630                 self.fatal(&format!("unknown macro variable `{}`", name)).emit();
2631                 return
2632             }
2633             token::Interpolated(ref nt) => {
2634                 self.meta_var_span = Some(self.span);
2635                 match **nt {
2636                     token::NtIdent(ident) => ident,
2637                     _ => return,
2638                 }
2639             }
2640             _ => return,
2641         };
2642         self.token = token::Ident(ident.node);
2643         self.span = ident.span;
2644     }
2645
2646     /// parse a single token tree from the input.
2647     pub fn parse_token_tree(&mut self) -> TokenTree {
2648         match self.token {
2649             token::OpenDelim(..) => {
2650                 let frame = mem::replace(&mut self.token_cursor.frame,
2651                                          self.token_cursor.stack.pop().unwrap());
2652                 self.span = frame.span;
2653                 self.bump();
2654                 TokenTree::Delimited(frame.span, Delimited {
2655                     delim: frame.delim,
2656                     tts: frame.tree_cursor.original_stream().into(),
2657                 })
2658             },
2659             token::CloseDelim(_) | token::Eof => unreachable!(),
2660             _ => {
2661                 let (token, span) = (mem::replace(&mut self.token, token::Underscore), self.span);
2662                 self.bump();
2663                 TokenTree::Token(span, token)
2664             }
2665         }
2666     }
2667
2668     // parse a stream of tokens into a list of TokenTree's,
2669     // up to EOF.
2670     pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
2671         let mut tts = Vec::new();
2672         while self.token != token::Eof {
2673             tts.push(self.parse_token_tree());
2674         }
2675         Ok(tts)
2676     }
2677
2678     pub fn parse_tokens(&mut self) -> TokenStream {
2679         let mut result = Vec::new();
2680         loop {
2681             match self.token {
2682                 token::Eof | token::CloseDelim(..) => break,
2683                 _ => result.push(self.parse_token_tree().into()),
2684             }
2685         }
2686         TokenStream::concat(result)
2687     }
2688
2689     /// Parse a prefix-unary-operator expr
2690     pub fn parse_prefix_expr(&mut self,
2691                              already_parsed_attrs: Option<ThinVec<Attribute>>)
2692                              -> PResult<'a, P<Expr>> {
2693         let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2694         let lo = self.span;
2695         // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
2696         let (hi, ex) = match self.token {
2697             token::Not => {
2698                 self.bump();
2699                 let e = self.parse_prefix_expr(None);
2700                 let (span, e) = self.interpolated_or_expr_span(e)?;
2701                 (span, self.mk_unary(UnOp::Not, e))
2702             }
2703             // Suggest `!` for bitwise negation when encountering a `~`
2704             token::Tilde => {
2705                 self.bump();
2706                 let e = self.parse_prefix_expr(None);
2707                 let (span, e) = self.interpolated_or_expr_span(e)?;
2708                 let span_of_tilde = lo;
2709                 let mut err = self.diagnostic().struct_span_err(span_of_tilde,
2710                         "`~` can not be used as a unary operator");
2711                 err.span_label(span_of_tilde, &"did you mean `!`?");
2712                 err.help("use `!` instead of `~` if you meant to perform bitwise negation");
2713                 err.emit();
2714                 (span, self.mk_unary(UnOp::Not, e))
2715             }
2716             token::BinOp(token::Minus) => {
2717                 self.bump();
2718                 let e = self.parse_prefix_expr(None);
2719                 let (span, e) = self.interpolated_or_expr_span(e)?;
2720                 (span, self.mk_unary(UnOp::Neg, e))
2721             }
2722             token::BinOp(token::Star) => {
2723                 self.bump();
2724                 let e = self.parse_prefix_expr(None);
2725                 let (span, e) = self.interpolated_or_expr_span(e)?;
2726                 (span, self.mk_unary(UnOp::Deref, e))
2727             }
2728             token::BinOp(token::And) | token::AndAnd => {
2729                 self.expect_and()?;
2730                 let m = self.parse_mutability();
2731                 let e = self.parse_prefix_expr(None);
2732                 let (span, e) = self.interpolated_or_expr_span(e)?;
2733                 (span, ExprKind::AddrOf(m, e))
2734             }
2735             token::Ident(..) if self.token.is_keyword(keywords::In) => {
2736                 self.bump();
2737                 let place = self.parse_expr_res(
2738                     RESTRICTION_NO_STRUCT_LITERAL,
2739                     None,
2740                 )?;
2741                 let blk = self.parse_block()?;
2742                 let span = blk.span;
2743                 let blk_expr = self.mk_expr(span, ExprKind::Block(blk), ThinVec::new());
2744                 (span, ExprKind::InPlace(place, blk_expr))
2745             }
2746             token::Ident(..) if self.token.is_keyword(keywords::Box) => {
2747                 self.bump();
2748                 let e = self.parse_prefix_expr(None);
2749                 let (span, e) = self.interpolated_or_expr_span(e)?;
2750                 (span, ExprKind::Box(e))
2751             }
2752             _ => return self.parse_dot_or_call_expr(Some(attrs))
2753         };
2754         return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2755     }
2756
2757     /// Parse an associative expression
2758     ///
2759     /// This parses an expression accounting for associativity and precedence of the operators in
2760     /// the expression.
2761     pub fn parse_assoc_expr(&mut self,
2762                             already_parsed_attrs: Option<ThinVec<Attribute>>)
2763                             -> PResult<'a, P<Expr>> {
2764         self.parse_assoc_expr_with(0, already_parsed_attrs.into())
2765     }
2766
2767     /// Parse an associative expression with operators of at least `min_prec` precedence
2768     pub fn parse_assoc_expr_with(&mut self,
2769                                  min_prec: usize,
2770                                  lhs: LhsExpr)
2771                                  -> PResult<'a, P<Expr>> {
2772         let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
2773             expr
2774         } else {
2775             let attrs = match lhs {
2776                 LhsExpr::AttributesParsed(attrs) => Some(attrs),
2777                 _ => None,
2778             };
2779             if self.token == token::DotDot || self.token == token::DotDotDot {
2780                 return self.parse_prefix_range_expr(attrs);
2781             } else {
2782                 self.parse_prefix_expr(attrs)?
2783             }
2784         };
2785
2786         if self.expr_is_complete(&lhs) {
2787             // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
2788             return Ok(lhs);
2789         }
2790         self.expected_tokens.push(TokenType::Operator);
2791         while let Some(op) = AssocOp::from_token(&self.token) {
2792
2793             let lhs_span = if self.prev_token_kind == PrevTokenKind::Interpolated {
2794                 self.prev_span
2795             } else {
2796                 lhs.span
2797             };
2798
2799             let cur_op_span = self.span;
2800             let restrictions = if op.is_assign_like() {
2801                 self.restrictions & RESTRICTION_NO_STRUCT_LITERAL
2802             } else {
2803                 self.restrictions
2804             };
2805             if op.precedence() < min_prec {
2806                 break;
2807             }
2808             self.bump();
2809             if op.is_comparison() {
2810                 self.check_no_chained_comparison(&lhs, &op);
2811             }
2812             // Special cases:
2813             if op == AssocOp::As {
2814                 let rhs = self.parse_ty_no_plus()?;
2815                 lhs = self.mk_expr(lhs_span.to(rhs.span), ExprKind::Cast(lhs, rhs), ThinVec::new());
2816                 continue
2817             } else if op == AssocOp::Colon {
2818                 let rhs = self.parse_ty_no_plus()?;
2819                 lhs = self.mk_expr(lhs_span.to(rhs.span), ExprKind::Type(lhs, rhs), ThinVec::new());
2820                 continue
2821             } else if op == AssocOp::DotDot || op == AssocOp::DotDotDot {
2822                 // If we didn’t have to handle `x..`/`x...`, it would be pretty easy to
2823                 // generalise it to the Fixity::None code.
2824                 //
2825                 // We have 2 alternatives here: `x..y`/`x...y` and `x..`/`x...` The other
2826                 // two variants are handled with `parse_prefix_range_expr` call above.
2827                 let rhs = if self.is_at_start_of_range_notation_rhs() {
2828                     Some(self.parse_assoc_expr_with(op.precedence() + 1,
2829                                                     LhsExpr::NotYetParsed)?)
2830                 } else {
2831                     None
2832                 };
2833                 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
2834                     x.span
2835                 } else {
2836                     cur_op_span
2837                 });
2838                 let limits = if op == AssocOp::DotDot {
2839                     RangeLimits::HalfOpen
2840                 } else {
2841                     RangeLimits::Closed
2842                 };
2843
2844                 let r = try!(self.mk_range(Some(lhs), rhs, limits));
2845                 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
2846                 break
2847             }
2848
2849             let rhs = match op.fixity() {
2850                 Fixity::Right => self.with_res(
2851                     restrictions - RESTRICTION_STMT_EXPR,
2852                     |this| {
2853                         this.parse_assoc_expr_with(op.precedence(),
2854                             LhsExpr::NotYetParsed)
2855                 }),
2856                 Fixity::Left => self.with_res(
2857                     restrictions - RESTRICTION_STMT_EXPR,
2858                     |this| {
2859                         this.parse_assoc_expr_with(op.precedence() + 1,
2860                             LhsExpr::NotYetParsed)
2861                 }),
2862                 // We currently have no non-associative operators that are not handled above by
2863                 // the special cases. The code is here only for future convenience.
2864                 Fixity::None => self.with_res(
2865                     restrictions - RESTRICTION_STMT_EXPR,
2866                     |this| {
2867                         this.parse_assoc_expr_with(op.precedence() + 1,
2868                             LhsExpr::NotYetParsed)
2869                 }),
2870             }?;
2871
2872             let span = lhs_span.to(rhs.span);
2873             lhs = match op {
2874                 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
2875                 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
2876                 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
2877                 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
2878                 AssocOp::Greater | AssocOp::GreaterEqual => {
2879                     let ast_op = op.to_ast_binop().unwrap();
2880                     let binary = self.mk_binary(codemap::respan(cur_op_span, ast_op), lhs, rhs);
2881                     self.mk_expr(span, binary, ThinVec::new())
2882                 }
2883                 AssocOp::Assign =>
2884                     self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
2885                 AssocOp::Inplace =>
2886                     self.mk_expr(span, ExprKind::InPlace(lhs, rhs), ThinVec::new()),
2887                 AssocOp::AssignOp(k) => {
2888                     let aop = match k {
2889                         token::Plus =>    BinOpKind::Add,
2890                         token::Minus =>   BinOpKind::Sub,
2891                         token::Star =>    BinOpKind::Mul,
2892                         token::Slash =>   BinOpKind::Div,
2893                         token::Percent => BinOpKind::Rem,
2894                         token::Caret =>   BinOpKind::BitXor,
2895                         token::And =>     BinOpKind::BitAnd,
2896                         token::Or =>      BinOpKind::BitOr,
2897                         token::Shl =>     BinOpKind::Shl,
2898                         token::Shr =>     BinOpKind::Shr,
2899                     };
2900                     let aopexpr = self.mk_assign_op(codemap::respan(cur_op_span, aop), lhs, rhs);
2901                     self.mk_expr(span, aopexpr, ThinVec::new())
2902                 }
2903                 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotDot => {
2904                     self.bug("As, Colon, DotDot or DotDotDot branch reached")
2905                 }
2906             };
2907
2908             if op.fixity() == Fixity::None { break }
2909         }
2910         Ok(lhs)
2911     }
2912
2913     /// Produce an error if comparison operators are chained (RFC #558).
2914     /// We only need to check lhs, not rhs, because all comparison ops
2915     /// have same precedence and are left-associative
2916     fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
2917         debug_assert!(outer_op.is_comparison());
2918         match lhs.node {
2919             ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
2920                 // respan to include both operators
2921                 let op_span = op.span.to(self.span);
2922                 let mut err = self.diagnostic().struct_span_err(op_span,
2923                     "chained comparison operators require parentheses");
2924                 if op.node == BinOpKind::Lt &&
2925                     *outer_op == AssocOp::Less ||  // Include `<` to provide this recommendation
2926                     *outer_op == AssocOp::Greater  // even in a case like the following:
2927                 {                                  //     Foo<Bar<Baz<Qux, ()>>>
2928                     err.help(
2929                         "use `::<...>` instead of `<...>` if you meant to specify type arguments");
2930                 }
2931                 err.emit();
2932             }
2933             _ => {}
2934         }
2935     }
2936
2937     /// Parse prefix-forms of range notation: `..expr`, `..`, `...expr`
2938     fn parse_prefix_range_expr(&mut self,
2939                                already_parsed_attrs: Option<ThinVec<Attribute>>)
2940                                -> PResult<'a, P<Expr>> {
2941         debug_assert!(self.token == token::DotDot || self.token == token::DotDotDot);
2942         let tok = self.token.clone();
2943         let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2944         let lo = self.span;
2945         let mut hi = self.span;
2946         self.bump();
2947         let opt_end = if self.is_at_start_of_range_notation_rhs() {
2948             // RHS must be parsed with more associativity than the dots.
2949             let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
2950             Some(self.parse_assoc_expr_with(next_prec,
2951                                             LhsExpr::NotYetParsed)
2952                 .map(|x|{
2953                     hi = x.span;
2954                     x
2955                 })?)
2956          } else {
2957             None
2958         };
2959         let limits = if tok == token::DotDot {
2960             RangeLimits::HalfOpen
2961         } else {
2962             RangeLimits::Closed
2963         };
2964
2965         let r = try!(self.mk_range(None,
2966                                    opt_end,
2967                                    limits));
2968         Ok(self.mk_expr(lo.to(hi), r, attrs))
2969     }
2970
2971     fn is_at_start_of_range_notation_rhs(&self) -> bool {
2972         if self.token.can_begin_expr() {
2973             // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
2974             if self.token == token::OpenDelim(token::Brace) {
2975                 return !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL);
2976             }
2977             true
2978         } else {
2979             false
2980         }
2981     }
2982
2983     /// Parse an 'if' or 'if let' expression ('if' token already eaten)
2984     pub fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
2985         if self.check_keyword(keywords::Let) {
2986             return self.parse_if_let_expr(attrs);
2987         }
2988         let lo = self.prev_span;
2989         let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
2990         let thn = self.parse_block()?;
2991         let mut els: Option<P<Expr>> = None;
2992         let mut hi = thn.span;
2993         if self.eat_keyword(keywords::Else) {
2994             let elexpr = self.parse_else_expr()?;
2995             hi = elexpr.span;
2996             els = Some(elexpr);
2997         }
2998         Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
2999     }
3000
3001     /// Parse an 'if let' expression ('if' token already eaten)
3002     pub fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3003                              -> PResult<'a, P<Expr>> {
3004         let lo = self.prev_span;
3005         self.expect_keyword(keywords::Let)?;
3006         let pat = self.parse_pat()?;
3007         self.expect(&token::Eq)?;
3008         let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3009         let thn = self.parse_block()?;
3010         let (hi, els) = if self.eat_keyword(keywords::Else) {
3011             let expr = self.parse_else_expr()?;
3012             (expr.span, Some(expr))
3013         } else {
3014             (thn.span, None)
3015         };
3016         Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pat, expr, thn, els), attrs))
3017     }
3018
3019     // `move |args| expr`
3020     pub fn parse_lambda_expr(&mut self,
3021                              lo: Span,
3022                              capture_clause: CaptureBy,
3023                              attrs: ThinVec<Attribute>)
3024                              -> PResult<'a, P<Expr>>
3025     {
3026         let decl = self.parse_fn_block_decl()?;
3027         let decl_hi = self.prev_span;
3028         let body = match decl.output {
3029             FunctionRetTy::Default(_) => self.parse_expr()?,
3030             _ => {
3031                 // If an explicit return type is given, require a
3032                 // block to appear (RFC 968).
3033                 let body_lo = self.span;
3034                 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3035             }
3036         };
3037
3038         Ok(self.mk_expr(
3039             lo.to(body.span),
3040             ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3041             attrs))
3042     }
3043
3044     // `else` token already eaten
3045     pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3046         if self.eat_keyword(keywords::If) {
3047             return self.parse_if_expr(ThinVec::new());
3048         } else {
3049             let blk = self.parse_block()?;
3050             return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3051         }
3052     }
3053
3054     /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3055     pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3056                           span_lo: Span,
3057                           mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3058         // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3059
3060         let pat = self.parse_pat()?;
3061         self.expect_keyword(keywords::In)?;
3062         let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3063         let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3064         attrs.extend(iattrs);
3065
3066         let hi = self.prev_span;
3067         Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3068     }
3069
3070     /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3071     pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3072                             span_lo: Span,
3073                             mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3074         if self.token.is_keyword(keywords::Let) {
3075             return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3076         }
3077         let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3078         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3079         attrs.extend(iattrs);
3080         let span = span_lo.to(body.span);
3081         return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3082     }
3083
3084     /// Parse a 'while let' expression ('while' token already eaten)
3085     pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3086                                 span_lo: Span,
3087                                 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3088         self.expect_keyword(keywords::Let)?;
3089         let pat = self.parse_pat()?;
3090         self.expect(&token::Eq)?;
3091         let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3092         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3093         attrs.extend(iattrs);
3094         let span = span_lo.to(body.span);
3095         return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3096     }
3097
3098     // parse `loop {...}`, `loop` token already eaten
3099     pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3100                            span_lo: Span,
3101                            mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3102         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3103         attrs.extend(iattrs);
3104         let span = span_lo.to(body.span);
3105         Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3106     }
3107
3108     /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3109     pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3110         -> PResult<'a, P<Expr>>
3111     {
3112         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3113         attrs.extend(iattrs);
3114         Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3115     }
3116
3117     // `match` token already eaten
3118     fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3119         let match_span = self.prev_span;
3120         let lo = self.prev_span;
3121         let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL,
3122                                                None)?;
3123         if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3124             if self.token == token::Token::Semi {
3125                 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3126             }
3127             return Err(e)
3128         }
3129         attrs.extend(self.parse_inner_attributes()?);
3130
3131         let mut arms: Vec<Arm> = Vec::new();
3132         while self.token != token::CloseDelim(token::Brace) {
3133             match self.parse_arm() {
3134                 Ok(arm) => arms.push(arm),
3135                 Err(mut e) => {
3136                     // Recover by skipping to the end of the block.
3137                     e.emit();
3138                     self.recover_stmt();
3139                     let span = lo.to(self.span);
3140                     if self.token == token::CloseDelim(token::Brace) {
3141                         self.bump();
3142                     }
3143                     return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3144                 }
3145             }
3146         }
3147         let hi = self.span;
3148         self.bump();
3149         return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3150     }
3151
3152     pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3153         maybe_whole!(self, NtArm, |x| x);
3154
3155         let attrs = self.parse_outer_attributes()?;
3156         let pats = self.parse_pats()?;
3157         let mut guard = None;
3158         if self.eat_keyword(keywords::If) {
3159             guard = Some(self.parse_expr()?);
3160         }
3161         self.expect(&token::FatArrow)?;
3162         let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR, None)?;
3163
3164         let require_comma =
3165             !classify::expr_is_simple_block(&expr)
3166             && self.token != token::CloseDelim(token::Brace);
3167
3168         if require_comma {
3169             self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3170         } else {
3171             self.eat(&token::Comma);
3172         }
3173
3174         Ok(ast::Arm {
3175             attrs: attrs,
3176             pats: pats,
3177             guard: guard,
3178             body: expr,
3179         })
3180     }
3181
3182     /// Parse an expression
3183     pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3184         self.parse_expr_res(Restrictions::empty(), None)
3185     }
3186
3187     /// Evaluate the closure with restrictions in place.
3188     ///
3189     /// After the closure is evaluated, restrictions are reset.
3190     pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3191         where F: FnOnce(&mut Self) -> T
3192     {
3193         let old = self.restrictions;
3194         self.restrictions = r;
3195         let r = f(self);
3196         self.restrictions = old;
3197         return r;
3198
3199     }
3200
3201     /// Parse an expression, subject to the given restrictions
3202     pub fn parse_expr_res(&mut self, r: Restrictions,
3203                           already_parsed_attrs: Option<ThinVec<Attribute>>)
3204                           -> PResult<'a, P<Expr>> {
3205         self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3206     }
3207
3208     /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3209     fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3210         if self.check(&token::Eq) {
3211             self.bump();
3212             Ok(Some(self.parse_expr()?))
3213         } else {
3214             Ok(None)
3215         }
3216     }
3217
3218     /// Parse patterns, separated by '|' s
3219     fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3220         let mut pats = Vec::new();
3221         loop {
3222             pats.push(self.parse_pat()?);
3223             if self.check(&token::BinOp(token::Or)) { self.bump();}
3224             else { return Ok(pats); }
3225         };
3226     }
3227
3228     fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3229                                 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3230         let mut fields = vec![];
3231         let mut ddpos = None;
3232
3233         while !self.check(&token::CloseDelim(token::Paren)) {
3234             if ddpos.is_none() && self.eat(&token::DotDot) {
3235                 ddpos = Some(fields.len());
3236                 if self.eat(&token::Comma) {
3237                     // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3238                     fields.push(self.parse_pat()?);
3239                 }
3240             } else if ddpos.is_some() && self.eat(&token::DotDot) {
3241                 // Emit a friendly error, ignore `..` and continue parsing
3242                 self.span_err(self.prev_span, "`..` can only be used once per \
3243                                                tuple or tuple struct pattern");
3244             } else {
3245                 fields.push(self.parse_pat()?);
3246             }
3247
3248             if !self.check(&token::CloseDelim(token::Paren)) ||
3249                     (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3250                 self.expect(&token::Comma)?;
3251             }
3252         }
3253
3254         Ok((fields, ddpos))
3255     }
3256
3257     fn parse_pat_vec_elements(
3258         &mut self,
3259     ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3260         let mut before = Vec::new();
3261         let mut slice = None;
3262         let mut after = Vec::new();
3263         let mut first = true;
3264         let mut before_slice = true;
3265
3266         while self.token != token::CloseDelim(token::Bracket) {
3267             if first {
3268                 first = false;
3269             } else {
3270                 self.expect(&token::Comma)?;
3271
3272                 if self.token == token::CloseDelim(token::Bracket)
3273                         && (before_slice || !after.is_empty()) {
3274                     break
3275                 }
3276             }
3277
3278             if before_slice {
3279                 if self.eat(&token::DotDot) {
3280
3281                     if self.check(&token::Comma) ||
3282                             self.check(&token::CloseDelim(token::Bracket)) {
3283                         slice = Some(P(ast::Pat {
3284                             id: ast::DUMMY_NODE_ID,
3285                             node: PatKind::Wild,
3286                             span: self.span,
3287                         }));
3288                         before_slice = false;
3289                     }
3290                     continue
3291                 }
3292             }
3293
3294             let subpat = self.parse_pat()?;
3295             if before_slice && self.eat(&token::DotDot) {
3296                 slice = Some(subpat);
3297                 before_slice = false;
3298             } else if before_slice {
3299                 before.push(subpat);
3300             } else {
3301                 after.push(subpat);
3302             }
3303         }
3304
3305         Ok((before, slice, after))
3306     }
3307
3308     /// Parse the fields of a struct-like pattern
3309     fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3310         let mut fields = Vec::new();
3311         let mut etc = false;
3312         let mut first = true;
3313         while self.token != token::CloseDelim(token::Brace) {
3314             if first {
3315                 first = false;
3316             } else {
3317                 self.expect(&token::Comma)?;
3318                 // accept trailing commas
3319                 if self.check(&token::CloseDelim(token::Brace)) { break }
3320             }
3321
3322             let attrs = self.parse_outer_attributes()?;
3323             let lo = self.span;
3324             let hi;
3325
3326             if self.check(&token::DotDot) {
3327                 self.bump();
3328                 if self.token != token::CloseDelim(token::Brace) {
3329                     let token_str = self.this_token_to_string();
3330                     return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3331                                        token_str)))
3332                 }
3333                 etc = true;
3334                 break;
3335             }
3336
3337             // Check if a colon exists one ahead. This means we're parsing a fieldname.
3338             let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3339                 // Parsing a pattern of the form "fieldname: pat"
3340                 let fieldname = self.parse_field_name()?;
3341                 self.bump();
3342                 let pat = self.parse_pat()?;
3343                 hi = pat.span;
3344                 (pat, fieldname, false)
3345             } else {
3346                 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3347                 let is_box = self.eat_keyword(keywords::Box);
3348                 let boxed_span = self.span;
3349                 let is_ref = self.eat_keyword(keywords::Ref);
3350                 let is_mut = self.eat_keyword(keywords::Mut);
3351                 let fieldname = self.parse_ident()?;
3352                 hi = self.prev_span;
3353
3354                 let bind_type = match (is_ref, is_mut) {
3355                     (true, true) => BindingMode::ByRef(Mutability::Mutable),
3356                     (true, false) => BindingMode::ByRef(Mutability::Immutable),
3357                     (false, true) => BindingMode::ByValue(Mutability::Mutable),
3358                     (false, false) => BindingMode::ByValue(Mutability::Immutable),
3359                 };
3360                 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3361                 let fieldpat = P(ast::Pat{
3362                     id: ast::DUMMY_NODE_ID,
3363                     node: PatKind::Ident(bind_type, fieldpath, None),
3364                     span: boxed_span.to(hi),
3365                 });
3366
3367                 let subpat = if is_box {
3368                     P(ast::Pat{
3369                         id: ast::DUMMY_NODE_ID,
3370                         node: PatKind::Box(fieldpat),
3371                         span: lo.to(hi),
3372                     })
3373                 } else {
3374                     fieldpat
3375                 };
3376                 (subpat, fieldname, true)
3377             };
3378
3379             fields.push(codemap::Spanned { span: lo.to(hi),
3380                                            node: ast::FieldPat {
3381                                                ident: fieldname,
3382                                                pat: subpat,
3383                                                is_shorthand: is_shorthand,
3384                                                attrs: attrs.into(),
3385                                            }
3386             });
3387         }
3388         return Ok((fields, etc));
3389     }
3390
3391     fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3392         if self.token.is_path_start() {
3393             let lo = self.span;
3394             let (qself, path) = if self.eat_lt() {
3395                 // Parse a qualified path
3396                 let (qself, path) =
3397                     self.parse_qualified_path(PathStyle::Expr)?;
3398                 (Some(qself), path)
3399             } else {
3400                 // Parse an unqualified path
3401                 (None, self.parse_path(PathStyle::Expr)?)
3402             };
3403             let hi = self.prev_span;
3404             Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3405         } else {
3406             self.parse_pat_literal_maybe_minus()
3407         }
3408     }
3409
3410     // helper function to decide whether to parse as ident binding or to try to do
3411     // something more complex like range patterns
3412     fn parse_as_ident(&mut self) -> bool {
3413         self.look_ahead(1, |t| match *t {
3414             token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3415             token::DotDotDot | token::ModSep | token::Not => Some(false),
3416             // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3417             // range pattern branch
3418             token::DotDot => None,
3419             _ => Some(true),
3420         }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3421             token::Comma | token::CloseDelim(token::Bracket) => true,
3422             _ => false,
3423         }))
3424     }
3425
3426     /// Parse a pattern.
3427     pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3428         maybe_whole!(self, NtPat, |x| x);
3429
3430         let lo = self.span;
3431         let pat;
3432         match self.token {
3433             token::Underscore => {
3434                 // Parse _
3435                 self.bump();
3436                 pat = PatKind::Wild;
3437             }
3438             token::BinOp(token::And) | token::AndAnd => {
3439                 // Parse &pat / &mut pat
3440                 self.expect_and()?;
3441                 let mutbl = self.parse_mutability();
3442                 if let token::Lifetime(ident) = self.token {
3443                     return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3444                 }
3445                 let subpat = self.parse_pat()?;
3446                 pat = PatKind::Ref(subpat, mutbl);
3447             }
3448             token::OpenDelim(token::Paren) => {
3449                 // Parse (pat,pat,pat,...) as tuple pattern
3450                 self.bump();
3451                 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3452                 self.expect(&token::CloseDelim(token::Paren))?;
3453                 pat = PatKind::Tuple(fields, ddpos);
3454             }
3455             token::OpenDelim(token::Bracket) => {
3456                 // Parse [pat,pat,...] as slice pattern
3457                 self.bump();
3458                 let (before, slice, after) = self.parse_pat_vec_elements()?;
3459                 self.expect(&token::CloseDelim(token::Bracket))?;
3460                 pat = PatKind::Slice(before, slice, after);
3461             }
3462             // At this point, token != _, &, &&, (, [
3463             _ => if self.eat_keyword(keywords::Mut) {
3464                 // Parse mut ident @ pat
3465                 pat = self.parse_pat_ident(BindingMode::ByValue(Mutability::Mutable))?;
3466             } else if self.eat_keyword(keywords::Ref) {
3467                 // Parse ref ident @ pat / ref mut ident @ pat
3468                 let mutbl = self.parse_mutability();
3469                 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3470             } else if self.eat_keyword(keywords::Box) {
3471                 // Parse box pat
3472                 let subpat = self.parse_pat()?;
3473                 pat = PatKind::Box(subpat);
3474             } else if self.token.is_ident() && !self.token.is_any_keyword() &&
3475                       self.parse_as_ident() {
3476                 // Parse ident @ pat
3477                 // This can give false positives and parse nullary enums,
3478                 // they are dealt with later in resolve
3479                 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3480                 pat = self.parse_pat_ident(binding_mode)?;
3481             } else if self.token.is_path_start() {
3482                 // Parse pattern starting with a path
3483                 let (qself, path) = if self.eat_lt() {
3484                     // Parse a qualified path
3485                     let (qself, path) = self.parse_qualified_path(PathStyle::Expr)?;
3486                     (Some(qself), path)
3487                 } else {
3488                     // Parse an unqualified path
3489                     (None, self.parse_path(PathStyle::Expr)?)
3490                 };
3491                 match self.token {
3492                     token::Not if qself.is_none() => {
3493                         // Parse macro invocation
3494                         self.bump();
3495                         let (_, tts) = self.expect_delimited_token_tree()?;
3496                         let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3497                         pat = PatKind::Mac(mac);
3498                     }
3499                     token::DotDotDot | token::DotDot => {
3500                         let end_kind = match self.token {
3501                             token::DotDot => RangeEnd::Excluded,
3502                             token::DotDotDot => RangeEnd::Included,
3503                             _ => panic!("can only parse `..` or `...` for ranges (checked above)"),
3504                         };
3505                         // Parse range
3506                         let span = lo.to(self.prev_span);
3507                         let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3508                         self.bump();
3509                         let end = self.parse_pat_range_end()?;
3510                         pat = PatKind::Range(begin, end, end_kind);
3511                     }
3512                     token::OpenDelim(token::Brace) => {
3513                         if qself.is_some() {
3514                             return Err(self.fatal("unexpected `{` after qualified path"));
3515                         }
3516                         // Parse struct pattern
3517                         self.bump();
3518                         let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3519                             e.emit();
3520                             self.recover_stmt();
3521                             (vec![], false)
3522                         });
3523                         self.bump();
3524                         pat = PatKind::Struct(path, fields, etc);
3525                     }
3526                     token::OpenDelim(token::Paren) => {
3527                         if qself.is_some() {
3528                             return Err(self.fatal("unexpected `(` after qualified path"));
3529                         }
3530                         // Parse tuple struct or enum pattern
3531                         self.bump();
3532                         let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3533                         self.expect(&token::CloseDelim(token::Paren))?;
3534                         pat = PatKind::TupleStruct(path, fields, ddpos)
3535                     }
3536                     _ => pat = PatKind::Path(qself, path),
3537                 }
3538             } else {
3539                 // Try to parse everything else as literal with optional minus
3540                 match self.parse_pat_literal_maybe_minus() {
3541                     Ok(begin) => {
3542                         if self.eat(&token::DotDotDot) {
3543                             let end = self.parse_pat_range_end()?;
3544                             pat = PatKind::Range(begin, end, RangeEnd::Included);
3545                         } else if self.eat(&token::DotDot) {
3546                             let end = self.parse_pat_range_end()?;
3547                             pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3548                         } else {
3549                             pat = PatKind::Lit(begin);
3550                         }
3551                     }
3552                     Err(mut err) => {
3553                         self.cancel(&mut err);
3554                         let msg = format!("expected pattern, found {}", self.this_token_descr());
3555                         return Err(self.fatal(&msg));
3556                     }
3557                 }
3558             }
3559         }
3560
3561         Ok(P(ast::Pat {
3562             id: ast::DUMMY_NODE_ID,
3563             node: pat,
3564             span: lo.to(self.prev_span),
3565         }))
3566     }
3567
3568     /// Parse ident or ident @ pat
3569     /// used by the copy foo and ref foo patterns to give a good
3570     /// error message when parsing mistakes like ref foo(a,b)
3571     fn parse_pat_ident(&mut self,
3572                        binding_mode: ast::BindingMode)
3573                        -> PResult<'a, PatKind> {
3574         let ident_span = self.span;
3575         let ident = self.parse_ident()?;
3576         let name = codemap::Spanned{span: ident_span, node: ident};
3577         let sub = if self.eat(&token::At) {
3578             Some(self.parse_pat()?)
3579         } else {
3580             None
3581         };
3582
3583         // just to be friendly, if they write something like
3584         //   ref Some(i)
3585         // we end up here with ( as the current token.  This shortly
3586         // leads to a parse error.  Note that if there is no explicit
3587         // binding mode then we do not end up here, because the lookahead
3588         // will direct us over to parse_enum_variant()
3589         if self.token == token::OpenDelim(token::Paren) {
3590             return Err(self.span_fatal(
3591                 self.prev_span,
3592                 "expected identifier, found enum pattern"))
3593         }
3594
3595         Ok(PatKind::Ident(binding_mode, name, sub))
3596     }
3597
3598     /// Parse a local variable declaration
3599     fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3600         let lo = self.span;
3601         let pat = self.parse_pat()?;
3602
3603         let mut ty = None;
3604         if self.eat(&token::Colon) {
3605             ty = Some(self.parse_ty()?);
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.len() > 0 {
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             match polarity {
4921                 ast::ImplPolarity::Negative => {
4922                     // This is a negated type implementation
4923                     // `impl !MyType {}`, which is not allowed.
4924                     self.span_err(neg_span, "inherent implementation can't be negated");
4925                 },
4926                 _ => {}
4927             }
4928             None
4929         };
4930
4931         if opt_trait.is_some() && self.eat(&token::DotDot) {
4932             if generics.is_parameterized() {
4933                 self.span_err(impl_span, "default trait implementations are not \
4934                                           allowed to have generics");
4935             }
4936
4937             if let ast::Defaultness::Default = defaultness {
4938                 self.span_err(impl_span, "`default impl` is not allowed for \
4939                                          default trait implementations");
4940             }
4941
4942             self.expect(&token::OpenDelim(token::Brace))?;
4943             self.expect(&token::CloseDelim(token::Brace))?;
4944             Ok((keywords::Invalid.ident(),
4945              ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
4946         } else {
4947             if opt_trait.is_some() {
4948                 ty = self.parse_ty()?;
4949             }
4950             generics.where_clause = self.parse_where_clause()?;
4951
4952             self.expect(&token::OpenDelim(token::Brace))?;
4953             let attrs = self.parse_inner_attributes()?;
4954
4955             let mut impl_items = vec![];
4956             while !self.eat(&token::CloseDelim(token::Brace)) {
4957                 let mut at_end = false;
4958                 match self.parse_impl_item(&mut at_end) {
4959                     Ok(item) => impl_items.push(item),
4960                     Err(mut e) => {
4961                         e.emit();
4962                         if !at_end {
4963                             self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
4964                         }
4965                     }
4966                 }
4967             }
4968
4969             Ok((keywords::Invalid.ident(),
4970              ItemKind::Impl(unsafety, polarity, defaultness, generics, opt_trait, ty, impl_items),
4971              Some(attrs)))
4972         }
4973     }
4974
4975     fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<LifetimeDef>> {
4976         if self.eat_keyword(keywords::For) {
4977             self.expect_lt()?;
4978             let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4979             self.expect_gt()?;
4980             if !ty_params.is_empty() {
4981                 self.span_err(ty_params[0].span,
4982                               "only lifetime parameters can be used in this context");
4983             }
4984             Ok(lifetime_defs)
4985         } else {
4986             Ok(Vec::new())
4987         }
4988     }
4989
4990     /// Parse struct Foo { ... }
4991     fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
4992         let class_name = self.parse_ident()?;
4993
4994         let mut generics = self.parse_generics()?;
4995
4996         // There is a special case worth noting here, as reported in issue #17904.
4997         // If we are parsing a tuple struct it is the case that the where clause
4998         // should follow the field list. Like so:
4999         //
5000         // struct Foo<T>(T) where T: Copy;
5001         //
5002         // If we are parsing a normal record-style struct it is the case
5003         // that the where clause comes before the body, and after the generics.
5004         // So if we look ahead and see a brace or a where-clause we begin
5005         // parsing a record style struct.
5006         //
5007         // Otherwise if we look ahead and see a paren we parse a tuple-style
5008         // struct.
5009
5010         let vdata = if self.token.is_keyword(keywords::Where) {
5011             generics.where_clause = self.parse_where_clause()?;
5012             if self.eat(&token::Semi) {
5013                 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5014                 VariantData::Unit(ast::DUMMY_NODE_ID)
5015             } else {
5016                 // If we see: `struct Foo<T> where T: Copy { ... }`
5017                 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5018             }
5019         // No `where` so: `struct Foo<T>;`
5020         } else if self.eat(&token::Semi) {
5021             VariantData::Unit(ast::DUMMY_NODE_ID)
5022         // Record-style struct definition
5023         } else if self.token == token::OpenDelim(token::Brace) {
5024             VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5025         // Tuple-style struct definition with optional where-clause.
5026         } else if self.token == token::OpenDelim(token::Paren) {
5027             let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5028             generics.where_clause = self.parse_where_clause()?;
5029             self.expect(&token::Semi)?;
5030             body
5031         } else {
5032             let token_str = self.this_token_to_string();
5033             return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5034                                             name, found `{}`", token_str)))
5035         };
5036
5037         Ok((class_name, ItemKind::Struct(vdata, generics), None))
5038     }
5039
5040     /// Parse union Foo { ... }
5041     fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5042         let class_name = self.parse_ident()?;
5043
5044         let mut generics = self.parse_generics()?;
5045
5046         let vdata = if self.token.is_keyword(keywords::Where) {
5047             generics.where_clause = self.parse_where_clause()?;
5048             VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5049         } else if self.token == token::OpenDelim(token::Brace) {
5050             VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5051         } else {
5052             let token_str = self.this_token_to_string();
5053             return Err(self.fatal(&format!("expected `where` or `{{` after union \
5054                                             name, found `{}`", token_str)))
5055         };
5056
5057         Ok((class_name, ItemKind::Union(vdata, generics), None))
5058     }
5059
5060     pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5061         let mut fields = Vec::new();
5062         if self.eat(&token::OpenDelim(token::Brace)) {
5063             while self.token != token::CloseDelim(token::Brace) {
5064                 fields.push(self.parse_struct_decl_field().map_err(|e| {
5065                     self.recover_stmt();
5066                     self.eat(&token::CloseDelim(token::Brace));
5067                     e
5068                 })?);
5069             }
5070
5071             self.bump();
5072         } else {
5073             let token_str = self.this_token_to_string();
5074             return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5075                                 name, found `{}`",
5076                                 token_str)));
5077         }
5078
5079         Ok(fields)
5080     }
5081
5082     pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5083         // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5084         // Unit like structs are handled in parse_item_struct function
5085         let fields = self.parse_unspanned_seq(
5086             &token::OpenDelim(token::Paren),
5087             &token::CloseDelim(token::Paren),
5088             SeqSep::trailing_allowed(token::Comma),
5089             |p| {
5090                 let attrs = p.parse_outer_attributes()?;
5091                 let lo = p.span;
5092                 let vis = p.parse_visibility(true)?;
5093                 let ty = p.parse_ty()?;
5094                 Ok(StructField {
5095                     span: lo.to(p.span),
5096                     vis: vis,
5097                     ident: None,
5098                     id: ast::DUMMY_NODE_ID,
5099                     ty: ty,
5100                     attrs: attrs,
5101                 })
5102             })?;
5103
5104         Ok(fields)
5105     }
5106
5107     /// Parse a structure field declaration
5108     pub fn parse_single_struct_field(&mut self,
5109                                      lo: Span,
5110                                      vis: Visibility,
5111                                      attrs: Vec<Attribute> )
5112                                      -> PResult<'a, StructField> {
5113         let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5114         match self.token {
5115             token::Comma => {
5116                 self.bump();
5117             }
5118             token::CloseDelim(token::Brace) => {}
5119             token::DocComment(_) => return Err(self.span_fatal_err(self.span,
5120                                                                    Error::UselessDocComment)),
5121             _ => return Err(self.span_fatal_help(self.span,
5122                     &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5123                     "struct fields should be separated by commas")),
5124         }
5125         Ok(a_var)
5126     }
5127
5128     /// Parse an element of a struct definition
5129     fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5130         let attrs = self.parse_outer_attributes()?;
5131         let lo = self.span;
5132         let vis = self.parse_visibility(false)?;
5133         self.parse_single_struct_field(lo, vis, attrs)
5134     }
5135
5136     /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5137     /// and `pub(super)` for `pub(in super)`.  If the following element can't be a tuple (i.e. it's
5138     /// a function definition, it's not a tuple struct field) and the contents within the parens
5139     /// isn't valid, emit a proper diagnostic.
5140     pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5141         maybe_whole!(self, NtVis, |x| x);
5142
5143         if !self.eat_keyword(keywords::Pub) {
5144             return Ok(Visibility::Inherited)
5145         }
5146
5147         if self.check(&token::OpenDelim(token::Paren)) {
5148             // We don't `self.bump()` the `(` yet because this might be a struct definition where
5149             // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5150             // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5151             // by the following tokens.
5152             if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5153                 // `pub(crate)`
5154                 self.bump(); // `(`
5155                 self.bump(); // `crate`
5156                 let vis = Visibility::Crate(self.prev_span);
5157                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5158                 return Ok(vis)
5159             } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5160                 // `pub(in path)`
5161                 self.bump(); // `(`
5162                 self.bump(); // `in`
5163                 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5164                 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5165                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5166                 return Ok(vis)
5167             } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5168                       self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5169                                              t.is_keyword(keywords::SelfValue)) {
5170                 // `pub(self)` or `pub(super)`
5171                 self.bump(); // `(`
5172                 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5173                 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5174                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5175                 return Ok(vis)
5176             } else if !can_take_tuple {  // Provide this diagnostic if this is not a tuple struct
5177                 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5178                 self.bump(); // `(`
5179                 let msg = "incorrect visibility restriction";
5180                 let suggestion = r##"some possible visibility restrictions are:
5181 `pub(crate)`: visible only on the current crate
5182 `pub(super)`: visible only in the current module's parent
5183 `pub(in path::to::module)`: visible only on the specified path"##;
5184                 let path = self.parse_path(PathStyle::Mod)?;
5185                 let path_span = self.prev_span;
5186                 let help_msg = format!("make this visible only to module `{}` with `in`:", path);
5187                 self.expect(&token::CloseDelim(token::Paren))?;  // `)`
5188                 let mut err = self.span_fatal_help(path_span, &msg, &suggestion);
5189                 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5190                 err.emit();  // emit diagnostic, but continue with public visibility
5191             }
5192         }
5193
5194         Ok(Visibility::Public)
5195     }
5196
5197     /// Parse defaultness: DEFAULT or nothing
5198     fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5199         if self.eat_contextual_keyword(keywords::Default.ident()) {
5200             Ok(Defaultness::Default)
5201         } else {
5202             Ok(Defaultness::Final)
5203         }
5204     }
5205
5206     /// Given a termination token, parse all of the items in a module
5207     fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5208         let mut items = vec![];
5209         while let Some(item) = self.parse_item()? {
5210             items.push(item);
5211         }
5212
5213         if !self.eat(term) {
5214             let token_str = self.this_token_to_string();
5215             return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5216         }
5217
5218         let hi = if self.span == syntax_pos::DUMMY_SP {
5219             inner_lo
5220         } else {
5221             self.prev_span
5222         };
5223
5224         Ok(ast::Mod {
5225             inner: inner_lo.to(hi),
5226             items: items
5227         })
5228     }
5229
5230     fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5231         let id = self.parse_ident()?;
5232         self.expect(&token::Colon)?;
5233         let ty = self.parse_ty()?;
5234         self.expect(&token::Eq)?;
5235         let e = self.parse_expr()?;
5236         self.expect(&token::Semi)?;
5237         let item = match m {
5238             Some(m) => ItemKind::Static(ty, m, e),
5239             None => ItemKind::Const(ty, e),
5240         };
5241         Ok((id, item, None))
5242     }
5243
5244     /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5245     fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5246         let (in_cfg, outer_attrs) = {
5247             let mut strip_unconfigured = ::config::StripUnconfigured {
5248                 sess: self.sess,
5249                 should_test: false, // irrelevant
5250                 features: None, // don't perform gated feature checking
5251             };
5252             let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5253             (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5254         };
5255
5256         let id_span = self.span;
5257         let id = self.parse_ident()?;
5258         if self.check(&token::Semi) {
5259             self.bump();
5260             if in_cfg {
5261                 // This mod is in an external file. Let's go get it!
5262                 let ModulePathSuccess { path, directory_ownership, warn } =
5263                     self.submod_path(id, &outer_attrs, id_span)?;
5264                 let (module, mut attrs) =
5265                     self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5266                 if warn {
5267                     let attr = ast::Attribute {
5268                         id: attr::mk_attr_id(),
5269                         style: ast::AttrStyle::Outer,
5270                         path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5271                                                     Ident::from_str("warn_directory_ownership")),
5272                         tokens: TokenStream::empty(),
5273                         is_sugared_doc: false,
5274                         span: syntax_pos::DUMMY_SP,
5275                     };
5276                     attr::mark_known(&attr);
5277                     attrs.push(attr);
5278                 }
5279                 Ok((id, module, Some(attrs)))
5280             } else {
5281                 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5282                 Ok((id, ItemKind::Mod(placeholder), None))
5283             }
5284         } else {
5285             let old_directory = self.directory.clone();
5286             self.push_directory(id, &outer_attrs);
5287             self.expect(&token::OpenDelim(token::Brace))?;
5288             let mod_inner_lo = self.span;
5289             let attrs = self.parse_inner_attributes()?;
5290             let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5291             self.directory = old_directory;
5292             Ok((id, ItemKind::Mod(module), Some(attrs)))
5293         }
5294     }
5295
5296     fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5297         if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5298             self.directory.path.push(&path.as_str());
5299             self.directory.ownership = DirectoryOwnership::Owned;
5300         } else {
5301             self.directory.path.push(&id.name.as_str());
5302         }
5303     }
5304
5305     pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5306         attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5307     }
5308
5309     /// Returns either a path to a module, or .
5310     pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5311         let mod_name = id.to_string();
5312         let default_path_str = format!("{}.rs", mod_name);
5313         let secondary_path_str = format!("{}{}mod.rs", mod_name, path::MAIN_SEPARATOR);
5314         let default_path = dir_path.join(&default_path_str);
5315         let secondary_path = dir_path.join(&secondary_path_str);
5316         let default_exists = codemap.file_exists(&default_path);
5317         let secondary_exists = codemap.file_exists(&secondary_path);
5318
5319         let result = match (default_exists, secondary_exists) {
5320             (true, false) => Ok(ModulePathSuccess {
5321                 path: default_path,
5322                 directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5323                 warn: false,
5324             }),
5325             (false, true) => Ok(ModulePathSuccess {
5326                 path: secondary_path,
5327                 directory_ownership: DirectoryOwnership::Owned,
5328                 warn: false,
5329             }),
5330             (false, false) => Err(Error::FileNotFoundForModule {
5331                 mod_name: mod_name.clone(),
5332                 default_path: default_path_str,
5333                 secondary_path: secondary_path_str,
5334                 dir_path: format!("{}", dir_path.display()),
5335             }),
5336             (true, true) => Err(Error::DuplicatePaths {
5337                 mod_name: mod_name.clone(),
5338                 default_path: default_path_str,
5339                 secondary_path: secondary_path_str,
5340             }),
5341         };
5342
5343         ModulePath {
5344             name: mod_name,
5345             path_exists: default_exists || secondary_exists,
5346             result: result,
5347         }
5348     }
5349
5350     fn submod_path(&mut self,
5351                    id: ast::Ident,
5352                    outer_attrs: &[ast::Attribute],
5353                    id_sp: Span) -> PResult<'a, ModulePathSuccess> {
5354         if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5355             return Ok(ModulePathSuccess {
5356                 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5357                     Some("mod.rs") => DirectoryOwnership::Owned,
5358                     _ => DirectoryOwnership::UnownedViaMod(true),
5359                 },
5360                 path: path,
5361                 warn: false,
5362             });
5363         }
5364
5365         let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5366
5367         if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5368             let msg =
5369                 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5370             let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5371             if paths.path_exists {
5372                 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5373                                   paths.name);
5374                 err.span_note(id_sp, &msg);
5375             }
5376             Err(err)
5377         } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5378             if warn {
5379                 if let Ok(result) = paths.result {
5380                     return Ok(ModulePathSuccess { warn: true, ..result });
5381                 }
5382             }
5383             let mut err = self.diagnostic().struct_span_err(id_sp,
5384                 "cannot declare a new module at this location");
5385             if id_sp != syntax_pos::DUMMY_SP {
5386                 let src_path = PathBuf::from(self.sess.codemap().span_to_filename(id_sp));
5387                 if let Some(stem) = src_path.file_stem() {
5388                     let mut dest_path = src_path.clone();
5389                     dest_path.set_file_name(stem);
5390                     dest_path.push("mod.rs");
5391                     err.span_note(id_sp,
5392                                   &format!("maybe move this module `{}` to its own \
5393                                             directory via `{}`", src_path.to_string_lossy(),
5394                                            dest_path.to_string_lossy()));
5395                 }
5396             }
5397             if paths.path_exists {
5398                 err.span_note(id_sp,
5399                               &format!("... or maybe `use` the module `{}` instead \
5400                                         of possibly redeclaring it",
5401                                        paths.name));
5402             }
5403             Err(err)
5404         } else {
5405             paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5406         }
5407     }
5408
5409     /// Read a module from a source file.
5410     fn eval_src_mod(&mut self,
5411                     path: PathBuf,
5412                     directory_ownership: DirectoryOwnership,
5413                     name: String,
5414                     id_sp: Span)
5415                     -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5416         let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5417         if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5418             let mut err = String::from("circular modules: ");
5419             let len = included_mod_stack.len();
5420             for p in &included_mod_stack[i.. len] {
5421                 err.push_str(&p.to_string_lossy());
5422                 err.push_str(" -> ");
5423             }
5424             err.push_str(&path.to_string_lossy());
5425             return Err(self.span_fatal(id_sp, &err[..]));
5426         }
5427         included_mod_stack.push(path.clone());
5428         drop(included_mod_stack);
5429
5430         let mut p0 =
5431             new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5432         p0.cfg_mods = self.cfg_mods;
5433         let mod_inner_lo = p0.span;
5434         let mod_attrs = p0.parse_inner_attributes()?;
5435         let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5436         self.sess.included_mod_stack.borrow_mut().pop();
5437         Ok((ast::ItemKind::Mod(m0), mod_attrs))
5438     }
5439
5440     /// Parse a function declaration from a foreign module
5441     fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5442                              -> PResult<'a, ForeignItem> {
5443         self.expect_keyword(keywords::Fn)?;
5444
5445         let (ident, mut generics) = self.parse_fn_header()?;
5446         let decl = self.parse_fn_decl(true)?;
5447         generics.where_clause = self.parse_where_clause()?;
5448         let hi = self.span;
5449         self.expect(&token::Semi)?;
5450         Ok(ast::ForeignItem {
5451             ident: ident,
5452             attrs: attrs,
5453             node: ForeignItemKind::Fn(decl, generics),
5454             id: ast::DUMMY_NODE_ID,
5455             span: lo.to(hi),
5456             vis: vis
5457         })
5458     }
5459
5460     /// Parse a static item from a foreign module
5461     fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5462                                  -> PResult<'a, ForeignItem> {
5463         self.expect_keyword(keywords::Static)?;
5464         let mutbl = self.eat_keyword(keywords::Mut);
5465
5466         let ident = self.parse_ident()?;
5467         self.expect(&token::Colon)?;
5468         let ty = self.parse_ty()?;
5469         let hi = self.span;
5470         self.expect(&token::Semi)?;
5471         Ok(ForeignItem {
5472             ident: ident,
5473             attrs: attrs,
5474             node: ForeignItemKind::Static(ty, mutbl),
5475             id: ast::DUMMY_NODE_ID,
5476             span: lo.to(hi),
5477             vis: vis
5478         })
5479     }
5480
5481     /// Parse extern crate links
5482     ///
5483     /// # Examples
5484     ///
5485     /// extern crate foo;
5486     /// extern crate bar as foo;
5487     fn parse_item_extern_crate(&mut self,
5488                                lo: Span,
5489                                visibility: Visibility,
5490                                attrs: Vec<Attribute>)
5491                                 -> PResult<'a, P<Item>> {
5492
5493         let crate_name = self.parse_ident()?;
5494         let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
5495             (Some(crate_name.name), ident)
5496         } else {
5497             (None, crate_name)
5498         };
5499         self.expect(&token::Semi)?;
5500
5501         let prev_span = self.prev_span;
5502         Ok(self.mk_item(lo.to(prev_span),
5503                         ident,
5504                         ItemKind::ExternCrate(maybe_path),
5505                         visibility,
5506                         attrs))
5507     }
5508
5509     /// Parse `extern` for foreign ABIs
5510     /// modules.
5511     ///
5512     /// `extern` is expected to have been
5513     /// consumed before calling this method
5514     ///
5515     /// # Examples:
5516     ///
5517     /// extern "C" {}
5518     /// extern {}
5519     fn parse_item_foreign_mod(&mut self,
5520                               lo: Span,
5521                               opt_abi: Option<abi::Abi>,
5522                               visibility: Visibility,
5523                               mut attrs: Vec<Attribute>)
5524                               -> PResult<'a, P<Item>> {
5525         self.expect(&token::OpenDelim(token::Brace))?;
5526
5527         let abi = opt_abi.unwrap_or(Abi::C);
5528
5529         attrs.extend(self.parse_inner_attributes()?);
5530
5531         let mut foreign_items = vec![];
5532         while let Some(item) = self.parse_foreign_item()? {
5533             foreign_items.push(item);
5534         }
5535         self.expect(&token::CloseDelim(token::Brace))?;
5536
5537         let prev_span = self.prev_span;
5538         let m = ast::ForeignMod {
5539             abi: abi,
5540             items: foreign_items
5541         };
5542         let invalid = keywords::Invalid.ident();
5543         Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
5544     }
5545
5546     /// Parse type Foo = Bar;
5547     fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5548         let ident = self.parse_ident()?;
5549         let mut tps = self.parse_generics()?;
5550         tps.where_clause = self.parse_where_clause()?;
5551         self.expect(&token::Eq)?;
5552         let ty = self.parse_ty()?;
5553         self.expect(&token::Semi)?;
5554         Ok((ident, ItemKind::Ty(ty, tps), None))
5555     }
5556
5557     /// Parse the part of an "enum" decl following the '{'
5558     fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5559         let mut variants = Vec::new();
5560         let mut all_nullary = true;
5561         let mut any_disr = None;
5562         while self.token != token::CloseDelim(token::Brace) {
5563             let variant_attrs = self.parse_outer_attributes()?;
5564             let vlo = self.span;
5565
5566             let struct_def;
5567             let mut disr_expr = None;
5568             let ident = self.parse_ident()?;
5569             if self.check(&token::OpenDelim(token::Brace)) {
5570                 // Parse a struct variant.
5571                 all_nullary = false;
5572                 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
5573                                                  ast::DUMMY_NODE_ID);
5574             } else if self.check(&token::OpenDelim(token::Paren)) {
5575                 all_nullary = false;
5576                 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
5577                                                 ast::DUMMY_NODE_ID);
5578             } else if self.eat(&token::Eq) {
5579                 disr_expr = Some(self.parse_expr()?);
5580                 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5581                 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5582             } else {
5583                 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5584             }
5585
5586             let vr = ast::Variant_ {
5587                 name: ident,
5588                 attrs: variant_attrs,
5589                 data: struct_def,
5590                 disr_expr: disr_expr,
5591             };
5592             variants.push(respan(vlo.to(self.prev_span), vr));
5593
5594             if !self.eat(&token::Comma) { break; }
5595         }
5596         self.expect(&token::CloseDelim(token::Brace))?;
5597         match any_disr {
5598             Some(disr_span) if !all_nullary =>
5599                 self.span_err(disr_span,
5600                     "discriminator values can only be used with a c-like enum"),
5601             _ => ()
5602         }
5603
5604         Ok(ast::EnumDef { variants: variants })
5605     }
5606
5607     /// Parse an "enum" declaration
5608     fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5609         let id = self.parse_ident()?;
5610         let mut generics = self.parse_generics()?;
5611         generics.where_clause = self.parse_where_clause()?;
5612         self.expect(&token::OpenDelim(token::Brace))?;
5613
5614         let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
5615             self.recover_stmt();
5616             self.eat(&token::CloseDelim(token::Brace));
5617             e
5618         })?;
5619         Ok((id, ItemKind::Enum(enum_definition, generics), None))
5620     }
5621
5622     /// Parses a string as an ABI spec on an extern type or module. Consumes
5623     /// the `extern` keyword, if one is found.
5624     fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5625         match self.token {
5626             token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5627                 let sp = self.span;
5628                 self.expect_no_suffix(sp, "ABI spec", suf);
5629                 self.bump();
5630                 match abi::lookup(&s.as_str()) {
5631                     Some(abi) => Ok(Some(abi)),
5632                     None => {
5633                         let prev_span = self.prev_span;
5634                         self.span_err(
5635                             prev_span,
5636                             &format!("invalid ABI: expected one of [{}], \
5637                                      found `{}`",
5638                                     abi::all_names().join(", "),
5639                                     s));
5640                         Ok(None)
5641                     }
5642                 }
5643             }
5644
5645             _ => Ok(None),
5646         }
5647     }
5648
5649     /// Parse one of the items allowed by the flags.
5650     /// NB: this function no longer parses the items inside an
5651     /// extern crate.
5652     fn parse_item_(&mut self, attrs: Vec<Attribute>,
5653                    macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5654         maybe_whole!(self, NtItem, |item| {
5655             let mut item = item.unwrap();
5656             let mut attrs = attrs;
5657             mem::swap(&mut item.attrs, &mut attrs);
5658             item.attrs.extend(attrs);
5659             Some(P(item))
5660         });
5661
5662         let lo = self.span;
5663
5664         let visibility = self.parse_visibility(false)?;
5665
5666         if self.eat_keyword(keywords::Use) {
5667             // USE ITEM
5668             let item_ = ItemKind::Use(self.parse_view_path()?);
5669             self.expect(&token::Semi)?;
5670
5671             let prev_span = self.prev_span;
5672             let invalid = keywords::Invalid.ident();
5673             let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
5674             return Ok(Some(item));
5675         }
5676
5677         if self.eat_keyword(keywords::Extern) {
5678             if self.eat_keyword(keywords::Crate) {
5679                 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
5680             }
5681
5682             let opt_abi = self.parse_opt_abi()?;
5683
5684             if self.eat_keyword(keywords::Fn) {
5685                 // EXTERN FUNCTION ITEM
5686                 let fn_span = self.prev_span;
5687                 let abi = opt_abi.unwrap_or(Abi::C);
5688                 let (ident, item_, extra_attrs) =
5689                     self.parse_item_fn(Unsafety::Normal,
5690                                        respan(fn_span, Constness::NotConst),
5691                                        abi)?;
5692                 let prev_span = self.prev_span;
5693                 let item = self.mk_item(lo.to(prev_span),
5694                                         ident,
5695                                         item_,
5696                                         visibility,
5697                                         maybe_append(attrs, extra_attrs));
5698                 return Ok(Some(item));
5699             } else if self.check(&token::OpenDelim(token::Brace)) {
5700                 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
5701             }
5702
5703             self.unexpected()?;
5704         }
5705
5706         if self.eat_keyword(keywords::Static) {
5707             // STATIC ITEM
5708             let m = if self.eat_keyword(keywords::Mut) {
5709                 Mutability::Mutable
5710             } else {
5711                 Mutability::Immutable
5712             };
5713             let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
5714             let prev_span = self.prev_span;
5715             let item = self.mk_item(lo.to(prev_span),
5716                                     ident,
5717                                     item_,
5718                                     visibility,
5719                                     maybe_append(attrs, extra_attrs));
5720             return Ok(Some(item));
5721         }
5722         if self.eat_keyword(keywords::Const) {
5723             let const_span = self.prev_span;
5724             if self.check_keyword(keywords::Fn)
5725                 || (self.check_keyword(keywords::Unsafe)
5726                     && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5727                 // CONST FUNCTION ITEM
5728                 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5729                     Unsafety::Unsafe
5730                 } else {
5731                     Unsafety::Normal
5732                 };
5733                 self.bump();
5734                 let (ident, item_, extra_attrs) =
5735                     self.parse_item_fn(unsafety,
5736                                        respan(const_span, Constness::Const),
5737                                        Abi::Rust)?;
5738                 let prev_span = self.prev_span;
5739                 let item = self.mk_item(lo.to(prev_span),
5740                                         ident,
5741                                         item_,
5742                                         visibility,
5743                                         maybe_append(attrs, extra_attrs));
5744                 return Ok(Some(item));
5745             }
5746
5747             // CONST ITEM
5748             if self.eat_keyword(keywords::Mut) {
5749                 let prev_span = self.prev_span;
5750                 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
5751                                  .help("did you mean to declare a static?")
5752                                  .emit();
5753             }
5754             let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
5755             let prev_span = self.prev_span;
5756             let item = self.mk_item(lo.to(prev_span),
5757                                     ident,
5758                                     item_,
5759                                     visibility,
5760                                     maybe_append(attrs, extra_attrs));
5761             return Ok(Some(item));
5762         }
5763         if self.check_keyword(keywords::Unsafe) &&
5764             self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5765         {
5766             // UNSAFE TRAIT ITEM
5767             self.expect_keyword(keywords::Unsafe)?;
5768             self.expect_keyword(keywords::Trait)?;
5769             let (ident, item_, extra_attrs) =
5770                 self.parse_item_trait(ast::Unsafety::Unsafe)?;
5771             let prev_span = self.prev_span;
5772             let item = self.mk_item(lo.to(prev_span),
5773                                     ident,
5774                                     item_,
5775                                     visibility,
5776                                     maybe_append(attrs, extra_attrs));
5777             return Ok(Some(item));
5778         }
5779         if (self.check_keyword(keywords::Unsafe) &&
5780             self.look_ahead(1, |t| t.is_keyword(keywords::Impl))) ||
5781            (self.check_keyword(keywords::Default) &&
5782             self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) &&
5783             self.look_ahead(2, |t| t.is_keyword(keywords::Impl)))
5784         {
5785             // IMPL ITEM
5786             let defaultness = self.parse_defaultness()?;
5787             self.expect_keyword(keywords::Unsafe)?;
5788             self.expect_keyword(keywords::Impl)?;
5789             let (ident,
5790                  item_,
5791                  extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe, defaultness)?;
5792             let prev_span = self.prev_span;
5793             let item = self.mk_item(lo.to(prev_span),
5794                                     ident,
5795                                     item_,
5796                                     visibility,
5797                                     maybe_append(attrs, extra_attrs));
5798             return Ok(Some(item));
5799         }
5800         if self.check_keyword(keywords::Fn) {
5801             // FUNCTION ITEM
5802             self.bump();
5803             let fn_span = self.prev_span;
5804             let (ident, item_, extra_attrs) =
5805                 self.parse_item_fn(Unsafety::Normal,
5806                                    respan(fn_span, Constness::NotConst),
5807                                    Abi::Rust)?;
5808             let prev_span = self.prev_span;
5809             let item = self.mk_item(lo.to(prev_span),
5810                                     ident,
5811                                     item_,
5812                                     visibility,
5813                                     maybe_append(attrs, extra_attrs));
5814             return Ok(Some(item));
5815         }
5816         if self.check_keyword(keywords::Unsafe)
5817             && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5818             // UNSAFE FUNCTION ITEM
5819             self.bump();
5820             let abi = if self.eat_keyword(keywords::Extern) {
5821                 self.parse_opt_abi()?.unwrap_or(Abi::C)
5822             } else {
5823                 Abi::Rust
5824             };
5825             self.expect_keyword(keywords::Fn)?;
5826             let fn_span = self.prev_span;
5827             let (ident, item_, extra_attrs) =
5828                 self.parse_item_fn(Unsafety::Unsafe,
5829                                    respan(fn_span, Constness::NotConst),
5830                                    abi)?;
5831             let prev_span = self.prev_span;
5832             let item = self.mk_item(lo.to(prev_span),
5833                                     ident,
5834                                     item_,
5835                                     visibility,
5836                                     maybe_append(attrs, extra_attrs));
5837             return Ok(Some(item));
5838         }
5839         if self.eat_keyword(keywords::Mod) {
5840             // MODULE ITEM
5841             let (ident, item_, extra_attrs) =
5842                 self.parse_item_mod(&attrs[..])?;
5843             let prev_span = self.prev_span;
5844             let item = self.mk_item(lo.to(prev_span),
5845                                     ident,
5846                                     item_,
5847                                     visibility,
5848                                     maybe_append(attrs, extra_attrs));
5849             return Ok(Some(item));
5850         }
5851         if self.eat_keyword(keywords::Type) {
5852             // TYPE ITEM
5853             let (ident, item_, extra_attrs) = self.parse_item_type()?;
5854             let prev_span = self.prev_span;
5855             let item = self.mk_item(lo.to(prev_span),
5856                                     ident,
5857                                     item_,
5858                                     visibility,
5859                                     maybe_append(attrs, extra_attrs));
5860             return Ok(Some(item));
5861         }
5862         if self.eat_keyword(keywords::Enum) {
5863             // ENUM ITEM
5864             let (ident, item_, extra_attrs) = self.parse_item_enum()?;
5865             let prev_span = self.prev_span;
5866             let item = self.mk_item(lo.to(prev_span),
5867                                     ident,
5868                                     item_,
5869                                     visibility,
5870                                     maybe_append(attrs, extra_attrs));
5871             return Ok(Some(item));
5872         }
5873         if self.eat_keyword(keywords::Trait) {
5874             // TRAIT ITEM
5875             let (ident, item_, extra_attrs) =
5876                 self.parse_item_trait(ast::Unsafety::Normal)?;
5877             let prev_span = self.prev_span;
5878             let item = self.mk_item(lo.to(prev_span),
5879                                     ident,
5880                                     item_,
5881                                     visibility,
5882                                     maybe_append(attrs, extra_attrs));
5883             return Ok(Some(item));
5884         }
5885         if (self.check_keyword(keywords::Impl)) ||
5886            (self.check_keyword(keywords::Default) &&
5887             self.look_ahead(1, |t| t.is_keyword(keywords::Impl)))
5888         {
5889             // IMPL ITEM
5890             let defaultness = self.parse_defaultness()?;
5891             self.expect_keyword(keywords::Impl)?;
5892             let (ident,
5893                  item_,
5894                  extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal, defaultness)?;
5895             let prev_span = self.prev_span;
5896             let item = self.mk_item(lo.to(prev_span),
5897                                     ident,
5898                                     item_,
5899                                     visibility,
5900                                     maybe_append(attrs, extra_attrs));
5901             return Ok(Some(item));
5902         }
5903         if self.eat_keyword(keywords::Struct) {
5904             // STRUCT ITEM
5905             let (ident, item_, extra_attrs) = self.parse_item_struct()?;
5906             let prev_span = self.prev_span;
5907             let item = self.mk_item(lo.to(prev_span),
5908                                     ident,
5909                                     item_,
5910                                     visibility,
5911                                     maybe_append(attrs, extra_attrs));
5912             return Ok(Some(item));
5913         }
5914         if self.is_union_item() {
5915             // UNION ITEM
5916             self.bump();
5917             let (ident, item_, extra_attrs) = self.parse_item_union()?;
5918             let prev_span = self.prev_span;
5919             let item = self.mk_item(lo.to(prev_span),
5920                                     ident,
5921                                     item_,
5922                                     visibility,
5923                                     maybe_append(attrs, extra_attrs));
5924             return Ok(Some(item));
5925         }
5926         if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility)? {
5927             return Ok(Some(macro_def));
5928         }
5929
5930         self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
5931     }
5932
5933     /// Parse a foreign item.
5934     fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
5935         let attrs = self.parse_outer_attributes()?;
5936         let lo = self.span;
5937         let visibility = self.parse_visibility(false)?;
5938
5939         if self.check_keyword(keywords::Static) {
5940             // FOREIGN STATIC ITEM
5941             return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
5942         }
5943         if self.check_keyword(keywords::Fn) {
5944             // FOREIGN FUNCTION ITEM
5945             return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
5946         }
5947
5948         // FIXME #5668: this will occur for a macro invocation:
5949         match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
5950             Some(item) => {
5951                 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
5952             }
5953             None => Ok(None)
5954         }
5955     }
5956
5957     /// This is the fall-through for parsing items.
5958     fn parse_macro_use_or_failure(
5959         &mut self,
5960         attrs: Vec<Attribute> ,
5961         macros_allowed: bool,
5962         attributes_allowed: bool,
5963         lo: Span,
5964         visibility: Visibility
5965     ) -> PResult<'a, Option<P<Item>>> {
5966         if macros_allowed && self.token.is_path_start() {
5967             // MACRO INVOCATION ITEM
5968
5969             let prev_span = self.prev_span;
5970             self.complain_if_pub_macro(&visibility, prev_span);
5971
5972             let mac_lo = self.span;
5973
5974             // item macro.
5975             let pth = self.parse_path(PathStyle::Mod)?;
5976             self.expect(&token::Not)?;
5977
5978             // a 'special' identifier (like what `macro_rules!` uses)
5979             // is optional. We should eventually unify invoc syntax
5980             // and remove this.
5981             let id = if self.token.is_ident() {
5982                 self.parse_ident()?
5983             } else {
5984                 keywords::Invalid.ident() // no special identifier
5985             };
5986             // eat a matched-delimiter token tree:
5987             let (delim, tts) = self.expect_delimited_token_tree()?;
5988             if delim != token::Brace {
5989                 if !self.eat(&token::Semi) {
5990                     let prev_span = self.prev_span;
5991                     self.span_err(prev_span,
5992                                   "macros that expand to items must either \
5993                                    be surrounded with braces or followed by \
5994                                    a semicolon");
5995                 }
5996             }
5997
5998             let hi = self.prev_span;
5999             let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6000             let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6001             return Ok(Some(item));
6002         }
6003
6004         // FAILURE TO PARSE ITEM
6005         match visibility {
6006             Visibility::Inherited => {}
6007             _ => {
6008                 let prev_span = self.prev_span;
6009                 return Err(self.span_fatal(prev_span, "unmatched visibility `pub`"));
6010             }
6011         }
6012
6013         if !attributes_allowed && !attrs.is_empty() {
6014             self.expected_item_err(&attrs);
6015         }
6016         Ok(None)
6017     }
6018
6019     pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6020         let attrs = self.parse_outer_attributes()?;
6021         self.parse_item_(attrs, true, false)
6022     }
6023
6024     fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> {
6025         self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
6026                                  &token::CloseDelim(token::Brace),
6027                                  SeqSep::trailing_allowed(token::Comma), |this| {
6028             let lo = this.span;
6029             let ident = if this.eat_keyword(keywords::SelfValue) {
6030                 keywords::SelfValue.ident()
6031             } else {
6032                 this.parse_ident()?
6033             };
6034             let rename = this.parse_rename()?;
6035             let node = ast::PathListItem_ {
6036                 name: ident,
6037                 rename: rename,
6038                 id: ast::DUMMY_NODE_ID
6039             };
6040             Ok(respan(lo.to(this.prev_span), node))
6041         })
6042     }
6043
6044     /// `::{` or `::*`
6045     fn is_import_coupler(&mut self) -> bool {
6046         self.check(&token::ModSep) &&
6047             self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6048                                    *t == token::BinOp(token::Star))
6049     }
6050
6051     /// Matches ViewPath:
6052     /// MOD_SEP? non_global_path
6053     /// MOD_SEP? non_global_path as IDENT
6054     /// MOD_SEP? non_global_path MOD_SEP STAR
6055     /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE
6056     /// MOD_SEP? LBRACE item_seq RBRACE
6057     fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
6058         let lo = self.span;
6059         if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) ||
6060            self.is_import_coupler() {
6061             // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`.
6062             self.eat(&token::ModSep);
6063             let prefix = ast::Path {
6064                 segments: vec![PathSegment::crate_root()],
6065                 span: lo.to(self.span),
6066             };
6067             let view_path_kind = if self.eat(&token::BinOp(token::Star)) {
6068                 ViewPathGlob(prefix)
6069             } else {
6070                 ViewPathList(prefix, self.parse_path_list_items()?)
6071             };
6072             Ok(P(respan(lo.to(self.span), view_path_kind)))
6073         } else {
6074             let prefix = self.parse_path(PathStyle::Mod)?.default_to_global();
6075             if self.is_import_coupler() {
6076                 // `foo::bar::{a, b}` or `foo::bar::*`
6077                 self.bump();
6078                 if self.check(&token::BinOp(token::Star)) {
6079                     self.bump();
6080                     Ok(P(respan(lo.to(self.span), ViewPathGlob(prefix))))
6081                 } else {
6082                     let items = self.parse_path_list_items()?;
6083                     Ok(P(respan(lo.to(self.span), ViewPathList(prefix, items))))
6084                 }
6085             } else {
6086                 // `foo::bar` or `foo::bar as baz`
6087                 let rename = self.parse_rename()?.
6088                                   unwrap_or(prefix.segments.last().unwrap().identifier);
6089                 Ok(P(respan(lo.to(self.prev_span), ViewPathSimple(rename, prefix))))
6090             }
6091         }
6092     }
6093
6094     fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6095         if self.eat_keyword(keywords::As) {
6096             self.parse_ident().map(Some)
6097         } else {
6098             Ok(None)
6099         }
6100     }
6101
6102     /// Parses a source module as a crate. This is the main
6103     /// entry point for the parser.
6104     pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6105         let lo = self.span;
6106         Ok(ast::Crate {
6107             attrs: self.parse_inner_attributes()?,
6108             module: self.parse_mod_items(&token::Eof, lo)?,
6109             span: lo.to(self.span),
6110         })
6111     }
6112
6113     pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6114         let ret = match self.token {
6115             token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6116             token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6117             _ => return None
6118         };
6119         self.bump();
6120         Some(ret)
6121     }
6122
6123     pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6124         match self.parse_optional_str() {
6125             Some((s, style, suf)) => {
6126                 let sp = self.prev_span;
6127                 self.expect_no_suffix(sp, "string literal", suf);
6128                 Ok((s, style))
6129             }
6130             _ =>  Err(self.fatal("expected string literal"))
6131         }
6132     }
6133 }