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