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