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