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