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