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