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