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