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