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