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