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