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