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