]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/parser.rs
Make fields of `Span` private
[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(_) => self.parse_expr()?,
3029             _ => {
3030                 // If an explicit return type is given, require a
3031                 // block to appear (RFC 968).
3032                 let body_lo = self.span;
3033                 self.parse_block_expr(body_lo, BlockCheckMode::Default, ThinVec::new())?
3034             }
3035         };
3036
3037         Ok(self.mk_expr(
3038             lo.to(body.span),
3039             ExprKind::Closure(capture_clause, decl, body, lo.to(decl_hi)),
3040             attrs))
3041     }
3042
3043     // `else` token already eaten
3044     pub fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3045         if self.eat_keyword(keywords::If) {
3046             return self.parse_if_expr(ThinVec::new());
3047         } else {
3048             let blk = self.parse_block()?;
3049             return Ok(self.mk_expr(blk.span, ExprKind::Block(blk), ThinVec::new()));
3050         }
3051     }
3052
3053     /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3054     pub fn parse_for_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3055                           span_lo: Span,
3056                           mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3057         // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3058
3059         let pat = self.parse_pat()?;
3060         self.expect_keyword(keywords::In)?;
3061         let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3062         let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
3063         attrs.extend(iattrs);
3064
3065         let hi = self.prev_span;
3066         Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_ident), attrs))
3067     }
3068
3069     /// Parse a 'while' or 'while let' expression ('while' token already eaten)
3070     pub fn parse_while_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3071                             span_lo: Span,
3072                             mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3073         if self.token.is_keyword(keywords::Let) {
3074             return self.parse_while_let_expr(opt_ident, span_lo, attrs);
3075         }
3076         let cond = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3077         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3078         attrs.extend(iattrs);
3079         let span = span_lo.to(body.span);
3080         return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_ident), attrs));
3081     }
3082
3083     /// Parse a 'while let' expression ('while' token already eaten)
3084     pub fn parse_while_let_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3085                                 span_lo: Span,
3086                                 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3087         self.expect_keyword(keywords::Let)?;
3088         let pat = self.parse_pat()?;
3089         self.expect(&token::Eq)?;
3090         let expr = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL, None)?;
3091         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3092         attrs.extend(iattrs);
3093         let span = span_lo.to(body.span);
3094         return Ok(self.mk_expr(span, ExprKind::WhileLet(pat, expr, body, opt_ident), attrs));
3095     }
3096
3097     // parse `loop {...}`, `loop` token already eaten
3098     pub fn parse_loop_expr(&mut self, opt_ident: Option<ast::SpannedIdent>,
3099                            span_lo: Span,
3100                            mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3101         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3102         attrs.extend(iattrs);
3103         let span = span_lo.to(body.span);
3104         Ok(self.mk_expr(span, ExprKind::Loop(body, opt_ident), attrs))
3105     }
3106
3107     /// Parse a `do catch {...}` expression (`do catch` token already eaten)
3108     pub fn parse_catch_expr(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
3109         -> PResult<'a, P<Expr>>
3110     {
3111         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
3112         attrs.extend(iattrs);
3113         Ok(self.mk_expr(span_lo.to(body.span), ExprKind::Catch(body), attrs))
3114     }
3115
3116     // `match` token already eaten
3117     fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3118         let match_span = self.prev_span;
3119         let lo = self.prev_span;
3120         let discriminant = self.parse_expr_res(RESTRICTION_NO_STRUCT_LITERAL,
3121                                                None)?;
3122         if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
3123             if self.token == token::Token::Semi {
3124                 e.span_note(match_span, "did you mean to remove this `match` keyword?");
3125             }
3126             return Err(e)
3127         }
3128         attrs.extend(self.parse_inner_attributes()?);
3129
3130         let mut arms: Vec<Arm> = Vec::new();
3131         while self.token != token::CloseDelim(token::Brace) {
3132             match self.parse_arm() {
3133                 Ok(arm) => arms.push(arm),
3134                 Err(mut e) => {
3135                     // Recover by skipping to the end of the block.
3136                     e.emit();
3137                     self.recover_stmt();
3138                     let span = lo.to(self.span);
3139                     if self.token == token::CloseDelim(token::Brace) {
3140                         self.bump();
3141                     }
3142                     return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
3143                 }
3144             }
3145         }
3146         let hi = self.span;
3147         self.bump();
3148         return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
3149     }
3150
3151     pub fn parse_arm(&mut self) -> PResult<'a, Arm> {
3152         maybe_whole!(self, NtArm, |x| x);
3153
3154         let attrs = self.parse_outer_attributes()?;
3155         let pats = self.parse_pats()?;
3156         let guard = if self.eat_keyword(keywords::If) {
3157             Some(self.parse_expr()?)
3158         } else {
3159             None
3160         };
3161         self.expect(&token::FatArrow)?;
3162         let expr = self.parse_expr_res(RESTRICTION_STMT_EXPR, None)?;
3163
3164         let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
3165             && self.token != token::CloseDelim(token::Brace);
3166
3167         if require_comma {
3168             self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])?;
3169         } else {
3170             self.eat(&token::Comma);
3171         }
3172
3173         Ok(ast::Arm {
3174             attrs,
3175             pats,
3176             guard,
3177             body: expr,
3178         })
3179     }
3180
3181     /// Parse an expression
3182     pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
3183         self.parse_expr_res(Restrictions::empty(), None)
3184     }
3185
3186     /// Evaluate the closure with restrictions in place.
3187     ///
3188     /// After the closure is evaluated, restrictions are reset.
3189     pub fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
3190         where F: FnOnce(&mut Self) -> T
3191     {
3192         let old = self.restrictions;
3193         self.restrictions = r;
3194         let r = f(self);
3195         self.restrictions = old;
3196         return r;
3197
3198     }
3199
3200     /// Parse an expression, subject to the given restrictions
3201     pub fn parse_expr_res(&mut self, r: Restrictions,
3202                           already_parsed_attrs: Option<ThinVec<Attribute>>)
3203                           -> PResult<'a, P<Expr>> {
3204         self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
3205     }
3206
3207     /// Parse the RHS of a local variable declaration (e.g. '= 14;')
3208     fn parse_initializer(&mut self) -> PResult<'a, Option<P<Expr>>> {
3209         if self.check(&token::Eq) {
3210             self.bump();
3211             Ok(Some(self.parse_expr()?))
3212         } else {
3213             Ok(None)
3214         }
3215     }
3216
3217     /// Parse patterns, separated by '|' s
3218     fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
3219         let mut pats = Vec::new();
3220         loop {
3221             pats.push(self.parse_pat()?);
3222             if self.check(&token::BinOp(token::Or)) { self.bump();}
3223             else { return Ok(pats); }
3224         };
3225     }
3226
3227     fn parse_pat_tuple_elements(&mut self, unary_needs_comma: bool)
3228                                 -> PResult<'a, (Vec<P<Pat>>, Option<usize>)> {
3229         let mut fields = vec![];
3230         let mut ddpos = None;
3231
3232         while !self.check(&token::CloseDelim(token::Paren)) {
3233             if ddpos.is_none() && self.eat(&token::DotDot) {
3234                 ddpos = Some(fields.len());
3235                 if self.eat(&token::Comma) {
3236                     // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
3237                     fields.push(self.parse_pat()?);
3238                 }
3239             } else if ddpos.is_some() && self.eat(&token::DotDot) {
3240                 // Emit a friendly error, ignore `..` and continue parsing
3241                 self.span_err(self.prev_span, "`..` can only be used once per \
3242                                                tuple or tuple struct pattern");
3243             } else {
3244                 fields.push(self.parse_pat()?);
3245             }
3246
3247             if !self.check(&token::CloseDelim(token::Paren)) ||
3248                     (unary_needs_comma && fields.len() == 1 && ddpos.is_none()) {
3249                 self.expect(&token::Comma)?;
3250             }
3251         }
3252
3253         Ok((fields, ddpos))
3254     }
3255
3256     fn parse_pat_vec_elements(
3257         &mut self,
3258     ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
3259         let mut before = Vec::new();
3260         let mut slice = None;
3261         let mut after = Vec::new();
3262         let mut first = true;
3263         let mut before_slice = true;
3264
3265         while self.token != token::CloseDelim(token::Bracket) {
3266             if first {
3267                 first = false;
3268             } else {
3269                 self.expect(&token::Comma)?;
3270
3271                 if self.token == token::CloseDelim(token::Bracket)
3272                         && (before_slice || !after.is_empty()) {
3273                     break
3274                 }
3275             }
3276
3277             if before_slice {
3278                 if self.eat(&token::DotDot) {
3279
3280                     if self.check(&token::Comma) ||
3281                             self.check(&token::CloseDelim(token::Bracket)) {
3282                         slice = Some(P(ast::Pat {
3283                             id: ast::DUMMY_NODE_ID,
3284                             node: PatKind::Wild,
3285                             span: self.span,
3286                         }));
3287                         before_slice = false;
3288                     }
3289                     continue
3290                 }
3291             }
3292
3293             let subpat = self.parse_pat()?;
3294             if before_slice && self.eat(&token::DotDot) {
3295                 slice = Some(subpat);
3296                 before_slice = false;
3297             } else if before_slice {
3298                 before.push(subpat);
3299             } else {
3300                 after.push(subpat);
3301             }
3302         }
3303
3304         Ok((before, slice, after))
3305     }
3306
3307     /// Parse the fields of a struct-like pattern
3308     fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<codemap::Spanned<ast::FieldPat>>, bool)> {
3309         let mut fields = Vec::new();
3310         let mut etc = false;
3311         let mut first = true;
3312         while self.token != token::CloseDelim(token::Brace) {
3313             if first {
3314                 first = false;
3315             } else {
3316                 self.expect(&token::Comma)?;
3317                 // accept trailing commas
3318                 if self.check(&token::CloseDelim(token::Brace)) { break }
3319             }
3320
3321             let attrs = self.parse_outer_attributes()?;
3322             let lo = self.span;
3323             let hi;
3324
3325             if self.check(&token::DotDot) {
3326                 self.bump();
3327                 if self.token != token::CloseDelim(token::Brace) {
3328                     let token_str = self.this_token_to_string();
3329                     return Err(self.fatal(&format!("expected `{}`, found `{}`", "}",
3330                                        token_str)))
3331                 }
3332                 etc = true;
3333                 break;
3334             }
3335
3336             // Check if a colon exists one ahead. This means we're parsing a fieldname.
3337             let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
3338                 // Parsing a pattern of the form "fieldname: pat"
3339                 let fieldname = self.parse_field_name()?;
3340                 self.bump();
3341                 let pat = self.parse_pat()?;
3342                 hi = pat.span;
3343                 (pat, fieldname, false)
3344             } else {
3345                 // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
3346                 let is_box = self.eat_keyword(keywords::Box);
3347                 let boxed_span = self.span;
3348                 let is_ref = self.eat_keyword(keywords::Ref);
3349                 let is_mut = self.eat_keyword(keywords::Mut);
3350                 let fieldname = self.parse_ident()?;
3351                 hi = self.prev_span;
3352
3353                 let bind_type = match (is_ref, is_mut) {
3354                     (true, true) => BindingMode::ByRef(Mutability::Mutable),
3355                     (true, false) => BindingMode::ByRef(Mutability::Immutable),
3356                     (false, true) => BindingMode::ByValue(Mutability::Mutable),
3357                     (false, false) => BindingMode::ByValue(Mutability::Immutable),
3358                 };
3359                 let fieldpath = codemap::Spanned{span:self.prev_span, node:fieldname};
3360                 let fieldpat = P(ast::Pat{
3361                     id: ast::DUMMY_NODE_ID,
3362                     node: PatKind::Ident(bind_type, fieldpath, None),
3363                     span: boxed_span.to(hi),
3364                 });
3365
3366                 let subpat = if is_box {
3367                     P(ast::Pat{
3368                         id: ast::DUMMY_NODE_ID,
3369                         node: PatKind::Box(fieldpat),
3370                         span: lo.to(hi),
3371                     })
3372                 } else {
3373                     fieldpat
3374                 };
3375                 (subpat, fieldname, true)
3376             };
3377
3378             fields.push(codemap::Spanned { span: lo.to(hi),
3379                                            node: ast::FieldPat {
3380                                                ident: fieldname,
3381                                                pat: subpat,
3382                                                is_shorthand,
3383                                                attrs: attrs.into(),
3384                                            }
3385             });
3386         }
3387         return Ok((fields, etc));
3388     }
3389
3390     fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
3391         if self.token.is_path_start() {
3392             let lo = self.span;
3393             let (qself, path) = if self.eat_lt() {
3394                 // Parse a qualified path
3395                 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3396                 (Some(qself), path)
3397             } else {
3398                 // Parse an unqualified path
3399                 (None, self.parse_path(PathStyle::Expr)?)
3400             };
3401             let hi = self.prev_span;
3402             Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
3403         } else {
3404             self.parse_pat_literal_maybe_minus()
3405         }
3406     }
3407
3408     // helper function to decide whether to parse as ident binding or to try to do
3409     // something more complex like range patterns
3410     fn parse_as_ident(&mut self) -> bool {
3411         self.look_ahead(1, |t| match *t {
3412             token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
3413             token::DotDotDot | token::ModSep | token::Not => Some(false),
3414             // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
3415             // range pattern branch
3416             token::DotDot => None,
3417             _ => Some(true),
3418         }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
3419             token::Comma | token::CloseDelim(token::Bracket) => true,
3420             _ => false,
3421         }))
3422     }
3423
3424     /// Parse a pattern.
3425     pub fn parse_pat(&mut self) -> PResult<'a, P<Pat>> {
3426         maybe_whole!(self, NtPat, |x| x);
3427
3428         let lo = self.span;
3429         let pat;
3430         match self.token {
3431             token::Underscore => {
3432                 // Parse _
3433                 self.bump();
3434                 pat = PatKind::Wild;
3435             }
3436             token::BinOp(token::And) | token::AndAnd => {
3437                 // Parse &pat / &mut pat
3438                 self.expect_and()?;
3439                 let mutbl = self.parse_mutability();
3440                 if let token::Lifetime(ident) = self.token {
3441                     return Err(self.fatal(&format!("unexpected lifetime `{}` in pattern", ident)));
3442                 }
3443                 let subpat = self.parse_pat()?;
3444                 pat = PatKind::Ref(subpat, mutbl);
3445             }
3446             token::OpenDelim(token::Paren) => {
3447                 // Parse (pat,pat,pat,...) as tuple pattern
3448                 self.bump();
3449                 let (fields, ddpos) = self.parse_pat_tuple_elements(true)?;
3450                 self.expect(&token::CloseDelim(token::Paren))?;
3451                 pat = PatKind::Tuple(fields, ddpos);
3452             }
3453             token::OpenDelim(token::Bracket) => {
3454                 // Parse [pat,pat,...] as slice pattern
3455                 self.bump();
3456                 let (before, slice, after) = self.parse_pat_vec_elements()?;
3457                 self.expect(&token::CloseDelim(token::Bracket))?;
3458                 pat = PatKind::Slice(before, slice, after);
3459             }
3460             // At this point, token != _, &, &&, (, [
3461             _ => if self.eat_keyword(keywords::Mut) {
3462                 // Parse mut ident @ pat / mut ref ident @ pat
3463                 let mutref_span = self.prev_span.to(self.span);
3464                 let binding_mode = if self.eat_keyword(keywords::Ref) {
3465                     self.diagnostic()
3466                         .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
3467                         .span_suggestion(mutref_span, "try switching the order", "ref mut".into())
3468                         .emit();
3469                     BindingMode::ByRef(Mutability::Mutable)
3470                 } else {
3471                     BindingMode::ByValue(Mutability::Mutable)
3472                 };
3473                 pat = self.parse_pat_ident(binding_mode)?;
3474             } else if self.eat_keyword(keywords::Ref) {
3475                 // Parse ref ident @ pat / ref mut ident @ pat
3476                 let mutbl = self.parse_mutability();
3477                 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
3478             } else if self.eat_keyword(keywords::Box) {
3479                 // Parse box pat
3480                 let subpat = self.parse_pat()?;
3481                 pat = PatKind::Box(subpat);
3482             } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
3483                       self.parse_as_ident() {
3484                 // Parse ident @ pat
3485                 // This can give false positives and parse nullary enums,
3486                 // they are dealt with later in resolve
3487                 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
3488                 pat = self.parse_pat_ident(binding_mode)?;
3489             } else if self.token.is_path_start() {
3490                 // Parse pattern starting with a path
3491                 let (qself, path) = if self.eat_lt() {
3492                     // Parse a qualified path
3493                     let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
3494                     (Some(qself), path)
3495                 } else {
3496                     // Parse an unqualified path
3497                     (None, self.parse_path(PathStyle::Expr)?)
3498                 };
3499                 match self.token {
3500                     token::Not if qself.is_none() => {
3501                         // Parse macro invocation
3502                         self.bump();
3503                         let (_, tts) = self.expect_delimited_token_tree()?;
3504                         let mac = respan(lo.to(self.prev_span), Mac_ { path: path, tts: tts });
3505                         pat = PatKind::Mac(mac);
3506                     }
3507                     token::DotDotDot | token::DotDot => {
3508                         let end_kind = match self.token {
3509                             token::DotDot => RangeEnd::Excluded,
3510                             token::DotDotDot => RangeEnd::Included,
3511                             _ => panic!("can only parse `..` or `...` for ranges (checked above)"),
3512                         };
3513                         // Parse range
3514                         let span = lo.to(self.prev_span);
3515                         let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
3516                         self.bump();
3517                         let end = self.parse_pat_range_end()?;
3518                         pat = PatKind::Range(begin, end, end_kind);
3519                     }
3520                     token::OpenDelim(token::Brace) => {
3521                         if qself.is_some() {
3522                             return Err(self.fatal("unexpected `{` after qualified path"));
3523                         }
3524                         // Parse struct pattern
3525                         self.bump();
3526                         let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
3527                             e.emit();
3528                             self.recover_stmt();
3529                             (vec![], false)
3530                         });
3531                         self.bump();
3532                         pat = PatKind::Struct(path, fields, etc);
3533                     }
3534                     token::OpenDelim(token::Paren) => {
3535                         if qself.is_some() {
3536                             return Err(self.fatal("unexpected `(` after qualified path"));
3537                         }
3538                         // Parse tuple struct or enum pattern
3539                         self.bump();
3540                         let (fields, ddpos) = self.parse_pat_tuple_elements(false)?;
3541                         self.expect(&token::CloseDelim(token::Paren))?;
3542                         pat = PatKind::TupleStruct(path, fields, ddpos)
3543                     }
3544                     _ => pat = PatKind::Path(qself, path),
3545                 }
3546             } else {
3547                 // Try to parse everything else as literal with optional minus
3548                 match self.parse_pat_literal_maybe_minus() {
3549                     Ok(begin) => {
3550                         if self.eat(&token::DotDotDot) {
3551                             let end = self.parse_pat_range_end()?;
3552                             pat = PatKind::Range(begin, end, RangeEnd::Included);
3553                         } else if self.eat(&token::DotDot) {
3554                             let end = self.parse_pat_range_end()?;
3555                             pat = PatKind::Range(begin, end, RangeEnd::Excluded);
3556                         } else {
3557                             pat = PatKind::Lit(begin);
3558                         }
3559                     }
3560                     Err(mut err) => {
3561                         self.cancel(&mut err);
3562                         let msg = format!("expected pattern, found {}", self.this_token_descr());
3563                         return Err(self.fatal(&msg));
3564                     }
3565                 }
3566             }
3567         }
3568
3569         Ok(P(ast::Pat {
3570             id: ast::DUMMY_NODE_ID,
3571             node: pat,
3572             span: lo.to(self.prev_span),
3573         }))
3574     }
3575
3576     /// Parse ident or ident @ pat
3577     /// used by the copy foo and ref foo patterns to give a good
3578     /// error message when parsing mistakes like ref foo(a,b)
3579     fn parse_pat_ident(&mut self,
3580                        binding_mode: ast::BindingMode)
3581                        -> PResult<'a, PatKind> {
3582         let ident_span = self.span;
3583         let ident = self.parse_ident()?;
3584         let name = codemap::Spanned{span: ident_span, node: ident};
3585         let sub = if self.eat(&token::At) {
3586             Some(self.parse_pat()?)
3587         } else {
3588             None
3589         };
3590
3591         // just to be friendly, if they write something like
3592         //   ref Some(i)
3593         // we end up here with ( as the current token.  This shortly
3594         // leads to a parse error.  Note that if there is no explicit
3595         // binding mode then we do not end up here, because the lookahead
3596         // will direct us over to parse_enum_variant()
3597         if self.token == token::OpenDelim(token::Paren) {
3598             return Err(self.span_fatal(
3599                 self.prev_span,
3600                 "expected identifier, found enum pattern"))
3601         }
3602
3603         Ok(PatKind::Ident(binding_mode, name, sub))
3604     }
3605
3606     /// Parse a local variable declaration
3607     fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
3608         let lo = self.prev_span;
3609         let pat = self.parse_pat()?;
3610
3611         let ty = if self.eat(&token::Colon) {
3612             Some(self.parse_ty()?)
3613         } else {
3614             None
3615         };
3616         let init = self.parse_initializer()?;
3617         Ok(P(ast::Local {
3618             ty,
3619             pat,
3620             init,
3621             id: ast::DUMMY_NODE_ID,
3622             span: lo.to(self.prev_span),
3623             attrs,
3624         }))
3625     }
3626
3627     /// Parse a structure field
3628     fn parse_name_and_ty(&mut self,
3629                          lo: Span,
3630                          vis: Visibility,
3631                          attrs: Vec<Attribute>)
3632                          -> PResult<'a, StructField> {
3633         let name = self.parse_ident()?;
3634         self.expect(&token::Colon)?;
3635         let ty = self.parse_ty()?;
3636         Ok(StructField {
3637             span: lo.to(self.prev_span),
3638             ident: Some(name),
3639             vis,
3640             id: ast::DUMMY_NODE_ID,
3641             ty,
3642             attrs,
3643         })
3644     }
3645
3646     /// Emit an expected item after attributes error.
3647     fn expected_item_err(&self, attrs: &[Attribute]) {
3648         let message = match attrs.last() {
3649             Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
3650             _ => "expected item after attributes",
3651         };
3652
3653         self.span_err(self.prev_span, message);
3654     }
3655
3656     /// Parse a statement. This stops just before trailing semicolons on everything but items.
3657     /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
3658     pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
3659         Ok(self.parse_stmt_(true))
3660     }
3661
3662     // Eat tokens until we can be relatively sure we reached the end of the
3663     // statement. This is something of a best-effort heuristic.
3664     //
3665     // We terminate when we find an unmatched `}` (without consuming it).
3666     fn recover_stmt(&mut self) {
3667         self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
3668     }
3669
3670     // If `break_on_semi` is `Break`, then we will stop consuming tokens after
3671     // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
3672     // approximate - it can mean we break too early due to macros, but that
3673     // shoud only lead to sub-optimal recovery, not inaccurate parsing).
3674     //
3675     // If `break_on_block` is `Break`, then we will stop consuming tokens
3676     // after finding (and consuming) a brace-delimited block.
3677     fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
3678         let mut brace_depth = 0;
3679         let mut bracket_depth = 0;
3680         let mut in_block = false;
3681         debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
3682                break_on_semi, break_on_block);
3683         loop {
3684             debug!("recover_stmt_ loop {:?}", self.token);
3685             match self.token {
3686                 token::OpenDelim(token::DelimToken::Brace) => {
3687                     brace_depth += 1;
3688                     self.bump();
3689                     if break_on_block == BlockMode::Break &&
3690                        brace_depth == 1 &&
3691                        bracket_depth == 0 {
3692                         in_block = true;
3693                     }
3694                 }
3695                 token::OpenDelim(token::DelimToken::Bracket) => {
3696                     bracket_depth += 1;
3697                     self.bump();
3698                 }
3699                 token::CloseDelim(token::DelimToken::Brace) => {
3700                     if brace_depth == 0 {
3701                         debug!("recover_stmt_ return - close delim {:?}", self.token);
3702                         return;
3703                     }
3704                     brace_depth -= 1;
3705                     self.bump();
3706                     if in_block && bracket_depth == 0 && brace_depth == 0 {
3707                         debug!("recover_stmt_ return - block end {:?}", self.token);
3708                         return;
3709                     }
3710                 }
3711                 token::CloseDelim(token::DelimToken::Bracket) => {
3712                     bracket_depth -= 1;
3713                     if bracket_depth < 0 {
3714                         bracket_depth = 0;
3715                     }
3716                     self.bump();
3717                 }
3718                 token::Eof => {
3719                     debug!("recover_stmt_ return - Eof");
3720                     return;
3721                 }
3722                 token::Semi => {
3723                     self.bump();
3724                     if break_on_semi == SemiColonMode::Break &&
3725                        brace_depth == 0 &&
3726                        bracket_depth == 0 {
3727                         debug!("recover_stmt_ return - Semi");
3728                         return;
3729                     }
3730                 }
3731                 _ => {
3732                     self.bump()
3733                 }
3734             }
3735         }
3736     }
3737
3738     fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
3739         self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
3740             e.emit();
3741             self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
3742             None
3743         })
3744     }
3745
3746     fn is_catch_expr(&mut self) -> bool {
3747         self.token.is_keyword(keywords::Do) &&
3748         self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
3749         self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
3750
3751         // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
3752         !self.restrictions.contains(RESTRICTION_NO_STRUCT_LITERAL)
3753     }
3754
3755     fn is_union_item(&self) -> bool {
3756         self.token.is_keyword(keywords::Union) &&
3757         self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
3758     }
3759
3760     fn is_defaultness(&self) -> bool {
3761         // `pub` is included for better error messages
3762         self.token.is_keyword(keywords::Default) &&
3763         self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
3764                         t.is_keyword(keywords::Const) ||
3765                         t.is_keyword(keywords::Fn) ||
3766                         t.is_keyword(keywords::Unsafe) ||
3767                         t.is_keyword(keywords::Extern) ||
3768                         t.is_keyword(keywords::Type) ||
3769                         t.is_keyword(keywords::Pub))
3770     }
3771
3772     fn eat_defaultness(&mut self) -> bool {
3773         let is_defaultness = self.is_defaultness();
3774         if is_defaultness {
3775             self.bump()
3776         } else {
3777             self.expected_tokens.push(TokenType::Keyword(keywords::Default));
3778         }
3779         is_defaultness
3780     }
3781
3782     fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility)
3783                      -> PResult<'a, Option<P<Item>>> {
3784         let lo = self.span;
3785         let (ident, def) = match self.token {
3786             token::Ident(ident) if ident.name == keywords::Macro.name() => {
3787                 self.bump();
3788                 let ident = self.parse_ident()?;
3789                 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
3790                     match self.parse_token_tree() {
3791                         TokenTree::Delimited(_, ref delimited) => delimited.stream(),
3792                         _ => unreachable!(),
3793                     }
3794                 } else if self.check(&token::OpenDelim(token::Paren)) {
3795                     let args = self.parse_token_tree();
3796                     let body = if self.check(&token::OpenDelim(token::Brace)) {
3797                         self.parse_token_tree()
3798                     } else {
3799                         self.unexpected()?;
3800                         unreachable!()
3801                     };
3802                     TokenStream::concat(vec![
3803                         args.into(),
3804                         TokenTree::Token(lo.to(self.prev_span), token::FatArrow).into(),
3805                         body.into(),
3806                     ])
3807                 } else {
3808                     self.unexpected()?;
3809                     unreachable!()
3810                 };
3811
3812                 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
3813             }
3814             token::Ident(ident) if ident.name == "macro_rules" &&
3815                                    self.look_ahead(1, |t| *t == token::Not) => {
3816                 let prev_span = self.prev_span;
3817                 self.complain_if_pub_macro(vis, prev_span);
3818                 self.bump();
3819                 self.bump();
3820
3821                 let ident = self.parse_ident()?;
3822                 let (delim, tokens) = self.expect_delimited_token_tree()?;
3823                 if delim != token::Brace {
3824                     if !self.eat(&token::Semi) {
3825                         let msg = "macros that expand to items must either \
3826                                    be surrounded with braces or followed by a semicolon";
3827                         self.span_err(self.prev_span, msg);
3828                     }
3829                 }
3830
3831                 (ident, ast::MacroDef { tokens: tokens, legacy: true })
3832             }
3833             _ => return Ok(None),
3834         };
3835
3836         let span = lo.to(self.prev_span);
3837         Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
3838     }
3839
3840     fn parse_stmt_without_recovery(&mut self,
3841                                    macro_legacy_warnings: bool)
3842                                    -> PResult<'a, Option<Stmt>> {
3843         maybe_whole!(self, NtStmt, |x| Some(x));
3844
3845         let attrs = self.parse_outer_attributes()?;
3846         let lo = self.span;
3847
3848         Ok(Some(if self.eat_keyword(keywords::Let) {
3849             Stmt {
3850                 id: ast::DUMMY_NODE_ID,
3851                 node: StmtKind::Local(self.parse_local(attrs.into())?),
3852                 span: lo.to(self.prev_span),
3853             }
3854         } else if let Some(macro_def) = self.eat_macro_def(&attrs, &Visibility::Inherited)? {
3855             Stmt {
3856                 id: ast::DUMMY_NODE_ID,
3857                 node: StmtKind::Item(macro_def),
3858                 span: lo.to(self.prev_span),
3859             }
3860         // Starts like a simple path, but not a union item.
3861         } else if self.token.is_path_start() &&
3862                   !self.token.is_qpath_start() &&
3863                   !self.is_union_item() {
3864             let pth = self.parse_path(PathStyle::Expr)?;
3865
3866             if !self.eat(&token::Not) {
3867                 let expr = if self.check(&token::OpenDelim(token::Brace)) {
3868                     self.parse_struct_expr(lo, pth, ThinVec::new())?
3869                 } else {
3870                     let hi = self.prev_span;
3871                     self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
3872                 };
3873
3874                 let expr = self.with_res(RESTRICTION_STMT_EXPR, |this| {
3875                     let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
3876                     this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
3877                 })?;
3878
3879                 return Ok(Some(Stmt {
3880                     id: ast::DUMMY_NODE_ID,
3881                     node: StmtKind::Expr(expr),
3882                     span: lo.to(self.prev_span),
3883                 }));
3884             }
3885
3886             // it's a macro invocation
3887             let id = match self.token {
3888                 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
3889                 _ => self.parse_ident()?,
3890             };
3891
3892             // check that we're pointing at delimiters (need to check
3893             // again after the `if`, because of `parse_ident`
3894             // consuming more tokens).
3895             let delim = match self.token {
3896                 token::OpenDelim(delim) => delim,
3897                 _ => {
3898                     // we only expect an ident if we didn't parse one
3899                     // above.
3900                     let ident_str = if id.name == keywords::Invalid.name() {
3901                         "identifier, "
3902                     } else {
3903                         ""
3904                     };
3905                     let tok_str = self.this_token_to_string();
3906                     return Err(self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
3907                                        ident_str,
3908                                        tok_str)))
3909                 },
3910             };
3911
3912             let (_, tts) = self.expect_delimited_token_tree()?;
3913             let hi = self.prev_span;
3914
3915             let style = if delim == token::Brace {
3916                 MacStmtStyle::Braces
3917             } else {
3918                 MacStmtStyle::NoBraces
3919             };
3920
3921             if id.name == keywords::Invalid.name() {
3922                 let mac = respan(lo.to(hi), Mac_ { path: pth, tts: tts });
3923                 let node = if delim == token::Brace ||
3924                               self.token == token::Semi || self.token == token::Eof {
3925                     StmtKind::Mac(P((mac, style, attrs.into())))
3926                 }
3927                 // We used to incorrectly stop parsing macro-expanded statements here.
3928                 // If the next token will be an error anyway but could have parsed with the
3929                 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
3930                 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
3931                     // These can continue an expression, so we can't stop parsing and warn.
3932                     token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
3933                     token::BinOp(token::Minus) | token::BinOp(token::Star) |
3934                     token::BinOp(token::And) | token::BinOp(token::Or) |
3935                     token::AndAnd | token::OrOr |
3936                     token::DotDot | token::DotDotDot => false,
3937                     _ => true,
3938                 } {
3939                     self.warn_missing_semicolon();
3940                     StmtKind::Mac(P((mac, style, attrs.into())))
3941                 } else {
3942                     let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
3943                     let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
3944                     let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
3945                     StmtKind::Expr(e)
3946                 };
3947                 Stmt {
3948                     id: ast::DUMMY_NODE_ID,
3949                     span: lo.to(hi),
3950                     node,
3951                 }
3952             } else {
3953                 // if it has a special ident, it's definitely an item
3954                 //
3955                 // Require a semicolon or braces.
3956                 if style != MacStmtStyle::Braces {
3957                     if !self.eat(&token::Semi) {
3958                         self.span_err(self.prev_span,
3959                                       "macros that expand to items must \
3960                                        either be surrounded with braces or \
3961                                        followed by a semicolon");
3962                     }
3963                 }
3964                 let span = lo.to(hi);
3965                 Stmt {
3966                     id: ast::DUMMY_NODE_ID,
3967                     span,
3968                     node: StmtKind::Item({
3969                         self.mk_item(
3970                             span, id /*id is good here*/,
3971                             ItemKind::Mac(respan(span, Mac_ { path: pth, tts: tts })),
3972                             Visibility::Inherited,
3973                             attrs)
3974                     }),
3975                 }
3976             }
3977         } else {
3978             // FIXME: Bad copy of attrs
3979             let old_directory_ownership =
3980                 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
3981             let item = self.parse_item_(attrs.clone(), false, true)?;
3982             self.directory.ownership = old_directory_ownership;
3983
3984             match item {
3985                 Some(i) => Stmt {
3986                     id: ast::DUMMY_NODE_ID,
3987                     span: lo.to(i.span),
3988                     node: StmtKind::Item(i),
3989                 },
3990                 None => {
3991                     let unused_attrs = |attrs: &[_], s: &mut Self| {
3992                         if !attrs.is_empty() {
3993                             if s.prev_token_kind == PrevTokenKind::DocComment {
3994                                 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
3995                             } else {
3996                                 s.span_err(s.span, "expected statement after outer attribute");
3997                             }
3998                         }
3999                     };
4000
4001                     // Do not attempt to parse an expression if we're done here.
4002                     if self.token == token::Semi {
4003                         unused_attrs(&attrs, self);
4004                         self.bump();
4005                         return Ok(None);
4006                     }
4007
4008                     if self.token == token::CloseDelim(token::Brace) {
4009                         unused_attrs(&attrs, self);
4010                         return Ok(None);
4011                     }
4012
4013                     // Remainder are line-expr stmts.
4014                     let e = self.parse_expr_res(
4015                         RESTRICTION_STMT_EXPR, Some(attrs.into()))?;
4016                     Stmt {
4017                         id: ast::DUMMY_NODE_ID,
4018                         span: lo.to(e.span),
4019                         node: StmtKind::Expr(e),
4020                     }
4021                 }
4022             }
4023         }))
4024     }
4025
4026     /// Is this expression a successfully-parsed statement?
4027     fn expr_is_complete(&mut self, e: &Expr) -> bool {
4028         self.restrictions.contains(RESTRICTION_STMT_EXPR) &&
4029             !classify::expr_requires_semi_to_be_stmt(e)
4030     }
4031
4032     /// Parse a block. No inner attrs are allowed.
4033     pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4034         maybe_whole!(self, NtBlock, |x| x);
4035
4036         let lo = self.span;
4037
4038         if !self.eat(&token::OpenDelim(token::Brace)) {
4039             let sp = self.span;
4040             let tok = self.this_token_to_string();
4041             let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4042
4043             // Check to see if the user has written something like
4044             //
4045             //    if (cond)
4046             //      bar;
4047             //
4048             // Which is valid in other languages, but not Rust.
4049             match self.parse_stmt_without_recovery(false) {
4050                 Ok(Some(stmt)) => {
4051                     let mut stmt_span = stmt.span;
4052                     // expand the span to include the semicolon, if it exists
4053                     if self.eat(&token::Semi) {
4054                         stmt_span = stmt_span.with_hi(self.prev_span.hi());
4055                     }
4056                     let sugg = pprust::to_string(|s| {
4057                         use print::pprust::{PrintState, INDENT_UNIT};
4058                         s.ibox(INDENT_UNIT)?;
4059                         s.bopen()?;
4060                         s.print_stmt(&stmt)?;
4061                         s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4062                     });
4063                     e.span_suggestion(stmt_span, "try placing this code inside a block", sugg);
4064                 }
4065                 Err(mut e) => {
4066                     self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4067                     self.cancel(&mut e);
4068                 }
4069                 _ => ()
4070             }
4071             return Err(e);
4072         }
4073
4074         self.parse_block_tail(lo, BlockCheckMode::Default)
4075     }
4076
4077     /// Parse a block. Inner attrs are allowed.
4078     fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4079         maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4080
4081         let lo = self.span;
4082         self.expect(&token::OpenDelim(token::Brace))?;
4083         Ok((self.parse_inner_attributes()?,
4084             self.parse_block_tail(lo, BlockCheckMode::Default)?))
4085     }
4086
4087     /// Parse the rest of a block expression or function body
4088     /// Precondition: already parsed the '{'.
4089     fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4090         let mut stmts = vec![];
4091
4092         while !self.eat(&token::CloseDelim(token::Brace)) {
4093             if let Some(stmt) = self.parse_full_stmt(false)? {
4094                 stmts.push(stmt);
4095             } else if self.token == token::Eof {
4096                 break;
4097             } else {
4098                 // Found only `;` or `}`.
4099                 continue;
4100             };
4101         }
4102
4103         Ok(P(ast::Block {
4104             stmts,
4105             id: ast::DUMMY_NODE_ID,
4106             rules: s,
4107             span: lo.to(self.prev_span),
4108         }))
4109     }
4110
4111     /// Parse a statement, including the trailing semicolon.
4112     pub fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4113         let mut stmt = match self.parse_stmt_(macro_legacy_warnings) {
4114             Some(stmt) => stmt,
4115             None => return Ok(None),
4116         };
4117
4118         match stmt.node {
4119             StmtKind::Expr(ref expr) if self.token != token::Eof => {
4120                 // expression without semicolon
4121                 if classify::expr_requires_semi_to_be_stmt(expr) {
4122                     // Just check for errors and recover; do not eat semicolon yet.
4123                     if let Err(mut e) =
4124                         self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4125                     {
4126                         e.emit();
4127                         self.recover_stmt();
4128                     }
4129                 }
4130             }
4131             StmtKind::Local(..) => {
4132                 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4133                 if macro_legacy_warnings && self.token != token::Semi {
4134                     self.warn_missing_semicolon();
4135                 } else {
4136                     self.expect_one_of(&[token::Semi], &[])?;
4137                 }
4138             }
4139             _ => {}
4140         }
4141
4142         if self.eat(&token::Semi) {
4143             stmt = stmt.add_trailing_semicolon();
4144         }
4145
4146         stmt.span = stmt.span.with_hi(self.prev_span.hi());
4147         Ok(Some(stmt))
4148     }
4149
4150     fn warn_missing_semicolon(&self) {
4151         self.diagnostic().struct_span_warn(self.span, {
4152             &format!("expected `;`, found `{}`", self.this_token_to_string())
4153         }).note({
4154             "This was erroneously allowed and will become a hard error in a future release"
4155         }).emit();
4156     }
4157
4158     // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4159     // BOUND = TY_BOUND | LT_BOUND
4160     // LT_BOUND = LIFETIME (e.g. `'a`)
4161     // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4162     // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4163     fn parse_ty_param_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, TyParamBounds> {
4164         let mut bounds = Vec::new();
4165         loop {
4166             let is_bound_start = self.check_path() || self.check_lifetime() ||
4167                                  self.check(&token::Question) ||
4168                                  self.check_keyword(keywords::For) ||
4169                                  self.check(&token::OpenDelim(token::Paren));
4170             if is_bound_start {
4171                 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4172                 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4173                 if self.token.is_lifetime() {
4174                     if let Some(question_span) = question {
4175                         self.span_err(question_span,
4176                                       "`?` may only modify trait bounds, not lifetime bounds");
4177                     }
4178                     bounds.push(RegionTyParamBound(self.expect_lifetime()));
4179                 } else {
4180                     let lo = self.span;
4181                     let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4182                     let path = self.parse_path(PathStyle::Type)?;
4183                     let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4184                     let modifier = if question.is_some() {
4185                         TraitBoundModifier::Maybe
4186                     } else {
4187                         TraitBoundModifier::None
4188                     };
4189                     bounds.push(TraitTyParamBound(poly_trait, modifier));
4190                 }
4191                 if has_parens {
4192                     self.expect(&token::CloseDelim(token::Paren))?;
4193                     if let Some(&RegionTyParamBound(..)) = bounds.last() {
4194                         self.span_err(self.prev_span,
4195                                       "parenthesized lifetime bounds are not supported");
4196                     }
4197                 }
4198             } else {
4199                 break
4200             }
4201
4202             if !allow_plus || !self.eat(&token::BinOp(token::Plus)) {
4203                 break
4204             }
4205         }
4206
4207         return Ok(bounds);
4208     }
4209
4210     fn parse_ty_param_bounds(&mut self) -> PResult<'a, TyParamBounds> {
4211         self.parse_ty_param_bounds_common(true)
4212     }
4213
4214     // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4215     // BOUND = LT_BOUND (e.g. `'a`)
4216     fn parse_lt_param_bounds(&mut self) -> Vec<Lifetime> {
4217         let mut lifetimes = Vec::new();
4218         while self.check_lifetime() {
4219             lifetimes.push(self.expect_lifetime());
4220
4221             if !self.eat(&token::BinOp(token::Plus)) {
4222                 break
4223             }
4224         }
4225         lifetimes
4226     }
4227
4228     /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4229     fn parse_ty_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, TyParam> {
4230         let span = self.span;
4231         let ident = self.parse_ident()?;
4232
4233         // Parse optional colon and param bounds.
4234         let bounds = if self.eat(&token::Colon) {
4235             self.parse_ty_param_bounds()?
4236         } else {
4237             Vec::new()
4238         };
4239
4240         let default = if self.eat(&token::Eq) {
4241             Some(self.parse_ty()?)
4242         } else {
4243             None
4244         };
4245
4246         Ok(TyParam {
4247             attrs: preceding_attrs.into(),
4248             ident,
4249             id: ast::DUMMY_NODE_ID,
4250             bounds,
4251             default,
4252             span,
4253         })
4254     }
4255
4256     /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4257     /// trailing comma and erroneous trailing attributes.
4258     pub fn parse_generic_params(&mut self) -> PResult<'a, (Vec<LifetimeDef>, Vec<TyParam>)> {
4259         let mut lifetime_defs = Vec::new();
4260         let mut ty_params = Vec::new();
4261         let mut seen_ty_param = false;
4262         loop {
4263             let attrs = self.parse_outer_attributes()?;
4264             if self.check_lifetime() {
4265                 let lifetime = self.expect_lifetime();
4266                 // Parse lifetime parameter.
4267                 let bounds = if self.eat(&token::Colon) {
4268                     self.parse_lt_param_bounds()
4269                 } else {
4270                     Vec::new()
4271                 };
4272                 lifetime_defs.push(LifetimeDef {
4273                     attrs: attrs.into(),
4274                     lifetime,
4275                     bounds,
4276                 });
4277                 if seen_ty_param {
4278                     self.span_err(self.prev_span,
4279                         "lifetime parameters must be declared prior to type parameters");
4280                 }
4281             } else if self.check_ident() {
4282                 // Parse type parameter.
4283                 ty_params.push(self.parse_ty_param(attrs)?);
4284                 seen_ty_param = true;
4285             } else {
4286                 // Check for trailing attributes and stop parsing.
4287                 if !attrs.is_empty() {
4288                     let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4289                     self.span_err(attrs[0].span,
4290                         &format!("trailing attribute after {} parameters", param_kind));
4291                 }
4292                 break
4293             }
4294
4295             if !self.eat(&token::Comma) {
4296                 break
4297             }
4298         }
4299         Ok((lifetime_defs, ty_params))
4300     }
4301
4302     /// Parse a set of optional generic type parameter declarations. Where
4303     /// clauses are not parsed here, and must be added later via
4304     /// `parse_where_clause()`.
4305     ///
4306     /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4307     ///                  | ( < lifetimes , typaramseq ( , )? > )
4308     /// where   typaramseq = ( typaram ) | ( typaram , typaramseq )
4309     pub fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4310         maybe_whole!(self, NtGenerics, |x| x);
4311
4312         let span_lo = self.span;
4313         if self.eat_lt() {
4314             let (lifetime_defs, ty_params) = self.parse_generic_params()?;
4315             self.expect_gt()?;
4316             Ok(ast::Generics {
4317                 lifetimes: lifetime_defs,
4318                 ty_params,
4319                 where_clause: WhereClause {
4320                     id: ast::DUMMY_NODE_ID,
4321                     predicates: Vec::new(),
4322                     span: syntax_pos::DUMMY_SP,
4323                 },
4324                 span: span_lo.to(self.prev_span),
4325             })
4326         } else {
4327             Ok(ast::Generics::default())
4328         }
4329     }
4330
4331     /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
4332     /// possibly including trailing comma.
4333     fn parse_generic_args(&mut self) -> PResult<'a, (Vec<Lifetime>, Vec<P<Ty>>, Vec<TypeBinding>)> {
4334         let mut lifetimes = Vec::new();
4335         let mut types = Vec::new();
4336         let mut bindings = Vec::new();
4337         let mut seen_type = false;
4338         let mut seen_binding = false;
4339         loop {
4340             if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4341                 // Parse lifetime argument.
4342                 lifetimes.push(self.expect_lifetime());
4343                 if seen_type || seen_binding {
4344                     self.span_err(self.prev_span,
4345                         "lifetime parameters must be declared prior to type parameters");
4346                 }
4347             } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
4348                 // Parse associated type binding.
4349                 let lo = self.span;
4350                 let ident = self.parse_ident()?;
4351                 self.bump();
4352                 let ty = self.parse_ty()?;
4353                 bindings.push(TypeBinding {
4354                     id: ast::DUMMY_NODE_ID,
4355                     ident,
4356                     ty,
4357                     span: lo.to(self.prev_span),
4358                 });
4359                 seen_binding = true;
4360             } else if self.check_type() {
4361                 // Parse type argument.
4362                 types.push(self.parse_ty()?);
4363                 if seen_binding {
4364                     self.span_err(types[types.len() - 1].span,
4365                         "type parameters must be declared prior to associated type bindings");
4366                 }
4367                 seen_type = true;
4368             } else {
4369                 break
4370             }
4371
4372             if !self.eat(&token::Comma) {
4373                 break
4374             }
4375         }
4376         Ok((lifetimes, types, bindings))
4377     }
4378
4379     /// Parses an optional `where` clause and places it in `generics`.
4380     ///
4381     /// ```ignore (only-for-syntax-highlight)
4382     /// where T : Trait<U, V> + 'b, 'a : 'b
4383     /// ```
4384     pub fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
4385         maybe_whole!(self, NtWhereClause, |x| x);
4386
4387         let mut where_clause = WhereClause {
4388             id: ast::DUMMY_NODE_ID,
4389             predicates: Vec::new(),
4390             span: syntax_pos::DUMMY_SP,
4391         };
4392
4393         if !self.eat_keyword(keywords::Where) {
4394             return Ok(where_clause);
4395         }
4396         let lo = self.prev_span;
4397
4398         // This is a temporary future proofing.
4399         //
4400         // We are considering adding generics to the `where` keyword as an alternative higher-rank
4401         // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
4402         // change, for now we refuse to parse `where < (ident | lifetime) (> | , | :)`.
4403         if token::Lt == self.token {
4404             let ident_or_lifetime = self.look_ahead(1, |t| t.is_ident() || t.is_lifetime());
4405             if ident_or_lifetime {
4406                 let gt_comma_or_colon = self.look_ahead(2, |t| {
4407                     *t == token::Gt || *t == token::Comma || *t == token::Colon
4408                 });
4409                 if gt_comma_or_colon {
4410                     self.span_err(self.span, "syntax `where<T>` is reserved for future use");
4411                 }
4412             }
4413         }
4414
4415         loop {
4416             let lo = self.span;
4417             if self.check_lifetime() && self.look_ahead(1, |t| t != &token::BinOp(token::Plus)) {
4418                 let lifetime = self.expect_lifetime();
4419                 // Bounds starting with a colon are mandatory, but possibly empty.
4420                 self.expect(&token::Colon)?;
4421                 let bounds = self.parse_lt_param_bounds();
4422                 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
4423                     ast::WhereRegionPredicate {
4424                         span: lo.to(self.prev_span),
4425                         lifetime,
4426                         bounds,
4427                     }
4428                 ));
4429             } else if self.check_type() {
4430                 // Parse optional `for<'a, 'b>`.
4431                 // This `for` is parsed greedily and applies to the whole predicate,
4432                 // the bounded type can have its own `for` applying only to it.
4433                 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
4434                 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
4435                 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
4436                 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4437
4438                 // Parse type with mandatory colon and (possibly empty) bounds,
4439                 // or with mandatory equality sign and the second type.
4440                 let ty = self.parse_ty()?;
4441                 if self.eat(&token::Colon) {
4442                     let bounds = self.parse_ty_param_bounds()?;
4443                     where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
4444                         ast::WhereBoundPredicate {
4445                             span: lo.to(self.prev_span),
4446                             bound_lifetimes: lifetime_defs,
4447                             bounded_ty: ty,
4448                             bounds,
4449                         }
4450                     ));
4451                 // FIXME: Decide what should be used here, `=` or `==`.
4452                 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
4453                     let rhs_ty = self.parse_ty()?;
4454                     where_clause.predicates.push(ast::WherePredicate::EqPredicate(
4455                         ast::WhereEqPredicate {
4456                             span: lo.to(self.prev_span),
4457                             lhs_ty: ty,
4458                             rhs_ty,
4459                             id: ast::DUMMY_NODE_ID,
4460                         }
4461                     ));
4462                 } else {
4463                     return self.unexpected();
4464                 }
4465             } else {
4466                 break
4467             }
4468
4469             if !self.eat(&token::Comma) {
4470                 break
4471             }
4472         }
4473
4474         where_clause.span = lo.to(self.prev_span);
4475         Ok(where_clause)
4476     }
4477
4478     fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
4479                      -> PResult<'a, (Vec<Arg> , bool)> {
4480         let sp = self.span;
4481         let mut variadic = false;
4482         let args: Vec<Option<Arg>> =
4483             self.parse_unspanned_seq(
4484                 &token::OpenDelim(token::Paren),
4485                 &token::CloseDelim(token::Paren),
4486                 SeqSep::trailing_allowed(token::Comma),
4487                 |p| {
4488                     if p.token == token::DotDotDot {
4489                         p.bump();
4490                         if allow_variadic {
4491                             if p.token != token::CloseDelim(token::Paren) {
4492                                 let span = p.span;
4493                                 p.span_err(span,
4494                                     "`...` must be last in argument list for variadic function");
4495                             }
4496                         } else {
4497                             let span = p.span;
4498                             p.span_err(span,
4499                                        "only foreign functions are allowed to be variadic");
4500                         }
4501                         variadic = true;
4502                         Ok(None)
4503                     } else {
4504                         match p.parse_arg_general(named_args) {
4505                             Ok(arg) => Ok(Some(arg)),
4506                             Err(mut e) => {
4507                                 e.emit();
4508                                 let lo = p.prev_span;
4509                                 // Skip every token until next possible arg or end.
4510                                 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
4511                                 // Create a placeholder argument for proper arg count (#34264).
4512                                 let span = lo.to(p.prev_span);
4513                                 Ok(Some(dummy_arg(span)))
4514                             }
4515                         }
4516                     }
4517                 }
4518             )?;
4519
4520         let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
4521
4522         if variadic && args.is_empty() {
4523             self.span_err(sp,
4524                           "variadic function must be declared with at least one named argument");
4525         }
4526
4527         Ok((args, variadic))
4528     }
4529
4530     /// Parse the argument list and result type of a function declaration
4531     pub fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
4532
4533         let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
4534         let ret_ty = self.parse_ret_ty()?;
4535
4536         Ok(P(FnDecl {
4537             inputs: args,
4538             output: ret_ty,
4539             variadic,
4540         }))
4541     }
4542
4543     /// Returns the parsed optional self argument and whether a self shortcut was used.
4544     fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
4545         let expect_ident = |this: &mut Self| match this.token {
4546             // Preserve hygienic context.
4547             token::Ident(ident) => { let sp = this.span; this.bump(); codemap::respan(sp, ident) }
4548             _ => unreachable!()
4549         };
4550         let isolated_self = |this: &mut Self, n| {
4551             this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
4552             this.look_ahead(n + 1, |t| t != &token::ModSep)
4553         };
4554
4555         // Parse optional self parameter of a method.
4556         // Only a limited set of initial token sequences is considered self parameters, anything
4557         // else is parsed as a normal function parameter list, so some lookahead is required.
4558         let eself_lo = self.span;
4559         let (eself, eself_ident) = match self.token {
4560             token::BinOp(token::And) => {
4561                 // &self
4562                 // &mut self
4563                 // &'lt self
4564                 // &'lt mut self
4565                 // &not_self
4566                 if isolated_self(self, 1) {
4567                     self.bump();
4568                     (SelfKind::Region(None, Mutability::Immutable), expect_ident(self))
4569                 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
4570                           isolated_self(self, 2) {
4571                     self.bump();
4572                     self.bump();
4573                     (SelfKind::Region(None, Mutability::Mutable), expect_ident(self))
4574                 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4575                           isolated_self(self, 2) {
4576                     self.bump();
4577                     let lt = self.expect_lifetime();
4578                     (SelfKind::Region(Some(lt), Mutability::Immutable), expect_ident(self))
4579                 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
4580                           self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
4581                           isolated_self(self, 3) {
4582                     self.bump();
4583                     let lt = self.expect_lifetime();
4584                     self.bump();
4585                     (SelfKind::Region(Some(lt), Mutability::Mutable), expect_ident(self))
4586                 } else {
4587                     return Ok(None);
4588                 }
4589             }
4590             token::BinOp(token::Star) => {
4591                 // *self
4592                 // *const self
4593                 // *mut self
4594                 // *not_self
4595                 // Emit special error for `self` cases.
4596                 if isolated_self(self, 1) {
4597                     self.bump();
4598                     self.span_err(self.span, "cannot pass `self` by raw pointer");
4599                     (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4600                 } else if self.look_ahead(1, |t| t.is_mutability()) &&
4601                           isolated_self(self, 2) {
4602                     self.bump();
4603                     self.bump();
4604                     self.span_err(self.span, "cannot pass `self` by raw pointer");
4605                     (SelfKind::Value(Mutability::Immutable), expect_ident(self))
4606                 } else {
4607                     return Ok(None);
4608                 }
4609             }
4610             token::Ident(..) => {
4611                 if isolated_self(self, 0) {
4612                     // self
4613                     // self: TYPE
4614                     let eself_ident = expect_ident(self);
4615                     if self.eat(&token::Colon) {
4616                         let ty = self.parse_ty()?;
4617                         (SelfKind::Explicit(ty, Mutability::Immutable), eself_ident)
4618                     } else {
4619                         (SelfKind::Value(Mutability::Immutable), eself_ident)
4620                     }
4621                 } else if self.token.is_keyword(keywords::Mut) &&
4622                           isolated_self(self, 1) {
4623                     // mut self
4624                     // mut self: TYPE
4625                     self.bump();
4626                     let eself_ident = expect_ident(self);
4627                     if self.eat(&token::Colon) {
4628                         let ty = self.parse_ty()?;
4629                         (SelfKind::Explicit(ty, Mutability::Mutable), eself_ident)
4630                     } else {
4631                         (SelfKind::Value(Mutability::Mutable), eself_ident)
4632                     }
4633                 } else {
4634                     return Ok(None);
4635                 }
4636             }
4637             _ => return Ok(None),
4638         };
4639
4640         let eself = codemap::respan(eself_lo.to(self.prev_span), eself);
4641         Ok(Some(Arg::from_self(eself, eself_ident)))
4642     }
4643
4644     /// Parse the parameter list and result type of a function that may have a `self` parameter.
4645     fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
4646         where F: FnMut(&mut Parser<'a>) -> PResult<'a,  Arg>,
4647     {
4648         self.expect(&token::OpenDelim(token::Paren))?;
4649
4650         // Parse optional self argument
4651         let self_arg = self.parse_self_arg()?;
4652
4653         // Parse the rest of the function parameter list.
4654         let sep = SeqSep::trailing_allowed(token::Comma);
4655         let fn_inputs = if let Some(self_arg) = self_arg {
4656             if self.check(&token::CloseDelim(token::Paren)) {
4657                 vec![self_arg]
4658             } else if self.eat(&token::Comma) {
4659                 let mut fn_inputs = vec![self_arg];
4660                 fn_inputs.append(&mut self.parse_seq_to_before_end(
4661                     &token::CloseDelim(token::Paren), sep, parse_arg_fn)
4662                 );
4663                 fn_inputs
4664             } else {
4665                 return self.unexpected();
4666             }
4667         } else {
4668             self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)
4669         };
4670
4671         // Parse closing paren and return type.
4672         self.expect(&token::CloseDelim(token::Paren))?;
4673         Ok(P(FnDecl {
4674             inputs: fn_inputs,
4675             output: self.parse_ret_ty()?,
4676             variadic: false
4677         }))
4678     }
4679
4680     // parse the |arg, arg| header on a lambda
4681     fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
4682         let inputs_captures = {
4683             if self.eat(&token::OrOr) {
4684                 Vec::new()
4685             } else {
4686                 self.expect(&token::BinOp(token::Or))?;
4687                 let args = self.parse_seq_to_before_end(
4688                     &token::BinOp(token::Or),
4689                     SeqSep::trailing_allowed(token::Comma),
4690                     |p| p.parse_fn_block_arg()
4691                 );
4692                 self.bump();
4693                 args
4694             }
4695         };
4696         let output = self.parse_ret_ty()?;
4697
4698         Ok(P(FnDecl {
4699             inputs: inputs_captures,
4700             output,
4701             variadic: false
4702         }))
4703     }
4704
4705     /// Parse the name and optional generic types of a function header.
4706     fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
4707         let id = self.parse_ident()?;
4708         let generics = self.parse_generics()?;
4709         Ok((id, generics))
4710     }
4711
4712     fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
4713                attrs: Vec<Attribute>) -> P<Item> {
4714         P(Item {
4715             ident,
4716             attrs,
4717             id: ast::DUMMY_NODE_ID,
4718             node,
4719             vis,
4720             span,
4721             tokens: None,
4722         })
4723     }
4724
4725     /// Parse an item-position function declaration.
4726     fn parse_item_fn(&mut self,
4727                      unsafety: Unsafety,
4728                      constness: Spanned<Constness>,
4729                      abi: abi::Abi)
4730                      -> PResult<'a, ItemInfo> {
4731         let (ident, mut generics) = self.parse_fn_header()?;
4732         let decl = self.parse_fn_decl(false)?;
4733         generics.where_clause = self.parse_where_clause()?;
4734         let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4735         Ok((ident, ItemKind::Fn(decl, unsafety, constness, abi, generics, body), Some(inner_attrs)))
4736     }
4737
4738     /// true if we are looking at `const ID`, false for things like `const fn` etc
4739     pub fn is_const_item(&mut self) -> bool {
4740         self.token.is_keyword(keywords::Const) &&
4741             !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
4742             !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
4743     }
4744
4745     /// parses all the "front matter" for a `fn` declaration, up to
4746     /// and including the `fn` keyword:
4747     ///
4748     /// - `const fn`
4749     /// - `unsafe fn`
4750     /// - `const unsafe fn`
4751     /// - `extern fn`
4752     /// - etc
4753     pub fn parse_fn_front_matter(&mut self)
4754                                  -> PResult<'a, (Spanned<ast::Constness>,
4755                                                 ast::Unsafety,
4756                                                 abi::Abi)> {
4757         let is_const_fn = self.eat_keyword(keywords::Const);
4758         let const_span = self.prev_span;
4759         let unsafety = self.parse_unsafety()?;
4760         let (constness, unsafety, abi) = if is_const_fn {
4761             (respan(const_span, Constness::Const), unsafety, Abi::Rust)
4762         } else {
4763             let abi = if self.eat_keyword(keywords::Extern) {
4764                 self.parse_opt_abi()?.unwrap_or(Abi::C)
4765             } else {
4766                 Abi::Rust
4767             };
4768             (respan(self.prev_span, Constness::NotConst), unsafety, abi)
4769         };
4770         self.expect_keyword(keywords::Fn)?;
4771         Ok((constness, unsafety, abi))
4772     }
4773
4774     /// Parse an impl item.
4775     pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
4776         maybe_whole!(self, NtImplItem, |x| x);
4777         let attrs = self.parse_outer_attributes()?;
4778         let (mut item, tokens) = self.collect_tokens(|this| {
4779             this.parse_impl_item_(at_end, attrs)
4780         })?;
4781
4782         // See `parse_item` for why this clause is here.
4783         if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
4784             item.tokens = Some(tokens);
4785         }
4786         Ok(item)
4787     }
4788
4789     fn parse_impl_item_(&mut self,
4790                         at_end: &mut bool,
4791                         mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
4792         let lo = self.span;
4793         let vis = self.parse_visibility(false)?;
4794         let defaultness = self.parse_defaultness()?;
4795         let (name, node) = if self.eat_keyword(keywords::Type) {
4796             let name = self.parse_ident()?;
4797             self.expect(&token::Eq)?;
4798             let typ = self.parse_ty()?;
4799             self.expect(&token::Semi)?;
4800             (name, ast::ImplItemKind::Type(typ))
4801         } else if self.is_const_item() {
4802             self.expect_keyword(keywords::Const)?;
4803             let name = self.parse_ident()?;
4804             self.expect(&token::Colon)?;
4805             let typ = self.parse_ty()?;
4806             self.expect(&token::Eq)?;
4807             let expr = self.parse_expr()?;
4808             self.expect(&token::Semi)?;
4809             (name, ast::ImplItemKind::Const(typ, expr))
4810         } else {
4811             let (name, inner_attrs, node) = self.parse_impl_method(&vis, at_end)?;
4812             attrs.extend(inner_attrs);
4813             (name, node)
4814         };
4815
4816         Ok(ImplItem {
4817             id: ast::DUMMY_NODE_ID,
4818             span: lo.to(self.prev_span),
4819             ident: name,
4820             vis,
4821             defaultness,
4822             attrs,
4823             node,
4824             tokens: None,
4825         })
4826     }
4827
4828     fn complain_if_pub_macro(&mut self, vis: &Visibility, sp: Span) {
4829         if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
4830             err.emit();
4831         }
4832     }
4833
4834     fn complain_if_pub_macro_diag(&mut self, vis: &Visibility, sp: Span) -> PResult<'a, ()> {
4835         match *vis {
4836             Visibility::Inherited => Ok(()),
4837             _ => {
4838                 let is_macro_rules: bool = match self.token {
4839                     token::Ident(sid) => sid.name == Symbol::intern("macro_rules"),
4840                     _ => false,
4841                 };
4842                 if is_macro_rules {
4843                     let mut err = self.diagnostic()
4844                         .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
4845                     err.help("did you mean #[macro_export]?");
4846                     Err(err)
4847                 } else {
4848                     let mut err = self.diagnostic()
4849                         .struct_span_err(sp, "can't qualify macro invocation with `pub`");
4850                     err.help("try adjusting the macro to put `pub` inside the invocation");
4851                     Err(err)
4852                 }
4853             }
4854         }
4855     }
4856
4857     fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
4858                                    -> DiagnosticBuilder<'a>
4859     {
4860         // Given this code `path(`, it seems like this is not
4861         // setting the visibility of a macro invocation, but rather
4862         // a mistyped method declaration.
4863         // Create a diagnostic pointing out that `fn` is missing.
4864         //
4865         // x |     pub path(&self) {
4866         //   |        ^ missing `fn`, `type`, or `const`
4867         //     pub  path(
4868         //        ^^ `sp` below will point to this
4869         let sp = prev_span.between(self.prev_span);
4870         let mut err = self.diagnostic().struct_span_err(
4871             sp,
4872             &format!("missing `fn`, `type`, or `const` for {}-item declaration",
4873                      item_type));
4874         err.span_label(sp, "missing `fn`, `type`, or `const`");
4875         err
4876     }
4877
4878     /// Parse a method or a macro invocation in a trait impl.
4879     fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
4880                          -> PResult<'a, (Ident, Vec<ast::Attribute>, ast::ImplItemKind)> {
4881         // code copied from parse_macro_use_or_failure... abstraction!
4882         if self.token.is_path_start() {
4883             // Method macro.
4884
4885             let prev_span = self.prev_span;
4886
4887             let lo = self.span;
4888             let pth = self.parse_path(PathStyle::Mod)?;
4889             if pth.segments.len() == 1 {
4890                 if !self.eat(&token::Not) {
4891                     return Err(self.missing_assoc_item_kind_err("impl", prev_span));
4892                 }
4893             } else {
4894                 self.expect(&token::Not)?;
4895             }
4896
4897             self.complain_if_pub_macro(vis, prev_span);
4898
4899             // eat a matched-delimiter token tree:
4900             *at_end = true;
4901             let (delim, tts) = self.expect_delimited_token_tree()?;
4902             if delim != token::Brace {
4903                 self.expect(&token::Semi)?
4904             }
4905
4906             let mac = respan(lo.to(self.prev_span), Mac_ { path: pth, tts: tts });
4907             Ok((keywords::Invalid.ident(), vec![], ast::ImplItemKind::Macro(mac)))
4908         } else {
4909             let (constness, unsafety, abi) = self.parse_fn_front_matter()?;
4910             let ident = self.parse_ident()?;
4911             let mut generics = self.parse_generics()?;
4912             let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
4913             generics.where_clause = self.parse_where_clause()?;
4914             *at_end = true;
4915             let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
4916             Ok((ident, inner_attrs, ast::ImplItemKind::Method(ast::MethodSig {
4917                 generics,
4918                 abi,
4919                 unsafety,
4920                 constness,
4921                 decl,
4922              }, body)))
4923         }
4924     }
4925
4926     /// Parse trait Foo { ... }
4927     fn parse_item_trait(&mut self, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
4928         let ident = self.parse_ident()?;
4929         let mut tps = self.parse_generics()?;
4930
4931         // Parse optional colon and supertrait bounds.
4932         let bounds = if self.eat(&token::Colon) {
4933             self.parse_ty_param_bounds()?
4934         } else {
4935             Vec::new()
4936         };
4937
4938         tps.where_clause = self.parse_where_clause()?;
4939
4940         self.expect(&token::OpenDelim(token::Brace))?;
4941         let mut trait_items = vec![];
4942         while !self.eat(&token::CloseDelim(token::Brace)) {
4943             let mut at_end = false;
4944             match self.parse_trait_item(&mut at_end) {
4945                 Ok(item) => trait_items.push(item),
4946                 Err(mut e) => {
4947                     e.emit();
4948                     if !at_end {
4949                         self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
4950                     }
4951                 }
4952             }
4953         }
4954         Ok((ident, ItemKind::Trait(unsafety, tps, bounds, trait_items), None))
4955     }
4956
4957     /// Parses items implementations variants
4958     ///    impl<T> Foo { ... }
4959     ///    impl<T> ToString for &'static T { ... }
4960     ///    impl Send for .. {}
4961     fn parse_item_impl(&mut self,
4962                        unsafety: ast::Unsafety,
4963                        defaultness: Defaultness) -> PResult<'a, ItemInfo> {
4964         let impl_span = self.span;
4965
4966         // First, parse type parameters if necessary.
4967         let mut generics = self.parse_generics()?;
4968
4969         // Special case: if the next identifier that follows is '(', don't
4970         // allow this to be parsed as a trait.
4971         let could_be_trait = self.token != token::OpenDelim(token::Paren);
4972
4973         let neg_span = self.span;
4974         let polarity = if self.eat(&token::Not) {
4975             ast::ImplPolarity::Negative
4976         } else {
4977             ast::ImplPolarity::Positive
4978         };
4979
4980         // Parse the trait.
4981         let mut ty = self.parse_ty()?;
4982
4983         // Parse traits, if necessary.
4984         let opt_trait = if could_be_trait && self.eat_keyword(keywords::For) {
4985             // New-style trait. Reinterpret the type as a trait.
4986             match ty.node {
4987                 TyKind::Path(None, ref path) => {
4988                     Some(TraitRef {
4989                         path: (*path).clone(),
4990                         ref_id: ty.id,
4991                     })
4992                 }
4993                 _ => {
4994                     self.span_err(ty.span, "not a trait");
4995                     None
4996                 }
4997             }
4998         } else {
4999             if polarity == ast::ImplPolarity::Negative {
5000                 // This is a negated type implementation
5001                 // `impl !MyType {}`, which is not allowed.
5002                 self.span_err(neg_span, "inherent implementation can't be negated");
5003             }
5004             None
5005         };
5006
5007         if opt_trait.is_some() && self.eat(&token::DotDot) {
5008             if generics.is_parameterized() {
5009                 self.span_err(impl_span, "default trait implementations are not \
5010                                           allowed to have generics");
5011             }
5012
5013             if let ast::Defaultness::Default = defaultness {
5014                 self.span_err(impl_span, "`default impl` is not allowed for \
5015                                          default trait implementations");
5016             }
5017
5018             self.expect(&token::OpenDelim(token::Brace))?;
5019             self.expect(&token::CloseDelim(token::Brace))?;
5020             Ok((keywords::Invalid.ident(),
5021              ItemKind::DefaultImpl(unsafety, opt_trait.unwrap()), None))
5022         } else {
5023             if opt_trait.is_some() {
5024                 ty = self.parse_ty()?;
5025             }
5026             generics.where_clause = self.parse_where_clause()?;
5027
5028             self.expect(&token::OpenDelim(token::Brace))?;
5029             let attrs = self.parse_inner_attributes()?;
5030
5031             let mut impl_items = vec![];
5032             while !self.eat(&token::CloseDelim(token::Brace)) {
5033                 let mut at_end = false;
5034                 match self.parse_impl_item(&mut at_end) {
5035                     Ok(item) => impl_items.push(item),
5036                     Err(mut e) => {
5037                         e.emit();
5038                         if !at_end {
5039                             self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5040                         }
5041                     }
5042                 }
5043             }
5044
5045             Ok((keywords::Invalid.ident(),
5046              ItemKind::Impl(unsafety, polarity, defaultness, generics, opt_trait, ty, impl_items),
5047              Some(attrs)))
5048         }
5049     }
5050
5051     fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<LifetimeDef>> {
5052         if self.eat_keyword(keywords::For) {
5053             self.expect_lt()?;
5054             let (lifetime_defs, ty_params) = self.parse_generic_params()?;
5055             self.expect_gt()?;
5056             if !ty_params.is_empty() {
5057                 self.span_err(ty_params[0].span,
5058                               "only lifetime parameters can be used in this context");
5059             }
5060             Ok(lifetime_defs)
5061         } else {
5062             Ok(Vec::new())
5063         }
5064     }
5065
5066     /// Parse struct Foo { ... }
5067     fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5068         let class_name = self.parse_ident()?;
5069
5070         let mut generics = self.parse_generics()?;
5071
5072         // There is a special case worth noting here, as reported in issue #17904.
5073         // If we are parsing a tuple struct it is the case that the where clause
5074         // should follow the field list. Like so:
5075         //
5076         // struct Foo<T>(T) where T: Copy;
5077         //
5078         // If we are parsing a normal record-style struct it is the case
5079         // that the where clause comes before the body, and after the generics.
5080         // So if we look ahead and see a brace or a where-clause we begin
5081         // parsing a record style struct.
5082         //
5083         // Otherwise if we look ahead and see a paren we parse a tuple-style
5084         // struct.
5085
5086         let vdata = if self.token.is_keyword(keywords::Where) {
5087             generics.where_clause = self.parse_where_clause()?;
5088             if self.eat(&token::Semi) {
5089                 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5090                 VariantData::Unit(ast::DUMMY_NODE_ID)
5091             } else {
5092                 // If we see: `struct Foo<T> where T: Copy { ... }`
5093                 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5094             }
5095         // No `where` so: `struct Foo<T>;`
5096         } else if self.eat(&token::Semi) {
5097             VariantData::Unit(ast::DUMMY_NODE_ID)
5098         // Record-style struct definition
5099         } else if self.token == token::OpenDelim(token::Brace) {
5100             VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5101         // Tuple-style struct definition with optional where-clause.
5102         } else if self.token == token::OpenDelim(token::Paren) {
5103             let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5104             generics.where_clause = self.parse_where_clause()?;
5105             self.expect(&token::Semi)?;
5106             body
5107         } else {
5108             let token_str = self.this_token_to_string();
5109             return Err(self.fatal(&format!("expected `where`, `{{`, `(`, or `;` after struct \
5110                                             name, found `{}`", token_str)))
5111         };
5112
5113         Ok((class_name, ItemKind::Struct(vdata, generics), None))
5114     }
5115
5116     /// Parse union Foo { ... }
5117     fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5118         let class_name = self.parse_ident()?;
5119
5120         let mut generics = self.parse_generics()?;
5121
5122         let vdata = if self.token.is_keyword(keywords::Where) {
5123             generics.where_clause = self.parse_where_clause()?;
5124             VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5125         } else if self.token == token::OpenDelim(token::Brace) {
5126             VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5127         } else {
5128             let token_str = self.this_token_to_string();
5129             return Err(self.fatal(&format!("expected `where` or `{{` after union \
5130                                             name, found `{}`", token_str)))
5131         };
5132
5133         Ok((class_name, ItemKind::Union(vdata, generics), None))
5134     }
5135
5136     pub fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5137         let mut fields = Vec::new();
5138         if self.eat(&token::OpenDelim(token::Brace)) {
5139             while self.token != token::CloseDelim(token::Brace) {
5140                 fields.push(self.parse_struct_decl_field().map_err(|e| {
5141                     self.recover_stmt();
5142                     self.eat(&token::CloseDelim(token::Brace));
5143                     e
5144                 })?);
5145             }
5146
5147             self.bump();
5148         } else {
5149             let token_str = self.this_token_to_string();
5150             return Err(self.fatal(&format!("expected `where`, or `{{` after struct \
5151                                 name, found `{}`",
5152                                 token_str)));
5153         }
5154
5155         Ok(fields)
5156     }
5157
5158     pub fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5159         // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5160         // Unit like structs are handled in parse_item_struct function
5161         let fields = self.parse_unspanned_seq(
5162             &token::OpenDelim(token::Paren),
5163             &token::CloseDelim(token::Paren),
5164             SeqSep::trailing_allowed(token::Comma),
5165             |p| {
5166                 let attrs = p.parse_outer_attributes()?;
5167                 let lo = p.span;
5168                 let vis = p.parse_visibility(true)?;
5169                 let ty = p.parse_ty()?;
5170                 Ok(StructField {
5171                     span: lo.to(p.span),
5172                     vis,
5173                     ident: None,
5174                     id: ast::DUMMY_NODE_ID,
5175                     ty,
5176                     attrs,
5177                 })
5178             })?;
5179
5180         Ok(fields)
5181     }
5182
5183     /// Parse a structure field declaration
5184     pub fn parse_single_struct_field(&mut self,
5185                                      lo: Span,
5186                                      vis: Visibility,
5187                                      attrs: Vec<Attribute> )
5188                                      -> PResult<'a, StructField> {
5189         let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5190         match self.token {
5191             token::Comma => {
5192                 self.bump();
5193             }
5194             token::CloseDelim(token::Brace) => {}
5195             token::DocComment(_) => return Err(self.span_fatal_err(self.span,
5196                                                                    Error::UselessDocComment)),
5197             _ => return Err(self.span_fatal_help(self.span,
5198                     &format!("expected `,`, or `}}`, found `{}`", self.this_token_to_string()),
5199                     "struct fields should be separated by commas")),
5200         }
5201         Ok(a_var)
5202     }
5203
5204     /// Parse an element of a struct definition
5205     fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
5206         let attrs = self.parse_outer_attributes()?;
5207         let lo = self.span;
5208         let vis = self.parse_visibility(false)?;
5209         self.parse_single_struct_field(lo, vis, attrs)
5210     }
5211
5212     /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
5213     /// and `pub(super)` for `pub(in super)`.  If the following element can't be a tuple (i.e. it's
5214     /// a function definition, it's not a tuple struct field) and the contents within the parens
5215     /// isn't valid, emit a proper diagnostic.
5216     pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
5217         maybe_whole!(self, NtVis, |x| x);
5218
5219         if !self.eat_keyword(keywords::Pub) {
5220             return Ok(Visibility::Inherited)
5221         }
5222
5223         if self.check(&token::OpenDelim(token::Paren)) {
5224             // We don't `self.bump()` the `(` yet because this might be a struct definition where
5225             // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
5226             // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
5227             // by the following tokens.
5228             if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
5229                 // `pub(crate)`
5230                 self.bump(); // `(`
5231                 self.bump(); // `crate`
5232                 let vis = Visibility::Crate(self.prev_span);
5233                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5234                 return Ok(vis)
5235             } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
5236                 // `pub(in path)`
5237                 self.bump(); // `(`
5238                 self.bump(); // `in`
5239                 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `path`
5240                 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5241                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5242                 return Ok(vis)
5243             } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
5244                       self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
5245                                              t.is_keyword(keywords::SelfValue)) {
5246                 // `pub(self)` or `pub(super)`
5247                 self.bump(); // `(`
5248                 let path = self.parse_path(PathStyle::Mod)?.default_to_global(); // `super`/`self`
5249                 let vis = Visibility::Restricted { path: P(path), id: ast::DUMMY_NODE_ID };
5250                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
5251                 return Ok(vis)
5252             } else if !can_take_tuple {  // Provide this diagnostic if this is not a tuple struct
5253                 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
5254                 self.bump(); // `(`
5255                 let msg = "incorrect visibility restriction";
5256                 let suggestion = r##"some possible visibility restrictions are:
5257 `pub(crate)`: visible only on the current crate
5258 `pub(super)`: visible only in the current module's parent
5259 `pub(in path::to::module)`: visible only on the specified path"##;
5260                 let path = self.parse_path(PathStyle::Mod)?;
5261                 let path_span = self.prev_span;
5262                 let help_msg = format!("make this visible only to module `{}` with `in`", path);
5263                 self.expect(&token::CloseDelim(token::Paren))?;  // `)`
5264                 let mut err = self.span_fatal_help(path_span, msg, suggestion);
5265                 err.span_suggestion(path_span, &help_msg, format!("in {}", path));
5266                 err.emit();  // emit diagnostic, but continue with public visibility
5267             }
5268         }
5269
5270         Ok(Visibility::Public)
5271     }
5272
5273     /// Parse defaultness: DEFAULT or nothing
5274     fn parse_defaultness(&mut self) -> PResult<'a, Defaultness> {
5275         if self.eat_defaultness() {
5276             Ok(Defaultness::Default)
5277         } else {
5278             Ok(Defaultness::Final)
5279         }
5280     }
5281
5282     /// Given a termination token, parse all of the items in a module
5283     fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
5284         let mut items = vec![];
5285         while let Some(item) = self.parse_item()? {
5286             items.push(item);
5287         }
5288
5289         if !self.eat(term) {
5290             let token_str = self.this_token_to_string();
5291             return Err(self.fatal(&format!("expected item, found `{}`", token_str)));
5292         }
5293
5294         let hi = if self.span == syntax_pos::DUMMY_SP {
5295             inner_lo
5296         } else {
5297             self.prev_span
5298         };
5299
5300         Ok(ast::Mod {
5301             inner: inner_lo.to(hi),
5302             items,
5303         })
5304     }
5305
5306     fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
5307         let id = self.parse_ident()?;
5308         self.expect(&token::Colon)?;
5309         let ty = self.parse_ty()?;
5310         self.expect(&token::Eq)?;
5311         let e = self.parse_expr()?;
5312         self.expect(&token::Semi)?;
5313         let item = match m {
5314             Some(m) => ItemKind::Static(ty, m, e),
5315             None => ItemKind::Const(ty, e),
5316         };
5317         Ok((id, item, None))
5318     }
5319
5320     /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
5321     fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
5322         let (in_cfg, outer_attrs) = {
5323             let mut strip_unconfigured = ::config::StripUnconfigured {
5324                 sess: self.sess,
5325                 should_test: false, // irrelevant
5326                 features: None, // don't perform gated feature checking
5327             };
5328             let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
5329             (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
5330         };
5331
5332         let id_span = self.span;
5333         let id = self.parse_ident()?;
5334         if self.check(&token::Semi) {
5335             self.bump();
5336             if in_cfg && self.recurse_into_file_modules {
5337                 // This mod is in an external file. Let's go get it!
5338                 let ModulePathSuccess { path, directory_ownership, warn } =
5339                     self.submod_path(id, &outer_attrs, id_span)?;
5340                 let (module, mut attrs) =
5341                     self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
5342                 if warn {
5343                     let attr = ast::Attribute {
5344                         id: attr::mk_attr_id(),
5345                         style: ast::AttrStyle::Outer,
5346                         path: ast::Path::from_ident(syntax_pos::DUMMY_SP,
5347                                                     Ident::from_str("warn_directory_ownership")),
5348                         tokens: TokenStream::empty(),
5349                         is_sugared_doc: false,
5350                         span: syntax_pos::DUMMY_SP,
5351                     };
5352                     attr::mark_known(&attr);
5353                     attrs.push(attr);
5354                 }
5355                 Ok((id, module, Some(attrs)))
5356             } else {
5357                 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
5358                 Ok((id, ItemKind::Mod(placeholder), None))
5359             }
5360         } else {
5361             let old_directory = self.directory.clone();
5362             self.push_directory(id, &outer_attrs);
5363
5364             self.expect(&token::OpenDelim(token::Brace))?;
5365             let mod_inner_lo = self.span;
5366             let attrs = self.parse_inner_attributes()?;
5367             let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
5368
5369             self.directory = old_directory;
5370             Ok((id, ItemKind::Mod(module), Some(attrs)))
5371         }
5372     }
5373
5374     fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
5375         if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
5376             self.directory.path.push(&path.as_str());
5377             self.directory.ownership = DirectoryOwnership::Owned;
5378         } else {
5379             self.directory.path.push(&id.name.as_str());
5380         }
5381     }
5382
5383     pub fn submod_path_from_attr(attrs: &[ast::Attribute], dir_path: &Path) -> Option<PathBuf> {
5384         attr::first_attr_value_str_by_name(attrs, "path").map(|d| dir_path.join(&d.as_str()))
5385     }
5386
5387     /// Returns either a path to a module, or .
5388     pub fn default_submod_path(id: ast::Ident, dir_path: &Path, codemap: &CodeMap) -> ModulePath {
5389         let mod_name = id.to_string();
5390         let default_path_str = format!("{}.rs", mod_name);
5391         let secondary_path_str = format!("{}{}mod.rs", mod_name, path::MAIN_SEPARATOR);
5392         let default_path = dir_path.join(&default_path_str);
5393         let secondary_path = dir_path.join(&secondary_path_str);
5394         let default_exists = codemap.file_exists(&default_path);
5395         let secondary_exists = codemap.file_exists(&secondary_path);
5396
5397         let result = match (default_exists, secondary_exists) {
5398             (true, false) => Ok(ModulePathSuccess {
5399                 path: default_path,
5400                 directory_ownership: DirectoryOwnership::UnownedViaMod(false),
5401                 warn: false,
5402             }),
5403             (false, true) => Ok(ModulePathSuccess {
5404                 path: secondary_path,
5405                 directory_ownership: DirectoryOwnership::Owned,
5406                 warn: false,
5407             }),
5408             (false, false) => Err(Error::FileNotFoundForModule {
5409                 mod_name: mod_name.clone(),
5410                 default_path: default_path_str,
5411                 secondary_path: secondary_path_str,
5412                 dir_path: format!("{}", dir_path.display()),
5413             }),
5414             (true, true) => Err(Error::DuplicatePaths {
5415                 mod_name: mod_name.clone(),
5416                 default_path: default_path_str,
5417                 secondary_path: secondary_path_str,
5418             }),
5419         };
5420
5421         ModulePath {
5422             name: mod_name,
5423             path_exists: default_exists || secondary_exists,
5424             result,
5425         }
5426     }
5427
5428     fn submod_path(&mut self,
5429                    id: ast::Ident,
5430                    outer_attrs: &[ast::Attribute],
5431                    id_sp: Span)
5432                    -> PResult<'a, ModulePathSuccess> {
5433         if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
5434             return Ok(ModulePathSuccess {
5435                 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
5436                     Some("mod.rs") => DirectoryOwnership::Owned,
5437                     _ => DirectoryOwnership::UnownedViaMod(true),
5438                 },
5439                 path,
5440                 warn: false,
5441             });
5442         }
5443
5444         let paths = Parser::default_submod_path(id, &self.directory.path, self.sess.codemap());
5445
5446         if let DirectoryOwnership::UnownedViaBlock = self.directory.ownership {
5447             let msg =
5448                 "Cannot declare a non-inline module inside a block unless it has a path attribute";
5449             let mut err = self.diagnostic().struct_span_err(id_sp, msg);
5450             if paths.path_exists {
5451                 let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
5452                                   paths.name);
5453                 err.span_note(id_sp, &msg);
5454             }
5455             Err(err)
5456         } else if let DirectoryOwnership::UnownedViaMod(warn) = self.directory.ownership {
5457             if warn {
5458                 if let Ok(result) = paths.result {
5459                     return Ok(ModulePathSuccess { warn: true, ..result });
5460                 }
5461             }
5462             let mut err = self.diagnostic().struct_span_err(id_sp,
5463                 "cannot declare a new module at this location");
5464             if id_sp != syntax_pos::DUMMY_SP {
5465                 let src_path = PathBuf::from(self.sess.codemap().span_to_filename(id_sp));
5466                 if let Some(stem) = src_path.file_stem() {
5467                     let mut dest_path = src_path.clone();
5468                     dest_path.set_file_name(stem);
5469                     dest_path.push("mod.rs");
5470                     err.span_note(id_sp,
5471                                   &format!("maybe move this module `{}` to its own \
5472                                             directory via `{}`", src_path.to_string_lossy(),
5473                                            dest_path.to_string_lossy()));
5474                 }
5475             }
5476             if paths.path_exists {
5477                 err.span_note(id_sp,
5478                               &format!("... or maybe `use` the module `{}` instead \
5479                                         of possibly redeclaring it",
5480                                        paths.name));
5481             }
5482             Err(err)
5483         } else {
5484             paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
5485         }
5486     }
5487
5488     /// Read a module from a source file.
5489     fn eval_src_mod(&mut self,
5490                     path: PathBuf,
5491                     directory_ownership: DirectoryOwnership,
5492                     name: String,
5493                     id_sp: Span)
5494                     -> PResult<'a, (ast::ItemKind, Vec<ast::Attribute> )> {
5495         let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
5496         if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
5497             let mut err = String::from("circular modules: ");
5498             let len = included_mod_stack.len();
5499             for p in &included_mod_stack[i.. len] {
5500                 err.push_str(&p.to_string_lossy());
5501                 err.push_str(" -> ");
5502             }
5503             err.push_str(&path.to_string_lossy());
5504             return Err(self.span_fatal(id_sp, &err[..]));
5505         }
5506         included_mod_stack.push(path.clone());
5507         drop(included_mod_stack);
5508
5509         let mut p0 =
5510             new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
5511         p0.cfg_mods = self.cfg_mods;
5512         let mod_inner_lo = p0.span;
5513         let mod_attrs = p0.parse_inner_attributes()?;
5514         let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
5515         self.sess.included_mod_stack.borrow_mut().pop();
5516         Ok((ast::ItemKind::Mod(m0), mod_attrs))
5517     }
5518
5519     /// Parse a function declaration from a foreign module
5520     fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5521                              -> PResult<'a, ForeignItem> {
5522         self.expect_keyword(keywords::Fn)?;
5523
5524         let (ident, mut generics) = self.parse_fn_header()?;
5525         let decl = self.parse_fn_decl(true)?;
5526         generics.where_clause = self.parse_where_clause()?;
5527         let hi = self.span;
5528         self.expect(&token::Semi)?;
5529         Ok(ast::ForeignItem {
5530             ident,
5531             attrs,
5532             node: ForeignItemKind::Fn(decl, generics),
5533             id: ast::DUMMY_NODE_ID,
5534             span: lo.to(hi),
5535             vis,
5536         })
5537     }
5538
5539     /// Parse a static item from a foreign module.
5540     /// Assumes that the `static` keyword is already parsed.
5541     fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
5542                                  -> PResult<'a, ForeignItem> {
5543         let mutbl = self.eat_keyword(keywords::Mut);
5544         let ident = self.parse_ident()?;
5545         self.expect(&token::Colon)?;
5546         let ty = self.parse_ty()?;
5547         let hi = self.span;
5548         self.expect(&token::Semi)?;
5549         Ok(ForeignItem {
5550             ident,
5551             attrs,
5552             node: ForeignItemKind::Static(ty, mutbl),
5553             id: ast::DUMMY_NODE_ID,
5554             span: lo.to(hi),
5555             vis,
5556         })
5557     }
5558
5559     /// Parse extern crate links
5560     ///
5561     /// # Examples
5562     ///
5563     /// extern crate foo;
5564     /// extern crate bar as foo;
5565     fn parse_item_extern_crate(&mut self,
5566                                lo: Span,
5567                                visibility: Visibility,
5568                                attrs: Vec<Attribute>)
5569                                 -> PResult<'a, P<Item>> {
5570
5571         let crate_name = self.parse_ident()?;
5572         let (maybe_path, ident) = if let Some(ident) = self.parse_rename()? {
5573             (Some(crate_name.name), ident)
5574         } else {
5575             (None, crate_name)
5576         };
5577         self.expect(&token::Semi)?;
5578
5579         let prev_span = self.prev_span;
5580         Ok(self.mk_item(lo.to(prev_span),
5581                         ident,
5582                         ItemKind::ExternCrate(maybe_path),
5583                         visibility,
5584                         attrs))
5585     }
5586
5587     /// Parse `extern` for foreign ABIs
5588     /// modules.
5589     ///
5590     /// `extern` is expected to have been
5591     /// consumed before calling this method
5592     ///
5593     /// # Examples:
5594     ///
5595     /// extern "C" {}
5596     /// extern {}
5597     fn parse_item_foreign_mod(&mut self,
5598                               lo: Span,
5599                               opt_abi: Option<abi::Abi>,
5600                               visibility: Visibility,
5601                               mut attrs: Vec<Attribute>)
5602                               -> PResult<'a, P<Item>> {
5603         self.expect(&token::OpenDelim(token::Brace))?;
5604
5605         let abi = opt_abi.unwrap_or(Abi::C);
5606
5607         attrs.extend(self.parse_inner_attributes()?);
5608
5609         let mut foreign_items = vec![];
5610         while let Some(item) = self.parse_foreign_item()? {
5611             foreign_items.push(item);
5612         }
5613         self.expect(&token::CloseDelim(token::Brace))?;
5614
5615         let prev_span = self.prev_span;
5616         let m = ast::ForeignMod {
5617             abi,
5618             items: foreign_items
5619         };
5620         let invalid = keywords::Invalid.ident();
5621         Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
5622     }
5623
5624     /// Parse type Foo = Bar;
5625     fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
5626         let ident = self.parse_ident()?;
5627         let mut tps = self.parse_generics()?;
5628         tps.where_clause = self.parse_where_clause()?;
5629         self.expect(&token::Eq)?;
5630         let ty = self.parse_ty()?;
5631         self.expect(&token::Semi)?;
5632         Ok((ident, ItemKind::Ty(ty, tps), None))
5633     }
5634
5635     /// Parse the part of an "enum" decl following the '{'
5636     fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
5637         let mut variants = Vec::new();
5638         let mut all_nullary = true;
5639         let mut any_disr = None;
5640         while self.token != token::CloseDelim(token::Brace) {
5641             let variant_attrs = self.parse_outer_attributes()?;
5642             let vlo = self.span;
5643
5644             let struct_def;
5645             let mut disr_expr = None;
5646             let ident = self.parse_ident()?;
5647             if self.check(&token::OpenDelim(token::Brace)) {
5648                 // Parse a struct variant.
5649                 all_nullary = false;
5650                 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
5651                                                  ast::DUMMY_NODE_ID);
5652             } else if self.check(&token::OpenDelim(token::Paren)) {
5653                 all_nullary = false;
5654                 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
5655                                                 ast::DUMMY_NODE_ID);
5656             } else if self.eat(&token::Eq) {
5657                 disr_expr = Some(self.parse_expr()?);
5658                 any_disr = disr_expr.as_ref().map(|expr| expr.span);
5659                 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5660             } else {
5661                 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
5662             }
5663
5664             let vr = ast::Variant_ {
5665                 name: ident,
5666                 attrs: variant_attrs,
5667                 data: struct_def,
5668                 disr_expr,
5669             };
5670             variants.push(respan(vlo.to(self.prev_span), vr));
5671
5672             if !self.eat(&token::Comma) { break; }
5673         }
5674         self.expect(&token::CloseDelim(token::Brace))?;
5675         match any_disr {
5676             Some(disr_span) if !all_nullary =>
5677                 self.span_err(disr_span,
5678                     "discriminator values can only be used with a c-like enum"),
5679             _ => ()
5680         }
5681
5682         Ok(ast::EnumDef { variants: variants })
5683     }
5684
5685     /// Parse an "enum" declaration
5686     fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
5687         let id = self.parse_ident()?;
5688         let mut generics = self.parse_generics()?;
5689         generics.where_clause = self.parse_where_clause()?;
5690         self.expect(&token::OpenDelim(token::Brace))?;
5691
5692         let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
5693             self.recover_stmt();
5694             self.eat(&token::CloseDelim(token::Brace));
5695             e
5696         })?;
5697         Ok((id, ItemKind::Enum(enum_definition, generics), None))
5698     }
5699
5700     /// Parses a string as an ABI spec on an extern type or module. Consumes
5701     /// the `extern` keyword, if one is found.
5702     fn parse_opt_abi(&mut self) -> PResult<'a, Option<abi::Abi>> {
5703         match self.token {
5704             token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
5705                 let sp = self.span;
5706                 self.expect_no_suffix(sp, "ABI spec", suf);
5707                 self.bump();
5708                 match abi::lookup(&s.as_str()) {
5709                     Some(abi) => Ok(Some(abi)),
5710                     None => {
5711                         let prev_span = self.prev_span;
5712                         self.span_err(
5713                             prev_span,
5714                             &format!("invalid ABI: expected one of [{}], \
5715                                      found `{}`",
5716                                     abi::all_names().join(", "),
5717                                     s));
5718                         Ok(None)
5719                     }
5720                 }
5721             }
5722
5723             _ => Ok(None),
5724         }
5725     }
5726
5727     /// Parse one of the items allowed by the flags.
5728     /// NB: this function no longer parses the items inside an
5729     /// extern crate.
5730     fn parse_item_(&mut self, attrs: Vec<Attribute>,
5731                    macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
5732         maybe_whole!(self, NtItem, |item| {
5733             let mut item = item.unwrap();
5734             let mut attrs = attrs;
5735             mem::swap(&mut item.attrs, &mut attrs);
5736             item.attrs.extend(attrs);
5737             Some(P(item))
5738         });
5739
5740         let lo = self.span;
5741
5742         let visibility = self.parse_visibility(false)?;
5743
5744         if self.eat_keyword(keywords::Use) {
5745             // USE ITEM
5746             let item_ = ItemKind::Use(self.parse_view_path()?);
5747             self.expect(&token::Semi)?;
5748
5749             let prev_span = self.prev_span;
5750             let invalid = keywords::Invalid.ident();
5751             let item = self.mk_item(lo.to(prev_span), invalid, item_, visibility, attrs);
5752             return Ok(Some(item));
5753         }
5754
5755         if self.eat_keyword(keywords::Extern) {
5756             if self.eat_keyword(keywords::Crate) {
5757                 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
5758             }
5759
5760             let opt_abi = self.parse_opt_abi()?;
5761
5762             if self.eat_keyword(keywords::Fn) {
5763                 // EXTERN FUNCTION ITEM
5764                 let fn_span = self.prev_span;
5765                 let abi = opt_abi.unwrap_or(Abi::C);
5766                 let (ident, item_, extra_attrs) =
5767                     self.parse_item_fn(Unsafety::Normal,
5768                                        respan(fn_span, Constness::NotConst),
5769                                        abi)?;
5770                 let prev_span = self.prev_span;
5771                 let item = self.mk_item(lo.to(prev_span),
5772                                         ident,
5773                                         item_,
5774                                         visibility,
5775                                         maybe_append(attrs, extra_attrs));
5776                 return Ok(Some(item));
5777             } else if self.check(&token::OpenDelim(token::Brace)) {
5778                 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
5779             }
5780
5781             self.unexpected()?;
5782         }
5783
5784         if self.eat_keyword(keywords::Static) {
5785             // STATIC ITEM
5786             let m = if self.eat_keyword(keywords::Mut) {
5787                 Mutability::Mutable
5788             } else {
5789                 Mutability::Immutable
5790             };
5791             let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
5792             let prev_span = self.prev_span;
5793             let item = self.mk_item(lo.to(prev_span),
5794                                     ident,
5795                                     item_,
5796                                     visibility,
5797                                     maybe_append(attrs, extra_attrs));
5798             return Ok(Some(item));
5799         }
5800         if self.eat_keyword(keywords::Const) {
5801             let const_span = self.prev_span;
5802             if self.check_keyword(keywords::Fn)
5803                 || (self.check_keyword(keywords::Unsafe)
5804                     && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
5805                 // CONST FUNCTION ITEM
5806                 let unsafety = if self.eat_keyword(keywords::Unsafe) {
5807                     Unsafety::Unsafe
5808                 } else {
5809                     Unsafety::Normal
5810                 };
5811                 self.bump();
5812                 let (ident, item_, extra_attrs) =
5813                     self.parse_item_fn(unsafety,
5814                                        respan(const_span, Constness::Const),
5815                                        Abi::Rust)?;
5816                 let prev_span = self.prev_span;
5817                 let item = self.mk_item(lo.to(prev_span),
5818                                         ident,
5819                                         item_,
5820                                         visibility,
5821                                         maybe_append(attrs, extra_attrs));
5822                 return Ok(Some(item));
5823             }
5824
5825             // CONST ITEM
5826             if self.eat_keyword(keywords::Mut) {
5827                 let prev_span = self.prev_span;
5828                 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
5829                                  .help("did you mean to declare a static?")
5830                                  .emit();
5831             }
5832             let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
5833             let prev_span = self.prev_span;
5834             let item = self.mk_item(lo.to(prev_span),
5835                                     ident,
5836                                     item_,
5837                                     visibility,
5838                                     maybe_append(attrs, extra_attrs));
5839             return Ok(Some(item));
5840         }
5841         if self.check_keyword(keywords::Unsafe) &&
5842             self.look_ahead(1, |t| t.is_keyword(keywords::Trait))
5843         {
5844             // UNSAFE TRAIT ITEM
5845             self.expect_keyword(keywords::Unsafe)?;
5846             self.expect_keyword(keywords::Trait)?;
5847             let (ident, item_, extra_attrs) =
5848                 self.parse_item_trait(ast::Unsafety::Unsafe)?;
5849             let prev_span = self.prev_span;
5850             let item = self.mk_item(lo.to(prev_span),
5851                                     ident,
5852                                     item_,
5853                                     visibility,
5854                                     maybe_append(attrs, extra_attrs));
5855             return Ok(Some(item));
5856         }
5857         if (self.check_keyword(keywords::Unsafe) &&
5858             self.look_ahead(1, |t| t.is_keyword(keywords::Impl))) ||
5859            (self.check_keyword(keywords::Default) &&
5860             self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) &&
5861             self.look_ahead(2, |t| t.is_keyword(keywords::Impl)))
5862         {
5863             // IMPL ITEM
5864             let defaultness = self.parse_defaultness()?;
5865             self.expect_keyword(keywords::Unsafe)?;
5866             self.expect_keyword(keywords::Impl)?;
5867             let (ident,
5868                  item_,
5869                  extra_attrs) = self.parse_item_impl(ast::Unsafety::Unsafe, defaultness)?;
5870             let prev_span = self.prev_span;
5871             let item = self.mk_item(lo.to(prev_span),
5872                                     ident,
5873                                     item_,
5874                                     visibility,
5875                                     maybe_append(attrs, extra_attrs));
5876             return Ok(Some(item));
5877         }
5878         if self.check_keyword(keywords::Fn) {
5879             // FUNCTION ITEM
5880             self.bump();
5881             let fn_span = self.prev_span;
5882             let (ident, item_, extra_attrs) =
5883                 self.parse_item_fn(Unsafety::Normal,
5884                                    respan(fn_span, Constness::NotConst),
5885                                    Abi::Rust)?;
5886             let prev_span = self.prev_span;
5887             let item = self.mk_item(lo.to(prev_span),
5888                                     ident,
5889                                     item_,
5890                                     visibility,
5891                                     maybe_append(attrs, extra_attrs));
5892             return Ok(Some(item));
5893         }
5894         if self.check_keyword(keywords::Unsafe)
5895             && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
5896             // UNSAFE FUNCTION ITEM
5897             self.bump();
5898             let abi = if self.eat_keyword(keywords::Extern) {
5899                 self.parse_opt_abi()?.unwrap_or(Abi::C)
5900             } else {
5901                 Abi::Rust
5902             };
5903             self.expect_keyword(keywords::Fn)?;
5904             let fn_span = self.prev_span;
5905             let (ident, item_, extra_attrs) =
5906                 self.parse_item_fn(Unsafety::Unsafe,
5907                                    respan(fn_span, Constness::NotConst),
5908                                    abi)?;
5909             let prev_span = self.prev_span;
5910             let item = self.mk_item(lo.to(prev_span),
5911                                     ident,
5912                                     item_,
5913                                     visibility,
5914                                     maybe_append(attrs, extra_attrs));
5915             return Ok(Some(item));
5916         }
5917         if self.eat_keyword(keywords::Mod) {
5918             // MODULE ITEM
5919             let (ident, item_, extra_attrs) =
5920                 self.parse_item_mod(&attrs[..])?;
5921             let prev_span = self.prev_span;
5922             let item = self.mk_item(lo.to(prev_span),
5923                                     ident,
5924                                     item_,
5925                                     visibility,
5926                                     maybe_append(attrs, extra_attrs));
5927             return Ok(Some(item));
5928         }
5929         if self.eat_keyword(keywords::Type) {
5930             // TYPE ITEM
5931             let (ident, item_, extra_attrs) = self.parse_item_type()?;
5932             let prev_span = self.prev_span;
5933             let item = self.mk_item(lo.to(prev_span),
5934                                     ident,
5935                                     item_,
5936                                     visibility,
5937                                     maybe_append(attrs, extra_attrs));
5938             return Ok(Some(item));
5939         }
5940         if self.eat_keyword(keywords::Enum) {
5941             // ENUM ITEM
5942             let (ident, item_, extra_attrs) = self.parse_item_enum()?;
5943             let prev_span = self.prev_span;
5944             let item = self.mk_item(lo.to(prev_span),
5945                                     ident,
5946                                     item_,
5947                                     visibility,
5948                                     maybe_append(attrs, extra_attrs));
5949             return Ok(Some(item));
5950         }
5951         if self.eat_keyword(keywords::Trait) {
5952             // TRAIT ITEM
5953             let (ident, item_, extra_attrs) =
5954                 self.parse_item_trait(ast::Unsafety::Normal)?;
5955             let prev_span = self.prev_span;
5956             let item = self.mk_item(lo.to(prev_span),
5957                                     ident,
5958                                     item_,
5959                                     visibility,
5960                                     maybe_append(attrs, extra_attrs));
5961             return Ok(Some(item));
5962         }
5963         if (self.check_keyword(keywords::Impl)) ||
5964            (self.check_keyword(keywords::Default) &&
5965             self.look_ahead(1, |t| t.is_keyword(keywords::Impl)))
5966         {
5967             // IMPL ITEM
5968             let defaultness = self.parse_defaultness()?;
5969             self.expect_keyword(keywords::Impl)?;
5970             let (ident,
5971                  item_,
5972                  extra_attrs) = self.parse_item_impl(ast::Unsafety::Normal, defaultness)?;
5973             let prev_span = self.prev_span;
5974             let item = self.mk_item(lo.to(prev_span),
5975                                     ident,
5976                                     item_,
5977                                     visibility,
5978                                     maybe_append(attrs, extra_attrs));
5979             return Ok(Some(item));
5980         }
5981         if self.eat_keyword(keywords::Struct) {
5982             // STRUCT ITEM
5983             let (ident, item_, extra_attrs) = self.parse_item_struct()?;
5984             let prev_span = self.prev_span;
5985             let item = self.mk_item(lo.to(prev_span),
5986                                     ident,
5987                                     item_,
5988                                     visibility,
5989                                     maybe_append(attrs, extra_attrs));
5990             return Ok(Some(item));
5991         }
5992         if self.is_union_item() {
5993             // UNION ITEM
5994             self.bump();
5995             let (ident, item_, extra_attrs) = self.parse_item_union()?;
5996             let prev_span = self.prev_span;
5997             let item = self.mk_item(lo.to(prev_span),
5998                                     ident,
5999                                     item_,
6000                                     visibility,
6001                                     maybe_append(attrs, extra_attrs));
6002             return Ok(Some(item));
6003         }
6004         if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility)? {
6005             return Ok(Some(macro_def));
6006         }
6007
6008         self.parse_macro_use_or_failure(attrs,macros_allowed,attributes_allowed,lo,visibility)
6009     }
6010
6011     /// Parse a foreign item.
6012     fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
6013         let attrs = self.parse_outer_attributes()?;
6014         let lo = self.span;
6015         let visibility = self.parse_visibility(false)?;
6016
6017         // FOREIGN STATIC ITEM
6018         // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
6019         if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
6020             if self.token.is_keyword(keywords::Const) {
6021                 self.diagnostic()
6022                     .struct_span_err(self.span, "extern items cannot be `const`")
6023                     .span_suggestion(self.span, "instead try using", "static".to_owned())
6024                     .emit();
6025             }
6026             self.bump(); // `static` or `const`
6027             return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
6028         }
6029         // FOREIGN FUNCTION ITEM
6030         if self.check_keyword(keywords::Fn) {
6031             return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
6032         }
6033
6034         // FIXME #5668: this will occur for a macro invocation:
6035         match self.parse_macro_use_or_failure(attrs, true, false, lo, visibility)? {
6036             Some(item) => {
6037                 return Err(self.span_fatal(item.span, "macros cannot expand to foreign items"));
6038             }
6039             None => Ok(None)
6040         }
6041     }
6042
6043     /// This is the fall-through for parsing items.
6044     fn parse_macro_use_or_failure(
6045         &mut self,
6046         attrs: Vec<Attribute> ,
6047         macros_allowed: bool,
6048         attributes_allowed: bool,
6049         lo: Span,
6050         visibility: Visibility
6051     ) -> PResult<'a, Option<P<Item>>> {
6052         if macros_allowed && self.token.is_path_start() {
6053             // MACRO INVOCATION ITEM
6054
6055             let prev_span = self.prev_span;
6056             self.complain_if_pub_macro(&visibility, prev_span);
6057
6058             let mac_lo = self.span;
6059
6060             // item macro.
6061             let pth = self.parse_path(PathStyle::Mod)?;
6062             self.expect(&token::Not)?;
6063
6064             // a 'special' identifier (like what `macro_rules!` uses)
6065             // is optional. We should eventually unify invoc syntax
6066             // and remove this.
6067             let id = if self.token.is_ident() {
6068                 self.parse_ident()?
6069             } else {
6070                 keywords::Invalid.ident() // no special identifier
6071             };
6072             // eat a matched-delimiter token tree:
6073             let (delim, tts) = self.expect_delimited_token_tree()?;
6074             if delim != token::Brace {
6075                 if !self.eat(&token::Semi) {
6076                     self.span_err(self.prev_span,
6077                                   "macros that expand to items must either \
6078                                    be surrounded with braces or followed by \
6079                                    a semicolon");
6080                 }
6081             }
6082
6083             let hi = self.prev_span;
6084             let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts: tts });
6085             let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
6086             return Ok(Some(item));
6087         }
6088
6089         // FAILURE TO PARSE ITEM
6090         match visibility {
6091             Visibility::Inherited => {}
6092             _ => {
6093                 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
6094             }
6095         }
6096
6097         if !attributes_allowed && !attrs.is_empty() {
6098             self.expected_item_err(&attrs);
6099         }
6100         Ok(None)
6101     }
6102
6103     fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
6104         where F: FnOnce(&mut Self) -> PResult<'a, R>
6105     {
6106         // Record all tokens we parse when parsing this item.
6107         let mut tokens = Vec::new();
6108         match self.token_cursor.frame.last_token {
6109             LastToken::Collecting(_) => {
6110                 panic!("cannot collect tokens recursively yet")
6111             }
6112             LastToken::Was(ref mut last) => tokens.extend(last.take()),
6113         }
6114         self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
6115         let prev = self.token_cursor.stack.len();
6116         let ret = f(self);
6117         let last_token = if self.token_cursor.stack.len() == prev {
6118             &mut self.token_cursor.frame.last_token
6119         } else {
6120             &mut self.token_cursor.stack[prev].last_token
6121         };
6122         let mut tokens = match *last_token {
6123             LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
6124             LastToken::Was(_) => panic!("our vector went away?"),
6125         };
6126
6127         // If we're not at EOF our current token wasn't actually consumed by
6128         // `f`, but it'll still be in our list that we pulled out. In that case
6129         // put it back.
6130         if self.token == token::Eof {
6131             *last_token = LastToken::Was(None);
6132         } else {
6133             *last_token = LastToken::Was(tokens.pop());
6134         }
6135
6136         Ok((ret?, tokens.into_iter().collect()))
6137     }
6138
6139     pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
6140         let attrs = self.parse_outer_attributes()?;
6141
6142         let (ret, tokens) = self.collect_tokens(|this| {
6143             this.parse_item_(attrs, true, false)
6144         })?;
6145
6146         // Once we've parsed an item and recorded the tokens we got while
6147         // parsing we may want to store `tokens` into the item we're about to
6148         // return. Note, though, that we specifically didn't capture tokens
6149         // related to outer attributes. The `tokens` field here may later be
6150         // used with procedural macros to convert this item back into a token
6151         // stream, but during expansion we may be removing attributes as we go
6152         // along.
6153         //
6154         // If we've got inner attributes then the `tokens` we've got above holds
6155         // these inner attributes. If an inner attribute is expanded we won't
6156         // actually remove it from the token stream, so we'll just keep yielding
6157         // it (bad!). To work around this case for now we just avoid recording
6158         // `tokens` if we detect any inner attributes. This should help keep
6159         // expansion correct, but we should fix this bug one day!
6160         Ok(ret.map(|item| {
6161             item.map(|mut i| {
6162                 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6163                     i.tokens = Some(tokens);
6164                 }
6165                 i
6166             })
6167         }))
6168     }
6169
6170     fn parse_path_list_items(&mut self) -> PResult<'a, Vec<ast::PathListItem>> {
6171         self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
6172                                  &token::CloseDelim(token::Brace),
6173                                  SeqSep::trailing_allowed(token::Comma), |this| {
6174             let lo = this.span;
6175             let ident = if this.eat_keyword(keywords::SelfValue) {
6176                 keywords::SelfValue.ident()
6177             } else {
6178                 this.parse_ident()?
6179             };
6180             let rename = this.parse_rename()?;
6181             let node = ast::PathListItem_ {
6182                 name: ident,
6183                 rename,
6184                 id: ast::DUMMY_NODE_ID
6185             };
6186             Ok(respan(lo.to(this.prev_span), node))
6187         })
6188     }
6189
6190     /// `::{` or `::*`
6191     fn is_import_coupler(&mut self) -> bool {
6192         self.check(&token::ModSep) &&
6193             self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
6194                                    *t == token::BinOp(token::Star))
6195     }
6196
6197     /// Matches ViewPath:
6198     /// MOD_SEP? non_global_path
6199     /// MOD_SEP? non_global_path as IDENT
6200     /// MOD_SEP? non_global_path MOD_SEP STAR
6201     /// MOD_SEP? non_global_path MOD_SEP LBRACE item_seq RBRACE
6202     /// MOD_SEP? LBRACE item_seq RBRACE
6203     fn parse_view_path(&mut self) -> PResult<'a, P<ViewPath>> {
6204         let lo = self.span;
6205         if self.check(&token::OpenDelim(token::Brace)) || self.check(&token::BinOp(token::Star)) ||
6206            self.is_import_coupler() {
6207             // `{foo, bar}`, `::{foo, bar}`, `*`, or `::*`.
6208             self.eat(&token::ModSep);
6209             let prefix = ast::Path {
6210                 segments: vec![PathSegment::crate_root(lo)],
6211                 span: lo.to(self.span),
6212             };
6213             let view_path_kind = if self.eat(&token::BinOp(token::Star)) {
6214                 ViewPathGlob(prefix)
6215             } else {
6216                 ViewPathList(prefix, self.parse_path_list_items()?)
6217             };
6218             Ok(P(respan(lo.to(self.span), view_path_kind)))
6219         } else {
6220             let prefix = self.parse_path(PathStyle::Mod)?.default_to_global();
6221             if self.is_import_coupler() {
6222                 // `foo::bar::{a, b}` or `foo::bar::*`
6223                 self.bump();
6224                 if self.check(&token::BinOp(token::Star)) {
6225                     self.bump();
6226                     Ok(P(respan(lo.to(self.span), ViewPathGlob(prefix))))
6227                 } else {
6228                     let items = self.parse_path_list_items()?;
6229                     Ok(P(respan(lo.to(self.span), ViewPathList(prefix, items))))
6230                 }
6231             } else {
6232                 // `foo::bar` or `foo::bar as baz`
6233                 let rename = self.parse_rename()?.
6234                                   unwrap_or(prefix.segments.last().unwrap().identifier);
6235                 Ok(P(respan(lo.to(self.prev_span), ViewPathSimple(rename, prefix))))
6236             }
6237         }
6238     }
6239
6240     fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
6241         if self.eat_keyword(keywords::As) {
6242             self.parse_ident().map(Some)
6243         } else {
6244             Ok(None)
6245         }
6246     }
6247
6248     /// Parses a source module as a crate. This is the main
6249     /// entry point for the parser.
6250     pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
6251         let lo = self.span;
6252         Ok(ast::Crate {
6253             attrs: self.parse_inner_attributes()?,
6254             module: self.parse_mod_items(&token::Eof, lo)?,
6255             span: lo.to(self.span),
6256         })
6257     }
6258
6259     pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
6260         let ret = match self.token {
6261             token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
6262             token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
6263             _ => return None
6264         };
6265         self.bump();
6266         Some(ret)
6267     }
6268
6269     pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
6270         match self.parse_optional_str() {
6271             Some((s, style, suf)) => {
6272                 let sp = self.prev_span;
6273                 self.expect_no_suffix(sp, "string literal", suf);
6274                 Ok((s, style))
6275             }
6276             _ =>  Err(self.fatal("expected string literal"))
6277         }
6278     }
6279 }