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