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