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