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