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