]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/parser.rs
Auto merge of #51678 - Zoxc:combine-lints, r=estebank
[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                         // Parse range
4028                         let span = lo.to(self.prev_span);
4029                         let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4030                         self.bump();
4031                         let end = self.parse_pat_range_end()?;
4032                         pat = PatKind::Range(begin, end, end_kind);
4033                     }
4034                     token::OpenDelim(token::Brace) => {
4035                         if qself.is_some() {
4036                             let msg = "unexpected `{` after qualified path";
4037                             let mut err = self.fatal(msg);
4038                             err.span_label(self.span, msg);
4039                             return Err(err);
4040                         }
4041                         // Parse struct pattern
4042                         self.bump();
4043                         let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4044                             e.emit();
4045                             self.recover_stmt();
4046                             (vec![], false)
4047                         });
4048                         self.bump();
4049                         pat = PatKind::Struct(path, fields, etc);
4050                     }
4051                     token::OpenDelim(token::Paren) => {
4052                         if qself.is_some() {
4053                             let msg = "unexpected `(` after qualified path";
4054                             let mut err = self.fatal(msg);
4055                             err.span_label(self.span, msg);
4056                             return Err(err);
4057                         }
4058                         // Parse tuple struct or enum pattern
4059                         let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4060                         pat = PatKind::TupleStruct(path, fields, ddpos)
4061                     }
4062                     _ => pat = PatKind::Path(qself, path),
4063                 }
4064             } else {
4065                 // Try to parse everything else as literal with optional minus
4066                 match self.parse_literal_maybe_minus() {
4067                     Ok(begin) => {
4068                         if self.eat(&token::DotDotDot) {
4069                             let end = self.parse_pat_range_end()?;
4070                             pat = PatKind::Range(begin, end,
4071                                     RangeEnd::Included(RangeSyntax::DotDotDot));
4072                         } else if self.eat(&token::DotDotEq) {
4073                             let end = self.parse_pat_range_end()?;
4074                             pat = PatKind::Range(begin, end,
4075                                     RangeEnd::Included(RangeSyntax::DotDotEq));
4076                         } else if self.eat(&token::DotDot) {
4077                             let end = self.parse_pat_range_end()?;
4078                             pat = PatKind::Range(begin, end, RangeEnd::Excluded);
4079                         } else {
4080                             pat = PatKind::Lit(begin);
4081                         }
4082                     }
4083                     Err(mut err) => {
4084                         self.cancel(&mut err);
4085                         let msg = format!("expected pattern, found {}", self.this_token_descr());
4086                         let mut err = self.fatal(&msg);
4087                         err.span_label(self.span, "expected pattern");
4088                         return Err(err);
4089                     }
4090                 }
4091             }
4092         }
4093
4094         let pat = Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID };
4095         let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4096
4097         if !allow_range_pat {
4098             match pat.node {
4099                 PatKind::Range(_, _, RangeEnd::Included(RangeSyntax::DotDotDot)) => {}
4100                 PatKind::Range(..) => {
4101                     let mut err = self.struct_span_err(
4102                         pat.span,
4103                         "the range pattern here has ambiguous interpretation",
4104                     );
4105                     err.span_suggestion_with_applicability(
4106                         pat.span,
4107                         "add parentheses to clarify the precedence",
4108                         format!("({})", pprust::pat_to_string(&pat)),
4109                         // "ambiguous interpretation" implies that we have to be guessing
4110                         Applicability::MaybeIncorrect
4111                     );
4112                     return Err(err);
4113                 }
4114                 _ => {}
4115             }
4116         }
4117
4118         Ok(P(pat))
4119     }
4120
4121     /// Parse ident or ident @ pat
4122     /// used by the copy foo and ref foo patterns to give a good
4123     /// error message when parsing mistakes like ref foo(a,b)
4124     fn parse_pat_ident(&mut self,
4125                        binding_mode: ast::BindingMode)
4126                        -> PResult<'a, PatKind> {
4127         let ident = self.parse_ident()?;
4128         let sub = if self.eat(&token::At) {
4129             Some(self.parse_pat()?)
4130         } else {
4131             None
4132         };
4133
4134         // just to be friendly, if they write something like
4135         //   ref Some(i)
4136         // we end up here with ( as the current token.  This shortly
4137         // leads to a parse error.  Note that if there is no explicit
4138         // binding mode then we do not end up here, because the lookahead
4139         // will direct us over to parse_enum_variant()
4140         if self.token == token::OpenDelim(token::Paren) {
4141             return Err(self.span_fatal(
4142                 self.prev_span,
4143                 "expected identifier, found enum pattern"))
4144         }
4145
4146         Ok(PatKind::Ident(binding_mode, ident, sub))
4147     }
4148
4149     /// Parse a local variable declaration
4150     fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4151         let lo = self.prev_span;
4152         let pat = self.parse_top_level_pat()?;
4153
4154         let (err, ty) = if self.eat(&token::Colon) {
4155             // Save the state of the parser before parsing type normally, in case there is a `:`
4156             // instead of an `=` typo.
4157             let parser_snapshot_before_type = self.clone();
4158             let colon_sp = self.prev_span;
4159             match self.parse_ty() {
4160                 Ok(ty) => (None, Some(ty)),
4161                 Err(mut err) => {
4162                     // Rewind to before attempting to parse the type and continue parsing
4163                     let parser_snapshot_after_type = self.clone();
4164                     mem::replace(self, parser_snapshot_before_type);
4165
4166                     let snippet = self.sess.codemap().span_to_snippet(pat.span).unwrap();
4167                     err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4168                     (Some((parser_snapshot_after_type, colon_sp, err)), None)
4169                 }
4170             }
4171         } else {
4172             (None, None)
4173         };
4174         let init = match (self.parse_initializer(err.is_some()), err) {
4175             (Ok(init), None) => {  // init parsed, ty parsed
4176                 init
4177             }
4178             (Ok(init), Some((_, colon_sp, mut err))) => {  // init parsed, ty error
4179                 // Could parse the type as if it were the initializer, it is likely there was a
4180                 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4181                 err.span_suggestion_short_with_applicability(
4182                     colon_sp,
4183                     "use `=` if you meant to assign",
4184                     "=".to_string(),
4185                     Applicability::MachineApplicable
4186                 );
4187                 err.emit();
4188                 // As this was parsed successfully, continue as if the code has been fixed for the
4189                 // rest of the file. It will still fail due to the emitted error, but we avoid
4190                 // extra noise.
4191                 init
4192             }
4193             (Err(mut init_err), Some((snapshot, _, ty_err))) => {  // init error, ty error
4194                 init_err.cancel();
4195                 // Couldn't parse the type nor the initializer, only raise the type error and
4196                 // return to the parser state before parsing the type as the initializer.
4197                 // let x: <parse_error>;
4198                 mem::replace(self, snapshot);
4199                 return Err(ty_err);
4200             }
4201             (Err(err), None) => {  // init error, ty parsed
4202                 // Couldn't parse the initializer and we're not attempting to recover a failed
4203                 // parse of the type, return the error.
4204                 return Err(err);
4205             }
4206         };
4207         let hi = if self.token == token::Semi {
4208             self.span
4209         } else {
4210             self.prev_span
4211         };
4212         Ok(P(ast::Local {
4213             ty,
4214             pat,
4215             init,
4216             id: ast::DUMMY_NODE_ID,
4217             span: lo.to(hi),
4218             attrs,
4219         }))
4220     }
4221
4222     /// Parse a structure field
4223     fn parse_name_and_ty(&mut self,
4224                          lo: Span,
4225                          vis: Visibility,
4226                          attrs: Vec<Attribute>)
4227                          -> PResult<'a, StructField> {
4228         let name = self.parse_ident()?;
4229         self.expect(&token::Colon)?;
4230         let ty = self.parse_ty()?;
4231         Ok(StructField {
4232             span: lo.to(self.prev_span),
4233             ident: Some(name),
4234             vis,
4235             id: ast::DUMMY_NODE_ID,
4236             ty,
4237             attrs,
4238         })
4239     }
4240
4241     /// Emit an expected item after attributes error.
4242     fn expected_item_err(&self, attrs: &[Attribute]) {
4243         let message = match attrs.last() {
4244             Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4245             _ => "expected item after attributes",
4246         };
4247
4248         self.span_err(self.prev_span, message);
4249     }
4250
4251     /// Parse a statement. This stops just before trailing semicolons on everything but items.
4252     /// e.g. a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4253     pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4254         Ok(self.parse_stmt_(true))
4255     }
4256
4257     // Eat tokens until we can be relatively sure we reached the end of the
4258     // statement. This is something of a best-effort heuristic.
4259     //
4260     // We terminate when we find an unmatched `}` (without consuming it).
4261     fn recover_stmt(&mut self) {
4262         self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4263     }
4264
4265     // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4266     // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4267     // approximate - it can mean we break too early due to macros, but that
4268     // shoud only lead to sub-optimal recovery, not inaccurate parsing).
4269     //
4270     // If `break_on_block` is `Break`, then we will stop consuming tokens
4271     // after finding (and consuming) a brace-delimited block.
4272     fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4273         let mut brace_depth = 0;
4274         let mut bracket_depth = 0;
4275         let mut in_block = false;
4276         debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
4277                break_on_semi, break_on_block);
4278         loop {
4279             debug!("recover_stmt_ loop {:?}", self.token);
4280             match self.token {
4281                 token::OpenDelim(token::DelimToken::Brace) => {
4282                     brace_depth += 1;
4283                     self.bump();
4284                     if break_on_block == BlockMode::Break &&
4285                        brace_depth == 1 &&
4286                        bracket_depth == 0 {
4287                         in_block = true;
4288                     }
4289                 }
4290                 token::OpenDelim(token::DelimToken::Bracket) => {
4291                     bracket_depth += 1;
4292                     self.bump();
4293                 }
4294                 token::CloseDelim(token::DelimToken::Brace) => {
4295                     if brace_depth == 0 {
4296                         debug!("recover_stmt_ return - close delim {:?}", self.token);
4297                         return;
4298                     }
4299                     brace_depth -= 1;
4300                     self.bump();
4301                     if in_block && bracket_depth == 0 && brace_depth == 0 {
4302                         debug!("recover_stmt_ return - block end {:?}", self.token);
4303                         return;
4304                     }
4305                 }
4306                 token::CloseDelim(token::DelimToken::Bracket) => {
4307                     bracket_depth -= 1;
4308                     if bracket_depth < 0 {
4309                         bracket_depth = 0;
4310                     }
4311                     self.bump();
4312                 }
4313                 token::Eof => {
4314                     debug!("recover_stmt_ return - Eof");
4315                     return;
4316                 }
4317                 token::Semi => {
4318                     self.bump();
4319                     if break_on_semi == SemiColonMode::Break &&
4320                        brace_depth == 0 &&
4321                        bracket_depth == 0 {
4322                         debug!("recover_stmt_ return - Semi");
4323                         return;
4324                     }
4325                 }
4326                 _ => {
4327                     self.bump()
4328                 }
4329             }
4330         }
4331     }
4332
4333     fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
4334         self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
4335             e.emit();
4336             self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4337             None
4338         })
4339     }
4340
4341     fn is_async_block(&mut self) -> bool {
4342         self.token.is_keyword(keywords::Async) &&
4343         (
4344             ( // `async move {`
4345                 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
4346                 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
4347             ) || ( // `async {`
4348                 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
4349             )
4350         )
4351     }
4352
4353     fn is_catch_expr(&mut self) -> bool {
4354         self.token.is_keyword(keywords::Do) &&
4355         self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
4356         self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
4357
4358         // prevent `while catch {} {}`, `if catch {} {} else {}`, etc.
4359         !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
4360     }
4361
4362     fn is_union_item(&self) -> bool {
4363         self.token.is_keyword(keywords::Union) &&
4364         self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
4365     }
4366
4367     fn is_crate_vis(&self) -> bool {
4368         self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
4369     }
4370
4371     fn is_extern_non_path(&self) -> bool {
4372         self.token.is_keyword(keywords::Extern) && self.look_ahead(1, |t| t != &token::ModSep)
4373     }
4374
4375     fn is_auto_trait_item(&mut self) -> bool {
4376         // auto trait
4377         (self.token.is_keyword(keywords::Auto)
4378             && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
4379         || // unsafe auto trait
4380         (self.token.is_keyword(keywords::Unsafe) &&
4381          self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
4382          self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
4383     }
4384
4385     fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
4386                      -> PResult<'a, Option<P<Item>>> {
4387         let token_lo = self.span;
4388         let (ident, def) = match self.token {
4389             token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
4390                 self.bump();
4391                 let ident = self.parse_ident()?;
4392                 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
4393                     match self.parse_token_tree() {
4394                         TokenTree::Delimited(_, ref delimited) => delimited.stream(),
4395                         _ => unreachable!(),
4396                     }
4397                 } else if self.check(&token::OpenDelim(token::Paren)) {
4398                     let args = self.parse_token_tree();
4399                     let body = if self.check(&token::OpenDelim(token::Brace)) {
4400                         self.parse_token_tree()
4401                     } else {
4402                         self.unexpected()?;
4403                         unreachable!()
4404                     };
4405                     TokenStream::concat(vec![
4406                         args.into(),
4407                         TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
4408                         body.into(),
4409                     ])
4410                 } else {
4411                     self.unexpected()?;
4412                     unreachable!()
4413                 };
4414
4415                 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
4416             }
4417             token::Ident(ident, _) if ident.name == "macro_rules" &&
4418                                    self.look_ahead(1, |t| *t == token::Not) => {
4419                 let prev_span = self.prev_span;
4420                 self.complain_if_pub_macro(&vis.node, prev_span);
4421                 self.bump();
4422                 self.bump();
4423
4424                 let ident = self.parse_ident()?;
4425                 let (delim, tokens) = self.expect_delimited_token_tree()?;
4426                 if delim != MacDelimiter::Brace {
4427                     if !self.eat(&token::Semi) {
4428                         let msg = "macros that expand to items must either \
4429                                    be surrounded with braces or followed by a semicolon";
4430                         self.span_err(self.prev_span, msg);
4431                     }
4432                 }
4433
4434                 (ident, ast::MacroDef { tokens: tokens, legacy: true })
4435             }
4436             _ => return Ok(None),
4437         };
4438
4439         let span = lo.to(self.prev_span);
4440         Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
4441     }
4442
4443     fn parse_stmt_without_recovery(&mut self,
4444                                    macro_legacy_warnings: bool)
4445                                    -> PResult<'a, Option<Stmt>> {
4446         maybe_whole!(self, NtStmt, |x| Some(x));
4447
4448         let attrs = self.parse_outer_attributes()?;
4449         let lo = self.span;
4450
4451         Ok(Some(if self.eat_keyword(keywords::Let) {
4452             Stmt {
4453                 id: ast::DUMMY_NODE_ID,
4454                 node: StmtKind::Local(self.parse_local(attrs.into())?),
4455                 span: lo.to(self.prev_span),
4456             }
4457         } else if let Some(macro_def) = self.eat_macro_def(
4458             &attrs,
4459             &codemap::respan(lo, VisibilityKind::Inherited),
4460             lo,
4461         )? {
4462             Stmt {
4463                 id: ast::DUMMY_NODE_ID,
4464                 node: StmtKind::Item(macro_def),
4465                 span: lo.to(self.prev_span),
4466             }
4467         // Starts like a simple path, being careful to avoid contextual keywords
4468         // such as a union items, item with `crate` visibility or auto trait items.
4469         // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
4470         // like a path (1 token), but it fact not a path.
4471         // `union::b::c` - path, `union U { ... }` - not a path.
4472         // `crate::b::c` - path, `crate struct S;` - not a path.
4473         // `extern::b::c` - path, `extern crate c;` - not a path.
4474         } else if self.token.is_path_start() &&
4475                   !self.token.is_qpath_start() &&
4476                   !self.is_union_item() &&
4477                   !self.is_crate_vis() &&
4478                   !self.is_extern_non_path() &&
4479                   !self.is_auto_trait_item() {
4480             let pth = self.parse_path(PathStyle::Expr)?;
4481
4482             if !self.eat(&token::Not) {
4483                 let expr = if self.check(&token::OpenDelim(token::Brace)) {
4484                     self.parse_struct_expr(lo, pth, ThinVec::new())?
4485                 } else {
4486                     let hi = self.prev_span;
4487                     self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
4488                 };
4489
4490                 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
4491                     let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
4492                     this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
4493                 })?;
4494
4495                 return Ok(Some(Stmt {
4496                     id: ast::DUMMY_NODE_ID,
4497                     node: StmtKind::Expr(expr),
4498                     span: lo.to(self.prev_span),
4499                 }));
4500             }
4501
4502             // it's a macro invocation
4503             let id = match self.token {
4504                 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
4505                 _ => self.parse_ident()?,
4506             };
4507
4508             // check that we're pointing at delimiters (need to check
4509             // again after the `if`, because of `parse_ident`
4510             // consuming more tokens).
4511             match self.token {
4512                 token::OpenDelim(_) => {}
4513                 _ => {
4514                     // we only expect an ident if we didn't parse one
4515                     // above.
4516                     let ident_str = if id.name == keywords::Invalid.name() {
4517                         "identifier, "
4518                     } else {
4519                         ""
4520                     };
4521                     let tok_str = self.this_token_to_string();
4522                     let mut err = self.fatal(&format!("expected {}`(` or `{{`, found `{}`",
4523                                                       ident_str,
4524                                                       tok_str));
4525                     err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
4526                     return Err(err)
4527                 },
4528             }
4529
4530             let (delim, tts) = self.expect_delimited_token_tree()?;
4531             let hi = self.prev_span;
4532
4533             let style = if delim == MacDelimiter::Brace {
4534                 MacStmtStyle::Braces
4535             } else {
4536                 MacStmtStyle::NoBraces
4537             };
4538
4539             if id.name == keywords::Invalid.name() {
4540                 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
4541                 let node = if delim == MacDelimiter::Brace ||
4542                               self.token == token::Semi || self.token == token::Eof {
4543                     StmtKind::Mac(P((mac, style, attrs.into())))
4544                 }
4545                 // We used to incorrectly stop parsing macro-expanded statements here.
4546                 // If the next token will be an error anyway but could have parsed with the
4547                 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
4548                 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
4549                     // These can continue an expression, so we can't stop parsing and warn.
4550                     token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
4551                     token::BinOp(token::Minus) | token::BinOp(token::Star) |
4552                     token::BinOp(token::And) | token::BinOp(token::Or) |
4553                     token::AndAnd | token::OrOr |
4554                     token::DotDot | token::DotDotDot | token::DotDotEq => false,
4555                     _ => true,
4556                 } {
4557                     self.warn_missing_semicolon();
4558                     StmtKind::Mac(P((mac, style, attrs.into())))
4559                 } else {
4560                     let e = self.mk_mac_expr(lo.to(hi), mac.node, ThinVec::new());
4561                     let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
4562                     let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
4563                     StmtKind::Expr(e)
4564                 };
4565                 Stmt {
4566                     id: ast::DUMMY_NODE_ID,
4567                     span: lo.to(hi),
4568                     node,
4569                 }
4570             } else {
4571                 // if it has a special ident, it's definitely an item
4572                 //
4573                 // Require a semicolon or braces.
4574                 if style != MacStmtStyle::Braces {
4575                     if !self.eat(&token::Semi) {
4576                         self.span_err(self.prev_span,
4577                                       "macros that expand to items must \
4578                                        either be surrounded with braces or \
4579                                        followed by a semicolon");
4580                     }
4581                 }
4582                 let span = lo.to(hi);
4583                 Stmt {
4584                     id: ast::DUMMY_NODE_ID,
4585                     span,
4586                     node: StmtKind::Item({
4587                         self.mk_item(
4588                             span, id /*id is good here*/,
4589                             ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
4590                             respan(lo, VisibilityKind::Inherited),
4591                             attrs)
4592                     }),
4593                 }
4594             }
4595         } else {
4596             // FIXME: Bad copy of attrs
4597             let old_directory_ownership =
4598                 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
4599             let item = self.parse_item_(attrs.clone(), false, true)?;
4600             self.directory.ownership = old_directory_ownership;
4601
4602             match item {
4603                 Some(i) => Stmt {
4604                     id: ast::DUMMY_NODE_ID,
4605                     span: lo.to(i.span),
4606                     node: StmtKind::Item(i),
4607                 },
4608                 None => {
4609                     let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
4610                         if !attrs.is_empty() {
4611                             if s.prev_token_kind == PrevTokenKind::DocComment {
4612                                 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
4613                             } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
4614                                 s.span_err(s.span, "expected statement after outer attribute");
4615                             }
4616                         }
4617                     };
4618
4619                     // Do not attempt to parse an expression if we're done here.
4620                     if self.token == token::Semi {
4621                         unused_attrs(&attrs, self);
4622                         self.bump();
4623                         return Ok(None);
4624                     }
4625
4626                     if self.token == token::CloseDelim(token::Brace) {
4627                         unused_attrs(&attrs, self);
4628                         return Ok(None);
4629                     }
4630
4631                     // Remainder are line-expr stmts.
4632                     let e = self.parse_expr_res(
4633                         Restrictions::STMT_EXPR, Some(attrs.into()))?;
4634                     Stmt {
4635                         id: ast::DUMMY_NODE_ID,
4636                         span: lo.to(e.span),
4637                         node: StmtKind::Expr(e),
4638                     }
4639                 }
4640             }
4641         }))
4642     }
4643
4644     /// Is this expression a successfully-parsed statement?
4645     fn expr_is_complete(&mut self, e: &Expr) -> bool {
4646         self.restrictions.contains(Restrictions::STMT_EXPR) &&
4647             !classify::expr_requires_semi_to_be_stmt(e)
4648     }
4649
4650     /// Parse a block. No inner attrs are allowed.
4651     pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
4652         maybe_whole!(self, NtBlock, |x| x);
4653
4654         let lo = self.span;
4655
4656         if !self.eat(&token::OpenDelim(token::Brace)) {
4657             let sp = self.span;
4658             let tok = self.this_token_to_string();
4659             let mut e = self.span_fatal(sp, &format!("expected `{{`, found `{}`", tok));
4660
4661             // Check to see if the user has written something like
4662             //
4663             //    if (cond)
4664             //      bar;
4665             //
4666             // Which is valid in other languages, but not Rust.
4667             match self.parse_stmt_without_recovery(false) {
4668                 Ok(Some(stmt)) => {
4669                     if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace)) {
4670                         // if the next token is an open brace (e.g., `if a b {`), the place-
4671                         // inside-a-block suggestion would be more likely wrong than right
4672                         return Err(e);
4673                     }
4674                     let mut stmt_span = stmt.span;
4675                     // expand the span to include the semicolon, if it exists
4676                     if self.eat(&token::Semi) {
4677                         stmt_span = stmt_span.with_hi(self.prev_span.hi());
4678                     }
4679                     let sugg = pprust::to_string(|s| {
4680                         use print::pprust::{PrintState, INDENT_UNIT};
4681                         s.ibox(INDENT_UNIT)?;
4682                         s.bopen()?;
4683                         s.print_stmt(&stmt)?;
4684                         s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
4685                     });
4686                     e.span_suggestion_with_applicability(
4687                         stmt_span,
4688                         "try placing this code inside a block",
4689                         sugg,
4690                         // speculative, has been misleading in the past (closed Issue #46836)
4691                         Applicability::MaybeIncorrect
4692                     );
4693                 }
4694                 Err(mut e) => {
4695                     self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
4696                     self.cancel(&mut e);
4697                 }
4698                 _ => ()
4699             }
4700             return Err(e);
4701         }
4702
4703         self.parse_block_tail(lo, BlockCheckMode::Default)
4704     }
4705
4706     /// Parse a block. Inner attrs are allowed.
4707     fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
4708         maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
4709
4710         let lo = self.span;
4711         self.expect(&token::OpenDelim(token::Brace))?;
4712         Ok((self.parse_inner_attributes()?,
4713             self.parse_block_tail(lo, BlockCheckMode::Default)?))
4714     }
4715
4716     /// Parse the rest of a block expression or function body
4717     /// Precondition: already parsed the '{'.
4718     fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
4719         let mut stmts = vec![];
4720         let mut recovered = false;
4721
4722         while !self.eat(&token::CloseDelim(token::Brace)) {
4723             let stmt = match self.parse_full_stmt(false) {
4724                 Err(mut err) => {
4725                     err.emit();
4726                     self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
4727                     self.eat(&token::CloseDelim(token::Brace));
4728                     recovered = true;
4729                     break;
4730                 }
4731                 Ok(stmt) => stmt,
4732             };
4733             if let Some(stmt) = stmt {
4734                 stmts.push(stmt);
4735             } else if self.token == token::Eof {
4736                 break;
4737             } else {
4738                 // Found only `;` or `}`.
4739                 continue;
4740             };
4741         }
4742         Ok(P(ast::Block {
4743             stmts,
4744             id: ast::DUMMY_NODE_ID,
4745             rules: s,
4746             span: lo.to(self.prev_span),
4747             recovered,
4748         }))
4749     }
4750
4751     /// Parse a statement, including the trailing semicolon.
4752     crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
4753         // skip looking for a trailing semicolon when we have an interpolated statement
4754         maybe_whole!(self, NtStmt, |x| Some(x));
4755
4756         let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
4757             Some(stmt) => stmt,
4758             None => return Ok(None),
4759         };
4760
4761         match stmt.node {
4762             StmtKind::Expr(ref expr) if self.token != token::Eof => {
4763                 // expression without semicolon
4764                 if classify::expr_requires_semi_to_be_stmt(expr) {
4765                     // Just check for errors and recover; do not eat semicolon yet.
4766                     if let Err(mut e) =
4767                         self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
4768                     {
4769                         e.emit();
4770                         self.recover_stmt();
4771                     }
4772                 }
4773             }
4774             StmtKind::Local(..) => {
4775                 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
4776                 if macro_legacy_warnings && self.token != token::Semi {
4777                     self.warn_missing_semicolon();
4778                 } else {
4779                     self.expect_one_of(&[], &[token::Semi])?;
4780                 }
4781             }
4782             _ => {}
4783         }
4784
4785         if self.eat(&token::Semi) {
4786             stmt = stmt.add_trailing_semicolon();
4787         }
4788
4789         stmt.span = stmt.span.with_hi(self.prev_span.hi());
4790         Ok(Some(stmt))
4791     }
4792
4793     fn warn_missing_semicolon(&self) {
4794         self.diagnostic().struct_span_warn(self.span, {
4795             &format!("expected `;`, found `{}`", self.this_token_to_string())
4796         }).note({
4797             "This was erroneously allowed and will become a hard error in a future release"
4798         }).emit();
4799     }
4800
4801     fn err_dotdotdot_syntax(&self, span: Span) {
4802         self.diagnostic().struct_span_err(span, {
4803             "unexpected token: `...`"
4804         }).span_suggestion_with_applicability(
4805             span, "use `..` for an exclusive range", "..".to_owned(),
4806             Applicability::MaybeIncorrect
4807         ).span_suggestion_with_applicability(
4808             span, "or `..=` for an inclusive range", "..=".to_owned(),
4809             Applicability::MaybeIncorrect
4810         ).emit();
4811     }
4812
4813     // Parse bounds of a type parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4814     // BOUND = TY_BOUND | LT_BOUND
4815     // LT_BOUND = LIFETIME (e.g. `'a`)
4816     // TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
4817     // TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g. `?for<'a: 'b> m::Trait<'a>`)
4818     fn parse_generic_bounds_common(&mut self, allow_plus: bool) -> PResult<'a, GenericBounds> {
4819         let mut bounds = Vec::new();
4820         loop {
4821             // This needs to be syncronized with `Token::can_begin_bound`.
4822             let is_bound_start = self.check_path() || self.check_lifetime() ||
4823                                  self.check(&token::Question) ||
4824                                  self.check_keyword(keywords::For) ||
4825                                  self.check(&token::OpenDelim(token::Paren));
4826             if is_bound_start {
4827                 let lo = self.span;
4828                 let has_parens = self.eat(&token::OpenDelim(token::Paren));
4829                 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
4830                 if self.token.is_lifetime() {
4831                     if let Some(question_span) = question {
4832                         self.span_err(question_span,
4833                                       "`?` may only modify trait bounds, not lifetime bounds");
4834                     }
4835                     bounds.push(GenericBound::Outlives(self.expect_lifetime()));
4836                     if has_parens {
4837                         self.expect(&token::CloseDelim(token::Paren))?;
4838                         self.span_err(self.prev_span,
4839                                       "parenthesized lifetime bounds are not supported");
4840                     }
4841                 } else {
4842                     let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
4843                     let path = self.parse_path(PathStyle::Type)?;
4844                     if has_parens {
4845                         self.expect(&token::CloseDelim(token::Paren))?;
4846                     }
4847                     let poly_trait = PolyTraitRef::new(lifetime_defs, path, lo.to(self.prev_span));
4848                     let modifier = if question.is_some() {
4849                         TraitBoundModifier::Maybe
4850                     } else {
4851                         TraitBoundModifier::None
4852                     };
4853                     bounds.push(GenericBound::Trait(poly_trait, modifier));
4854                 }
4855             } else {
4856                 break
4857             }
4858
4859             if !allow_plus || !self.eat_plus() {
4860                 break
4861             }
4862         }
4863
4864         return Ok(bounds);
4865     }
4866
4867     fn parse_generic_bounds(&mut self) -> PResult<'a, GenericBounds> {
4868         self.parse_generic_bounds_common(true)
4869     }
4870
4871     // Parse bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
4872     // BOUND = LT_BOUND (e.g. `'a`)
4873     fn parse_lt_param_bounds(&mut self) -> GenericBounds {
4874         let mut lifetimes = Vec::new();
4875         while self.check_lifetime() {
4876             lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
4877
4878             if !self.eat_plus() {
4879                 break
4880             }
4881         }
4882         lifetimes
4883     }
4884
4885     /// Matches typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?
4886     fn parse_ty_param(&mut self,
4887                       preceding_attrs: Vec<Attribute>)
4888                       -> PResult<'a, GenericParam> {
4889         let ident = self.parse_ident()?;
4890
4891         // Parse optional colon and param bounds.
4892         let bounds = if self.eat(&token::Colon) {
4893             self.parse_generic_bounds()?
4894         } else {
4895             Vec::new()
4896         };
4897
4898         let default = if self.eat(&token::Eq) {
4899             Some(self.parse_ty()?)
4900         } else {
4901             None
4902         };
4903
4904         Ok(GenericParam {
4905             ident,
4906             id: ast::DUMMY_NODE_ID,
4907             attrs: preceding_attrs.into(),
4908             bounds,
4909             kind: GenericParamKind::Type {
4910                 default,
4911             }
4912         })
4913     }
4914
4915     /// Parses the following grammar:
4916     ///     TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
4917     fn parse_trait_item_assoc_ty(&mut self)
4918         -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
4919         let ident = self.parse_ident()?;
4920         let mut generics = self.parse_generics()?;
4921
4922         // Parse optional colon and param bounds.
4923         let bounds = if self.eat(&token::Colon) {
4924             self.parse_generic_bounds()?
4925         } else {
4926             Vec::new()
4927         };
4928         generics.where_clause = self.parse_where_clause()?;
4929
4930         let default = if self.eat(&token::Eq) {
4931             Some(self.parse_ty()?)
4932         } else {
4933             None
4934         };
4935         self.expect(&token::Semi)?;
4936
4937         Ok((ident, TraitItemKind::Type(bounds, default), generics))
4938     }
4939
4940     /// Parses (possibly empty) list of lifetime and type parameters, possibly including
4941     /// trailing comma and erroneous trailing attributes.
4942     crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
4943         let mut params = Vec::new();
4944         let mut seen_ty_param = false;
4945         loop {
4946             let attrs = self.parse_outer_attributes()?;
4947             if self.check_lifetime() {
4948                 let lifetime = self.expect_lifetime();
4949                 // Parse lifetime parameter.
4950                 let bounds = if self.eat(&token::Colon) {
4951                     self.parse_lt_param_bounds()
4952                 } else {
4953                     Vec::new()
4954                 };
4955                 params.push(ast::GenericParam {
4956                     ident: lifetime.ident,
4957                     id: lifetime.id,
4958                     attrs: attrs.into(),
4959                     bounds,
4960                     kind: ast::GenericParamKind::Lifetime,
4961                 });
4962                 if seen_ty_param {
4963                     self.span_err(self.prev_span,
4964                         "lifetime parameters must be declared prior to type parameters");
4965                 }
4966             } else if self.check_ident() {
4967                 // Parse type parameter.
4968                 params.push(self.parse_ty_param(attrs)?);
4969                 seen_ty_param = true;
4970             } else {
4971                 // Check for trailing attributes and stop parsing.
4972                 if !attrs.is_empty() {
4973                     let param_kind = if seen_ty_param { "type" } else { "lifetime" };
4974                     self.span_err(attrs[0].span,
4975                         &format!("trailing attribute after {} parameters", param_kind));
4976                 }
4977                 break
4978             }
4979
4980             if !self.eat(&token::Comma) {
4981                 break
4982             }
4983         }
4984         Ok(params)
4985     }
4986
4987     /// Parse a set of optional generic type parameter declarations. Where
4988     /// clauses are not parsed here, and must be added later via
4989     /// `parse_where_clause()`.
4990     ///
4991     /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
4992     ///                  | ( < lifetimes , typaramseq ( , )? > )
4993     /// where   typaramseq = ( typaram ) | ( typaram , typaramseq )
4994     fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
4995         maybe_whole!(self, NtGenerics, |x| x);
4996
4997         let span_lo = self.span;
4998         if self.eat_lt() {
4999             let params = self.parse_generic_params()?;
5000             self.expect_gt()?;
5001             Ok(ast::Generics {
5002                 params,
5003                 where_clause: WhereClause {
5004                     id: ast::DUMMY_NODE_ID,
5005                     predicates: Vec::new(),
5006                     span: syntax_pos::DUMMY_SP,
5007                 },
5008                 span: span_lo.to(self.prev_span),
5009             })
5010         } else {
5011             Ok(ast::Generics::default())
5012         }
5013     }
5014
5015     /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5016     /// possibly including trailing comma.
5017     fn parse_generic_args(&mut self)
5018                           -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5019         let mut args = Vec::new();
5020         let mut bindings = Vec::new();
5021         let mut seen_type = false;
5022         let mut seen_binding = false;
5023         loop {
5024             if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5025                 // Parse lifetime argument.
5026                 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5027                 if seen_type || seen_binding {
5028                     self.span_err(self.prev_span,
5029                         "lifetime parameters must be declared prior to type parameters");
5030                 }
5031             } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5032                 // Parse associated type binding.
5033                 let lo = self.span;
5034                 let ident = self.parse_ident()?;
5035                 self.bump();
5036                 let ty = self.parse_ty()?;
5037                 bindings.push(TypeBinding {
5038                     id: ast::DUMMY_NODE_ID,
5039                     ident,
5040                     ty,
5041                     span: lo.to(self.prev_span),
5042                 });
5043                 seen_binding = true;
5044             } else if self.check_type() {
5045                 // Parse type argument.
5046                 let ty_param = self.parse_ty()?;
5047                 if seen_binding {
5048                     self.span_err(ty_param.span,
5049                         "type parameters must be declared prior to associated type bindings");
5050                 }
5051                 args.push(GenericArg::Type(ty_param));
5052                 seen_type = true;
5053             } else {
5054                 break
5055             }
5056
5057             if !self.eat(&token::Comma) {
5058                 break
5059             }
5060         }
5061         Ok((args, bindings))
5062     }
5063
5064     /// Parses an optional `where` clause and places it in `generics`.
5065     ///
5066     /// ```ignore (only-for-syntax-highlight)
5067     /// where T : Trait<U, V> + 'b, 'a : 'b
5068     /// ```
5069     fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
5070         maybe_whole!(self, NtWhereClause, |x| x);
5071
5072         let mut where_clause = WhereClause {
5073             id: ast::DUMMY_NODE_ID,
5074             predicates: Vec::new(),
5075             span: syntax_pos::DUMMY_SP,
5076         };
5077
5078         if !self.eat_keyword(keywords::Where) {
5079             return Ok(where_clause);
5080         }
5081         let lo = self.prev_span;
5082
5083         // We are considering adding generics to the `where` keyword as an alternative higher-rank
5084         // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
5085         // change we parse those generics now, but report an error.
5086         if self.choose_generics_over_qpath() {
5087             let generics = self.parse_generics()?;
5088             self.span_err(generics.span,
5089                           "generic parameters on `where` clauses are reserved for future use");
5090         }
5091
5092         loop {
5093             let lo = self.span;
5094             if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5095                 let lifetime = self.expect_lifetime();
5096                 // Bounds starting with a colon are mandatory, but possibly empty.
5097                 self.expect(&token::Colon)?;
5098                 let bounds = self.parse_lt_param_bounds();
5099                 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
5100                     ast::WhereRegionPredicate {
5101                         span: lo.to(self.prev_span),
5102                         lifetime,
5103                         bounds,
5104                     }
5105                 ));
5106             } else if self.check_type() {
5107                 // Parse optional `for<'a, 'b>`.
5108                 // This `for` is parsed greedily and applies to the whole predicate,
5109                 // the bounded type can have its own `for` applying only to it.
5110                 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
5111                 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
5112                 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
5113                 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5114
5115                 // Parse type with mandatory colon and (possibly empty) bounds,
5116                 // or with mandatory equality sign and the second type.
5117                 let ty = self.parse_ty()?;
5118                 if self.eat(&token::Colon) {
5119                     let bounds = self.parse_generic_bounds()?;
5120                     where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
5121                         ast::WhereBoundPredicate {
5122                             span: lo.to(self.prev_span),
5123                             bound_generic_params: lifetime_defs,
5124                             bounded_ty: ty,
5125                             bounds,
5126                         }
5127                     ));
5128                 // FIXME: Decide what should be used here, `=` or `==`.
5129                 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
5130                 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
5131                     let rhs_ty = self.parse_ty()?;
5132                     where_clause.predicates.push(ast::WherePredicate::EqPredicate(
5133                         ast::WhereEqPredicate {
5134                             span: lo.to(self.prev_span),
5135                             lhs_ty: ty,
5136                             rhs_ty,
5137                             id: ast::DUMMY_NODE_ID,
5138                         }
5139                     ));
5140                 } else {
5141                     return self.unexpected();
5142                 }
5143             } else {
5144                 break
5145             }
5146
5147             if !self.eat(&token::Comma) {
5148                 break
5149             }
5150         }
5151
5152         where_clause.span = lo.to(self.prev_span);
5153         Ok(where_clause)
5154     }
5155
5156     fn parse_fn_args(&mut self, named_args: bool, allow_variadic: bool)
5157                      -> PResult<'a, (Vec<Arg> , bool)> {
5158         let sp = self.span;
5159         let mut variadic = false;
5160         let args: Vec<Option<Arg>> =
5161             self.parse_unspanned_seq(
5162                 &token::OpenDelim(token::Paren),
5163                 &token::CloseDelim(token::Paren),
5164                 SeqSep::trailing_allowed(token::Comma),
5165                 |p| {
5166                     if p.token == token::DotDotDot {
5167                         p.bump();
5168                         variadic = true;
5169                         if allow_variadic {
5170                             if p.token != token::CloseDelim(token::Paren) {
5171                                 let span = p.span;
5172                                 p.span_err(span,
5173                                     "`...` must be last in argument list for variadic function");
5174                             }
5175                             Ok(None)
5176                         } else {
5177                             let span = p.prev_span;
5178                             if p.token == token::CloseDelim(token::Paren) {
5179                                 // continue parsing to present any further errors
5180                                 p.struct_span_err(
5181                                     span,
5182                                     "only foreign functions are allowed to be variadic"
5183                                 ).emit();
5184                                 Ok(Some(dummy_arg(span)))
5185                            } else {
5186                                // this function definition looks beyond recovery, stop parsing
5187                                 p.span_err(span,
5188                                            "only foreign functions are allowed to be variadic");
5189                                 Ok(None)
5190                             }
5191                         }
5192                     } else {
5193                         match p.parse_arg_general(named_args) {
5194                             Ok(arg) => Ok(Some(arg)),
5195                             Err(mut e) => {
5196                                 e.emit();
5197                                 let lo = p.prev_span;
5198                                 // Skip every token until next possible arg or end.
5199                                 p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
5200                                 // Create a placeholder argument for proper arg count (#34264).
5201                                 let span = lo.to(p.prev_span);
5202                                 Ok(Some(dummy_arg(span)))
5203                             }
5204                         }
5205                     }
5206                 }
5207             )?;
5208
5209         let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
5210
5211         if variadic && args.is_empty() {
5212             self.span_err(sp,
5213                           "variadic function must be declared with at least one named argument");
5214         }
5215
5216         Ok((args, variadic))
5217     }
5218
5219     /// Parse the argument list and result type of a function declaration
5220     fn parse_fn_decl(&mut self, allow_variadic: bool) -> PResult<'a, P<FnDecl>> {
5221
5222         let (args, variadic) = self.parse_fn_args(true, allow_variadic)?;
5223         let ret_ty = self.parse_ret_ty(true)?;
5224
5225         Ok(P(FnDecl {
5226             inputs: args,
5227             output: ret_ty,
5228             variadic,
5229         }))
5230     }
5231
5232     /// Returns the parsed optional self argument and whether a self shortcut was used.
5233     fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
5234         let expect_ident = |this: &mut Self| match this.token {
5235             // Preserve hygienic context.
5236             token::Ident(ident, _) =>
5237                 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
5238             _ => unreachable!()
5239         };
5240         let isolated_self = |this: &mut Self, n| {
5241             this.look_ahead(n, |t| t.is_keyword(keywords::SelfValue)) &&
5242             this.look_ahead(n + 1, |t| t != &token::ModSep)
5243         };
5244
5245         // Parse optional self parameter of a method.
5246         // Only a limited set of initial token sequences is considered self parameters, anything
5247         // else is parsed as a normal function parameter list, so some lookahead is required.
5248         let eself_lo = self.span;
5249         let (eself, eself_ident, eself_hi) = match self.token {
5250             token::BinOp(token::And) => {
5251                 // &self
5252                 // &mut self
5253                 // &'lt self
5254                 // &'lt mut self
5255                 // &not_self
5256                 (if isolated_self(self, 1) {
5257                     self.bump();
5258                     SelfKind::Region(None, Mutability::Immutable)
5259                 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
5260                           isolated_self(self, 2) {
5261                     self.bump();
5262                     self.bump();
5263                     SelfKind::Region(None, Mutability::Mutable)
5264                 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5265                           isolated_self(self, 2) {
5266                     self.bump();
5267                     let lt = self.expect_lifetime();
5268                     SelfKind::Region(Some(lt), Mutability::Immutable)
5269                 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
5270                           self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
5271                           isolated_self(self, 3) {
5272                     self.bump();
5273                     let lt = self.expect_lifetime();
5274                     self.bump();
5275                     SelfKind::Region(Some(lt), Mutability::Mutable)
5276                 } else {
5277                     return Ok(None);
5278                 }, expect_ident(self), self.prev_span)
5279             }
5280             token::BinOp(token::Star) => {
5281                 // *self
5282                 // *const self
5283                 // *mut self
5284                 // *not_self
5285                 // Emit special error for `self` cases.
5286                 (if isolated_self(self, 1) {
5287                     self.bump();
5288                     self.span_err(self.span, "cannot pass `self` by raw pointer");
5289                     SelfKind::Value(Mutability::Immutable)
5290                 } else if self.look_ahead(1, |t| t.is_mutability()) &&
5291                           isolated_self(self, 2) {
5292                     self.bump();
5293                     self.bump();
5294                     self.span_err(self.span, "cannot pass `self` by raw pointer");
5295                     SelfKind::Value(Mutability::Immutable)
5296                 } else {
5297                     return Ok(None);
5298                 }, expect_ident(self), self.prev_span)
5299             }
5300             token::Ident(..) => {
5301                 if isolated_self(self, 0) {
5302                     // self
5303                     // self: TYPE
5304                     let eself_ident = expect_ident(self);
5305                     let eself_hi = self.prev_span;
5306                     (if self.eat(&token::Colon) {
5307                         let ty = self.parse_ty()?;
5308                         SelfKind::Explicit(ty, Mutability::Immutable)
5309                     } else {
5310                         SelfKind::Value(Mutability::Immutable)
5311                     }, eself_ident, eself_hi)
5312                 } else if self.token.is_keyword(keywords::Mut) &&
5313                           isolated_self(self, 1) {
5314                     // mut self
5315                     // mut self: TYPE
5316                     self.bump();
5317                     let eself_ident = expect_ident(self);
5318                     let eself_hi = self.prev_span;
5319                     (if self.eat(&token::Colon) {
5320                         let ty = self.parse_ty()?;
5321                         SelfKind::Explicit(ty, Mutability::Mutable)
5322                     } else {
5323                         SelfKind::Value(Mutability::Mutable)
5324                     }, eself_ident, eself_hi)
5325                 } else {
5326                     return Ok(None);
5327                 }
5328             }
5329             _ => return Ok(None),
5330         };
5331
5332         let eself = codemap::respan(eself_lo.to(eself_hi), eself);
5333         Ok(Some(Arg::from_self(eself, eself_ident)))
5334     }
5335
5336     /// Parse the parameter list and result type of a function that may have a `self` parameter.
5337     fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
5338         where F: FnMut(&mut Parser<'a>) -> PResult<'a,  Arg>,
5339     {
5340         self.expect(&token::OpenDelim(token::Paren))?;
5341
5342         // Parse optional self argument
5343         let self_arg = self.parse_self_arg()?;
5344
5345         // Parse the rest of the function parameter list.
5346         let sep = SeqSep::trailing_allowed(token::Comma);
5347         let fn_inputs = if let Some(self_arg) = self_arg {
5348             if self.check(&token::CloseDelim(token::Paren)) {
5349                 vec![self_arg]
5350             } else if self.eat(&token::Comma) {
5351                 let mut fn_inputs = vec![self_arg];
5352                 fn_inputs.append(&mut self.parse_seq_to_before_end(
5353                     &token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5354                 );
5355                 fn_inputs
5356             } else {
5357                 return self.unexpected();
5358             }
5359         } else {
5360             self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
5361         };
5362
5363         // Parse closing paren and return type.
5364         self.expect(&token::CloseDelim(token::Paren))?;
5365         Ok(P(FnDecl {
5366             inputs: fn_inputs,
5367             output: self.parse_ret_ty(true)?,
5368             variadic: false
5369         }))
5370     }
5371
5372     // parse the |arg, arg| header on a lambda
5373     fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
5374         let inputs_captures = {
5375             if self.eat(&token::OrOr) {
5376                 Vec::new()
5377             } else {
5378                 self.expect(&token::BinOp(token::Or))?;
5379                 let args = self.parse_seq_to_before_tokens(
5380                     &[&token::BinOp(token::Or), &token::OrOr],
5381                     SeqSep::trailing_allowed(token::Comma),
5382                     TokenExpectType::NoExpect,
5383                     |p| p.parse_fn_block_arg()
5384                 )?;
5385                 self.expect_or()?;
5386                 args
5387             }
5388         };
5389         let output = self.parse_ret_ty(true)?;
5390
5391         Ok(P(FnDecl {
5392             inputs: inputs_captures,
5393             output,
5394             variadic: false
5395         }))
5396     }
5397
5398     /// Parse the name and optional generic types of a function header.
5399     fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
5400         let id = self.parse_ident()?;
5401         let generics = self.parse_generics()?;
5402         Ok((id, generics))
5403     }
5404
5405     fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
5406                attrs: Vec<Attribute>) -> P<Item> {
5407         P(Item {
5408             ident,
5409             attrs,
5410             id: ast::DUMMY_NODE_ID,
5411             node,
5412             vis,
5413             span,
5414             tokens: None,
5415         })
5416     }
5417
5418     /// Parse an item-position function declaration.
5419     fn parse_item_fn(&mut self,
5420                      unsafety: Unsafety,
5421                      asyncness: IsAsync,
5422                      constness: Spanned<Constness>,
5423                      abi: Abi)
5424                      -> PResult<'a, ItemInfo> {
5425         let (ident, mut generics) = self.parse_fn_header()?;
5426         let decl = self.parse_fn_decl(false)?;
5427         generics.where_clause = self.parse_where_clause()?;
5428         let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5429         let header = FnHeader { unsafety, asyncness, constness, abi };
5430         Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
5431     }
5432
5433     /// true if we are looking at `const ID`, false for things like `const fn` etc
5434     fn is_const_item(&mut self) -> bool {
5435         self.token.is_keyword(keywords::Const) &&
5436             !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
5437             !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
5438     }
5439
5440     /// parses all the "front matter" for a `fn` declaration, up to
5441     /// and including the `fn` keyword:
5442     ///
5443     /// - `const fn`
5444     /// - `unsafe fn`
5445     /// - `const unsafe fn`
5446     /// - `extern fn`
5447     /// - etc
5448     fn parse_fn_front_matter(&mut self)
5449         -> PResult<'a, (
5450             Spanned<Constness>,
5451             Unsafety,
5452             IsAsync,
5453             Abi
5454         )>
5455     {
5456         let is_const_fn = self.eat_keyword(keywords::Const);
5457         let const_span = self.prev_span;
5458         let unsafety = self.parse_unsafety();
5459         let asyncness = self.parse_asyncness();
5460         let (constness, unsafety, abi) = if is_const_fn {
5461             (respan(const_span, Constness::Const), unsafety, Abi::Rust)
5462         } else {
5463             let abi = if self.eat_keyword(keywords::Extern) {
5464                 self.parse_opt_abi()?.unwrap_or(Abi::C)
5465             } else {
5466                 Abi::Rust
5467             };
5468             (respan(self.prev_span, Constness::NotConst), unsafety, abi)
5469         };
5470         self.expect_keyword(keywords::Fn)?;
5471         Ok((constness, unsafety, asyncness, abi))
5472     }
5473
5474     /// Parse an impl item.
5475     pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
5476         maybe_whole!(self, NtImplItem, |x| x);
5477         let attrs = self.parse_outer_attributes()?;
5478         let (mut item, tokens) = self.collect_tokens(|this| {
5479             this.parse_impl_item_(at_end, attrs)
5480         })?;
5481
5482         // See `parse_item` for why this clause is here.
5483         if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
5484             item.tokens = Some(tokens);
5485         }
5486         Ok(item)
5487     }
5488
5489     fn parse_impl_item_(&mut self,
5490                         at_end: &mut bool,
5491                         mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
5492         let lo = self.span;
5493         let vis = self.parse_visibility(false)?;
5494         let defaultness = self.parse_defaultness();
5495         let (name, node, generics) = if self.eat_keyword(keywords::Type) {
5496             // This parses the grammar:
5497             //     ImplItemAssocTy = Ident ["<"...">"] ["where" ...] "=" Ty ";"
5498             let name = self.parse_ident()?;
5499             let mut generics = self.parse_generics()?;
5500             generics.where_clause = self.parse_where_clause()?;
5501             self.expect(&token::Eq)?;
5502             let typ = self.parse_ty()?;
5503             self.expect(&token::Semi)?;
5504             (name, ast::ImplItemKind::Type(typ), generics)
5505         } else if self.is_const_item() {
5506             // This parses the grammar:
5507             //     ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
5508             self.expect_keyword(keywords::Const)?;
5509             let name = self.parse_ident()?;
5510             self.expect(&token::Colon)?;
5511             let typ = self.parse_ty()?;
5512             self.expect(&token::Eq)?;
5513             let expr = self.parse_expr()?;
5514             self.expect(&token::Semi)?;
5515             (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
5516         } else {
5517             let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
5518             attrs.extend(inner_attrs);
5519             (name, node, generics)
5520         };
5521
5522         Ok(ImplItem {
5523             id: ast::DUMMY_NODE_ID,
5524             span: lo.to(self.prev_span),
5525             ident: name,
5526             vis,
5527             defaultness,
5528             attrs,
5529             generics,
5530             node,
5531             tokens: None,
5532         })
5533     }
5534
5535     fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
5536         if let Err(mut err) = self.complain_if_pub_macro_diag(vis, sp) {
5537             err.emit();
5538         }
5539     }
5540
5541     fn complain_if_pub_macro_diag(&mut self, vis: &VisibilityKind, sp: Span) -> PResult<'a, ()> {
5542         match *vis {
5543             VisibilityKind::Inherited => Ok(()),
5544             _ => {
5545                 let is_macro_rules: bool = match self.token {
5546                     token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
5547                     _ => false,
5548                 };
5549                 if is_macro_rules {
5550                     let mut err = self.diagnostic()
5551                         .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
5552                     err.span_suggestion_with_applicability(
5553                         sp,
5554                         "try exporting the macro",
5555                         "#[macro_export]".to_owned(),
5556                         Applicability::MaybeIncorrect // speculative
5557                     );
5558                     Err(err)
5559                 } else {
5560                     let mut err = self.diagnostic()
5561                         .struct_span_err(sp, "can't qualify macro invocation with `pub`");
5562                     err.help("try adjusting the macro to put `pub` inside the invocation");
5563                     Err(err)
5564                 }
5565             }
5566         }
5567     }
5568
5569     fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
5570                                    -> DiagnosticBuilder<'a>
5571     {
5572         let expected_kinds = if item_type == "extern" {
5573             "missing `fn`, `type`, or `static`"
5574         } else {
5575             "missing `fn`, `type`, or `const`"
5576         };
5577
5578         // Given this code `path(`, it seems like this is not
5579         // setting the visibility of a macro invocation, but rather
5580         // a mistyped method declaration.
5581         // Create a diagnostic pointing out that `fn` is missing.
5582         //
5583         // x |     pub path(&self) {
5584         //   |        ^ missing `fn`, `type`, or `const`
5585         //     pub  path(
5586         //        ^^ `sp` below will point to this
5587         let sp = prev_span.between(self.prev_span);
5588         let mut err = self.diagnostic().struct_span_err(
5589             sp,
5590             &format!("{} for {}-item declaration",
5591                      expected_kinds, item_type));
5592         err.span_label(sp, expected_kinds);
5593         err
5594     }
5595
5596     /// Parse a method or a macro invocation in a trait impl.
5597     fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
5598                          -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
5599                              ast::ImplItemKind)> {
5600         // code copied from parse_macro_use_or_failure... abstraction!
5601         if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
5602             // Method macro.
5603             Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
5604                 ast::ImplItemKind::Macro(mac)))
5605         } else {
5606             let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
5607             let ident = self.parse_ident()?;
5608             let mut generics = self.parse_generics()?;
5609             let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
5610             generics.where_clause = self.parse_where_clause()?;
5611             *at_end = true;
5612             let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
5613             let header = ast::FnHeader { abi, unsafety, constness, asyncness };
5614             Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
5615                 ast::MethodSig { header, decl },
5616                 body
5617             )))
5618         }
5619     }
5620
5621     /// Parse `trait Foo { ... }` or `trait Foo = Bar;`
5622     fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
5623         let ident = self.parse_ident()?;
5624         let mut tps = self.parse_generics()?;
5625
5626         // Parse optional colon and supertrait bounds.
5627         let bounds = if self.eat(&token::Colon) {
5628             self.parse_generic_bounds()?
5629         } else {
5630             Vec::new()
5631         };
5632
5633         if self.eat(&token::Eq) {
5634             // it's a trait alias
5635             let bounds = self.parse_generic_bounds()?;
5636             tps.where_clause = self.parse_where_clause()?;
5637             self.expect(&token::Semi)?;
5638             if unsafety != Unsafety::Normal {
5639                 self.span_err(self.prev_span, "trait aliases cannot be unsafe");
5640             }
5641             Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
5642         } else {
5643             // it's a normal trait
5644             tps.where_clause = self.parse_where_clause()?;
5645             self.expect(&token::OpenDelim(token::Brace))?;
5646             let mut trait_items = vec![];
5647             while !self.eat(&token::CloseDelim(token::Brace)) {
5648                 let mut at_end = false;
5649                 match self.parse_trait_item(&mut at_end) {
5650                     Ok(item) => trait_items.push(item),
5651                     Err(mut e) => {
5652                         e.emit();
5653                         if !at_end {
5654                             self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5655                         }
5656                     }
5657                 }
5658             }
5659             Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
5660         }
5661     }
5662
5663     fn choose_generics_over_qpath(&self) -> bool {
5664         // There's an ambiguity between generic parameters and qualified paths in impls.
5665         // If we see `<` it may start both, so we have to inspect some following tokens.
5666         // The following combinations can only start generics,
5667         // but not qualified paths (with one exception):
5668         //     `<` `>` - empty generic parameters
5669         //     `<` `#` - generic parameters with attributes
5670         //     `<` (LIFETIME|IDENT) `>` - single generic parameter
5671         //     `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
5672         //     `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
5673         //     `<` (LIFETIME|IDENT) `=` - generic parameter with a default
5674         // The only truly ambiguous case is
5675         //     `<` IDENT `>` `::` IDENT ...
5676         // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
5677         // because this is what almost always expected in practice, qualified paths in impls
5678         // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
5679         self.token == token::Lt &&
5680             (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
5681              self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
5682                 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
5683                                        t == &token::Colon || t == &token::Eq))
5684     }
5685
5686     fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
5687         self.expect(&token::OpenDelim(token::Brace))?;
5688         let attrs = self.parse_inner_attributes()?;
5689
5690         let mut impl_items = Vec::new();
5691         while !self.eat(&token::CloseDelim(token::Brace)) {
5692             let mut at_end = false;
5693             match self.parse_impl_item(&mut at_end) {
5694                 Ok(impl_item) => impl_items.push(impl_item),
5695                 Err(mut err) => {
5696                     err.emit();
5697                     if !at_end {
5698                         self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
5699                     }
5700                 }
5701             }
5702         }
5703         Ok((impl_items, attrs))
5704     }
5705
5706     /// Parses an implementation item, `impl` keyword is already parsed.
5707     ///    impl<'a, T> TYPE { /* impl items */ }
5708     ///    impl<'a, T> TRAIT for TYPE { /* impl items */ }
5709     ///    impl<'a, T> !TRAIT for TYPE { /* impl items */ }
5710     /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
5711     ///     `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
5712     ///     `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
5713     fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
5714                        -> PResult<'a, ItemInfo> {
5715         // First, parse generic parameters if necessary.
5716         let mut generics = if self.choose_generics_over_qpath() {
5717             self.parse_generics()?
5718         } else {
5719             ast::Generics::default()
5720         };
5721
5722         // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
5723         let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
5724             self.bump(); // `!`
5725             ast::ImplPolarity::Negative
5726         } else {
5727             ast::ImplPolarity::Positive
5728         };
5729
5730         // Parse both types and traits as a type, then reinterpret if necessary.
5731         let ty_first = self.parse_ty()?;
5732
5733         // If `for` is missing we try to recover.
5734         let has_for = self.eat_keyword(keywords::For);
5735         let missing_for_span = self.prev_span.between(self.span);
5736
5737         let ty_second = if self.token == token::DotDot {
5738             // We need to report this error after `cfg` expansion for compatibility reasons
5739             self.bump(); // `..`, do not add it to expected tokens
5740             Some(P(Ty { node: TyKind::Err, span: self.prev_span, id: ast::DUMMY_NODE_ID }))
5741         } else if has_for || self.token.can_begin_type() {
5742             Some(self.parse_ty()?)
5743         } else {
5744             None
5745         };
5746
5747         generics.where_clause = self.parse_where_clause()?;
5748
5749         let (impl_items, attrs) = self.parse_impl_body()?;
5750
5751         let item_kind = match ty_second {
5752             Some(ty_second) => {
5753                 // impl Trait for Type
5754                 if !has_for {
5755                     self.span_err(missing_for_span, "missing `for` in a trait impl");
5756                 }
5757
5758                 let ty_first = ty_first.into_inner();
5759                 let path = match ty_first.node {
5760                     // This notably includes paths passed through `ty` macro fragments (#46438).
5761                     TyKind::Path(None, path) => path,
5762                     _ => {
5763                         self.span_err(ty_first.span, "expected a trait, found type");
5764                         ast::Path::from_ident(Ident::new(keywords::Invalid.name(), ty_first.span))
5765                     }
5766                 };
5767                 let trait_ref = TraitRef { path, ref_id: ty_first.id };
5768
5769                 ItemKind::Impl(unsafety, polarity, defaultness,
5770                                generics, Some(trait_ref), ty_second, impl_items)
5771             }
5772             None => {
5773                 // impl Type
5774                 ItemKind::Impl(unsafety, polarity, defaultness,
5775                                generics, None, ty_first, impl_items)
5776             }
5777         };
5778
5779         Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
5780     }
5781
5782     fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
5783         if self.eat_keyword(keywords::For) {
5784             self.expect_lt()?;
5785             let params = self.parse_generic_params()?;
5786             self.expect_gt()?;
5787             // We rely on AST validation to rule out invalid cases: There must not be type
5788             // parameters, and the lifetime parameters must not have bounds.
5789             Ok(params)
5790         } else {
5791             Ok(Vec::new())
5792         }
5793     }
5794
5795     /// Parse struct Foo { ... }
5796     fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
5797         let class_name = self.parse_ident()?;
5798
5799         let mut generics = self.parse_generics()?;
5800
5801         // There is a special case worth noting here, as reported in issue #17904.
5802         // If we are parsing a tuple struct it is the case that the where clause
5803         // should follow the field list. Like so:
5804         //
5805         // struct Foo<T>(T) where T: Copy;
5806         //
5807         // If we are parsing a normal record-style struct it is the case
5808         // that the where clause comes before the body, and after the generics.
5809         // So if we look ahead and see a brace or a where-clause we begin
5810         // parsing a record style struct.
5811         //
5812         // Otherwise if we look ahead and see a paren we parse a tuple-style
5813         // struct.
5814
5815         let vdata = if self.token.is_keyword(keywords::Where) {
5816             generics.where_clause = self.parse_where_clause()?;
5817             if self.eat(&token::Semi) {
5818                 // If we see a: `struct Foo<T> where T: Copy;` style decl.
5819                 VariantData::Unit(ast::DUMMY_NODE_ID)
5820             } else {
5821                 // If we see: `struct Foo<T> where T: Copy { ... }`
5822                 VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5823             }
5824         // No `where` so: `struct Foo<T>;`
5825         } else if self.eat(&token::Semi) {
5826             VariantData::Unit(ast::DUMMY_NODE_ID)
5827         // Record-style struct definition
5828         } else if self.token == token::OpenDelim(token::Brace) {
5829             VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5830         // Tuple-style struct definition with optional where-clause.
5831         } else if self.token == token::OpenDelim(token::Paren) {
5832             let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
5833             generics.where_clause = self.parse_where_clause()?;
5834             self.expect(&token::Semi)?;
5835             body
5836         } else {
5837             let token_str = self.this_token_to_string();
5838             let mut err = self.fatal(&format!(
5839                 "expected `where`, `{{`, `(`, or `;` after struct name, found `{}`",
5840                 token_str
5841             ));
5842             err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
5843             return Err(err);
5844         };
5845
5846         Ok((class_name, ItemKind::Struct(vdata, generics), None))
5847     }
5848
5849     /// Parse union Foo { ... }
5850     fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
5851         let class_name = self.parse_ident()?;
5852
5853         let mut generics = self.parse_generics()?;
5854
5855         let vdata = if self.token.is_keyword(keywords::Where) {
5856             generics.where_clause = self.parse_where_clause()?;
5857             VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5858         } else if self.token == token::OpenDelim(token::Brace) {
5859             VariantData::Struct(self.parse_record_struct_body()?, ast::DUMMY_NODE_ID)
5860         } else {
5861             let token_str = self.this_token_to_string();
5862             let mut err = self.fatal(&format!(
5863                 "expected `where` or `{{` after union name, found `{}`", token_str));
5864             err.span_label(self.span, "expected `where` or `{` after union name");
5865             return Err(err);
5866         };
5867
5868         Ok((class_name, ItemKind::Union(vdata, generics), None))
5869     }
5870
5871     fn consume_block(&mut self, delim: token::DelimToken) {
5872         let mut brace_depth = 0;
5873         if !self.eat(&token::OpenDelim(delim)) {
5874             return;
5875         }
5876         loop {
5877             if self.eat(&token::OpenDelim(delim)) {
5878                 brace_depth += 1;
5879             } else if self.eat(&token::CloseDelim(delim)) {
5880                 if brace_depth == 0 {
5881                     return;
5882                 } else {
5883                     brace_depth -= 1;
5884                     continue;
5885                 }
5886             } else if self.eat(&token::Eof) || self.eat(&token::CloseDelim(token::NoDelim)) {
5887                 return;
5888             } else {
5889                 self.bump();
5890             }
5891         }
5892     }
5893
5894     fn parse_record_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5895         let mut fields = Vec::new();
5896         if self.eat(&token::OpenDelim(token::Brace)) {
5897             while self.token != token::CloseDelim(token::Brace) {
5898                 let field = self.parse_struct_decl_field().map_err(|e| {
5899                     self.recover_stmt();
5900                     e
5901                 });
5902                 match field {
5903                     Ok(field) => fields.push(field),
5904                     Err(mut err) => {
5905                         err.emit();
5906                     }
5907                 }
5908             }
5909             self.eat(&token::CloseDelim(token::Brace));
5910         } else {
5911             let token_str = self.this_token_to_string();
5912             let mut err = self.fatal(&format!(
5913                     "expected `where`, or `{{` after struct name, found `{}`", token_str));
5914             err.span_label(self.span, "expected `where`, or `{` after struct name");
5915             return Err(err);
5916         }
5917
5918         Ok(fields)
5919     }
5920
5921     fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
5922         // This is the case where we find `struct Foo<T>(T) where T: Copy;`
5923         // Unit like structs are handled in parse_item_struct function
5924         let fields = self.parse_unspanned_seq(
5925             &token::OpenDelim(token::Paren),
5926             &token::CloseDelim(token::Paren),
5927             SeqSep::trailing_allowed(token::Comma),
5928             |p| {
5929                 let attrs = p.parse_outer_attributes()?;
5930                 let lo = p.span;
5931                 let vis = p.parse_visibility(true)?;
5932                 let ty = p.parse_ty()?;
5933                 Ok(StructField {
5934                     span: lo.to(ty.span),
5935                     vis,
5936                     ident: None,
5937                     id: ast::DUMMY_NODE_ID,
5938                     ty,
5939                     attrs,
5940                 })
5941             })?;
5942
5943         Ok(fields)
5944     }
5945
5946     /// Parse a structure field declaration
5947     fn parse_single_struct_field(&mut self,
5948                                      lo: Span,
5949                                      vis: Visibility,
5950                                      attrs: Vec<Attribute> )
5951                                      -> PResult<'a, StructField> {
5952         let mut seen_comma: bool = false;
5953         let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
5954         if self.token == token::Comma {
5955             seen_comma = true;
5956         }
5957         match self.token {
5958             token::Comma => {
5959                 self.bump();
5960             }
5961             token::CloseDelim(token::Brace) => {}
5962             token::DocComment(_) => {
5963                 let previous_span = self.prev_span;
5964                 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
5965                 self.bump(); // consume the doc comment
5966                 let comma_after_doc_seen = self.eat(&token::Comma);
5967                 // `seen_comma` is always false, because we are inside doc block
5968                 // condition is here to make code more readable
5969                 if seen_comma == false && comma_after_doc_seen == true {
5970                     seen_comma = true;
5971                 }
5972                 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
5973                     err.emit();
5974                 } else {
5975                     if seen_comma == false {
5976                         let sp = self.sess.codemap().next_point(previous_span);
5977                         err.span_suggestion_with_applicability(
5978                             sp,
5979                             "missing comma here",
5980                             ",".into(),
5981                             Applicability::MachineApplicable
5982                         );
5983                     }
5984                     return Err(err);
5985                 }
5986             }
5987             _ => {
5988                 let sp = self.sess.codemap().next_point(self.prev_span);
5989                 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found `{}`",
5990                                                                 self.this_token_to_string()));
5991                 if self.token.is_ident() {
5992                     // This is likely another field; emit the diagnostic and keep going
5993                     err.span_suggestion(sp, "try adding a comma", ",".into());
5994                     err.emit();
5995                 } else {
5996                     return Err(err)
5997                 }
5998             }
5999         }
6000         Ok(a_var)
6001     }
6002
6003     /// Parse an element of a struct definition
6004     fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
6005         let attrs = self.parse_outer_attributes()?;
6006         let lo = self.span;
6007         let vis = self.parse_visibility(false)?;
6008         self.parse_single_struct_field(lo, vis, attrs)
6009     }
6010
6011     /// Parse `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `pub(self)` for `pub(in self)`
6012     /// and `pub(super)` for `pub(in super)`.  If the following element can't be a tuple (i.e. it's
6013     /// a function definition, it's not a tuple struct field) and the contents within the parens
6014     /// isn't valid, emit a proper diagnostic.
6015     pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
6016         maybe_whole!(self, NtVis, |x| x);
6017
6018         self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
6019         if self.is_crate_vis() {
6020             self.bump(); // `crate`
6021             return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
6022         }
6023
6024         if !self.eat_keyword(keywords::Pub) {
6025             return Ok(respan(self.prev_span, VisibilityKind::Inherited))
6026         }
6027         let lo = self.prev_span;
6028
6029         if self.check(&token::OpenDelim(token::Paren)) {
6030             // We don't `self.bump()` the `(` yet because this might be a struct definition where
6031             // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
6032             // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
6033             // by the following tokens.
6034             if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
6035                 // `pub(crate)`
6036                 self.bump(); // `(`
6037                 self.bump(); // `crate`
6038                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6039                 let vis = respan(
6040                     lo.to(self.prev_span),
6041                     VisibilityKind::Crate(CrateSugar::PubCrate),
6042                 );
6043                 return Ok(vis)
6044             } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
6045                 // `pub(in path)`
6046                 self.bump(); // `(`
6047                 self.bump(); // `in`
6048                 let path = self.parse_path(PathStyle::Mod)?; // `path`
6049                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6050                 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6051                     path: P(path),
6052                     id: ast::DUMMY_NODE_ID,
6053                 });
6054                 return Ok(vis)
6055             } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
6056                       self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
6057                                              t.is_keyword(keywords::SelfValue))
6058             {
6059                 // `pub(self)` or `pub(super)`
6060                 self.bump(); // `(`
6061                 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
6062                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
6063                 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
6064                     path: P(path),
6065                     id: ast::DUMMY_NODE_ID,
6066                 });
6067                 return Ok(vis)
6068             } else if !can_take_tuple {  // Provide this diagnostic if this is not a tuple struct
6069                 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
6070                 self.bump(); // `(`
6071                 let msg = "incorrect visibility restriction";
6072                 let suggestion = r##"some possible visibility restrictions are:
6073 `pub(crate)`: visible only on the current crate
6074 `pub(super)`: visible only in the current module's parent
6075 `pub(in path::to::module)`: visible only on the specified path"##;
6076                 let path = self.parse_path(PathStyle::Mod)?;
6077                 let sp = self.prev_span;
6078                 let help_msg = format!("make this visible only to module `{}` with `in`", path);
6079                 self.expect(&token::CloseDelim(token::Paren))?;  // `)`
6080                 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
6081                 err.help(suggestion);
6082                 err.span_suggestion_with_applicability(
6083                     sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
6084                 );
6085                 err.emit();  // emit diagnostic, but continue with public visibility
6086             }
6087         }
6088
6089         Ok(respan(lo, VisibilityKind::Public))
6090     }
6091
6092     /// Parse defaultness: `default` or nothing.
6093     fn parse_defaultness(&mut self) -> Defaultness {
6094         // `pub` is included for better error messages
6095         if self.check_keyword(keywords::Default) &&
6096            self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
6097                                   t.is_keyword(keywords::Const) ||
6098                                   t.is_keyword(keywords::Fn) ||
6099                                   t.is_keyword(keywords::Unsafe) ||
6100                                   t.is_keyword(keywords::Extern) ||
6101                                   t.is_keyword(keywords::Type) ||
6102                                   t.is_keyword(keywords::Pub)) {
6103             self.bump(); // `default`
6104             Defaultness::Default
6105         } else {
6106             Defaultness::Final
6107         }
6108     }
6109
6110     /// Given a termination token, parse all of the items in a module
6111     fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
6112         let mut items = vec![];
6113         while let Some(item) = self.parse_item()? {
6114             items.push(item);
6115         }
6116
6117         if !self.eat(term) {
6118             let token_str = self.this_token_to_string();
6119             let mut err = self.fatal(&format!("expected item, found `{}`", token_str));
6120             if token_str == ";" {
6121                 let msg = "consider removing this semicolon";
6122                 err.span_suggestion_short_with_applicability(
6123                     self.span, msg, "".to_string(), Applicability::MachineApplicable
6124                 );
6125             } else {
6126                 err.span_label(self.span, "expected item");
6127             }
6128             return Err(err);
6129         }
6130
6131         let hi = if self.span == syntax_pos::DUMMY_SP {
6132             inner_lo
6133         } else {
6134             self.prev_span
6135         };
6136
6137         Ok(ast::Mod {
6138             inner: inner_lo.to(hi),
6139             items,
6140         })
6141     }
6142
6143     fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
6144         let id = self.parse_ident()?;
6145         self.expect(&token::Colon)?;
6146         let ty = self.parse_ty()?;
6147         self.expect(&token::Eq)?;
6148         let e = self.parse_expr()?;
6149         self.expect(&token::Semi)?;
6150         let item = match m {
6151             Some(m) => ItemKind::Static(ty, m, e),
6152             None => ItemKind::Const(ty, e),
6153         };
6154         Ok((id, item, None))
6155     }
6156
6157     /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
6158     fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
6159         let (in_cfg, outer_attrs) = {
6160             let mut strip_unconfigured = ::config::StripUnconfigured {
6161                 sess: self.sess,
6162                 should_test: false, // irrelevant
6163                 features: None, // don't perform gated feature checking
6164             };
6165             let outer_attrs = strip_unconfigured.process_cfg_attrs(outer_attrs.to_owned());
6166             (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
6167         };
6168
6169         let id_span = self.span;
6170         let id = self.parse_ident()?;
6171         if self.check(&token::Semi) {
6172             self.bump();
6173             if in_cfg && self.recurse_into_file_modules {
6174                 // This mod is in an external file. Let's go get it!
6175                 let ModulePathSuccess { path, directory_ownership, warn } =
6176                     self.submod_path(id, &outer_attrs, id_span)?;
6177                 let (module, mut attrs) =
6178                     self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
6179                 if warn {
6180                     let attr = Attribute {
6181                         id: attr::mk_attr_id(),
6182                         style: ast::AttrStyle::Outer,
6183                         path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
6184                         tokens: TokenStream::empty(),
6185                         is_sugared_doc: false,
6186                         span: syntax_pos::DUMMY_SP,
6187                     };
6188                     attr::mark_known(&attr);
6189                     attrs.push(attr);
6190                 }
6191                 Ok((id, module, Some(attrs)))
6192             } else {
6193                 let placeholder = ast::Mod { inner: syntax_pos::DUMMY_SP, items: Vec::new() };
6194                 Ok((id, ItemKind::Mod(placeholder), None))
6195             }
6196         } else {
6197             let old_directory = self.directory.clone();
6198             self.push_directory(id, &outer_attrs);
6199
6200             self.expect(&token::OpenDelim(token::Brace))?;
6201             let mod_inner_lo = self.span;
6202             let attrs = self.parse_inner_attributes()?;
6203             let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
6204
6205             self.directory = old_directory;
6206             Ok((id, ItemKind::Mod(module), Some(attrs)))
6207         }
6208     }
6209
6210     fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
6211         if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
6212             self.directory.path.to_mut().push(&path.as_str());
6213             self.directory.ownership = DirectoryOwnership::Owned { relative: None };
6214         } else {
6215             self.directory.path.to_mut().push(&id.as_str());
6216         }
6217     }
6218
6219     pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
6220         if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
6221             let s = s.as_str();
6222
6223             // On windows, the base path might have the form
6224             // `\\?\foo\bar` in which case it does not tolerate
6225             // mixed `/` and `\` separators, so canonicalize
6226             // `/` to `\`.
6227             #[cfg(windows)]
6228             let s = s.replace("/", "\\");
6229             Some(dir_path.join(s))
6230         } else {
6231             None
6232         }
6233     }
6234
6235     /// Returns either a path to a module, or .
6236     pub fn default_submod_path(
6237         id: ast::Ident,
6238         relative: Option<ast::Ident>,
6239         dir_path: &Path,
6240         codemap: &CodeMap) -> ModulePath
6241     {
6242         // If we're in a foo.rs file instead of a mod.rs file,
6243         // we need to look for submodules in
6244         // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
6245         // `./<id>.rs` and `./<id>/mod.rs`.
6246         let relative_prefix_string;
6247         let relative_prefix = if let Some(ident) = relative {
6248             relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
6249             &relative_prefix_string
6250         } else {
6251             ""
6252         };
6253
6254         let mod_name = id.to_string();
6255         let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
6256         let secondary_path_str = format!("{}{}{}mod.rs",
6257                                          relative_prefix, mod_name, path::MAIN_SEPARATOR);
6258         let default_path = dir_path.join(&default_path_str);
6259         let secondary_path = dir_path.join(&secondary_path_str);
6260         let default_exists = codemap.file_exists(&default_path);
6261         let secondary_exists = codemap.file_exists(&secondary_path);
6262
6263         let result = match (default_exists, secondary_exists) {
6264             (true, false) => Ok(ModulePathSuccess {
6265                 path: default_path,
6266                 directory_ownership: DirectoryOwnership::Owned {
6267                     relative: Some(id),
6268                 },
6269                 warn: false,
6270             }),
6271             (false, true) => Ok(ModulePathSuccess {
6272                 path: secondary_path,
6273                 directory_ownership: DirectoryOwnership::Owned {
6274                     relative: None,
6275                 },
6276                 warn: false,
6277             }),
6278             (false, false) => Err(Error::FileNotFoundForModule {
6279                 mod_name: mod_name.clone(),
6280                 default_path: default_path_str,
6281                 secondary_path: secondary_path_str,
6282                 dir_path: format!("{}", dir_path.display()),
6283             }),
6284             (true, true) => Err(Error::DuplicatePaths {
6285                 mod_name: mod_name.clone(),
6286                 default_path: default_path_str,
6287                 secondary_path: secondary_path_str,
6288             }),
6289         };
6290
6291         ModulePath {
6292             name: mod_name,
6293             path_exists: default_exists || secondary_exists,
6294             result,
6295         }
6296     }
6297
6298     fn submod_path(&mut self,
6299                    id: ast::Ident,
6300                    outer_attrs: &[Attribute],
6301                    id_sp: Span)
6302                    -> PResult<'a, ModulePathSuccess> {
6303         if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
6304             return Ok(ModulePathSuccess {
6305                 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
6306                     // All `#[path]` files are treated as though they are a `mod.rs` file.
6307                     // This means that `mod foo;` declarations inside `#[path]`-included
6308                     // files are siblings,
6309                     //
6310                     // Note that this will produce weirdness when a file named `foo.rs` is
6311                     // `#[path]` included and contains a `mod foo;` declaration.
6312                     // If you encounter this, it's your own darn fault :P
6313                     Some(_) => DirectoryOwnership::Owned { relative: None },
6314                     _ => DirectoryOwnership::UnownedViaMod(true),
6315                 },
6316                 path,
6317                 warn: false,
6318             });
6319         }
6320
6321         let relative = match self.directory.ownership {
6322             DirectoryOwnership::Owned { relative } => {
6323                 // Push the usage onto the list of non-mod.rs mod uses.
6324                 // This is used later for feature-gate error reporting.
6325                 if let Some(cur_file_ident) = relative {
6326                     self.sess
6327                         .non_modrs_mods.borrow_mut()
6328                         .push((cur_file_ident, id_sp));
6329                 }
6330                 relative
6331             },
6332             DirectoryOwnership::UnownedViaBlock |
6333             DirectoryOwnership::UnownedViaMod(_) => None,
6334         };
6335         let paths = Parser::default_submod_path(
6336                         id, relative, &self.directory.path, self.sess.codemap());
6337
6338         match self.directory.ownership {
6339             DirectoryOwnership::Owned { .. } => {
6340                 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
6341             },
6342             DirectoryOwnership::UnownedViaBlock => {
6343                 let msg =
6344                     "Cannot declare a non-inline module inside a block \
6345                     unless it has a path attribute";
6346                 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
6347                 if paths.path_exists {
6348                     let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
6349                                       paths.name);
6350                     err.span_note(id_sp, &msg);
6351                 }
6352                 Err(err)
6353             }
6354             DirectoryOwnership::UnownedViaMod(warn) => {
6355                 if warn {
6356                     if let Ok(result) = paths.result {
6357                         return Ok(ModulePathSuccess { warn: true, ..result });
6358                     }
6359                 }
6360                 let mut err = self.diagnostic().struct_span_err(id_sp,
6361                     "cannot declare a new module at this location");
6362                 if id_sp != syntax_pos::DUMMY_SP {
6363                     let src_path = self.sess.codemap().span_to_filename(id_sp);
6364                     if let FileName::Real(src_path) = src_path {
6365                         if let Some(stem) = src_path.file_stem() {
6366                             let mut dest_path = src_path.clone();
6367                             dest_path.set_file_name(stem);
6368                             dest_path.push("mod.rs");
6369                             err.span_note(id_sp,
6370                                     &format!("maybe move this module `{}` to its own \
6371                                                 directory via `{}`", src_path.display(),
6372                                             dest_path.display()));
6373                         }
6374                     }
6375                 }
6376                 if paths.path_exists {
6377                     err.span_note(id_sp,
6378                                   &format!("... or maybe `use` the module `{}` instead \
6379                                             of possibly redeclaring it",
6380                                            paths.name));
6381                 }
6382                 Err(err)
6383             }
6384         }
6385     }
6386
6387     /// Read a module from a source file.
6388     fn eval_src_mod(&mut self,
6389                     path: PathBuf,
6390                     directory_ownership: DirectoryOwnership,
6391                     name: String,
6392                     id_sp: Span)
6393                     -> PResult<'a, (ast::ItemKind, Vec<Attribute> )> {
6394         let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
6395         if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
6396             let mut err = String::from("circular modules: ");
6397             let len = included_mod_stack.len();
6398             for p in &included_mod_stack[i.. len] {
6399                 err.push_str(&p.to_string_lossy());
6400                 err.push_str(" -> ");
6401             }
6402             err.push_str(&path.to_string_lossy());
6403             return Err(self.span_fatal(id_sp, &err[..]));
6404         }
6405         included_mod_stack.push(path.clone());
6406         drop(included_mod_stack);
6407
6408         let mut p0 =
6409             new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
6410         p0.cfg_mods = self.cfg_mods;
6411         let mod_inner_lo = p0.span;
6412         let mod_attrs = p0.parse_inner_attributes()?;
6413         let m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
6414         self.sess.included_mod_stack.borrow_mut().pop();
6415         Ok((ast::ItemKind::Mod(m0), mod_attrs))
6416     }
6417
6418     /// Parse a function declaration from a foreign module
6419     fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6420                              -> PResult<'a, ForeignItem> {
6421         self.expect_keyword(keywords::Fn)?;
6422
6423         let (ident, mut generics) = self.parse_fn_header()?;
6424         let decl = self.parse_fn_decl(true)?;
6425         generics.where_clause = self.parse_where_clause()?;
6426         let hi = self.span;
6427         self.expect(&token::Semi)?;
6428         Ok(ast::ForeignItem {
6429             ident,
6430             attrs,
6431             node: ForeignItemKind::Fn(decl, generics),
6432             id: ast::DUMMY_NODE_ID,
6433             span: lo.to(hi),
6434             vis,
6435         })
6436     }
6437
6438     /// Parse a static item from a foreign module.
6439     /// Assumes that the `static` keyword is already parsed.
6440     fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6441                                  -> PResult<'a, ForeignItem> {
6442         let mutbl = self.eat_keyword(keywords::Mut);
6443         let ident = self.parse_ident()?;
6444         self.expect(&token::Colon)?;
6445         let ty = self.parse_ty()?;
6446         let hi = self.span;
6447         self.expect(&token::Semi)?;
6448         Ok(ForeignItem {
6449             ident,
6450             attrs,
6451             node: ForeignItemKind::Static(ty, mutbl),
6452             id: ast::DUMMY_NODE_ID,
6453             span: lo.to(hi),
6454             vis,
6455         })
6456     }
6457
6458     /// Parse a type from a foreign module
6459     fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
6460                              -> PResult<'a, ForeignItem> {
6461         self.expect_keyword(keywords::Type)?;
6462
6463         let ident = self.parse_ident()?;
6464         let hi = self.span;
6465         self.expect(&token::Semi)?;
6466         Ok(ast::ForeignItem {
6467             ident: ident,
6468             attrs: attrs,
6469             node: ForeignItemKind::Ty,
6470             id: ast::DUMMY_NODE_ID,
6471             span: lo.to(hi),
6472             vis: vis
6473         })
6474     }
6475
6476     /// Parse extern crate links
6477     ///
6478     /// # Examples
6479     ///
6480     /// extern crate foo;
6481     /// extern crate bar as foo;
6482     fn parse_item_extern_crate(&mut self,
6483                                lo: Span,
6484                                visibility: Visibility,
6485                                attrs: Vec<Attribute>)
6486                                -> PResult<'a, P<Item>> {
6487         let orig_name = self.parse_ident()?;
6488         let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
6489             (rename, Some(orig_name.name))
6490         } else {
6491             (orig_name, None)
6492         };
6493         self.expect(&token::Semi)?;
6494
6495         let span = lo.to(self.prev_span);
6496         Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
6497     }
6498
6499     /// Parse `extern` for foreign ABIs
6500     /// modules.
6501     ///
6502     /// `extern` is expected to have been
6503     /// consumed before calling this method
6504     ///
6505     /// # Examples:
6506     ///
6507     /// extern "C" {}
6508     /// extern {}
6509     fn parse_item_foreign_mod(&mut self,
6510                               lo: Span,
6511                               opt_abi: Option<Abi>,
6512                               visibility: Visibility,
6513                               mut attrs: Vec<Attribute>)
6514                               -> PResult<'a, P<Item>> {
6515         self.expect(&token::OpenDelim(token::Brace))?;
6516
6517         let abi = opt_abi.unwrap_or(Abi::C);
6518
6519         attrs.extend(self.parse_inner_attributes()?);
6520
6521         let mut foreign_items = vec![];
6522         while let Some(item) = self.parse_foreign_item()? {
6523             foreign_items.push(item);
6524         }
6525         self.expect(&token::CloseDelim(token::Brace))?;
6526
6527         let prev_span = self.prev_span;
6528         let m = ast::ForeignMod {
6529             abi,
6530             items: foreign_items
6531         };
6532         let invalid = keywords::Invalid.ident();
6533         Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
6534     }
6535
6536     /// Parse type Foo = Bar;
6537     fn parse_item_type(&mut self) -> PResult<'a, ItemInfo> {
6538         let ident = self.parse_ident()?;
6539         let mut tps = self.parse_generics()?;
6540         tps.where_clause = self.parse_where_clause()?;
6541         self.expect(&token::Eq)?;
6542         let ty = self.parse_ty()?;
6543         self.expect(&token::Semi)?;
6544         Ok((ident, ItemKind::Ty(ty, tps), None))
6545     }
6546
6547     /// Parse the part of an "enum" decl following the '{'
6548     fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
6549         let mut variants = Vec::new();
6550         let mut all_nullary = true;
6551         let mut any_disr = None;
6552         while self.token != token::CloseDelim(token::Brace) {
6553             let variant_attrs = self.parse_outer_attributes()?;
6554             let vlo = self.span;
6555
6556             let struct_def;
6557             let mut disr_expr = None;
6558             let ident = self.parse_ident()?;
6559             if self.check(&token::OpenDelim(token::Brace)) {
6560                 // Parse a struct variant.
6561                 all_nullary = false;
6562                 struct_def = VariantData::Struct(self.parse_record_struct_body()?,
6563                                                  ast::DUMMY_NODE_ID);
6564             } else if self.check(&token::OpenDelim(token::Paren)) {
6565                 all_nullary = false;
6566                 struct_def = VariantData::Tuple(self.parse_tuple_struct_body()?,
6567                                                 ast::DUMMY_NODE_ID);
6568             } else if self.eat(&token::Eq) {
6569                 disr_expr = Some(AnonConst {
6570                     id: ast::DUMMY_NODE_ID,
6571                     value: self.parse_expr()?,
6572                 });
6573                 any_disr = disr_expr.as_ref().map(|c| c.value.span);
6574                 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6575             } else {
6576                 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
6577             }
6578
6579             let vr = ast::Variant_ {
6580                 ident,
6581                 attrs: variant_attrs,
6582                 data: struct_def,
6583                 disr_expr,
6584             };
6585             variants.push(respan(vlo.to(self.prev_span), vr));
6586
6587             if !self.eat(&token::Comma) { break; }
6588         }
6589         self.expect(&token::CloseDelim(token::Brace))?;
6590         match any_disr {
6591             Some(disr_span) if !all_nullary =>
6592                 self.span_err(disr_span,
6593                     "discriminator values can only be used with a field-less enum"),
6594             _ => ()
6595         }
6596
6597         Ok(ast::EnumDef { variants: variants })
6598     }
6599
6600     /// Parse an "enum" declaration
6601     fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
6602         let id = self.parse_ident()?;
6603         let mut generics = self.parse_generics()?;
6604         generics.where_clause = self.parse_where_clause()?;
6605         self.expect(&token::OpenDelim(token::Brace))?;
6606
6607         let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
6608             self.recover_stmt();
6609             self.eat(&token::CloseDelim(token::Brace));
6610             e
6611         })?;
6612         Ok((id, ItemKind::Enum(enum_definition, generics), None))
6613     }
6614
6615     /// Parses a string as an ABI spec on an extern type or module. Consumes
6616     /// the `extern` keyword, if one is found.
6617     fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
6618         match self.token {
6619             token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
6620                 let sp = self.span;
6621                 self.expect_no_suffix(sp, "ABI spec", suf);
6622                 self.bump();
6623                 match abi::lookup(&s.as_str()) {
6624                     Some(abi) => Ok(Some(abi)),
6625                     None => {
6626                         let prev_span = self.prev_span;
6627                         let mut err = struct_span_err!(
6628                             self.sess.span_diagnostic,
6629                             prev_span,
6630                             E0703,
6631                             "invalid ABI: found `{}`",
6632                             s);
6633                         err.span_label(prev_span, "invalid ABI");
6634                         err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
6635                         err.emit();
6636                         Ok(None)
6637                     }
6638                 }
6639             }
6640
6641             _ => Ok(None),
6642         }
6643     }
6644
6645     fn is_static_global(&mut self) -> bool {
6646         if self.check_keyword(keywords::Static) {
6647             // Check if this could be a closure
6648             !self.look_ahead(1, |token| {
6649                 if token.is_keyword(keywords::Move) {
6650                     return true;
6651                 }
6652                 match *token {
6653                     token::BinOp(token::Or) | token::OrOr => true,
6654                     _ => false,
6655                 }
6656             })
6657         } else {
6658             false
6659         }
6660     }
6661
6662     /// Parse one of the items allowed by the flags.
6663     /// NB: this function no longer parses the items inside an
6664     /// extern crate.
6665     fn parse_item_(&mut self, attrs: Vec<Attribute>,
6666                    macros_allowed: bool, attributes_allowed: bool) -> PResult<'a, Option<P<Item>>> {
6667         maybe_whole!(self, NtItem, |item| {
6668             let mut item = item.into_inner();
6669             let mut attrs = attrs;
6670             mem::swap(&mut item.attrs, &mut attrs);
6671             item.attrs.extend(attrs);
6672             Some(P(item))
6673         });
6674
6675         let lo = self.span;
6676
6677         let visibility = self.parse_visibility(false)?;
6678
6679         if self.eat_keyword(keywords::Use) {
6680             // USE ITEM
6681             let item_ = ItemKind::Use(P(self.parse_use_tree()?));
6682             self.expect(&token::Semi)?;
6683
6684             let span = lo.to(self.prev_span);
6685             let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
6686             return Ok(Some(item));
6687         }
6688
6689         if self.check_keyword(keywords::Extern) && self.is_extern_non_path() {
6690             self.bump(); // `extern`
6691             if self.eat_keyword(keywords::Crate) {
6692                 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
6693             }
6694
6695             let opt_abi = self.parse_opt_abi()?;
6696
6697             if self.eat_keyword(keywords::Fn) {
6698                 // EXTERN FUNCTION ITEM
6699                 let fn_span = self.prev_span;
6700                 let abi = opt_abi.unwrap_or(Abi::C);
6701                 let (ident, item_, extra_attrs) =
6702                     self.parse_item_fn(Unsafety::Normal,
6703                                        IsAsync::NotAsync,
6704                                        respan(fn_span, Constness::NotConst),
6705                                        abi)?;
6706                 let prev_span = self.prev_span;
6707                 let item = self.mk_item(lo.to(prev_span),
6708                                         ident,
6709                                         item_,
6710                                         visibility,
6711                                         maybe_append(attrs, extra_attrs));
6712                 return Ok(Some(item));
6713             } else if self.check(&token::OpenDelim(token::Brace)) {
6714                 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
6715             }
6716
6717             self.unexpected()?;
6718         }
6719
6720         if self.is_static_global() {
6721             self.bump();
6722             // STATIC ITEM
6723             let m = if self.eat_keyword(keywords::Mut) {
6724                 Mutability::Mutable
6725             } else {
6726                 Mutability::Immutable
6727             };
6728             let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
6729             let prev_span = self.prev_span;
6730             let item = self.mk_item(lo.to(prev_span),
6731                                     ident,
6732                                     item_,
6733                                     visibility,
6734                                     maybe_append(attrs, extra_attrs));
6735             return Ok(Some(item));
6736         }
6737         if self.eat_keyword(keywords::Const) {
6738             let const_span = self.prev_span;
6739             if self.check_keyword(keywords::Fn)
6740                 || (self.check_keyword(keywords::Unsafe)
6741                     && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
6742                 // CONST FUNCTION ITEM
6743                 let unsafety = self.parse_unsafety();
6744                 self.bump();
6745                 let (ident, item_, extra_attrs) =
6746                     self.parse_item_fn(unsafety,
6747                                        IsAsync::NotAsync,
6748                                        respan(const_span, Constness::Const),
6749                                        Abi::Rust)?;
6750                 let prev_span = self.prev_span;
6751                 let item = self.mk_item(lo.to(prev_span),
6752                                         ident,
6753                                         item_,
6754                                         visibility,
6755                                         maybe_append(attrs, extra_attrs));
6756                 return Ok(Some(item));
6757             }
6758
6759             // CONST ITEM
6760             if self.eat_keyword(keywords::Mut) {
6761                 let prev_span = self.prev_span;
6762                 self.diagnostic().struct_span_err(prev_span, "const globals cannot be mutable")
6763                                  .help("did you mean to declare a static?")
6764                                  .emit();
6765             }
6766             let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
6767             let prev_span = self.prev_span;
6768             let item = self.mk_item(lo.to(prev_span),
6769                                     ident,
6770                                     item_,
6771                                     visibility,
6772                                     maybe_append(attrs, extra_attrs));
6773             return Ok(Some(item));
6774         }
6775
6776         // `unsafe async fn` or `async fn`
6777         if (
6778             self.check_keyword(keywords::Unsafe) &&
6779             self.look_ahead(1, |t| t.is_keyword(keywords::Async))
6780         ) || (
6781             self.check_keyword(keywords::Async) &&
6782             self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
6783         )
6784         {
6785             // ASYNC FUNCTION ITEM
6786             let unsafety = self.parse_unsafety();
6787             self.expect_keyword(keywords::Async)?;
6788             self.expect_keyword(keywords::Fn)?;
6789             let fn_span = self.prev_span;
6790             let (ident, item_, extra_attrs) =
6791                 self.parse_item_fn(unsafety,
6792                                    IsAsync::Async(ast::DUMMY_NODE_ID),
6793                                    respan(fn_span, Constness::NotConst),
6794                                    Abi::Rust)?;
6795             let prev_span = self.prev_span;
6796             let item = self.mk_item(lo.to(prev_span),
6797                                     ident,
6798                                     item_,
6799                                     visibility,
6800                                     maybe_append(attrs, extra_attrs));
6801             return Ok(Some(item));
6802         }
6803         if self.check_keyword(keywords::Unsafe) &&
6804             (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
6805             self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
6806         {
6807             // UNSAFE TRAIT ITEM
6808             self.bump(); // `unsafe`
6809             let is_auto = if self.eat_keyword(keywords::Trait) {
6810                 IsAuto::No
6811             } else {
6812                 self.expect_keyword(keywords::Auto)?;
6813                 self.expect_keyword(keywords::Trait)?;
6814                 IsAuto::Yes
6815             };
6816             let (ident, item_, extra_attrs) =
6817                 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
6818             let prev_span = self.prev_span;
6819             let item = self.mk_item(lo.to(prev_span),
6820                                     ident,
6821                                     item_,
6822                                     visibility,
6823                                     maybe_append(attrs, extra_attrs));
6824             return Ok(Some(item));
6825         }
6826         if self.check_keyword(keywords::Impl) ||
6827            self.check_keyword(keywords::Unsafe) &&
6828                 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6829            self.check_keyword(keywords::Default) &&
6830                 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
6831            self.check_keyword(keywords::Default) &&
6832                 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
6833             // IMPL ITEM
6834             let defaultness = self.parse_defaultness();
6835             let unsafety = self.parse_unsafety();
6836             self.expect_keyword(keywords::Impl)?;
6837             let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
6838             let span = lo.to(self.prev_span);
6839             return Ok(Some(self.mk_item(span, ident, item, visibility,
6840                                         maybe_append(attrs, extra_attrs))));
6841         }
6842         if self.check_keyword(keywords::Fn) {
6843             // FUNCTION ITEM
6844             self.bump();
6845             let fn_span = self.prev_span;
6846             let (ident, item_, extra_attrs) =
6847                 self.parse_item_fn(Unsafety::Normal,
6848                                    IsAsync::NotAsync,
6849                                    respan(fn_span, Constness::NotConst),
6850                                    Abi::Rust)?;
6851             let prev_span = self.prev_span;
6852             let item = self.mk_item(lo.to(prev_span),
6853                                     ident,
6854                                     item_,
6855                                     visibility,
6856                                     maybe_append(attrs, extra_attrs));
6857             return Ok(Some(item));
6858         }
6859         if self.check_keyword(keywords::Unsafe)
6860             && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
6861             // UNSAFE FUNCTION ITEM
6862             self.bump(); // `unsafe`
6863             // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
6864             self.check(&token::OpenDelim(token::Brace));
6865             let abi = if self.eat_keyword(keywords::Extern) {
6866                 self.parse_opt_abi()?.unwrap_or(Abi::C)
6867             } else {
6868                 Abi::Rust
6869             };
6870             self.expect_keyword(keywords::Fn)?;
6871             let fn_span = self.prev_span;
6872             let (ident, item_, extra_attrs) =
6873                 self.parse_item_fn(Unsafety::Unsafe,
6874                                    IsAsync::NotAsync,
6875                                    respan(fn_span, Constness::NotConst),
6876                                    abi)?;
6877             let prev_span = self.prev_span;
6878             let item = self.mk_item(lo.to(prev_span),
6879                                     ident,
6880                                     item_,
6881                                     visibility,
6882                                     maybe_append(attrs, extra_attrs));
6883             return Ok(Some(item));
6884         }
6885         if self.eat_keyword(keywords::Mod) {
6886             // MODULE ITEM
6887             let (ident, item_, extra_attrs) =
6888                 self.parse_item_mod(&attrs[..])?;
6889             let prev_span = self.prev_span;
6890             let item = self.mk_item(lo.to(prev_span),
6891                                     ident,
6892                                     item_,
6893                                     visibility,
6894                                     maybe_append(attrs, extra_attrs));
6895             return Ok(Some(item));
6896         }
6897         if self.eat_keyword(keywords::Type) {
6898             // TYPE ITEM
6899             let (ident, item_, extra_attrs) = self.parse_item_type()?;
6900             let prev_span = self.prev_span;
6901             let item = self.mk_item(lo.to(prev_span),
6902                                     ident,
6903                                     item_,
6904                                     visibility,
6905                                     maybe_append(attrs, extra_attrs));
6906             return Ok(Some(item));
6907         }
6908         if self.eat_keyword(keywords::Enum) {
6909             // ENUM ITEM
6910             let (ident, item_, extra_attrs) = self.parse_item_enum()?;
6911             let prev_span = self.prev_span;
6912             let item = self.mk_item(lo.to(prev_span),
6913                                     ident,
6914                                     item_,
6915                                     visibility,
6916                                     maybe_append(attrs, extra_attrs));
6917             return Ok(Some(item));
6918         }
6919         if self.check_keyword(keywords::Trait)
6920             || (self.check_keyword(keywords::Auto)
6921                 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
6922         {
6923             let is_auto = if self.eat_keyword(keywords::Trait) {
6924                 IsAuto::No
6925             } else {
6926                 self.expect_keyword(keywords::Auto)?;
6927                 self.expect_keyword(keywords::Trait)?;
6928                 IsAuto::Yes
6929             };
6930             // TRAIT ITEM
6931             let (ident, item_, extra_attrs) =
6932                 self.parse_item_trait(is_auto, Unsafety::Normal)?;
6933             let prev_span = self.prev_span;
6934             let item = self.mk_item(lo.to(prev_span),
6935                                     ident,
6936                                     item_,
6937                                     visibility,
6938                                     maybe_append(attrs, extra_attrs));
6939             return Ok(Some(item));
6940         }
6941         if self.eat_keyword(keywords::Struct) {
6942             // STRUCT ITEM
6943             let (ident, item_, extra_attrs) = self.parse_item_struct()?;
6944             let prev_span = self.prev_span;
6945             let item = self.mk_item(lo.to(prev_span),
6946                                     ident,
6947                                     item_,
6948                                     visibility,
6949                                     maybe_append(attrs, extra_attrs));
6950             return Ok(Some(item));
6951         }
6952         if self.is_union_item() {
6953             // UNION ITEM
6954             self.bump();
6955             let (ident, item_, extra_attrs) = self.parse_item_union()?;
6956             let prev_span = self.prev_span;
6957             let item = self.mk_item(lo.to(prev_span),
6958                                     ident,
6959                                     item_,
6960                                     visibility,
6961                                     maybe_append(attrs, extra_attrs));
6962             return Ok(Some(item));
6963         }
6964         if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
6965             return Ok(Some(macro_def));
6966         }
6967
6968         // Verify whether we have encountered a struct or method definition where the user forgot to
6969         // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
6970         if visibility.node == VisibilityKind::Public &&
6971             self.check_ident() &&
6972             self.look_ahead(1, |t| *t != token::Not)
6973         {
6974             // Space between `pub` keyword and the identifier
6975             //
6976             //     pub   S {}
6977             //        ^^^ `sp` points here
6978             let sp = self.prev_span.between(self.span);
6979             let full_sp = self.prev_span.to(self.span);
6980             let ident_sp = self.span;
6981             if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
6982                 // possible public struct definition where `struct` was forgotten
6983                 let ident = self.parse_ident().unwrap();
6984                 let msg = format!("add `struct` here to parse `{}` as a public struct",
6985                                   ident);
6986                 let mut err = self.diagnostic()
6987                     .struct_span_err(sp, "missing `struct` for struct definition");
6988                 err.span_suggestion_short_with_applicability(
6989                     sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
6990                 );
6991                 return Err(err);
6992             } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
6993                 let ident = self.parse_ident().unwrap();
6994                 self.consume_block(token::Paren);
6995                 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) ||
6996                     self.check(&token::OpenDelim(token::Brace))
6997                 {
6998                     ("fn", "method", false)
6999                 } else if self.check(&token::Colon) {
7000                     let kw = "struct";
7001                     (kw, kw, false)
7002                 } else {
7003                     ("fn` or `struct", "method or struct", true)
7004                 };
7005
7006                 let msg = format!("missing `{}` for {} definition", kw, kw_name);
7007                 let mut err = self.diagnostic().struct_span_err(sp, &msg);
7008                 if !ambiguous {
7009                     let suggestion = format!("add `{}` here to parse `{}` as a public {}",
7010                                              kw,
7011                                              ident,
7012                                              kw_name);
7013                     err.span_suggestion_short_with_applicability(
7014                         sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
7015                     );
7016                 } else {
7017                     if let Ok(snippet) = self.sess.codemap().span_to_snippet(ident_sp) {
7018                         err.span_suggestion_with_applicability(
7019                             full_sp,
7020                             "if you meant to call a macro, try",
7021                             format!("{}!", snippet),
7022                             // this is the `ambiguous` conditional branch
7023                             Applicability::MaybeIncorrect
7024                         );
7025                     } else {
7026                         err.help("if you meant to call a macro, remove the `pub` \
7027                                   and add a trailing `!` after the identifier");
7028                     }
7029                 }
7030                 return Err(err);
7031             }
7032         }
7033         self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
7034     }
7035
7036     /// Parse a foreign item.
7037     crate fn parse_foreign_item(&mut self) -> PResult<'a, Option<ForeignItem>> {
7038         maybe_whole!(self, NtForeignItem, |ni| Some(ni));
7039
7040         let attrs = self.parse_outer_attributes()?;
7041         let lo = self.span;
7042         let visibility = self.parse_visibility(false)?;
7043
7044         // FOREIGN STATIC ITEM
7045         // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
7046         if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
7047             if self.token.is_keyword(keywords::Const) {
7048                 self.diagnostic()
7049                     .struct_span_err(self.span, "extern items cannot be `const`")
7050                     .span_suggestion_with_applicability(
7051                         self.span,
7052                         "try using a static value",
7053                         "static".to_owned(),
7054                         Applicability::MachineApplicable
7055                     ).emit();
7056             }
7057             self.bump(); // `static` or `const`
7058             return Ok(Some(self.parse_item_foreign_static(visibility, lo, attrs)?));
7059         }
7060         // FOREIGN FUNCTION ITEM
7061         if self.check_keyword(keywords::Fn) {
7062             return Ok(Some(self.parse_item_foreign_fn(visibility, lo, attrs)?));
7063         }
7064         // FOREIGN TYPE ITEM
7065         if self.check_keyword(keywords::Type) {
7066             return Ok(Some(self.parse_item_foreign_type(visibility, lo, attrs)?));
7067         }
7068
7069         match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
7070             Some(mac) => {
7071                 Ok(Some(
7072                     ForeignItem {
7073                         ident: keywords::Invalid.ident(),
7074                         span: lo.to(self.prev_span),
7075                         id: ast::DUMMY_NODE_ID,
7076                         attrs,
7077                         vis: visibility,
7078                         node: ForeignItemKind::Macro(mac),
7079                     }
7080                 ))
7081             }
7082             None => {
7083                 if !attrs.is_empty() {
7084                     self.expected_item_err(&attrs);
7085                 }
7086
7087                 Ok(None)
7088             }
7089         }
7090     }
7091
7092     /// This is the fall-through for parsing items.
7093     fn parse_macro_use_or_failure(
7094         &mut self,
7095         attrs: Vec<Attribute> ,
7096         macros_allowed: bool,
7097         attributes_allowed: bool,
7098         lo: Span,
7099         visibility: Visibility
7100     ) -> PResult<'a, Option<P<Item>>> {
7101         if macros_allowed && self.token.is_path_start() {
7102             // MACRO INVOCATION ITEM
7103
7104             let prev_span = self.prev_span;
7105             self.complain_if_pub_macro(&visibility.node, prev_span);
7106
7107             let mac_lo = self.span;
7108
7109             // item macro.
7110             let pth = self.parse_path(PathStyle::Mod)?;
7111             self.expect(&token::Not)?;
7112
7113             // a 'special' identifier (like what `macro_rules!` uses)
7114             // is optional. We should eventually unify invoc syntax
7115             // and remove this.
7116             let id = if self.token.is_ident() {
7117                 self.parse_ident()?
7118             } else {
7119                 keywords::Invalid.ident() // no special identifier
7120             };
7121             // eat a matched-delimiter token tree:
7122             let (delim, tts) = self.expect_delimited_token_tree()?;
7123             if delim != MacDelimiter::Brace {
7124                 if !self.eat(&token::Semi) {
7125                     self.span_err(self.prev_span,
7126                                   "macros that expand to items must either \
7127                                    be surrounded with braces or followed by \
7128                                    a semicolon");
7129                 }
7130             }
7131
7132             let hi = self.prev_span;
7133             let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
7134             let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
7135             return Ok(Some(item));
7136         }
7137
7138         // FAILURE TO PARSE ITEM
7139         match visibility.node {
7140             VisibilityKind::Inherited => {}
7141             _ => {
7142                 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
7143             }
7144         }
7145
7146         if !attributes_allowed && !attrs.is_empty() {
7147             self.expected_item_err(&attrs);
7148         }
7149         Ok(None)
7150     }
7151
7152     /// Parse a macro invocation inside a `trait`, `impl` or `extern` block
7153     fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
7154                                at_end: &mut bool) -> PResult<'a, Option<Mac>>
7155     {
7156         if self.token.is_path_start() && !self.is_extern_non_path() {
7157             let prev_span = self.prev_span;
7158             let lo = self.span;
7159             let pth = self.parse_path(PathStyle::Mod)?;
7160
7161             if pth.segments.len() == 1 {
7162                 if !self.eat(&token::Not) {
7163                     return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
7164                 }
7165             } else {
7166                 self.expect(&token::Not)?;
7167             }
7168
7169             if let Some(vis) = vis {
7170                 self.complain_if_pub_macro(&vis.node, prev_span);
7171             }
7172
7173             *at_end = true;
7174
7175             // eat a matched-delimiter token tree:
7176             let (delim, tts) = self.expect_delimited_token_tree()?;
7177             if delim != MacDelimiter::Brace {
7178                 self.expect(&token::Semi)?
7179             }
7180
7181             Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
7182         } else {
7183             Ok(None)
7184         }
7185     }
7186
7187     fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
7188         where F: FnOnce(&mut Self) -> PResult<'a, R>
7189     {
7190         // Record all tokens we parse when parsing this item.
7191         let mut tokens = Vec::new();
7192         match self.token_cursor.frame.last_token {
7193             LastToken::Collecting(_) => {
7194                 panic!("cannot collect tokens recursively yet")
7195             }
7196             LastToken::Was(ref mut last) => tokens.extend(last.take()),
7197         }
7198         self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
7199         let prev = self.token_cursor.stack.len();
7200         let ret = f(self);
7201         let last_token = if self.token_cursor.stack.len() == prev {
7202             &mut self.token_cursor.frame.last_token
7203         } else {
7204             &mut self.token_cursor.stack[prev].last_token
7205         };
7206         let mut tokens = match *last_token {
7207             LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
7208             LastToken::Was(_) => panic!("our vector went away?"),
7209         };
7210
7211         // If we're not at EOF our current token wasn't actually consumed by
7212         // `f`, but it'll still be in our list that we pulled out. In that case
7213         // put it back.
7214         if self.token == token::Eof {
7215             *last_token = LastToken::Was(None);
7216         } else {
7217             *last_token = LastToken::Was(tokens.pop());
7218         }
7219
7220         Ok((ret?, tokens.into_iter().collect()))
7221     }
7222
7223     pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
7224         let attrs = self.parse_outer_attributes()?;
7225
7226         let (ret, tokens) = self.collect_tokens(|this| {
7227             this.parse_item_(attrs, true, false)
7228         })?;
7229
7230         // Once we've parsed an item and recorded the tokens we got while
7231         // parsing we may want to store `tokens` into the item we're about to
7232         // return. Note, though, that we specifically didn't capture tokens
7233         // related to outer attributes. The `tokens` field here may later be
7234         // used with procedural macros to convert this item back into a token
7235         // stream, but during expansion we may be removing attributes as we go
7236         // along.
7237         //
7238         // If we've got inner attributes then the `tokens` we've got above holds
7239         // these inner attributes. If an inner attribute is expanded we won't
7240         // actually remove it from the token stream, so we'll just keep yielding
7241         // it (bad!). To work around this case for now we just avoid recording
7242         // `tokens` if we detect any inner attributes. This should help keep
7243         // expansion correct, but we should fix this bug one day!
7244         Ok(ret.map(|item| {
7245             item.map(|mut i| {
7246                 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7247                     i.tokens = Some(tokens);
7248                 }
7249                 i
7250             })
7251         }))
7252     }
7253
7254     /// `::{` or `::*`
7255     fn is_import_coupler(&mut self) -> bool {
7256         self.check(&token::ModSep) &&
7257             self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
7258                                    *t == token::BinOp(token::Star))
7259     }
7260
7261     /// Parse UseTree
7262     ///
7263     /// USE_TREE = [`::`] `*` |
7264     ///            [`::`] `{` USE_TREE_LIST `}` |
7265     ///            PATH `::` `*` |
7266     ///            PATH `::` `{` USE_TREE_LIST `}` |
7267     ///            PATH [`as` IDENT]
7268     fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
7269         let lo = self.span;
7270
7271         let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
7272         let kind = if self.check(&token::OpenDelim(token::Brace)) ||
7273                       self.check(&token::BinOp(token::Star)) ||
7274                       self.is_import_coupler() {
7275             // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
7276             if self.eat(&token::ModSep) {
7277                 prefix.segments.push(PathSegment::crate_root(lo.shrink_to_lo()));
7278             }
7279
7280             if self.eat(&token::BinOp(token::Star)) {
7281                 UseTreeKind::Glob
7282             } else {
7283                 UseTreeKind::Nested(self.parse_use_tree_list()?)
7284             }
7285         } else {
7286             // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
7287             prefix = self.parse_path(PathStyle::Mod)?;
7288
7289             if self.eat(&token::ModSep) {
7290                 if self.eat(&token::BinOp(token::Star)) {
7291                     UseTreeKind::Glob
7292                 } else {
7293                     UseTreeKind::Nested(self.parse_use_tree_list()?)
7294                 }
7295             } else {
7296                 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
7297             }
7298         };
7299
7300         Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
7301     }
7302
7303     /// Parse UseTreeKind::Nested(list)
7304     ///
7305     /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
7306     fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
7307         self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
7308                                  &token::CloseDelim(token::Brace),
7309                                  SeqSep::trailing_allowed(token::Comma), |this| {
7310             Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
7311         })
7312     }
7313
7314     fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
7315         if self.eat_keyword(keywords::As) {
7316             match self.token {
7317                 token::Ident(ident, false) if ident.name == keywords::Underscore.name() => {
7318                     self.bump(); // `_`
7319                     Ok(Some(Ident::new(ident.name.gensymed(), ident.span)))
7320                 }
7321                 _ => self.parse_ident().map(Some),
7322             }
7323         } else {
7324             Ok(None)
7325         }
7326     }
7327
7328     /// Parses a source module as a crate. This is the main
7329     /// entry point for the parser.
7330     pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
7331         let lo = self.span;
7332         Ok(ast::Crate {
7333             attrs: self.parse_inner_attributes()?,
7334             module: self.parse_mod_items(&token::Eof, lo)?,
7335             span: lo.to(self.span),
7336         })
7337     }
7338
7339     pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
7340         let ret = match self.token {
7341             token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
7342             token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
7343             _ => return None
7344         };
7345         self.bump();
7346         Some(ret)
7347     }
7348
7349     pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
7350         match self.parse_optional_str() {
7351             Some((s, style, suf)) => {
7352                 let sp = self.prev_span;
7353                 self.expect_no_suffix(sp, "string literal", suf);
7354                 Ok((s, style))
7355             }
7356             _ => {
7357                 let msg = "expected string literal";
7358                 let mut err = self.fatal(msg);
7359                 err.span_label(self.span, msg);
7360                 Err(err)
7361             }
7362         }
7363     }
7364 }