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