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