]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/parser.rs
Rollup merge of #60520 - matklad:rustfmt-all-the-new-things, r=Centril
[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 d = 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, &d);
1589
1590             let sig = ast::MethodSig {
1591                 header: FnHeader {
1592                     unsafety,
1593                     constness,
1594                     abi,
1595                     asyncness,
1596                 },
1597                 decl: d,
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) => true,
2323             _ => false,
2324         };
2325         let check_args_start = |this: &mut Self| {
2326             this.expected_tokens.extend_from_slice(
2327                 &[TokenType::Token(token::Lt), TokenType::Token(token::OpenDelim(token::Paren))]
2328             );
2329             is_args_start(&this.token)
2330         };
2331
2332         Ok(if style == PathStyle::Type && check_args_start(self) ||
2333               style != PathStyle::Mod && self.check(&token::ModSep)
2334                                       && self.look_ahead(1, |t| is_args_start(t)) {
2335             // We use `style == PathStyle::Expr` to check if this is in a recursion or not. If
2336             // it isn't, then we reset the unmatched angle bracket count as we're about to start
2337             // parsing a new path.
2338             if style == PathStyle::Expr {
2339                 self.unmatched_angle_bracket_count = 0;
2340                 self.max_angle_bracket_count = 0;
2341             }
2342
2343             // Generic arguments are found - `<`, `(`, `::<` or `::(`.
2344             self.eat(&token::ModSep);
2345             let lo = self.span;
2346             let args = if self.eat_lt() {
2347                 // `<'a, T, A = U>`
2348                 let (args, bindings) =
2349                     self.parse_generic_args_with_leaning_angle_bracket_recovery(style, lo)?;
2350                 self.expect_gt()?;
2351                 let span = lo.to(self.prev_span);
2352                 AngleBracketedArgs { args, bindings, span }.into()
2353             } else {
2354                 // `(T, U) -> R`
2355                 self.bump(); // `(`
2356                 let (inputs, recovered) = self.parse_seq_to_before_tokens(
2357                     &[&token::CloseDelim(token::Paren)],
2358                     SeqSep::trailing_allowed(token::Comma),
2359                     TokenExpectType::Expect,
2360                     |p| p.parse_ty())?;
2361                 if !recovered {
2362                     self.bump(); // `)`
2363                 }
2364                 let span = lo.to(self.prev_span);
2365                 let output = if self.eat(&token::RArrow) {
2366                     Some(self.parse_ty_common(false, false, false)?)
2367                 } else {
2368                     None
2369                 };
2370                 ParenthesizedArgs { inputs, output, span }.into()
2371             };
2372
2373             PathSegment { ident, args, id: ast::DUMMY_NODE_ID }
2374         } else {
2375             // Generic arguments are not found.
2376             PathSegment::from_ident(ident)
2377         })
2378     }
2379
2380     crate fn check_lifetime(&mut self) -> bool {
2381         self.expected_tokens.push(TokenType::Lifetime);
2382         self.token.is_lifetime()
2383     }
2384
2385     /// Parses a single lifetime `'a` or panics.
2386     crate fn expect_lifetime(&mut self) -> Lifetime {
2387         if let Some(ident) = self.token.lifetime() {
2388             let span = self.span;
2389             self.bump();
2390             Lifetime { ident: Ident::new(ident.name, span), id: ast::DUMMY_NODE_ID }
2391         } else {
2392             self.span_bug(self.span, "not a lifetime")
2393         }
2394     }
2395
2396     fn eat_label(&mut self) -> Option<Label> {
2397         if let Some(ident) = self.token.lifetime() {
2398             let span = self.span;
2399             self.bump();
2400             Some(Label { ident: Ident::new(ident.name, span) })
2401         } else {
2402             None
2403         }
2404     }
2405
2406     /// Parses mutability (`mut` or nothing).
2407     fn parse_mutability(&mut self) -> Mutability {
2408         if self.eat_keyword(keywords::Mut) {
2409             Mutability::Mutable
2410         } else {
2411             Mutability::Immutable
2412         }
2413     }
2414
2415     fn parse_field_name(&mut self) -> PResult<'a, Ident> {
2416         if let token::Literal(token::Integer(name), suffix) = self.token {
2417             self.expect_no_suffix(self.span, "a tuple index", suffix);
2418             self.bump();
2419             Ok(Ident::new(name, self.prev_span))
2420         } else {
2421             self.parse_ident_common(false)
2422         }
2423     }
2424
2425     /// Parse ident (COLON expr)?
2426     fn parse_field(&mut self) -> PResult<'a, Field> {
2427         let attrs = self.parse_outer_attributes()?;
2428         let lo = self.span;
2429
2430         // Check if a colon exists one ahead. This means we're parsing a fieldname.
2431         let (fieldname, expr, is_shorthand) = if self.look_ahead(1, |t| {
2432             t == &token::Colon || t == &token::Eq
2433         }) {
2434             let fieldname = self.parse_field_name()?;
2435
2436             // Check for an equals token. This means the source incorrectly attempts to
2437             // initialize a field with an eq rather than a colon.
2438             if self.token == token::Eq {
2439                 self.diagnostic()
2440                     .struct_span_err(self.span, "expected `:`, found `=`")
2441                     .span_suggestion(
2442                         fieldname.span.shrink_to_hi().to(self.span),
2443                         "replace equals symbol with a colon",
2444                         ":".to_string(),
2445                         Applicability::MachineApplicable,
2446                     )
2447                     .emit();
2448             }
2449             self.bump(); // `:`
2450             (fieldname, self.parse_expr()?, false)
2451         } else {
2452             let fieldname = self.parse_ident_common(false)?;
2453
2454             // Mimic `x: x` for the `x` field shorthand.
2455             let path = ast::Path::from_ident(fieldname);
2456             let expr = self.mk_expr(fieldname.span, ExprKind::Path(None, path), ThinVec::new());
2457             (fieldname, expr, true)
2458         };
2459         Ok(ast::Field {
2460             ident: fieldname,
2461             span: lo.to(expr.span),
2462             expr,
2463             is_shorthand,
2464             attrs: attrs.into(),
2465         })
2466     }
2467
2468     fn mk_expr(&mut self, span: Span, node: ExprKind, attrs: ThinVec<Attribute>) -> P<Expr> {
2469         P(Expr { node, span, attrs, id: ast::DUMMY_NODE_ID })
2470     }
2471
2472     fn mk_unary(&mut self, unop: ast::UnOp, expr: P<Expr>) -> ast::ExprKind {
2473         ExprKind::Unary(unop, expr)
2474     }
2475
2476     fn mk_binary(&mut self, binop: ast::BinOp, lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2477         ExprKind::Binary(binop, lhs, rhs)
2478     }
2479
2480     fn mk_call(&mut self, f: P<Expr>, args: Vec<P<Expr>>) -> ast::ExprKind {
2481         ExprKind::Call(f, args)
2482     }
2483
2484     fn mk_index(&mut self, expr: P<Expr>, idx: P<Expr>) -> ast::ExprKind {
2485         ExprKind::Index(expr, idx)
2486     }
2487
2488     fn mk_range(&mut self,
2489                     start: Option<P<Expr>>,
2490                     end: Option<P<Expr>>,
2491                     limits: RangeLimits)
2492                     -> PResult<'a, ast::ExprKind> {
2493         if end.is_none() && limits == RangeLimits::Closed {
2494             Err(self.span_fatal_err(self.span, Error::InclusiveRangeWithNoEnd))
2495         } else {
2496             Ok(ExprKind::Range(start, end, limits))
2497         }
2498     }
2499
2500     fn mk_assign_op(&mut self, binop: ast::BinOp,
2501                         lhs: P<Expr>, rhs: P<Expr>) -> ast::ExprKind {
2502         ExprKind::AssignOp(binop, lhs, rhs)
2503     }
2504
2505     fn expect_delimited_token_tree(&mut self) -> PResult<'a, (MacDelimiter, TokenStream)> {
2506         let delim = match self.token {
2507             token::OpenDelim(delim) => delim,
2508             _ => {
2509                 let msg = "expected open delimiter";
2510                 let mut err = self.fatal(msg);
2511                 err.span_label(self.span, msg);
2512                 return Err(err)
2513             }
2514         };
2515         let tts = match self.parse_token_tree() {
2516             TokenTree::Delimited(_, _, tts) => tts,
2517             _ => unreachable!(),
2518         };
2519         let delim = match delim {
2520             token::Paren => MacDelimiter::Parenthesis,
2521             token::Bracket => MacDelimiter::Bracket,
2522             token::Brace => MacDelimiter::Brace,
2523             token::NoDelim => self.bug("unexpected no delimiter"),
2524         };
2525         Ok((delim, tts.into()))
2526     }
2527
2528     /// At the bottom (top?) of the precedence hierarchy,
2529     /// Parses things like parenthesized exprs, macros, `return`, etc.
2530     ///
2531     /// N.B., this does not parse outer attributes, and is private because it only works
2532     /// correctly if called from `parse_dot_or_call_expr()`.
2533     fn parse_bottom_expr(&mut self) -> PResult<'a, P<Expr>> {
2534         maybe_recover_from_interpolated_ty_qpath!(self, true);
2535         maybe_whole_expr!(self);
2536
2537         // Outer attributes are already parsed and will be
2538         // added to the return value after the fact.
2539         //
2540         // Therefore, prevent sub-parser from parsing
2541         // attributes by giving them a empty "already parsed" list.
2542         let mut attrs = ThinVec::new();
2543
2544         let lo = self.span;
2545         let mut hi = self.span;
2546
2547         let ex: ExprKind;
2548
2549         // Note: when adding new syntax here, don't forget to adjust Token::can_begin_expr().
2550         match self.token {
2551             token::OpenDelim(token::Paren) => {
2552                 self.bump();
2553
2554                 attrs.extend(self.parse_inner_attributes()?);
2555
2556                 // (e) is parenthesized e
2557                 // (e,) is a tuple with only one field, e
2558                 let mut es = vec![];
2559                 let mut trailing_comma = false;
2560                 let mut recovered = false;
2561                 while self.token != token::CloseDelim(token::Paren) {
2562                     es.push(match self.parse_expr() {
2563                         Ok(es) => es,
2564                         Err(err) => {
2565                             // recover from parse error in tuple list
2566                             return Ok(self.recover_seq_parse_error(token::Paren, lo, Err(err)));
2567                         }
2568                     });
2569                     recovered = self.expect_one_of(
2570                         &[],
2571                         &[token::Comma, token::CloseDelim(token::Paren)],
2572                     )?;
2573                     if self.eat(&token::Comma) {
2574                         trailing_comma = true;
2575                     } else {
2576                         trailing_comma = false;
2577                         break;
2578                     }
2579                 }
2580                 if !recovered {
2581                     self.bump();
2582                 }
2583
2584                 hi = self.prev_span;
2585                 ex = if es.len() == 1 && !trailing_comma {
2586                     ExprKind::Paren(es.into_iter().nth(0).unwrap())
2587                 } else {
2588                     ExprKind::Tup(es)
2589                 };
2590             }
2591             token::OpenDelim(token::Brace) => {
2592                 return self.parse_block_expr(None, lo, BlockCheckMode::Default, attrs);
2593             }
2594             token::BinOp(token::Or) | token::OrOr => {
2595                 return self.parse_lambda_expr(attrs);
2596             }
2597             token::OpenDelim(token::Bracket) => {
2598                 self.bump();
2599
2600                 attrs.extend(self.parse_inner_attributes()?);
2601
2602                 if self.eat(&token::CloseDelim(token::Bracket)) {
2603                     // Empty vector.
2604                     ex = ExprKind::Array(Vec::new());
2605                 } else {
2606                     // Nonempty vector.
2607                     let first_expr = self.parse_expr()?;
2608                     if self.eat(&token::Semi) {
2609                         // Repeating array syntax: [ 0; 512 ]
2610                         let count = AnonConst {
2611                             id: ast::DUMMY_NODE_ID,
2612                             value: self.parse_expr()?,
2613                         };
2614                         self.expect(&token::CloseDelim(token::Bracket))?;
2615                         ex = ExprKind::Repeat(first_expr, count);
2616                     } else if self.eat(&token::Comma) {
2617                         // Vector with two or more elements.
2618                         let remaining_exprs = self.parse_seq_to_end(
2619                             &token::CloseDelim(token::Bracket),
2620                             SeqSep::trailing_allowed(token::Comma),
2621                             |p| Ok(p.parse_expr()?)
2622                         )?;
2623                         let mut exprs = vec![first_expr];
2624                         exprs.extend(remaining_exprs);
2625                         ex = ExprKind::Array(exprs);
2626                     } else {
2627                         // Vector with one element.
2628                         self.expect(&token::CloseDelim(token::Bracket))?;
2629                         ex = ExprKind::Array(vec![first_expr]);
2630                     }
2631                 }
2632                 hi = self.prev_span;
2633             }
2634             _ => {
2635                 if self.eat_lt() {
2636                     let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
2637                     hi = path.span;
2638                     return Ok(self.mk_expr(lo.to(hi), ExprKind::Path(Some(qself), path), attrs));
2639                 }
2640                 if self.span.rust_2018() && self.check_keyword(keywords::Async)
2641                 {
2642                     if self.is_async_block() { // check for `async {` and `async move {`
2643                         return self.parse_async_block(attrs);
2644                     } else {
2645                         return self.parse_lambda_expr(attrs);
2646                     }
2647                 }
2648                 if self.check_keyword(keywords::Move) || self.check_keyword(keywords::Static) {
2649                     return self.parse_lambda_expr(attrs);
2650                 }
2651                 if self.eat_keyword(keywords::If) {
2652                     return self.parse_if_expr(attrs);
2653                 }
2654                 if self.eat_keyword(keywords::For) {
2655                     let lo = self.prev_span;
2656                     return self.parse_for_expr(None, lo, attrs);
2657                 }
2658                 if self.eat_keyword(keywords::While) {
2659                     let lo = self.prev_span;
2660                     return self.parse_while_expr(None, lo, attrs);
2661                 }
2662                 if let Some(label) = self.eat_label() {
2663                     let lo = label.ident.span;
2664                     self.expect(&token::Colon)?;
2665                     if self.eat_keyword(keywords::While) {
2666                         return self.parse_while_expr(Some(label), lo, attrs)
2667                     }
2668                     if self.eat_keyword(keywords::For) {
2669                         return self.parse_for_expr(Some(label), lo, attrs)
2670                     }
2671                     if self.eat_keyword(keywords::Loop) {
2672                         return self.parse_loop_expr(Some(label), lo, attrs)
2673                     }
2674                     if self.token == token::OpenDelim(token::Brace) {
2675                         return self.parse_block_expr(Some(label),
2676                                                      lo,
2677                                                      BlockCheckMode::Default,
2678                                                      attrs);
2679                     }
2680                     let msg = "expected `while`, `for`, `loop` or `{` after a label";
2681                     let mut err = self.fatal(msg);
2682                     err.span_label(self.span, msg);
2683                     return Err(err);
2684                 }
2685                 if self.eat_keyword(keywords::Loop) {
2686                     let lo = self.prev_span;
2687                     return self.parse_loop_expr(None, lo, attrs);
2688                 }
2689                 if self.eat_keyword(keywords::Continue) {
2690                     let label = self.eat_label();
2691                     let ex = ExprKind::Continue(label);
2692                     let hi = self.prev_span;
2693                     return Ok(self.mk_expr(lo.to(hi), ex, attrs));
2694                 }
2695                 if self.eat_keyword(keywords::Match) {
2696                     let match_sp = self.prev_span;
2697                     return self.parse_match_expr(attrs).map_err(|mut err| {
2698                         err.span_label(match_sp, "while parsing this match expression");
2699                         err
2700                     });
2701                 }
2702                 if self.eat_keyword(keywords::Unsafe) {
2703                     return self.parse_block_expr(
2704                         None,
2705                         lo,
2706                         BlockCheckMode::Unsafe(ast::UserProvided),
2707                         attrs);
2708                 }
2709                 if self.is_do_catch_block() {
2710                     let mut db = self.fatal("found removed `do catch` syntax");
2711                     db.help("Following RFC #2388, the new non-placeholder syntax is `try`");
2712                     return Err(db);
2713                 }
2714                 if self.is_try_block() {
2715                     let lo = self.span;
2716                     assert!(self.eat_keyword(keywords::Try));
2717                     return self.parse_try_block(lo, attrs);
2718                 }
2719                 if self.eat_keyword(keywords::Return) {
2720                     if self.token.can_begin_expr() {
2721                         let e = self.parse_expr()?;
2722                         hi = e.span;
2723                         ex = ExprKind::Ret(Some(e));
2724                     } else {
2725                         ex = ExprKind::Ret(None);
2726                     }
2727                 } else if self.eat_keyword(keywords::Break) {
2728                     let label = self.eat_label();
2729                     let e = if self.token.can_begin_expr()
2730                                && !(self.token == token::OpenDelim(token::Brace)
2731                                     && self.restrictions.contains(
2732                                            Restrictions::NO_STRUCT_LITERAL)) {
2733                         Some(self.parse_expr()?)
2734                     } else {
2735                         None
2736                     };
2737                     ex = ExprKind::Break(label, e);
2738                     hi = self.prev_span;
2739                 } else if self.eat_keyword(keywords::Yield) {
2740                     if self.token.can_begin_expr() {
2741                         let e = self.parse_expr()?;
2742                         hi = e.span;
2743                         ex = ExprKind::Yield(Some(e));
2744                     } else {
2745                         ex = ExprKind::Yield(None);
2746                     }
2747                 } else if self.token.is_keyword(keywords::Let) {
2748                     // Catch this syntax error here, instead of in `parse_ident`, so
2749                     // that we can explicitly mention that let is not to be used as an expression
2750                     let mut db = self.fatal("expected expression, found statement (`let`)");
2751                     db.span_label(self.span, "expected expression");
2752                     db.note("variable declaration using `let` is a statement");
2753                     return Err(db);
2754                 } else if self.token.is_path_start() {
2755                     let path = self.parse_path(PathStyle::Expr)?;
2756
2757                     // `!`, as an operator, is prefix, so we know this isn't that
2758                     if self.eat(&token::Not) {
2759                         // MACRO INVOCATION expression
2760                         let (delim, tts) = self.expect_delimited_token_tree()?;
2761                         hi = self.prev_span;
2762                         ex = ExprKind::Mac(respan(lo.to(hi), Mac_ { path, tts, delim }));
2763                     } else if self.check(&token::OpenDelim(token::Brace)) {
2764                         if let Some(expr) = self.maybe_parse_struct_expr(lo, &path, &attrs) {
2765                             return expr;
2766                         } else {
2767                             hi = path.span;
2768                             ex = ExprKind::Path(None, path);
2769                         }
2770                     } else {
2771                         hi = path.span;
2772                         ex = ExprKind::Path(None, path);
2773                     }
2774                 } else {
2775                     if !self.unclosed_delims.is_empty() && self.check(&token::Semi) {
2776                         // Don't complain about bare semicolons after unclosed braces
2777                         // recovery in order to keep the error count down. Fixing the
2778                         // delimiters will possibly also fix the bare semicolon found in
2779                         // expression context. For example, silence the following error:
2780                         // ```
2781                         // error: expected expression, found `;`
2782                         //  --> file.rs:2:13
2783                         //   |
2784                         // 2 |     foo(bar(;
2785                         //   |             ^ expected expression
2786                         // ```
2787                         self.bump();
2788                         return Ok(self.mk_expr(self.span, ExprKind::Err, ThinVec::new()));
2789                     }
2790                     match self.parse_literal_maybe_minus() {
2791                         Ok(expr) => {
2792                             hi = expr.span;
2793                             ex = expr.node.clone();
2794                         }
2795                         Err(mut err) => {
2796                             self.cancel(&mut err);
2797                             let msg = format!("expected expression, found {}",
2798                                               self.this_token_descr());
2799                             let mut err = self.fatal(&msg);
2800                             err.span_label(self.span, "expected expression");
2801                             return Err(err);
2802                         }
2803                     }
2804                 }
2805             }
2806         }
2807
2808         let expr = self.mk_expr(lo.to(hi), ex, attrs);
2809         self.maybe_recover_from_bad_qpath(expr, true)
2810     }
2811
2812     fn maybe_parse_struct_expr(
2813         &mut self,
2814         lo: Span,
2815         path: &ast::Path,
2816         attrs: &ThinVec<Attribute>,
2817     ) -> Option<PResult<'a, P<Expr>>> {
2818         let struct_allowed = !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
2819         let certainly_not_a_block = || self.look_ahead(1, |t| t.is_ident()) && (
2820             // `{ ident, ` cannot start a block
2821             self.look_ahead(2, |t| t == &token::Comma) ||
2822             self.look_ahead(2, |t| t == &token::Colon) && (
2823                 // `{ ident: token, ` cannot start a block
2824                 self.look_ahead(4, |t| t == &token::Comma) ||
2825                 // `{ ident: ` cannot start a block unless it's a type ascription `ident: Type`
2826                 self.look_ahead(3, |t| !t.can_begin_type())
2827             )
2828         );
2829
2830         if struct_allowed || certainly_not_a_block() {
2831             // This is a struct literal, but we don't can't accept them here
2832             let expr = self.parse_struct_expr(lo, path.clone(), attrs.clone());
2833             if let (Ok(expr), false) = (&expr, struct_allowed) {
2834                 let mut err = self.diagnostic().struct_span_err(
2835                     expr.span,
2836                     "struct literals are not allowed here",
2837                 );
2838                 err.multipart_suggestion(
2839                     "surround the struct literal with parenthesis",
2840                     vec![
2841                         (lo.shrink_to_lo(), "(".to_string()),
2842                         (expr.span.shrink_to_hi(), ")".to_string()),
2843                     ],
2844                     Applicability::MachineApplicable,
2845                 );
2846                 err.emit();
2847             }
2848             return Some(expr);
2849         }
2850         None
2851     }
2852
2853     fn parse_struct_expr(&mut self, lo: Span, pth: ast::Path, mut attrs: ThinVec<Attribute>)
2854                          -> PResult<'a, P<Expr>> {
2855         let struct_sp = lo.to(self.prev_span);
2856         self.bump();
2857         let mut fields = Vec::new();
2858         let mut base = None;
2859
2860         attrs.extend(self.parse_inner_attributes()?);
2861
2862         while self.token != token::CloseDelim(token::Brace) {
2863             if self.eat(&token::DotDot) {
2864                 let exp_span = self.prev_span;
2865                 match self.parse_expr() {
2866                     Ok(e) => {
2867                         base = Some(e);
2868                     }
2869                     Err(mut e) => {
2870                         e.emit();
2871                         self.recover_stmt();
2872                     }
2873                 }
2874                 if self.token == token::Comma {
2875                     let mut err = self.sess.span_diagnostic.mut_span_err(
2876                         exp_span.to(self.prev_span),
2877                         "cannot use a comma after the base struct",
2878                     );
2879                     err.span_suggestion_short(
2880                         self.span,
2881                         "remove this comma",
2882                         String::new(),
2883                         Applicability::MachineApplicable
2884                     );
2885                     err.note("the base struct must always be the last field");
2886                     err.emit();
2887                     self.recover_stmt();
2888                 }
2889                 break;
2890             }
2891
2892             let mut recovery_field = None;
2893             if let token::Ident(ident, _) = self.token {
2894                 if !self.token.is_reserved_ident() && self.look_ahead(1, |t| *t == token::Colon) {
2895                     // Use in case of error after field-looking code: `S { foo: () with a }`
2896                     let mut ident = ident.clone();
2897                     ident.span = self.span;
2898                     recovery_field = Some(ast::Field {
2899                         ident,
2900                         span: self.span,
2901                         expr: self.mk_expr(self.span, ExprKind::Err, ThinVec::new()),
2902                         is_shorthand: false,
2903                         attrs: ThinVec::new(),
2904                     });
2905                 }
2906             }
2907             let mut parsed_field = None;
2908             match self.parse_field() {
2909                 Ok(f) => parsed_field = Some(f),
2910                 Err(mut e) => {
2911                     e.span_label(struct_sp, "while parsing this struct");
2912                     e.emit();
2913
2914                     // If the next token is a comma, then try to parse
2915                     // what comes next as additional fields, rather than
2916                     // bailing out until next `}`.
2917                     if self.token != token::Comma {
2918                         self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2919                         if self.token != token::Comma {
2920                             break;
2921                         }
2922                     }
2923                 }
2924             }
2925
2926             match self.expect_one_of(&[token::Comma],
2927                                      &[token::CloseDelim(token::Brace)]) {
2928                 Ok(_) => if let Some(f) = parsed_field.or(recovery_field) {
2929                     // only include the field if there's no parse error for the field name
2930                     fields.push(f);
2931                 }
2932                 Err(mut e) => {
2933                     if let Some(f) = recovery_field {
2934                         fields.push(f);
2935                     }
2936                     e.span_label(struct_sp, "while parsing this struct");
2937                     e.emit();
2938                     self.recover_stmt_(SemiColonMode::Comma, BlockMode::Ignore);
2939                     self.eat(&token::Comma);
2940                 }
2941             }
2942         }
2943
2944         let span = lo.to(self.span);
2945         self.expect(&token::CloseDelim(token::Brace))?;
2946         return Ok(self.mk_expr(span, ExprKind::Struct(pth, fields, base), attrs));
2947     }
2948
2949     fn parse_or_use_outer_attributes(&mut self,
2950                                      already_parsed_attrs: Option<ThinVec<Attribute>>)
2951                                      -> PResult<'a, ThinVec<Attribute>> {
2952         if let Some(attrs) = already_parsed_attrs {
2953             Ok(attrs)
2954         } else {
2955             self.parse_outer_attributes().map(|a| a.into())
2956         }
2957     }
2958
2959     /// Parses a block or unsafe block.
2960     fn parse_block_expr(&mut self, opt_label: Option<Label>,
2961                             lo: Span, blk_mode: BlockCheckMode,
2962                             outer_attrs: ThinVec<Attribute>)
2963                             -> PResult<'a, P<Expr>> {
2964         self.expect(&token::OpenDelim(token::Brace))?;
2965
2966         let mut attrs = outer_attrs;
2967         attrs.extend(self.parse_inner_attributes()?);
2968
2969         let blk = self.parse_block_tail(lo, blk_mode)?;
2970         return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, opt_label), attrs));
2971     }
2972
2973     /// Parses `a.b` or `a(13)` or `a[4]` or just `a`.
2974     fn parse_dot_or_call_expr(&mut self,
2975                                   already_parsed_attrs: Option<ThinVec<Attribute>>)
2976                                   -> PResult<'a, P<Expr>> {
2977         let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
2978
2979         let b = self.parse_bottom_expr();
2980         let (span, b) = self.interpolated_or_expr_span(b)?;
2981         self.parse_dot_or_call_expr_with(b, span, attrs)
2982     }
2983
2984     fn parse_dot_or_call_expr_with(&mut self,
2985                                        e0: P<Expr>,
2986                                        lo: Span,
2987                                        mut attrs: ThinVec<Attribute>)
2988                                        -> PResult<'a, P<Expr>> {
2989         // Stitch the list of outer attributes onto the return value.
2990         // A little bit ugly, but the best way given the current code
2991         // structure
2992         self.parse_dot_or_call_expr_with_(e0, lo)
2993         .map(|expr|
2994             expr.map(|mut expr| {
2995                 attrs.extend::<Vec<_>>(expr.attrs.into());
2996                 expr.attrs = attrs;
2997                 match expr.node {
2998                     ExprKind::If(..) | ExprKind::IfLet(..) => {
2999                         if !expr.attrs.is_empty() {
3000                             // Just point to the first attribute in there...
3001                             let span = expr.attrs[0].span;
3002
3003                             self.span_err(span,
3004                                 "attributes are not yet allowed on `if` \
3005                                 expressions");
3006                         }
3007                     }
3008                     _ => {}
3009                 }
3010                 expr
3011             })
3012         )
3013     }
3014
3015     // Assuming we have just parsed `.`, continue parsing into an expression.
3016     fn parse_dot_suffix(&mut self, self_arg: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3017         let segment = self.parse_path_segment(PathStyle::Expr)?;
3018         self.check_trailing_angle_brackets(&segment, token::OpenDelim(token::Paren));
3019
3020         Ok(match self.token {
3021             token::OpenDelim(token::Paren) => {
3022                 // Method call `expr.f()`
3023                 let mut args = self.parse_unspanned_seq(
3024                     &token::OpenDelim(token::Paren),
3025                     &token::CloseDelim(token::Paren),
3026                     SeqSep::trailing_allowed(token::Comma),
3027                     |p| Ok(p.parse_expr()?)
3028                 )?;
3029                 args.insert(0, self_arg);
3030
3031                 let span = lo.to(self.prev_span);
3032                 self.mk_expr(span, ExprKind::MethodCall(segment, args), ThinVec::new())
3033             }
3034             _ => {
3035                 // Field access `expr.f`
3036                 if let Some(args) = segment.args {
3037                     self.span_err(args.span(),
3038                                   "field expressions may not have generic arguments");
3039                 }
3040
3041                 let span = lo.to(self.prev_span);
3042                 self.mk_expr(span, ExprKind::Field(self_arg, segment.ident), ThinVec::new())
3043             }
3044         })
3045     }
3046
3047     /// This function checks if there are trailing angle brackets and produces
3048     /// a diagnostic to suggest removing them.
3049     ///
3050     /// ```ignore (diagnostic)
3051     /// let _ = vec![1, 2, 3].into_iter().collect::<Vec<usize>>>>();
3052     ///                                                        ^^ help: remove extra angle brackets
3053     /// ```
3054     fn check_trailing_angle_brackets(&mut self, segment: &PathSegment, end: token::Token) {
3055         // This function is intended to be invoked after parsing a path segment where there are two
3056         // cases:
3057         //
3058         // 1. A specific token is expected after the path segment.
3059         //    eg. `x.foo(`, `x.foo::<u32>(` (parenthesis - method call),
3060         //        `Foo::`, or `Foo::<Bar>::` (mod sep - continued path).
3061         // 2. No specific token is expected after the path segment.
3062         //    eg. `x.foo` (field access)
3063         //
3064         // This function is called after parsing `.foo` and before parsing the token `end` (if
3065         // present). This includes any angle bracket arguments, such as `.foo::<u32>` or
3066         // `Foo::<Bar>`.
3067
3068         // We only care about trailing angle brackets if we previously parsed angle bracket
3069         // arguments. This helps stop us incorrectly suggesting that extra angle brackets be
3070         // removed in this case:
3071         //
3072         // `x.foo >> (3)` (where `x.foo` is a `u32` for example)
3073         //
3074         // This case is particularly tricky as we won't notice it just looking at the tokens -
3075         // it will appear the same (in terms of upcoming tokens) as below (since the `::<u32>` will
3076         // have already been parsed):
3077         //
3078         // `x.foo::<u32>>>(3)`
3079         let parsed_angle_bracket_args = segment.args
3080             .as_ref()
3081             .map(|args| args.is_angle_bracketed())
3082             .unwrap_or(false);
3083
3084         debug!(
3085             "check_trailing_angle_brackets: parsed_angle_bracket_args={:?}",
3086             parsed_angle_bracket_args,
3087         );
3088         if !parsed_angle_bracket_args {
3089             return;
3090         }
3091
3092         // Keep the span at the start so we can highlight the sequence of `>` characters to be
3093         // removed.
3094         let lo = self.span;
3095
3096         // We need to look-ahead to see if we have `>` characters without moving the cursor forward
3097         // (since we might have the field access case and the characters we're eating are
3098         // actual operators and not trailing characters - ie `x.foo >> 3`).
3099         let mut position = 0;
3100
3101         // We can encounter `>` or `>>` tokens in any order, so we need to keep track of how
3102         // many of each (so we can correctly pluralize our error messages) and continue to
3103         // advance.
3104         let mut number_of_shr = 0;
3105         let mut number_of_gt = 0;
3106         while self.look_ahead(position, |t| {
3107             trace!("check_trailing_angle_brackets: t={:?}", t);
3108             if *t == token::BinOp(token::BinOpToken::Shr) {
3109                 number_of_shr += 1;
3110                 true
3111             } else if *t == token::Gt {
3112                 number_of_gt += 1;
3113                 true
3114             } else {
3115                 false
3116             }
3117         }) {
3118             position += 1;
3119         }
3120
3121         // If we didn't find any trailing `>` characters, then we have nothing to error about.
3122         debug!(
3123             "check_trailing_angle_brackets: number_of_gt={:?} number_of_shr={:?}",
3124             number_of_gt, number_of_shr,
3125         );
3126         if number_of_gt < 1 && number_of_shr < 1 {
3127             return;
3128         }
3129
3130         // Finally, double check that we have our end token as otherwise this is the
3131         // second case.
3132         if self.look_ahead(position, |t| {
3133             trace!("check_trailing_angle_brackets: t={:?}", t);
3134             *t == end
3135         }) {
3136             // Eat from where we started until the end token so that parsing can continue
3137             // as if we didn't have those extra angle brackets.
3138             self.eat_to_tokens(&[&end]);
3139             let span = lo.until(self.span);
3140
3141             let plural = number_of_gt > 1 || number_of_shr >= 1;
3142             self.diagnostic()
3143                 .struct_span_err(
3144                     span,
3145                     &format!("unmatched angle bracket{}", if plural { "s" } else { "" }),
3146                 )
3147                 .span_suggestion(
3148                     span,
3149                     &format!("remove extra angle bracket{}", if plural { "s" } else { "" }),
3150                     String::new(),
3151                     Applicability::MachineApplicable,
3152                 )
3153                 .emit();
3154         }
3155     }
3156
3157     fn parse_dot_or_call_expr_with_(&mut self, e0: P<Expr>, lo: Span) -> PResult<'a, P<Expr>> {
3158         let mut e = e0;
3159         let mut hi;
3160         loop {
3161             // expr?
3162             while self.eat(&token::Question) {
3163                 let hi = self.prev_span;
3164                 e = self.mk_expr(lo.to(hi), ExprKind::Try(e), ThinVec::new());
3165             }
3166
3167             // expr.f
3168             if self.eat(&token::Dot) {
3169                 match self.token {
3170                     token::Ident(..) => {
3171                         e = self.parse_dot_suffix(e, lo)?;
3172                     }
3173                     token::Literal(token::Integer(name), suffix) => {
3174                         let span = self.span;
3175                         self.bump();
3176                         let field = ExprKind::Field(e, Ident::new(name, span));
3177                         e = self.mk_expr(lo.to(span), field, ThinVec::new());
3178
3179                         self.expect_no_suffix(span, "a tuple index", suffix);
3180                     }
3181                     token::Literal(token::Float(n), _suf) => {
3182                       self.bump();
3183                       let fstr = n.as_str();
3184                       let mut err = self.diagnostic()
3185                           .struct_span_err(self.prev_span, &format!("unexpected token: `{}`", n));
3186                       err.span_label(self.prev_span, "unexpected token");
3187                       if fstr.chars().all(|x| "0123456789.".contains(x)) {
3188                           let float = match fstr.parse::<f64>().ok() {
3189                               Some(f) => f,
3190                               None => continue,
3191                           };
3192                           let sugg = pprust::to_string(|s| {
3193                               use crate::print::pprust::PrintState;
3194                               s.popen()?;
3195                               s.print_expr(&e)?;
3196                               s.s.word( ".")?;
3197                               s.print_usize(float.trunc() as usize)?;
3198                               s.pclose()?;
3199                               s.s.word(".")?;
3200                               s.s.word(fstr.splitn(2, ".").last().unwrap().to_string())
3201                           });
3202                           err.span_suggestion(
3203                               lo.to(self.prev_span),
3204                               "try parenthesizing the first index",
3205                               sugg,
3206                               Applicability::MachineApplicable
3207                           );
3208                       }
3209                       return Err(err);
3210
3211                     }
3212                     _ => {
3213                         // FIXME Could factor this out into non_fatal_unexpected or something.
3214                         let actual = self.this_token_to_string();
3215                         self.span_err(self.span, &format!("unexpected token: `{}`", actual));
3216                     }
3217                 }
3218                 continue;
3219             }
3220             if self.expr_is_complete(&e) { break; }
3221             match self.token {
3222                 // expr(...)
3223                 token::OpenDelim(token::Paren) => {
3224                     let seq = self.parse_unspanned_seq(
3225                         &token::OpenDelim(token::Paren),
3226                         &token::CloseDelim(token::Paren),
3227                         SeqSep::trailing_allowed(token::Comma),
3228                         |p| Ok(p.parse_expr()?)
3229                     ).map(|es| {
3230                         let nd = self.mk_call(e, es);
3231                         let hi = self.prev_span;
3232                         self.mk_expr(lo.to(hi), nd, ThinVec::new())
3233                     });
3234                     e = self.recover_seq_parse_error(token::Paren, lo, seq);
3235                 }
3236
3237                 // expr[...]
3238                 // Could be either an index expression or a slicing expression.
3239                 token::OpenDelim(token::Bracket) => {
3240                     self.bump();
3241                     let ix = self.parse_expr()?;
3242                     hi = self.span;
3243                     self.expect(&token::CloseDelim(token::Bracket))?;
3244                     let index = self.mk_index(e, ix);
3245                     e = self.mk_expr(lo.to(hi), index, ThinVec::new())
3246                 }
3247                 _ => return Ok(e)
3248             }
3249         }
3250         return Ok(e);
3251     }
3252
3253     fn recover_seq_parse_error(
3254         &mut self,
3255         delim: token::DelimToken,
3256         lo: Span,
3257         result: PResult<'a, P<Expr>>,
3258     ) -> P<Expr> {
3259         match result {
3260             Ok(x) => x,
3261             Err(mut err) => {
3262                 err.emit();
3263                 // recover from parse error
3264                 self.consume_block(delim);
3265                 self.mk_expr(lo.to(self.prev_span), ExprKind::Err, ThinVec::new())
3266             }
3267         }
3268     }
3269
3270     crate fn process_potential_macro_variable(&mut self) {
3271         let (token, span) = match self.token {
3272             token::Dollar if self.span.ctxt() != syntax_pos::hygiene::SyntaxContext::empty() &&
3273                              self.look_ahead(1, |t| t.is_ident()) => {
3274                 self.bump();
3275                 let name = match self.token {
3276                     token::Ident(ident, _) => ident,
3277                     _ => unreachable!()
3278                 };
3279                 let mut err = self.fatal(&format!("unknown macro variable `{}`", name));
3280                 err.span_label(self.span, "unknown macro variable");
3281                 err.emit();
3282                 self.bump();
3283                 return
3284             }
3285             token::Interpolated(ref nt) => {
3286                 self.meta_var_span = Some(self.span);
3287                 // Interpolated identifier and lifetime tokens are replaced with usual identifier
3288                 // and lifetime tokens, so the former are never encountered during normal parsing.
3289                 match **nt {
3290                     token::NtIdent(ident, is_raw) => (token::Ident(ident, is_raw), ident.span),
3291                     token::NtLifetime(ident) => (token::Lifetime(ident), ident.span),
3292                     _ => return,
3293                 }
3294             }
3295             _ => return,
3296         };
3297         self.token = token;
3298         self.span = span;
3299     }
3300
3301     /// Parses a single token tree from the input.
3302     crate fn parse_token_tree(&mut self) -> TokenTree {
3303         match self.token {
3304             token::OpenDelim(..) => {
3305                 let frame = mem::replace(&mut self.token_cursor.frame,
3306                                          self.token_cursor.stack.pop().unwrap());
3307                 self.span = frame.span.entire();
3308                 self.bump();
3309                 TokenTree::Delimited(
3310                     frame.span,
3311                     frame.delim,
3312                     frame.tree_cursor.stream.into(),
3313                 )
3314             },
3315             token::CloseDelim(_) | token::Eof => unreachable!(),
3316             _ => {
3317                 let (token, span) = (mem::replace(&mut self.token, token::Whitespace), self.span);
3318                 self.bump();
3319                 TokenTree::Token(span, token)
3320             }
3321         }
3322     }
3323
3324     // parse a stream of tokens into a list of TokenTree's,
3325     // up to EOF.
3326     pub fn parse_all_token_trees(&mut self) -> PResult<'a, Vec<TokenTree>> {
3327         let mut tts = Vec::new();
3328         while self.token != token::Eof {
3329             tts.push(self.parse_token_tree());
3330         }
3331         Ok(tts)
3332     }
3333
3334     pub fn parse_tokens(&mut self) -> TokenStream {
3335         let mut result = Vec::new();
3336         loop {
3337             match self.token {
3338                 token::Eof | token::CloseDelim(..) => break,
3339                 _ => result.push(self.parse_token_tree().into()),
3340             }
3341         }
3342         TokenStream::new(result)
3343     }
3344
3345     /// Parse a prefix-unary-operator expr
3346     fn parse_prefix_expr(&mut self,
3347                              already_parsed_attrs: Option<ThinVec<Attribute>>)
3348                              -> PResult<'a, P<Expr>> {
3349         let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3350         let lo = self.span;
3351         // Note: when adding new unary operators, don't forget to adjust Token::can_begin_expr()
3352         let (hi, ex) = match self.token {
3353             token::Not => {
3354                 self.bump();
3355                 let e = self.parse_prefix_expr(None);
3356                 let (span, e) = self.interpolated_or_expr_span(e)?;
3357                 (lo.to(span), self.mk_unary(UnOp::Not, e))
3358             }
3359             // Suggest `!` for bitwise negation when encountering a `~`
3360             token::Tilde => {
3361                 self.bump();
3362                 let e = self.parse_prefix_expr(None);
3363                 let (span, e) = self.interpolated_or_expr_span(e)?;
3364                 let span_of_tilde = lo;
3365                 let mut err = self.diagnostic()
3366                     .struct_span_err(span_of_tilde, "`~` cannot be used as a unary operator");
3367                 err.span_suggestion_short(
3368                     span_of_tilde,
3369                     "use `!` to perform bitwise negation",
3370                     "!".to_owned(),
3371                     Applicability::MachineApplicable
3372                 );
3373                 err.emit();
3374                 (lo.to(span), self.mk_unary(UnOp::Not, e))
3375             }
3376             token::BinOp(token::Minus) => {
3377                 self.bump();
3378                 let e = self.parse_prefix_expr(None);
3379                 let (span, e) = self.interpolated_or_expr_span(e)?;
3380                 (lo.to(span), self.mk_unary(UnOp::Neg, e))
3381             }
3382             token::BinOp(token::Star) => {
3383                 self.bump();
3384                 let e = self.parse_prefix_expr(None);
3385                 let (span, e) = self.interpolated_or_expr_span(e)?;
3386                 (lo.to(span), self.mk_unary(UnOp::Deref, e))
3387             }
3388             token::BinOp(token::And) | token::AndAnd => {
3389                 self.expect_and()?;
3390                 let m = self.parse_mutability();
3391                 let e = self.parse_prefix_expr(None);
3392                 let (span, e) = self.interpolated_or_expr_span(e)?;
3393                 (lo.to(span), ExprKind::AddrOf(m, e))
3394             }
3395             token::Ident(..) if self.token.is_keyword(keywords::In) => {
3396                 self.bump();
3397                 let place = self.parse_expr_res(
3398                     Restrictions::NO_STRUCT_LITERAL,
3399                     None,
3400                 )?;
3401                 let blk = self.parse_block()?;
3402                 let span = blk.span;
3403                 let blk_expr = self.mk_expr(span, ExprKind::Block(blk, None), ThinVec::new());
3404                 (lo.to(span), ExprKind::ObsoleteInPlace(place, blk_expr))
3405             }
3406             token::Ident(..) if self.token.is_keyword(keywords::Box) => {
3407                 self.bump();
3408                 let e = self.parse_prefix_expr(None);
3409                 let (span, e) = self.interpolated_or_expr_span(e)?;
3410                 (lo.to(span), ExprKind::Box(e))
3411             }
3412             token::Ident(..) if self.token.is_ident_named("not") => {
3413                 // `not` is just an ordinary identifier in Rust-the-language,
3414                 // but as `rustc`-the-compiler, we can issue clever diagnostics
3415                 // for confused users who really want to say `!`
3416                 let token_cannot_continue_expr = |t: &token::Token| match *t {
3417                     // These tokens can start an expression after `!`, but
3418                     // can't continue an expression after an ident
3419                     token::Ident(ident, is_raw) => token::ident_can_begin_expr(ident, is_raw),
3420                     token::Literal(..) | token::Pound => true,
3421                     token::Interpolated(ref nt) => match **nt {
3422                         token::NtIdent(..) | token::NtExpr(..) |
3423                         token::NtBlock(..) | token::NtPath(..) => true,
3424                         _ => false,
3425                     },
3426                     _ => false
3427                 };
3428                 let cannot_continue_expr = self.look_ahead(1, token_cannot_continue_expr);
3429                 if cannot_continue_expr {
3430                     self.bump();
3431                     // Emit the error ...
3432                     let mut err = self.diagnostic()
3433                         .struct_span_err(self.span,
3434                                          &format!("unexpected {} after identifier",
3435                                                   self.this_token_descr()));
3436                     // span the `not` plus trailing whitespace to avoid
3437                     // trailing whitespace after the `!` in our suggestion
3438                     let to_replace = self.sess.source_map()
3439                         .span_until_non_whitespace(lo.to(self.span));
3440                     err.span_suggestion_short(
3441                         to_replace,
3442                         "use `!` to perform logical negation",
3443                         "!".to_owned(),
3444                         Applicability::MachineApplicable
3445                     );
3446                     err.emit();
3447                     // —and recover! (just as if we were in the block
3448                     // for the `token::Not` arm)
3449                     let e = self.parse_prefix_expr(None);
3450                     let (span, e) = self.interpolated_or_expr_span(e)?;
3451                     (lo.to(span), self.mk_unary(UnOp::Not, e))
3452                 } else {
3453                     return self.parse_dot_or_call_expr(Some(attrs));
3454                 }
3455             }
3456             _ => { return self.parse_dot_or_call_expr(Some(attrs)); }
3457         };
3458         return Ok(self.mk_expr(lo.to(hi), ex, attrs));
3459     }
3460
3461     /// Parses an associative expression.
3462     ///
3463     /// This parses an expression accounting for associativity and precedence of the operators in
3464     /// the expression.
3465     #[inline]
3466     fn parse_assoc_expr(&mut self,
3467                             already_parsed_attrs: Option<ThinVec<Attribute>>)
3468                             -> PResult<'a, P<Expr>> {
3469         self.parse_assoc_expr_with(0, already_parsed_attrs.into())
3470     }
3471
3472     /// Parses an associative expression with operators of at least `min_prec` precedence.
3473     fn parse_assoc_expr_with(&mut self,
3474                                  min_prec: usize,
3475                                  lhs: LhsExpr)
3476                                  -> PResult<'a, P<Expr>> {
3477         let mut lhs = if let LhsExpr::AlreadyParsed(expr) = lhs {
3478             expr
3479         } else {
3480             let attrs = match lhs {
3481                 LhsExpr::AttributesParsed(attrs) => Some(attrs),
3482                 _ => None,
3483             };
3484             if [token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token) {
3485                 return self.parse_prefix_range_expr(attrs);
3486             } else {
3487                 self.parse_prefix_expr(attrs)?
3488             }
3489         };
3490
3491         if self.expr_is_complete(&lhs) {
3492             // Semi-statement forms are odd. See https://github.com/rust-lang/rust/issues/29071
3493             return Ok(lhs);
3494         }
3495         self.expected_tokens.push(TokenType::Operator);
3496         while let Some(op) = AssocOp::from_token(&self.token) {
3497
3498             // Adjust the span for interpolated LHS to point to the `$lhs` token and not to what
3499             // it refers to. Interpolated identifiers are unwrapped early and never show up here
3500             // as `PrevTokenKind::Interpolated` so if LHS is a single identifier we always process
3501             // it as "interpolated", it doesn't change the answer for non-interpolated idents.
3502             let lhs_span = match (self.prev_token_kind, &lhs.node) {
3503                 (PrevTokenKind::Interpolated, _) => self.prev_span,
3504                 (PrevTokenKind::Ident, &ExprKind::Path(None, ref path))
3505                     if path.segments.len() == 1 => self.prev_span,
3506                 _ => lhs.span,
3507             };
3508
3509             let cur_op_span = self.span;
3510             let restrictions = if op.is_assign_like() {
3511                 self.restrictions & Restrictions::NO_STRUCT_LITERAL
3512             } else {
3513                 self.restrictions
3514             };
3515             if op.precedence() < min_prec {
3516                 break;
3517             }
3518             // Check for deprecated `...` syntax
3519             if self.token == token::DotDotDot && op == AssocOp::DotDotEq {
3520                 self.err_dotdotdot_syntax(self.span);
3521             }
3522
3523             self.bump();
3524             if op.is_comparison() {
3525                 self.check_no_chained_comparison(&lhs, &op);
3526             }
3527             // Special cases:
3528             if op == AssocOp::As {
3529                 lhs = self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Cast)?;
3530                 continue
3531             } else if op == AssocOp::Colon {
3532                 let maybe_path = self.could_ascription_be_path(&lhs.node);
3533                 let next_sp = self.span;
3534
3535                 lhs = match self.parse_assoc_op_cast(lhs, lhs_span, ExprKind::Type) {
3536                     Ok(lhs) => lhs,
3537                     Err(mut err) => {
3538                         self.bad_type_ascription(
3539                             &mut err,
3540                             lhs_span,
3541                             cur_op_span,
3542                             next_sp,
3543                             maybe_path,
3544                         );
3545                         return Err(err);
3546                     }
3547                 };
3548                 continue
3549             } else if op == AssocOp::DotDot || op == AssocOp::DotDotEq {
3550                 // If we didn’t have to handle `x..`/`x..=`, it would be pretty easy to
3551                 // generalise it to the Fixity::None code.
3552                 //
3553                 // We have 2 alternatives here: `x..y`/`x..=y` and `x..`/`x..=` The other
3554                 // two variants are handled with `parse_prefix_range_expr` call above.
3555                 let rhs = if self.is_at_start_of_range_notation_rhs() {
3556                     Some(self.parse_assoc_expr_with(op.precedence() + 1,
3557                                                     LhsExpr::NotYetParsed)?)
3558                 } else {
3559                     None
3560                 };
3561                 let (lhs_span, rhs_span) = (lhs.span, if let Some(ref x) = rhs {
3562                     x.span
3563                 } else {
3564                     cur_op_span
3565                 });
3566                 let limits = if op == AssocOp::DotDot {
3567                     RangeLimits::HalfOpen
3568                 } else {
3569                     RangeLimits::Closed
3570                 };
3571
3572                 let r = self.mk_range(Some(lhs), rhs, limits)?;
3573                 lhs = self.mk_expr(lhs_span.to(rhs_span), r, ThinVec::new());
3574                 break
3575             }
3576
3577             let rhs = match op.fixity() {
3578                 Fixity::Right => self.with_res(
3579                     restrictions - Restrictions::STMT_EXPR,
3580                     |this| {
3581                         this.parse_assoc_expr_with(op.precedence(),
3582                             LhsExpr::NotYetParsed)
3583                 }),
3584                 Fixity::Left => self.with_res(
3585                     restrictions - Restrictions::STMT_EXPR,
3586                     |this| {
3587                         this.parse_assoc_expr_with(op.precedence() + 1,
3588                             LhsExpr::NotYetParsed)
3589                 }),
3590                 // We currently have no non-associative operators that are not handled above by
3591                 // the special cases. The code is here only for future convenience.
3592                 Fixity::None => self.with_res(
3593                     restrictions - Restrictions::STMT_EXPR,
3594                     |this| {
3595                         this.parse_assoc_expr_with(op.precedence() + 1,
3596                             LhsExpr::NotYetParsed)
3597                 }),
3598             }?;
3599
3600             // Make sure that the span of the parent node is larger than the span of lhs and rhs,
3601             // including the attributes.
3602             let lhs_span = lhs
3603                 .attrs
3604                 .iter()
3605                 .filter(|a| a.style == AttrStyle::Outer)
3606                 .next()
3607                 .map_or(lhs_span, |a| a.span);
3608             let span = lhs_span.to(rhs.span);
3609             lhs = match op {
3610                 AssocOp::Add | AssocOp::Subtract | AssocOp::Multiply | AssocOp::Divide |
3611                 AssocOp::Modulus | AssocOp::LAnd | AssocOp::LOr | AssocOp::BitXor |
3612                 AssocOp::BitAnd | AssocOp::BitOr | AssocOp::ShiftLeft | AssocOp::ShiftRight |
3613                 AssocOp::Equal | AssocOp::Less | AssocOp::LessEqual | AssocOp::NotEqual |
3614                 AssocOp::Greater | AssocOp::GreaterEqual => {
3615                     let ast_op = op.to_ast_binop().unwrap();
3616                     let binary = self.mk_binary(source_map::respan(cur_op_span, ast_op), lhs, rhs);
3617                     self.mk_expr(span, binary, ThinVec::new())
3618                 }
3619                 AssocOp::Assign =>
3620                     self.mk_expr(span, ExprKind::Assign(lhs, rhs), ThinVec::new()),
3621                 AssocOp::ObsoleteInPlace =>
3622                     self.mk_expr(span, ExprKind::ObsoleteInPlace(lhs, rhs), ThinVec::new()),
3623                 AssocOp::AssignOp(k) => {
3624                     let aop = match k {
3625                         token::Plus =>    BinOpKind::Add,
3626                         token::Minus =>   BinOpKind::Sub,
3627                         token::Star =>    BinOpKind::Mul,
3628                         token::Slash =>   BinOpKind::Div,
3629                         token::Percent => BinOpKind::Rem,
3630                         token::Caret =>   BinOpKind::BitXor,
3631                         token::And =>     BinOpKind::BitAnd,
3632                         token::Or =>      BinOpKind::BitOr,
3633                         token::Shl =>     BinOpKind::Shl,
3634                         token::Shr =>     BinOpKind::Shr,
3635                     };
3636                     let aopexpr = self.mk_assign_op(source_map::respan(cur_op_span, aop), lhs, rhs);
3637                     self.mk_expr(span, aopexpr, ThinVec::new())
3638                 }
3639                 AssocOp::As | AssocOp::Colon | AssocOp::DotDot | AssocOp::DotDotEq => {
3640                     self.bug("AssocOp should have been handled by special case")
3641                 }
3642             };
3643
3644             if op.fixity() == Fixity::None { break }
3645         }
3646         Ok(lhs)
3647     }
3648
3649     fn could_ascription_be_path(&self, node: &ast::ExprKind) -> bool {
3650         self.token.is_ident() &&
3651             if let ast::ExprKind::Path(..) = node { true } else { false } &&
3652             !self.token.is_reserved_ident() &&           // v `foo:bar(baz)`
3653             self.look_ahead(1, |t| t == &token::OpenDelim(token::Paren)) ||
3654             self.look_ahead(1, |t| t == &token::Lt) &&     // `foo:bar<baz`
3655             self.look_ahead(2, |t| t.is_ident()) ||
3656             self.look_ahead(1, |t| t == &token::Colon) &&  // `foo:bar:baz`
3657             self.look_ahead(2, |t| t.is_ident()) ||
3658             self.look_ahead(1, |t| t == &token::ModSep) &&  // `foo:bar::baz`
3659             self.look_ahead(2, |t| t.is_ident())
3660     }
3661
3662     fn bad_type_ascription(
3663         &self,
3664         err: &mut DiagnosticBuilder<'a>,
3665         lhs_span: Span,
3666         cur_op_span: Span,
3667         next_sp: Span,
3668         maybe_path: bool,
3669     ) {
3670         err.span_label(self.span, "expecting a type here because of type ascription");
3671         let cm = self.sess.source_map();
3672         let next_pos = cm.lookup_char_pos(next_sp.lo());
3673         let op_pos = cm.lookup_char_pos(cur_op_span.hi());
3674         if op_pos.line != next_pos.line {
3675             err.span_suggestion(
3676                 cur_op_span,
3677                 "try using a semicolon",
3678                 ";".to_string(),
3679                 Applicability::MaybeIncorrect,
3680             );
3681         } else {
3682             if maybe_path {
3683                 err.span_suggestion(
3684                     cur_op_span,
3685                     "maybe you meant to write a path separator here",
3686                     "::".to_string(),
3687                     Applicability::MaybeIncorrect,
3688                 );
3689             } else {
3690                 err.note("type ascription is a nightly-only feature that lets \
3691                           you annotate an expression with a type: `<expr>: <type>`");
3692                 err.span_note(
3693                     lhs_span,
3694                     "this expression expects an ascribed type after the colon",
3695                 );
3696                 err.help("this might be indicative of a syntax error elsewhere");
3697             }
3698         }
3699     }
3700
3701     fn parse_assoc_op_cast(&mut self, lhs: P<Expr>, lhs_span: Span,
3702                            expr_kind: fn(P<Expr>, P<Ty>) -> ExprKind)
3703                            -> PResult<'a, P<Expr>> {
3704         let mk_expr = |this: &mut Self, rhs: P<Ty>| {
3705             this.mk_expr(lhs_span.to(rhs.span), expr_kind(lhs, rhs), ThinVec::new())
3706         };
3707
3708         // Save the state of the parser before parsing type normally, in case there is a
3709         // LessThan comparison after this cast.
3710         let parser_snapshot_before_type = self.clone();
3711         match self.parse_ty_no_plus() {
3712             Ok(rhs) => {
3713                 Ok(mk_expr(self, rhs))
3714             }
3715             Err(mut type_err) => {
3716                 // Rewind to before attempting to parse the type with generics, to recover
3717                 // from situations like `x as usize < y` in which we first tried to parse
3718                 // `usize < y` as a type with generic arguments.
3719                 let parser_snapshot_after_type = self.clone();
3720                 mem::replace(self, parser_snapshot_before_type);
3721
3722                 match self.parse_path(PathStyle::Expr) {
3723                     Ok(path) => {
3724                         let (op_noun, op_verb) = match self.token {
3725                             token::Lt => ("comparison", "comparing"),
3726                             token::BinOp(token::Shl) => ("shift", "shifting"),
3727                             _ => {
3728                                 // We can end up here even without `<` being the next token, for
3729                                 // example because `parse_ty_no_plus` returns `Err` on keywords,
3730                                 // but `parse_path` returns `Ok` on them due to error recovery.
3731                                 // Return original error and parser state.
3732                                 mem::replace(self, parser_snapshot_after_type);
3733                                 return Err(type_err);
3734                             }
3735                         };
3736
3737                         // Successfully parsed the type path leaving a `<` yet to parse.
3738                         type_err.cancel();
3739
3740                         // Report non-fatal diagnostics, keep `x as usize` as an expression
3741                         // in AST and continue parsing.
3742                         let msg = format!("`<` is interpreted as a start of generic \
3743                                            arguments for `{}`, not a {}", path, op_noun);
3744                         let mut err = self.sess.span_diagnostic.struct_span_err(self.span, &msg);
3745                         err.span_label(self.look_ahead_span(1).to(parser_snapshot_after_type.span),
3746                                        "interpreted as generic arguments");
3747                         err.span_label(self.span, format!("not interpreted as {}", op_noun));
3748
3749                         let expr = mk_expr(self, P(Ty {
3750                             span: path.span,
3751                             node: TyKind::Path(None, path),
3752                             id: ast::DUMMY_NODE_ID
3753                         }));
3754
3755                         let expr_str = self.sess.source_map().span_to_snippet(expr.span)
3756                                                 .unwrap_or_else(|_| pprust::expr_to_string(&expr));
3757                         err.span_suggestion(
3758                             expr.span,
3759                             &format!("try {} the cast value", op_verb),
3760                             format!("({})", expr_str),
3761                             Applicability::MachineApplicable
3762                         );
3763                         err.emit();
3764
3765                         Ok(expr)
3766                     }
3767                     Err(mut path_err) => {
3768                         // Couldn't parse as a path, return original error and parser state.
3769                         path_err.cancel();
3770                         mem::replace(self, parser_snapshot_after_type);
3771                         Err(type_err)
3772                     }
3773                 }
3774             }
3775         }
3776     }
3777
3778     /// Produce an error if comparison operators are chained (RFC #558).
3779     /// We only need to check lhs, not rhs, because all comparison ops
3780     /// have same precedence and are left-associative
3781     fn check_no_chained_comparison(&mut self, lhs: &Expr, outer_op: &AssocOp) {
3782         debug_assert!(outer_op.is_comparison(),
3783                       "check_no_chained_comparison: {:?} is not comparison",
3784                       outer_op);
3785         match lhs.node {
3786             ExprKind::Binary(op, _, _) if op.node.is_comparison() => {
3787                 // respan to include both operators
3788                 let op_span = op.span.to(self.span);
3789                 let mut err = self.diagnostic().struct_span_err(op_span,
3790                     "chained comparison operators require parentheses");
3791                 if op.node == BinOpKind::Lt &&
3792                     *outer_op == AssocOp::Less ||  // Include `<` to provide this recommendation
3793                     *outer_op == AssocOp::Greater  // even in a case like the following:
3794                 {                                  //     Foo<Bar<Baz<Qux, ()>>>
3795                     err.help(
3796                         "use `::<...>` instead of `<...>` if you meant to specify type arguments");
3797                     err.help("or use `(...)` if you meant to specify fn arguments");
3798                 }
3799                 err.emit();
3800             }
3801             _ => {}
3802         }
3803     }
3804
3805     /// Parse prefix-forms of range notation: `..expr`, `..`, `..=expr`
3806     fn parse_prefix_range_expr(&mut self,
3807                                already_parsed_attrs: Option<ThinVec<Attribute>>)
3808                                -> PResult<'a, P<Expr>> {
3809         // Check for deprecated `...` syntax
3810         if self.token == token::DotDotDot {
3811             self.err_dotdotdot_syntax(self.span);
3812         }
3813
3814         debug_assert!([token::DotDot, token::DotDotDot, token::DotDotEq].contains(&self.token),
3815                       "parse_prefix_range_expr: token {:?} is not DotDot/DotDotEq",
3816                       self.token);
3817         let tok = self.token.clone();
3818         let attrs = self.parse_or_use_outer_attributes(already_parsed_attrs)?;
3819         let lo = self.span;
3820         let mut hi = self.span;
3821         self.bump();
3822         let opt_end = if self.is_at_start_of_range_notation_rhs() {
3823             // RHS must be parsed with more associativity than the dots.
3824             let next_prec = AssocOp::from_token(&tok).unwrap().precedence() + 1;
3825             Some(self.parse_assoc_expr_with(next_prec,
3826                                             LhsExpr::NotYetParsed)
3827                 .map(|x|{
3828                     hi = x.span;
3829                     x
3830                 })?)
3831          } else {
3832             None
3833         };
3834         let limits = if tok == token::DotDot {
3835             RangeLimits::HalfOpen
3836         } else {
3837             RangeLimits::Closed
3838         };
3839
3840         let r = self.mk_range(None, opt_end, limits)?;
3841         Ok(self.mk_expr(lo.to(hi), r, attrs))
3842     }
3843
3844     fn is_at_start_of_range_notation_rhs(&self) -> bool {
3845         if self.token.can_begin_expr() {
3846             // parse `for i in 1.. { }` as infinite loop, not as `for i in (1..{})`.
3847             if self.token == token::OpenDelim(token::Brace) {
3848                 return !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL);
3849             }
3850             true
3851         } else {
3852             false
3853         }
3854     }
3855
3856     /// Parses an `if` or `if let` expression (`if` token already eaten).
3857     fn parse_if_expr(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3858         if self.check_keyword(keywords::Let) {
3859             return self.parse_if_let_expr(attrs);
3860         }
3861         let lo = self.prev_span;
3862         let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3863
3864         // Verify that the parsed `if` condition makes sense as a condition. If it is a block, then
3865         // verify that the last statement is either an implicit return (no `;`) or an explicit
3866         // return. This won't catch blocks with an explicit `return`, but that would be caught by
3867         // the dead code lint.
3868         if self.eat_keyword(keywords::Else) || !cond.returns() {
3869             let sp = self.sess.source_map().next_point(lo);
3870             let mut err = self.diagnostic()
3871                 .struct_span_err(sp, "missing condition for `if` statemement");
3872             err.span_label(sp, "expected if condition here");
3873             return Err(err)
3874         }
3875         let not_block = self.token != token::OpenDelim(token::Brace);
3876         let thn = self.parse_block().map_err(|mut err| {
3877             if not_block {
3878                 err.span_label(lo, "this `if` statement has a condition, but no block");
3879             }
3880             err
3881         })?;
3882         let mut els: Option<P<Expr>> = None;
3883         let mut hi = thn.span;
3884         if self.eat_keyword(keywords::Else) {
3885             let elexpr = self.parse_else_expr()?;
3886             hi = elexpr.span;
3887             els = Some(elexpr);
3888         }
3889         Ok(self.mk_expr(lo.to(hi), ExprKind::If(cond, thn, els), attrs))
3890     }
3891
3892     /// Parses an `if let` expression (`if` token already eaten).
3893     fn parse_if_let_expr(&mut self, attrs: ThinVec<Attribute>)
3894                              -> PResult<'a, P<Expr>> {
3895         let lo = self.prev_span;
3896         self.expect_keyword(keywords::Let)?;
3897         let pats = self.parse_pats()?;
3898         self.expect(&token::Eq)?;
3899         let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3900         let thn = self.parse_block()?;
3901         let (hi, els) = if self.eat_keyword(keywords::Else) {
3902             let expr = self.parse_else_expr()?;
3903             (expr.span, Some(expr))
3904         } else {
3905             (thn.span, None)
3906         };
3907         Ok(self.mk_expr(lo.to(hi), ExprKind::IfLet(pats, expr, thn, els), attrs))
3908     }
3909
3910     /// Parses `move |args| expr`.
3911     fn parse_lambda_expr(&mut self,
3912                              attrs: ThinVec<Attribute>)
3913                              -> PResult<'a, P<Expr>>
3914     {
3915         let lo = self.span;
3916         let movability = if self.eat_keyword(keywords::Static) {
3917             Movability::Static
3918         } else {
3919             Movability::Movable
3920         };
3921         let asyncness = if self.span.rust_2018() {
3922             self.parse_asyncness()
3923         } else {
3924             IsAsync::NotAsync
3925         };
3926         let capture_clause = if self.eat_keyword(keywords::Move) {
3927             CaptureBy::Value
3928         } else {
3929             CaptureBy::Ref
3930         };
3931         let decl = self.parse_fn_block_decl()?;
3932         let decl_hi = self.prev_span;
3933         let body = match decl.output {
3934             FunctionRetTy::Default(_) => {
3935                 let restrictions = self.restrictions - Restrictions::STMT_EXPR;
3936                 self.parse_expr_res(restrictions, None)?
3937             },
3938             _ => {
3939                 // If an explicit return type is given, require a
3940                 // block to appear (RFC 968).
3941                 let body_lo = self.span;
3942                 self.parse_block_expr(None, body_lo, BlockCheckMode::Default, ThinVec::new())?
3943             }
3944         };
3945
3946         Ok(self.mk_expr(
3947             lo.to(body.span),
3948             ExprKind::Closure(capture_clause, asyncness, movability, decl, body, lo.to(decl_hi)),
3949             attrs))
3950     }
3951
3952     // `else` token already eaten
3953     fn parse_else_expr(&mut self) -> PResult<'a, P<Expr>> {
3954         if self.eat_keyword(keywords::If) {
3955             return self.parse_if_expr(ThinVec::new());
3956         } else {
3957             let blk = self.parse_block()?;
3958             return Ok(self.mk_expr(blk.span, ExprKind::Block(blk, None), ThinVec::new()));
3959         }
3960     }
3961
3962     /// Parse a 'for' .. 'in' expression ('for' token already eaten)
3963     fn parse_for_expr(&mut self, opt_label: Option<Label>,
3964                           span_lo: Span,
3965                           mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
3966         // Parse: `for <src_pat> in <src_expr> <src_loop_block>`
3967
3968         let pat = self.parse_top_level_pat()?;
3969         if !self.eat_keyword(keywords::In) {
3970             let in_span = self.prev_span.between(self.span);
3971             let mut err = self.sess.span_diagnostic
3972                 .struct_span_err(in_span, "missing `in` in `for` loop");
3973             err.span_suggestion_short(
3974                 in_span, "try adding `in` here", " in ".into(),
3975                 // has been misleading, at least in the past (closed Issue #48492)
3976                 Applicability::MaybeIncorrect
3977             );
3978             err.emit();
3979         }
3980         let in_span = self.prev_span;
3981         if self.eat_keyword(keywords::In) {
3982             // a common typo: `for _ in in bar {}`
3983             let mut err = self.sess.span_diagnostic.struct_span_err(
3984                 self.prev_span,
3985                 "expected iterable, found keyword `in`",
3986             );
3987             err.span_suggestion_short(
3988                 in_span.until(self.prev_span),
3989                 "remove the duplicated `in`",
3990                 String::new(),
3991                 Applicability::MachineApplicable,
3992             );
3993             err.note("if you meant to use emplacement syntax, it is obsolete (for now, anyway)");
3994             err.note("for more information on the status of emplacement syntax, see <\
3995                       https://github.com/rust-lang/rust/issues/27779#issuecomment-378416911>");
3996             err.emit();
3997         }
3998         let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
3999         let (iattrs, loop_block) = self.parse_inner_attrs_and_block()?;
4000         attrs.extend(iattrs);
4001
4002         let hi = self.prev_span;
4003         Ok(self.mk_expr(span_lo.to(hi), ExprKind::ForLoop(pat, expr, loop_block, opt_label), attrs))
4004     }
4005
4006     /// Parses a `while` or `while let` expression (`while` token already eaten).
4007     fn parse_while_expr(&mut self, opt_label: Option<Label>,
4008                             span_lo: Span,
4009                             mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4010         if self.token.is_keyword(keywords::Let) {
4011             return self.parse_while_let_expr(opt_label, span_lo, attrs);
4012         }
4013         let cond = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4014         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4015         attrs.extend(iattrs);
4016         let span = span_lo.to(body.span);
4017         return Ok(self.mk_expr(span, ExprKind::While(cond, body, opt_label), attrs));
4018     }
4019
4020     /// Parses a `while let` expression (`while` token already eaten).
4021     fn parse_while_let_expr(&mut self, opt_label: Option<Label>,
4022                                 span_lo: Span,
4023                                 mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4024         self.expect_keyword(keywords::Let)?;
4025         let pats = self.parse_pats()?;
4026         self.expect(&token::Eq)?;
4027         let expr = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL, None)?;
4028         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4029         attrs.extend(iattrs);
4030         let span = span_lo.to(body.span);
4031         return Ok(self.mk_expr(span, ExprKind::WhileLet(pats, expr, body, opt_label), attrs));
4032     }
4033
4034     // parse `loop {...}`, `loop` token already eaten
4035     fn parse_loop_expr(&mut self, opt_label: Option<Label>,
4036                            span_lo: Span,
4037                            mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4038         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4039         attrs.extend(iattrs);
4040         let span = span_lo.to(body.span);
4041         Ok(self.mk_expr(span, ExprKind::Loop(body, opt_label), attrs))
4042     }
4043
4044     /// Parses an `async move {...}` expression.
4045     pub fn parse_async_block(&mut self, mut attrs: ThinVec<Attribute>)
4046         -> PResult<'a, P<Expr>>
4047     {
4048         let span_lo = self.span;
4049         self.expect_keyword(keywords::Async)?;
4050         let capture_clause = if self.eat_keyword(keywords::Move) {
4051             CaptureBy::Value
4052         } else {
4053             CaptureBy::Ref
4054         };
4055         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4056         attrs.extend(iattrs);
4057         Ok(self.mk_expr(
4058             span_lo.to(body.span),
4059             ExprKind::Async(capture_clause, ast::DUMMY_NODE_ID, body), attrs))
4060     }
4061
4062     /// Parses a `try {...}` expression (`try` token already eaten).
4063     fn parse_try_block(&mut self, span_lo: Span, mut attrs: ThinVec<Attribute>)
4064         -> PResult<'a, P<Expr>>
4065     {
4066         let (iattrs, body) = self.parse_inner_attrs_and_block()?;
4067         attrs.extend(iattrs);
4068         if self.eat_keyword(keywords::Catch) {
4069             let mut error = self.struct_span_err(self.prev_span,
4070                                                  "keyword `catch` cannot follow a `try` block");
4071             error.help("try using `match` on the result of the `try` block instead");
4072             error.emit();
4073             Err(error)
4074         } else {
4075             Ok(self.mk_expr(span_lo.to(body.span), ExprKind::TryBlock(body), attrs))
4076         }
4077     }
4078
4079     // `match` token already eaten
4080     fn parse_match_expr(&mut self, mut attrs: ThinVec<Attribute>) -> PResult<'a, P<Expr>> {
4081         let match_span = self.prev_span;
4082         let lo = self.prev_span;
4083         let discriminant = self.parse_expr_res(Restrictions::NO_STRUCT_LITERAL,
4084                                                None)?;
4085         if let Err(mut e) = self.expect(&token::OpenDelim(token::Brace)) {
4086             if self.token == token::Token::Semi {
4087                 e.span_suggestion_short(
4088                     match_span,
4089                     "try removing this `match`",
4090                     String::new(),
4091                     Applicability::MaybeIncorrect // speculative
4092                 );
4093             }
4094             return Err(e)
4095         }
4096         attrs.extend(self.parse_inner_attributes()?);
4097
4098         let mut arms: Vec<Arm> = Vec::new();
4099         while self.token != token::CloseDelim(token::Brace) {
4100             match self.parse_arm() {
4101                 Ok(arm) => arms.push(arm),
4102                 Err(mut e) => {
4103                     // Recover by skipping to the end of the block.
4104                     e.emit();
4105                     self.recover_stmt();
4106                     let span = lo.to(self.span);
4107                     if self.token == token::CloseDelim(token::Brace) {
4108                         self.bump();
4109                     }
4110                     return Ok(self.mk_expr(span, ExprKind::Match(discriminant, arms), attrs));
4111                 }
4112             }
4113         }
4114         let hi = self.span;
4115         self.bump();
4116         return Ok(self.mk_expr(lo.to(hi), ExprKind::Match(discriminant, arms), attrs));
4117     }
4118
4119     crate fn parse_arm(&mut self) -> PResult<'a, Arm> {
4120         maybe_whole!(self, NtArm, |x| x);
4121
4122         let attrs = self.parse_outer_attributes()?;
4123         let pats = self.parse_pats()?;
4124         let guard = if self.eat_keyword(keywords::If) {
4125             Some(Guard::If(self.parse_expr()?))
4126         } else {
4127             None
4128         };
4129         let arrow_span = self.span;
4130         self.expect(&token::FatArrow)?;
4131         let arm_start_span = self.span;
4132
4133         let expr = self.parse_expr_res(Restrictions::STMT_EXPR, None)
4134             .map_err(|mut err| {
4135                 err.span_label(arrow_span, "while parsing the `match` arm starting here");
4136                 err
4137             })?;
4138
4139         let require_comma = classify::expr_requires_semi_to_be_stmt(&expr)
4140             && self.token != token::CloseDelim(token::Brace);
4141
4142         if require_comma {
4143             let cm = self.sess.source_map();
4144             self.expect_one_of(&[token::Comma], &[token::CloseDelim(token::Brace)])
4145                 .map_err(|mut err| {
4146                     match (cm.span_to_lines(expr.span), cm.span_to_lines(arm_start_span)) {
4147                         (Ok(ref expr_lines), Ok(ref arm_start_lines))
4148                         if arm_start_lines.lines[0].end_col == expr_lines.lines[0].end_col
4149                             && expr_lines.lines.len() == 2
4150                             && self.token == token::FatArrow => {
4151                             // We check whether there's any trailing code in the parse span,
4152                             // if there isn't, we very likely have the following:
4153                             //
4154                             // X |     &Y => "y"
4155                             //   |        --    - missing comma
4156                             //   |        |
4157                             //   |        arrow_span
4158                             // X |     &X => "x"
4159                             //   |      - ^^ self.span
4160                             //   |      |
4161                             //   |      parsed until here as `"y" & X`
4162                             err.span_suggestion_short(
4163                                 cm.next_point(arm_start_span),
4164                                 "missing a comma here to end this `match` arm",
4165                                 ",".to_owned(),
4166                                 Applicability::MachineApplicable
4167                             );
4168                         }
4169                         _ => {
4170                             err.span_label(arrow_span,
4171                                            "while parsing the `match` arm starting here");
4172                         }
4173                     }
4174                     err
4175                 })?;
4176         } else {
4177             self.eat(&token::Comma);
4178         }
4179
4180         Ok(ast::Arm {
4181             attrs,
4182             pats,
4183             guard,
4184             body: expr,
4185         })
4186     }
4187
4188     /// Parses an expression.
4189     #[inline]
4190     pub fn parse_expr(&mut self) -> PResult<'a, P<Expr>> {
4191         self.parse_expr_res(Restrictions::empty(), None)
4192     }
4193
4194     /// Evaluates the closure with restrictions in place.
4195     ///
4196     /// Afters the closure is evaluated, restrictions are reset.
4197     fn with_res<F, T>(&mut self, r: Restrictions, f: F) -> T
4198         where F: FnOnce(&mut Self) -> T
4199     {
4200         let old = self.restrictions;
4201         self.restrictions = r;
4202         let r = f(self);
4203         self.restrictions = old;
4204         return r;
4205
4206     }
4207
4208     /// Parses an expression, subject to the given restrictions.
4209     #[inline]
4210     fn parse_expr_res(&mut self, r: Restrictions,
4211                           already_parsed_attrs: Option<ThinVec<Attribute>>)
4212                           -> PResult<'a, P<Expr>> {
4213         self.with_res(r, |this| this.parse_assoc_expr(already_parsed_attrs))
4214     }
4215
4216     /// Parses the RHS of a local variable declaration (e.g., '= 14;').
4217     fn parse_initializer(&mut self, skip_eq: bool) -> PResult<'a, Option<P<Expr>>> {
4218         if self.eat(&token::Eq) {
4219             Ok(Some(self.parse_expr()?))
4220         } else if skip_eq {
4221             Ok(Some(self.parse_expr()?))
4222         } else {
4223             Ok(None)
4224         }
4225     }
4226
4227     /// Parses patterns, separated by '|' s.
4228     fn parse_pats(&mut self) -> PResult<'a, Vec<P<Pat>>> {
4229         // Allow a '|' before the pats (RFC 1925 + RFC 2530)
4230         self.eat(&token::BinOp(token::Or));
4231
4232         let mut pats = Vec::new();
4233         loop {
4234             pats.push(self.parse_top_level_pat()?);
4235
4236             if self.token == token::OrOr {
4237                 let mut err = self.struct_span_err(self.span,
4238                                                    "unexpected token `||` after pattern");
4239                 err.span_suggestion(
4240                     self.span,
4241                     "use a single `|` to specify multiple patterns",
4242                     "|".to_owned(),
4243                     Applicability::MachineApplicable
4244                 );
4245                 err.emit();
4246                 self.bump();
4247             } else if self.eat(&token::BinOp(token::Or)) {
4248                 // This is a No-op. Continue the loop to parse the next
4249                 // pattern.
4250             } else {
4251                 return Ok(pats);
4252             }
4253         };
4254     }
4255
4256     // Parses a parenthesized list of patterns like
4257     // `()`, `(p)`, `(p,)`, `(p, q)`, or `(p, .., q)`. Returns:
4258     // - a vector of the patterns that were parsed
4259     // - an option indicating the index of the `..` element
4260     // - a boolean indicating whether a trailing comma was present.
4261     // Trailing commas are significant because (p) and (p,) are different patterns.
4262     fn parse_parenthesized_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4263         self.expect(&token::OpenDelim(token::Paren))?;
4264         let result = match self.parse_pat_list() {
4265             Ok(result) => result,
4266             Err(mut err) => { // recover from parse error in tuple pattern list
4267                 err.emit();
4268                 self.consume_block(token::Paren);
4269                 return Ok((vec![], Some(0), false));
4270             }
4271         };
4272         self.expect(&token::CloseDelim(token::Paren))?;
4273         Ok(result)
4274     }
4275
4276     fn parse_pat_list(&mut self) -> PResult<'a, (Vec<P<Pat>>, Option<usize>, bool)> {
4277         let mut fields = Vec::new();
4278         let mut ddpos = None;
4279         let mut prev_dd_sp = None;
4280         let mut trailing_comma = false;
4281         loop {
4282             if self.eat(&token::DotDot) {
4283                 if ddpos.is_none() {
4284                     ddpos = Some(fields.len());
4285                     prev_dd_sp = Some(self.prev_span);
4286                 } else {
4287                     // Emit a friendly error, ignore `..` and continue parsing
4288                     let mut err = self.struct_span_err(
4289                         self.prev_span,
4290                         "`..` can only be used once per tuple or tuple struct pattern",
4291                     );
4292                     err.span_label(self.prev_span, "can only be used once per pattern");
4293                     if let Some(sp) = prev_dd_sp {
4294                         err.span_label(sp, "previously present here");
4295                     }
4296                     err.emit();
4297                 }
4298             } else if !self.check(&token::CloseDelim(token::Paren)) {
4299                 fields.push(self.parse_pat(None)?);
4300             } else {
4301                 break
4302             }
4303
4304             trailing_comma = self.eat(&token::Comma);
4305             if !trailing_comma {
4306                 break
4307             }
4308         }
4309
4310         if ddpos == Some(fields.len()) && trailing_comma {
4311             // `..` needs to be followed by `)` or `, pat`, `..,)` is disallowed.
4312             let msg = "trailing comma is not permitted after `..`";
4313             self.struct_span_err(self.prev_span, msg)
4314                 .span_label(self.prev_span, msg)
4315                 .emit();
4316         }
4317
4318         Ok((fields, ddpos, trailing_comma))
4319     }
4320
4321     fn parse_pat_vec_elements(
4322         &mut self,
4323     ) -> PResult<'a, (Vec<P<Pat>>, Option<P<Pat>>, Vec<P<Pat>>)> {
4324         let mut before = Vec::new();
4325         let mut slice = None;
4326         let mut after = Vec::new();
4327         let mut first = true;
4328         let mut before_slice = true;
4329
4330         while self.token != token::CloseDelim(token::Bracket) {
4331             if first {
4332                 first = false;
4333             } else {
4334                 self.expect(&token::Comma)?;
4335
4336                 if self.token == token::CloseDelim(token::Bracket)
4337                         && (before_slice || !after.is_empty()) {
4338                     break
4339                 }
4340             }
4341
4342             if before_slice {
4343                 if self.eat(&token::DotDot) {
4344
4345                     if self.check(&token::Comma) ||
4346                             self.check(&token::CloseDelim(token::Bracket)) {
4347                         slice = Some(P(Pat {
4348                             id: ast::DUMMY_NODE_ID,
4349                             node: PatKind::Wild,
4350                             span: self.prev_span,
4351                         }));
4352                         before_slice = false;
4353                     }
4354                     continue
4355                 }
4356             }
4357
4358             let subpat = self.parse_pat(None)?;
4359             if before_slice && self.eat(&token::DotDot) {
4360                 slice = Some(subpat);
4361                 before_slice = false;
4362             } else if before_slice {
4363                 before.push(subpat);
4364             } else {
4365                 after.push(subpat);
4366             }
4367         }
4368
4369         Ok((before, slice, after))
4370     }
4371
4372     fn parse_pat_field(
4373         &mut self,
4374         lo: Span,
4375         attrs: Vec<Attribute>
4376     ) -> PResult<'a, source_map::Spanned<ast::FieldPat>> {
4377         // Check if a colon exists one ahead. This means we're parsing a fieldname.
4378         let hi;
4379         let (subpat, fieldname, is_shorthand) = if self.look_ahead(1, |t| t == &token::Colon) {
4380             // Parsing a pattern of the form "fieldname: pat"
4381             let fieldname = self.parse_field_name()?;
4382             self.bump();
4383             let pat = self.parse_pat(None)?;
4384             hi = pat.span;
4385             (pat, fieldname, false)
4386         } else {
4387             // Parsing a pattern of the form "(box) (ref) (mut) fieldname"
4388             let is_box = self.eat_keyword(keywords::Box);
4389             let boxed_span = self.span;
4390             let is_ref = self.eat_keyword(keywords::Ref);
4391             let is_mut = self.eat_keyword(keywords::Mut);
4392             let fieldname = self.parse_ident()?;
4393             hi = self.prev_span;
4394
4395             let bind_type = match (is_ref, is_mut) {
4396                 (true, true) => BindingMode::ByRef(Mutability::Mutable),
4397                 (true, false) => BindingMode::ByRef(Mutability::Immutable),
4398                 (false, true) => BindingMode::ByValue(Mutability::Mutable),
4399                 (false, false) => BindingMode::ByValue(Mutability::Immutable),
4400             };
4401             let fieldpat = P(Pat {
4402                 id: ast::DUMMY_NODE_ID,
4403                 node: PatKind::Ident(bind_type, fieldname, None),
4404                 span: boxed_span.to(hi),
4405             });
4406
4407             let subpat = if is_box {
4408                 P(Pat {
4409                     id: ast::DUMMY_NODE_ID,
4410                     node: PatKind::Box(fieldpat),
4411                     span: lo.to(hi),
4412                 })
4413             } else {
4414                 fieldpat
4415             };
4416             (subpat, fieldname, true)
4417         };
4418
4419         Ok(source_map::Spanned {
4420             span: lo.to(hi),
4421             node: ast::FieldPat {
4422                 ident: fieldname,
4423                 pat: subpat,
4424                 is_shorthand,
4425                 attrs: attrs.into(),
4426            }
4427         })
4428     }
4429
4430     /// Parses the fields of a struct-like pattern.
4431     fn parse_pat_fields(&mut self) -> PResult<'a, (Vec<source_map::Spanned<ast::FieldPat>>, bool)> {
4432         let mut fields = Vec::new();
4433         let mut etc = false;
4434         let mut ate_comma = true;
4435         let mut delayed_err: Option<DiagnosticBuilder<'a>> = None;
4436         let mut etc_span = None;
4437
4438         while self.token != token::CloseDelim(token::Brace) {
4439             let attrs = self.parse_outer_attributes()?;
4440             let lo = self.span;
4441
4442             // check that a comma comes after every field
4443             if !ate_comma {
4444                 let err = self.struct_span_err(self.prev_span, "expected `,`");
4445                 if let Some(mut delayed) = delayed_err {
4446                     delayed.emit();
4447                 }
4448                 return Err(err);
4449             }
4450             ate_comma = false;
4451
4452             if self.check(&token::DotDot) || self.token == token::DotDotDot {
4453                 etc = true;
4454                 let mut etc_sp = self.span;
4455
4456                 if self.token == token::DotDotDot { // Issue #46718
4457                     // Accept `...` as if it were `..` to avoid further errors
4458                     let mut err = self.struct_span_err(self.span,
4459                                                        "expected field pattern, found `...`");
4460                     err.span_suggestion(
4461                         self.span,
4462                         "to omit remaining fields, use one fewer `.`",
4463                         "..".to_owned(),
4464                         Applicability::MachineApplicable
4465                     );
4466                     err.emit();
4467                 }
4468                 self.bump();  // `..` || `...`
4469
4470                 if self.token == token::CloseDelim(token::Brace) {
4471                     etc_span = Some(etc_sp);
4472                     break;
4473                 }
4474                 let token_str = self.this_token_descr();
4475                 let mut err = self.fatal(&format!("expected `}}`, found {}", token_str));
4476
4477                 err.span_label(self.span, "expected `}`");
4478                 let mut comma_sp = None;
4479                 if self.token == token::Comma { // Issue #49257
4480                     etc_sp = etc_sp.to(self.sess.source_map().span_until_non_whitespace(self.span));
4481                     err.span_label(etc_sp,
4482                                    "`..` must be at the end and cannot have a trailing comma");
4483                     comma_sp = Some(self.span);
4484                     self.bump();
4485                     ate_comma = true;
4486                 }
4487
4488                 etc_span = Some(etc_sp.until(self.span));
4489                 if self.token == token::CloseDelim(token::Brace) {
4490                     // If the struct looks otherwise well formed, recover and continue.
4491                     if let Some(sp) = comma_sp {
4492                         err.span_suggestion_short(
4493                             sp,
4494                             "remove this comma",
4495                             String::new(),
4496                             Applicability::MachineApplicable,
4497                         );
4498                     }
4499                     err.emit();
4500                     break;
4501                 } else if self.token.is_ident() && ate_comma {
4502                     // Accept fields coming after `..,`.
4503                     // This way we avoid "pattern missing fields" errors afterwards.
4504                     // We delay this error until the end in order to have a span for a
4505                     // suggested fix.
4506                     if let Some(mut delayed_err) = delayed_err {
4507                         delayed_err.emit();
4508                         return Err(err);
4509                     } else {
4510                         delayed_err = Some(err);
4511                     }
4512                 } else {
4513                     if let Some(mut err) = delayed_err {
4514                         err.emit();
4515                     }
4516                     return Err(err);
4517                 }
4518             }
4519
4520             fields.push(match self.parse_pat_field(lo, attrs) {
4521                 Ok(field) => field,
4522                 Err(err) => {
4523                     if let Some(mut delayed_err) = delayed_err {
4524                         delayed_err.emit();
4525                     }
4526                     return Err(err);
4527                 }
4528             });
4529             ate_comma = self.eat(&token::Comma);
4530         }
4531
4532         if let Some(mut err) = delayed_err {
4533             if let Some(etc_span) = etc_span {
4534                 err.multipart_suggestion(
4535                     "move the `..` to the end of the field list",
4536                     vec![
4537                         (etc_span, String::new()),
4538                         (self.span, format!("{}.. }}", if ate_comma { "" } else { ", " })),
4539                     ],
4540                     Applicability::MachineApplicable,
4541                 );
4542             }
4543             err.emit();
4544         }
4545         return Ok((fields, etc));
4546     }
4547
4548     fn parse_pat_range_end(&mut self) -> PResult<'a, P<Expr>> {
4549         if self.token.is_path_start() {
4550             let lo = self.span;
4551             let (qself, path) = if self.eat_lt() {
4552                 // Parse a qualified path
4553                 let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4554                 (Some(qself), path)
4555             } else {
4556                 // Parse an unqualified path
4557                 (None, self.parse_path(PathStyle::Expr)?)
4558             };
4559             let hi = self.prev_span;
4560             Ok(self.mk_expr(lo.to(hi), ExprKind::Path(qself, path), ThinVec::new()))
4561         } else {
4562             self.parse_literal_maybe_minus()
4563         }
4564     }
4565
4566     // helper function to decide whether to parse as ident binding or to try to do
4567     // something more complex like range patterns
4568     fn parse_as_ident(&mut self) -> bool {
4569         self.look_ahead(1, |t| match *t {
4570             token::OpenDelim(token::Paren) | token::OpenDelim(token::Brace) |
4571             token::DotDotDot | token::DotDotEq | token::ModSep | token::Not => Some(false),
4572             // ensure slice patterns [a, b.., c] and [a, b, c..] don't go into the
4573             // range pattern branch
4574             token::DotDot => None,
4575             _ => Some(true),
4576         }).unwrap_or_else(|| self.look_ahead(2, |t| match *t {
4577             token::Comma | token::CloseDelim(token::Bracket) => true,
4578             _ => false,
4579         }))
4580     }
4581
4582     /// A wrapper around `parse_pat` with some special error handling for the
4583     /// "top-level" patterns in a match arm, `for` loop, `let`, &c. (in contrast
4584     /// to subpatterns within such).
4585     fn parse_top_level_pat(&mut self) -> PResult<'a, P<Pat>> {
4586         let pat = self.parse_pat(None)?;
4587         if self.token == token::Comma {
4588             // An unexpected comma after a top-level pattern is a clue that the
4589             // user (perhaps more accustomed to some other language) forgot the
4590             // parentheses in what should have been a tuple pattern; return a
4591             // suggestion-enhanced error here rather than choking on the comma
4592             // later.
4593             let comma_span = self.span;
4594             self.bump();
4595             if let Err(mut err) = self.parse_pat_list() {
4596                 // We didn't expect this to work anyway; we just wanted
4597                 // to advance to the end of the comma-sequence so we know
4598                 // the span to suggest parenthesizing
4599                 err.cancel();
4600             }
4601             let seq_span = pat.span.to(self.prev_span);
4602             let mut err = self.struct_span_err(comma_span,
4603                                                "unexpected `,` in pattern");
4604             if let Ok(seq_snippet) = self.sess.source_map().span_to_snippet(seq_span) {
4605                 err.span_suggestion(
4606                     seq_span,
4607                     "try adding parentheses to match on a tuple..",
4608                     format!("({})", seq_snippet),
4609                     Applicability::MachineApplicable
4610                 ).span_suggestion(
4611                     seq_span,
4612                     "..or a vertical bar to match on multiple alternatives",
4613                     format!("{}", seq_snippet.replace(",", " |")),
4614                     Applicability::MachineApplicable
4615                 );
4616             }
4617             return Err(err);
4618         }
4619         Ok(pat)
4620     }
4621
4622     /// Parses a pattern.
4623     pub fn parse_pat(&mut self, expected: Option<&'static str>) -> PResult<'a, P<Pat>> {
4624         self.parse_pat_with_range_pat(true, expected)
4625     }
4626
4627     /// Parses a pattern, with a setting whether modern range patterns (e.g., `a..=b`, `a..b` are
4628     /// allowed).
4629     fn parse_pat_with_range_pat(
4630         &mut self,
4631         allow_range_pat: bool,
4632         expected: Option<&'static str>,
4633     ) -> PResult<'a, P<Pat>> {
4634         maybe_recover_from_interpolated_ty_qpath!(self, true);
4635         maybe_whole!(self, NtPat, |x| x);
4636
4637         let lo = self.span;
4638         let pat;
4639         match self.token {
4640             token::BinOp(token::And) | token::AndAnd => {
4641                 // Parse &pat / &mut pat
4642                 self.expect_and()?;
4643                 let mutbl = self.parse_mutability();
4644                 if let token::Lifetime(ident) = self.token {
4645                     let mut err = self.fatal(&format!("unexpected lifetime `{}` in pattern",
4646                                                       ident));
4647                     err.span_label(self.span, "unexpected lifetime");
4648                     return Err(err);
4649                 }
4650                 let subpat = self.parse_pat_with_range_pat(false, expected)?;
4651                 pat = PatKind::Ref(subpat, mutbl);
4652             }
4653             token::OpenDelim(token::Paren) => {
4654                 // Parse (pat,pat,pat,...) as tuple pattern
4655                 let (fields, ddpos, trailing_comma) = self.parse_parenthesized_pat_list()?;
4656                 pat = if fields.len() == 1 && ddpos.is_none() && !trailing_comma {
4657                     PatKind::Paren(fields.into_iter().nth(0).unwrap())
4658                 } else {
4659                     PatKind::Tuple(fields, ddpos)
4660                 };
4661             }
4662             token::OpenDelim(token::Bracket) => {
4663                 // Parse [pat,pat,...] as slice pattern
4664                 self.bump();
4665                 let (before, slice, after) = self.parse_pat_vec_elements()?;
4666                 self.expect(&token::CloseDelim(token::Bracket))?;
4667                 pat = PatKind::Slice(before, slice, after);
4668             }
4669             // At this point, token != &, &&, (, [
4670             _ => if self.eat_keyword(keywords::Underscore) {
4671                 // Parse _
4672                 pat = PatKind::Wild;
4673             } else if self.eat_keyword(keywords::Mut) {
4674                 // Parse mut ident @ pat / mut ref ident @ pat
4675                 let mutref_span = self.prev_span.to(self.span);
4676                 let binding_mode = if self.eat_keyword(keywords::Ref) {
4677                     self.diagnostic()
4678                         .struct_span_err(mutref_span, "the order of `mut` and `ref` is incorrect")
4679                         .span_suggestion(
4680                             mutref_span,
4681                             "try switching the order",
4682                             "ref mut".into(),
4683                             Applicability::MachineApplicable
4684                         ).emit();
4685                     BindingMode::ByRef(Mutability::Mutable)
4686                 } else {
4687                     BindingMode::ByValue(Mutability::Mutable)
4688                 };
4689                 pat = self.parse_pat_ident(binding_mode)?;
4690             } else if self.eat_keyword(keywords::Ref) {
4691                 // Parse ref ident @ pat / ref mut ident @ pat
4692                 let mutbl = self.parse_mutability();
4693                 pat = self.parse_pat_ident(BindingMode::ByRef(mutbl))?;
4694             } else if self.eat_keyword(keywords::Box) {
4695                 // Parse box pat
4696                 let subpat = self.parse_pat_with_range_pat(false, None)?;
4697                 pat = PatKind::Box(subpat);
4698             } else if self.token.is_ident() && !self.token.is_reserved_ident() &&
4699                       self.parse_as_ident() {
4700                 // Parse ident @ pat
4701                 // This can give false positives and parse nullary enums,
4702                 // they are dealt with later in resolve
4703                 let binding_mode = BindingMode::ByValue(Mutability::Immutable);
4704                 pat = self.parse_pat_ident(binding_mode)?;
4705             } else if self.token.is_path_start() {
4706                 // Parse pattern starting with a path
4707                 let (qself, path) = if self.eat_lt() {
4708                     // Parse a qualified path
4709                     let (qself, path) = self.parse_qpath(PathStyle::Expr)?;
4710                     (Some(qself), path)
4711                 } else {
4712                     // Parse an unqualified path
4713                     (None, self.parse_path(PathStyle::Expr)?)
4714                 };
4715                 match self.token {
4716                     token::Not if qself.is_none() => {
4717                         // Parse macro invocation
4718                         self.bump();
4719                         let (delim, tts) = self.expect_delimited_token_tree()?;
4720                         let mac = respan(lo.to(self.prev_span), Mac_ { path, tts, delim });
4721                         pat = PatKind::Mac(mac);
4722                     }
4723                     token::DotDotDot | token::DotDotEq | token::DotDot => {
4724                         let end_kind = match self.token {
4725                             token::DotDot => RangeEnd::Excluded,
4726                             token::DotDotDot => RangeEnd::Included(RangeSyntax::DotDotDot),
4727                             token::DotDotEq => RangeEnd::Included(RangeSyntax::DotDotEq),
4728                             _ => panic!("can only parse `..`/`...`/`..=` for ranges \
4729                                          (checked above)"),
4730                         };
4731                         let op_span = self.span;
4732                         // Parse range
4733                         let span = lo.to(self.prev_span);
4734                         let begin = self.mk_expr(span, ExprKind::Path(qself, path), ThinVec::new());
4735                         self.bump();
4736                         let end = self.parse_pat_range_end()?;
4737                         let op = Spanned { span: op_span, node: end_kind };
4738                         pat = PatKind::Range(begin, end, op);
4739                     }
4740                     token::OpenDelim(token::Brace) => {
4741                         if qself.is_some() {
4742                             let msg = "unexpected `{` after qualified path";
4743                             let mut err = self.fatal(msg);
4744                             err.span_label(self.span, msg);
4745                             return Err(err);
4746                         }
4747                         // Parse struct pattern
4748                         self.bump();
4749                         let (fields, etc) = self.parse_pat_fields().unwrap_or_else(|mut e| {
4750                             e.emit();
4751                             self.recover_stmt();
4752                             (vec![], true)
4753                         });
4754                         self.bump();
4755                         pat = PatKind::Struct(path, fields, etc);
4756                     }
4757                     token::OpenDelim(token::Paren) => {
4758                         if qself.is_some() {
4759                             let msg = "unexpected `(` after qualified path";
4760                             let mut err = self.fatal(msg);
4761                             err.span_label(self.span, msg);
4762                             return Err(err);
4763                         }
4764                         // Parse tuple struct or enum pattern
4765                         let (fields, ddpos, _) = self.parse_parenthesized_pat_list()?;
4766                         pat = PatKind::TupleStruct(path, fields, ddpos)
4767                     }
4768                     _ => pat = PatKind::Path(qself, path),
4769                 }
4770             } else {
4771                 // Try to parse everything else as literal with optional minus
4772                 match self.parse_literal_maybe_minus() {
4773                     Ok(begin) => {
4774                         let op_span = self.span;
4775                         if self.check(&token::DotDot) || self.check(&token::DotDotEq) ||
4776                                 self.check(&token::DotDotDot) {
4777                             let end_kind = if self.eat(&token::DotDotDot) {
4778                                 RangeEnd::Included(RangeSyntax::DotDotDot)
4779                             } else if self.eat(&token::DotDotEq) {
4780                                 RangeEnd::Included(RangeSyntax::DotDotEq)
4781                             } else if self.eat(&token::DotDot) {
4782                                 RangeEnd::Excluded
4783                             } else {
4784                                 panic!("impossible case: we already matched \
4785                                         on a range-operator token")
4786                             };
4787                             let end = self.parse_pat_range_end()?;
4788                             let op = Spanned { span: op_span, node: end_kind };
4789                             pat = PatKind::Range(begin, end, op);
4790                         } else {
4791                             pat = PatKind::Lit(begin);
4792                         }
4793                     }
4794                     Err(mut err) => {
4795                         self.cancel(&mut err);
4796                         let expected = expected.unwrap_or("pattern");
4797                         let msg = format!(
4798                             "expected {}, found {}",
4799                             expected,
4800                             self.this_token_descr(),
4801                         );
4802                         let mut err = self.fatal(&msg);
4803                         err.span_label(self.span, format!("expected {}", expected));
4804                         return Err(err);
4805                     }
4806                 }
4807             }
4808         }
4809
4810         let pat = P(Pat { node: pat, span: lo.to(self.prev_span), id: ast::DUMMY_NODE_ID });
4811         let pat = self.maybe_recover_from_bad_qpath(pat, true)?;
4812
4813         if !allow_range_pat {
4814             match pat.node {
4815                 PatKind::Range(
4816                     _, _, Spanned { node: RangeEnd::Included(RangeSyntax::DotDotDot), .. }
4817                 ) => {},
4818                 PatKind::Range(..) => {
4819                     let mut err = self.struct_span_err(
4820                         pat.span,
4821                         "the range pattern here has ambiguous interpretation",
4822                     );
4823                     err.span_suggestion(
4824                         pat.span,
4825                         "add parentheses to clarify the precedence",
4826                         format!("({})", pprust::pat_to_string(&pat)),
4827                         // "ambiguous interpretation" implies that we have to be guessing
4828                         Applicability::MaybeIncorrect
4829                     );
4830                     return Err(err);
4831                 }
4832                 _ => {}
4833             }
4834         }
4835
4836         Ok(pat)
4837     }
4838
4839     /// Parses `ident` or `ident @ pat`.
4840     /// used by the copy foo and ref foo patterns to give a good
4841     /// error message when parsing mistakes like `ref foo(a, b)`.
4842     fn parse_pat_ident(&mut self,
4843                        binding_mode: ast::BindingMode)
4844                        -> PResult<'a, PatKind> {
4845         let ident = self.parse_ident()?;
4846         let sub = if self.eat(&token::At) {
4847             Some(self.parse_pat(Some("binding pattern"))?)
4848         } else {
4849             None
4850         };
4851
4852         // just to be friendly, if they write something like
4853         //   ref Some(i)
4854         // we end up here with ( as the current token.  This shortly
4855         // leads to a parse error.  Note that if there is no explicit
4856         // binding mode then we do not end up here, because the lookahead
4857         // will direct us over to parse_enum_variant()
4858         if self.token == token::OpenDelim(token::Paren) {
4859             return Err(self.span_fatal(
4860                 self.prev_span,
4861                 "expected identifier, found enum pattern"))
4862         }
4863
4864         Ok(PatKind::Ident(binding_mode, ident, sub))
4865     }
4866
4867     /// Parses a local variable declaration.
4868     fn parse_local(&mut self, attrs: ThinVec<Attribute>) -> PResult<'a, P<Local>> {
4869         let lo = self.prev_span;
4870         let pat = self.parse_top_level_pat()?;
4871
4872         let (err, ty) = if self.eat(&token::Colon) {
4873             // Save the state of the parser before parsing type normally, in case there is a `:`
4874             // instead of an `=` typo.
4875             let parser_snapshot_before_type = self.clone();
4876             let colon_sp = self.prev_span;
4877             match self.parse_ty() {
4878                 Ok(ty) => (None, Some(ty)),
4879                 Err(mut err) => {
4880                     // Rewind to before attempting to parse the type and continue parsing
4881                     let parser_snapshot_after_type = self.clone();
4882                     mem::replace(self, parser_snapshot_before_type);
4883
4884                     let snippet = self.sess.source_map().span_to_snippet(pat.span).unwrap();
4885                     err.span_label(pat.span, format!("while parsing the type for `{}`", snippet));
4886                     (Some((parser_snapshot_after_type, colon_sp, err)), None)
4887                 }
4888             }
4889         } else {
4890             (None, None)
4891         };
4892         let init = match (self.parse_initializer(err.is_some()), err) {
4893             (Ok(init), None) => {  // init parsed, ty parsed
4894                 init
4895             }
4896             (Ok(init), Some((_, colon_sp, mut err))) => {  // init parsed, ty error
4897                 // Could parse the type as if it were the initializer, it is likely there was a
4898                 // typo in the code: `:` instead of `=`. Add suggestion and emit the error.
4899                 err.span_suggestion_short(
4900                     colon_sp,
4901                     "use `=` if you meant to assign",
4902                     "=".to_string(),
4903                     Applicability::MachineApplicable
4904                 );
4905                 err.emit();
4906                 // As this was parsed successfully, continue as if the code has been fixed for the
4907                 // rest of the file. It will still fail due to the emitted error, but we avoid
4908                 // extra noise.
4909                 init
4910             }
4911             (Err(mut init_err), Some((snapshot, _, ty_err))) => {  // init error, ty error
4912                 init_err.cancel();
4913                 // Couldn't parse the type nor the initializer, only raise the type error and
4914                 // return to the parser state before parsing the type as the initializer.
4915                 // let x: <parse_error>;
4916                 mem::replace(self, snapshot);
4917                 return Err(ty_err);
4918             }
4919             (Err(err), None) => {  // init error, ty parsed
4920                 // Couldn't parse the initializer and we're not attempting to recover a failed
4921                 // parse of the type, return the error.
4922                 return Err(err);
4923             }
4924         };
4925         let hi = if self.token == token::Semi {
4926             self.span
4927         } else {
4928             self.prev_span
4929         };
4930         Ok(P(ast::Local {
4931             ty,
4932             pat,
4933             init,
4934             id: ast::DUMMY_NODE_ID,
4935             span: lo.to(hi),
4936             attrs,
4937             source: LocalSource::Normal,
4938         }))
4939     }
4940
4941     /// Parses a structure field.
4942     fn parse_name_and_ty(&mut self,
4943                          lo: Span,
4944                          vis: Visibility,
4945                          attrs: Vec<Attribute>)
4946                          -> PResult<'a, StructField> {
4947         let name = self.parse_ident()?;
4948         self.expect(&token::Colon)?;
4949         let ty = self.parse_ty()?;
4950         Ok(StructField {
4951             span: lo.to(self.prev_span),
4952             ident: Some(name),
4953             vis,
4954             id: ast::DUMMY_NODE_ID,
4955             ty,
4956             attrs,
4957         })
4958     }
4959
4960     /// Emits an expected-item-after-attributes error.
4961     fn expected_item_err(&mut self, attrs: &[Attribute]) -> PResult<'a,  ()> {
4962         let message = match attrs.last() {
4963             Some(&Attribute { is_sugared_doc: true, .. }) => "expected item after doc comment",
4964             _ => "expected item after attributes",
4965         };
4966
4967         let mut err = self.diagnostic().struct_span_err(self.prev_span, message);
4968         if attrs.last().unwrap().is_sugared_doc {
4969             err.span_label(self.prev_span, "this doc comment doesn't document anything");
4970         }
4971         Err(err)
4972     }
4973
4974     /// Parse a statement. This stops just before trailing semicolons on everything but items.
4975     /// e.g., a `StmtKind::Semi` parses to a `StmtKind::Expr`, leaving the trailing `;` unconsumed.
4976     pub fn parse_stmt(&mut self) -> PResult<'a, Option<Stmt>> {
4977         Ok(self.parse_stmt_(true))
4978     }
4979
4980     // Eat tokens until we can be relatively sure we reached the end of the
4981     // statement. This is something of a best-effort heuristic.
4982     //
4983     // We terminate when we find an unmatched `}` (without consuming it).
4984     fn recover_stmt(&mut self) {
4985         self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore)
4986     }
4987
4988     // If `break_on_semi` is `Break`, then we will stop consuming tokens after
4989     // finding (and consuming) a `;` outside of `{}` or `[]` (note that this is
4990     // approximate - it can mean we break too early due to macros, but that
4991     // should only lead to sub-optimal recovery, not inaccurate parsing).
4992     //
4993     // If `break_on_block` is `Break`, then we will stop consuming tokens
4994     // after finding (and consuming) a brace-delimited block.
4995     fn recover_stmt_(&mut self, break_on_semi: SemiColonMode, break_on_block: BlockMode) {
4996         let mut brace_depth = 0;
4997         let mut bracket_depth = 0;
4998         let mut in_block = false;
4999         debug!("recover_stmt_ enter loop (semi={:?}, block={:?})",
5000                break_on_semi, break_on_block);
5001         loop {
5002             debug!("recover_stmt_ loop {:?}", self.token);
5003             match self.token {
5004                 token::OpenDelim(token::DelimToken::Brace) => {
5005                     brace_depth += 1;
5006                     self.bump();
5007                     if break_on_block == BlockMode::Break &&
5008                        brace_depth == 1 &&
5009                        bracket_depth == 0 {
5010                         in_block = true;
5011                     }
5012                 }
5013                 token::OpenDelim(token::DelimToken::Bracket) => {
5014                     bracket_depth += 1;
5015                     self.bump();
5016                 }
5017                 token::CloseDelim(token::DelimToken::Brace) => {
5018                     if brace_depth == 0 {
5019                         debug!("recover_stmt_ return - close delim {:?}", self.token);
5020                         break;
5021                     }
5022                     brace_depth -= 1;
5023                     self.bump();
5024                     if in_block && bracket_depth == 0 && brace_depth == 0 {
5025                         debug!("recover_stmt_ return - block end {:?}", self.token);
5026                         break;
5027                     }
5028                 }
5029                 token::CloseDelim(token::DelimToken::Bracket) => {
5030                     bracket_depth -= 1;
5031                     if bracket_depth < 0 {
5032                         bracket_depth = 0;
5033                     }
5034                     self.bump();
5035                 }
5036                 token::Eof => {
5037                     debug!("recover_stmt_ return - Eof");
5038                     break;
5039                 }
5040                 token::Semi => {
5041                     self.bump();
5042                     if break_on_semi == SemiColonMode::Break &&
5043                        brace_depth == 0 &&
5044                        bracket_depth == 0 {
5045                         debug!("recover_stmt_ return - Semi");
5046                         break;
5047                     }
5048                 }
5049                 token::Comma => {
5050                     if break_on_semi == SemiColonMode::Comma &&
5051                        brace_depth == 0 &&
5052                        bracket_depth == 0 {
5053                         debug!("recover_stmt_ return - Semi");
5054                         break;
5055                     } else {
5056                         self.bump();
5057                     }
5058                 }
5059                 _ => {
5060                     self.bump()
5061                 }
5062             }
5063         }
5064     }
5065
5066     fn parse_stmt_(&mut self, macro_legacy_warnings: bool) -> Option<Stmt> {
5067         self.parse_stmt_without_recovery(macro_legacy_warnings).unwrap_or_else(|mut e| {
5068             e.emit();
5069             self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5070             None
5071         })
5072     }
5073
5074     fn is_async_block(&mut self) -> bool {
5075         self.token.is_keyword(keywords::Async) &&
5076         (
5077             ( // `async move {`
5078                 self.look_ahead(1, |t| t.is_keyword(keywords::Move)) &&
5079                 self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace))
5080             ) || ( // `async {`
5081                 self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace))
5082             )
5083         )
5084     }
5085
5086     fn is_async_fn(&mut self) -> bool {
5087         self.token.is_keyword(keywords::Async) &&
5088             self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
5089     }
5090
5091     fn is_do_catch_block(&mut self) -> bool {
5092         self.token.is_keyword(keywords::Do) &&
5093         self.look_ahead(1, |t| t.is_keyword(keywords::Catch)) &&
5094         self.look_ahead(2, |t| *t == token::OpenDelim(token::Brace)) &&
5095         !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5096     }
5097
5098     fn is_try_block(&mut self) -> bool {
5099         self.token.is_keyword(keywords::Try) &&
5100         self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) &&
5101         self.span.rust_2018() &&
5102         // prevent `while try {} {}`, `if try {} {} else {}`, etc.
5103         !self.restrictions.contains(Restrictions::NO_STRUCT_LITERAL)
5104     }
5105
5106     fn is_union_item(&self) -> bool {
5107         self.token.is_keyword(keywords::Union) &&
5108         self.look_ahead(1, |t| t.is_ident() && !t.is_reserved_ident())
5109     }
5110
5111     fn is_crate_vis(&self) -> bool {
5112         self.token.is_keyword(keywords::Crate) && self.look_ahead(1, |t| t != &token::ModSep)
5113     }
5114
5115     fn is_existential_type_decl(&self) -> bool {
5116         self.token.is_keyword(keywords::Existential) &&
5117         self.look_ahead(1, |t| t.is_keyword(keywords::Type))
5118     }
5119
5120     fn is_auto_trait_item(&mut self) -> bool {
5121         // auto trait
5122         (self.token.is_keyword(keywords::Auto)
5123             && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
5124         || // unsafe auto trait
5125         (self.token.is_keyword(keywords::Unsafe) &&
5126          self.look_ahead(1, |t| t.is_keyword(keywords::Auto)) &&
5127          self.look_ahead(2, |t| t.is_keyword(keywords::Trait)))
5128     }
5129
5130     fn eat_macro_def(&mut self, attrs: &[Attribute], vis: &Visibility, lo: Span)
5131                      -> PResult<'a, Option<P<Item>>> {
5132         let token_lo = self.span;
5133         let (ident, def) = match self.token {
5134             token::Ident(ident, false) if ident.name == keywords::Macro.name() => {
5135                 self.bump();
5136                 let ident = self.parse_ident()?;
5137                 let tokens = if self.check(&token::OpenDelim(token::Brace)) {
5138                     match self.parse_token_tree() {
5139                         TokenTree::Delimited(_, _, tts) => tts,
5140                         _ => unreachable!(),
5141                     }
5142                 } else if self.check(&token::OpenDelim(token::Paren)) {
5143                     let args = self.parse_token_tree();
5144                     let body = if self.check(&token::OpenDelim(token::Brace)) {
5145                         self.parse_token_tree()
5146                     } else {
5147                         self.unexpected()?;
5148                         unreachable!()
5149                     };
5150                     TokenStream::new(vec![
5151                         args.into(),
5152                         TokenTree::Token(token_lo.to(self.prev_span), token::FatArrow).into(),
5153                         body.into(),
5154                     ])
5155                 } else {
5156                     self.unexpected()?;
5157                     unreachable!()
5158                 };
5159
5160                 (ident, ast::MacroDef { tokens: tokens.into(), legacy: false })
5161             }
5162             token::Ident(ident, _) if ident.name == "macro_rules" &&
5163                                    self.look_ahead(1, |t| *t == token::Not) => {
5164                 let prev_span = self.prev_span;
5165                 self.complain_if_pub_macro(&vis.node, prev_span);
5166                 self.bump();
5167                 self.bump();
5168
5169                 let ident = self.parse_ident()?;
5170                 let (delim, tokens) = self.expect_delimited_token_tree()?;
5171                 if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
5172                     self.report_invalid_macro_expansion_item();
5173                 }
5174
5175                 (ident, ast::MacroDef { tokens: tokens, legacy: true })
5176             }
5177             _ => return Ok(None),
5178         };
5179
5180         let span = lo.to(self.prev_span);
5181         Ok(Some(self.mk_item(span, ident, ItemKind::MacroDef(def), vis.clone(), attrs.to_vec())))
5182     }
5183
5184     fn parse_stmt_without_recovery(&mut self,
5185                                    macro_legacy_warnings: bool)
5186                                    -> PResult<'a, Option<Stmt>> {
5187         maybe_whole!(self, NtStmt, |x| Some(x));
5188
5189         let attrs = self.parse_outer_attributes()?;
5190         let lo = self.span;
5191
5192         Ok(Some(if self.eat_keyword(keywords::Let) {
5193             Stmt {
5194                 id: ast::DUMMY_NODE_ID,
5195                 node: StmtKind::Local(self.parse_local(attrs.into())?),
5196                 span: lo.to(self.prev_span),
5197             }
5198         } else if let Some(macro_def) = self.eat_macro_def(
5199             &attrs,
5200             &source_map::respan(lo, VisibilityKind::Inherited),
5201             lo,
5202         )? {
5203             Stmt {
5204                 id: ast::DUMMY_NODE_ID,
5205                 node: StmtKind::Item(macro_def),
5206                 span: lo.to(self.prev_span),
5207             }
5208         // Starts like a simple path, being careful to avoid contextual keywords
5209         // such as a union items, item with `crate` visibility or auto trait items.
5210         // Our goal here is to parse an arbitrary path `a::b::c` but not something that starts
5211         // like a path (1 token), but it fact not a path.
5212         // `union::b::c` - path, `union U { ... }` - not a path.
5213         // `crate::b::c` - path, `crate struct S;` - not a path.
5214         } else if self.token.is_path_start() &&
5215                   !self.token.is_qpath_start() &&
5216                   !self.is_union_item() &&
5217                   !self.is_crate_vis() &&
5218                   !self.is_existential_type_decl() &&
5219                   !self.is_auto_trait_item() &&
5220                   !self.is_async_fn() {
5221             let pth = self.parse_path(PathStyle::Expr)?;
5222
5223             if !self.eat(&token::Not) {
5224                 let expr = if self.check(&token::OpenDelim(token::Brace)) {
5225                     self.parse_struct_expr(lo, pth, ThinVec::new())?
5226                 } else {
5227                     let hi = self.prev_span;
5228                     self.mk_expr(lo.to(hi), ExprKind::Path(None, pth), ThinVec::new())
5229                 };
5230
5231                 let expr = self.with_res(Restrictions::STMT_EXPR, |this| {
5232                     let expr = this.parse_dot_or_call_expr_with(expr, lo, attrs.into())?;
5233                     this.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(expr))
5234                 })?;
5235
5236                 return Ok(Some(Stmt {
5237                     id: ast::DUMMY_NODE_ID,
5238                     node: StmtKind::Expr(expr),
5239                     span: lo.to(self.prev_span),
5240                 }));
5241             }
5242
5243             // it's a macro invocation
5244             let id = match self.token {
5245                 token::OpenDelim(_) => keywords::Invalid.ident(), // no special identifier
5246                 _ => self.parse_ident()?,
5247             };
5248
5249             // check that we're pointing at delimiters (need to check
5250             // again after the `if`, because of `parse_ident`
5251             // consuming more tokens).
5252             match self.token {
5253                 token::OpenDelim(_) => {}
5254                 _ => {
5255                     // we only expect an ident if we didn't parse one
5256                     // above.
5257                     let ident_str = if id.name == keywords::Invalid.name() {
5258                         "identifier, "
5259                     } else {
5260                         ""
5261                     };
5262                     let tok_str = self.this_token_descr();
5263                     let mut err = self.fatal(&format!("expected {}`(` or `{{`, found {}",
5264                                                       ident_str,
5265                                                       tok_str));
5266                     err.span_label(self.span, format!("expected {}`(` or `{{`", ident_str));
5267                     return Err(err)
5268                 },
5269             }
5270
5271             let (delim, tts) = self.expect_delimited_token_tree()?;
5272             let hi = self.prev_span;
5273
5274             let style = if delim == MacDelimiter::Brace {
5275                 MacStmtStyle::Braces
5276             } else {
5277                 MacStmtStyle::NoBraces
5278             };
5279
5280             if id.name == keywords::Invalid.name() {
5281                 let mac = respan(lo.to(hi), Mac_ { path: pth, tts, delim });
5282                 let node = if delim == MacDelimiter::Brace ||
5283                               self.token == token::Semi || self.token == token::Eof {
5284                     StmtKind::Mac(P((mac, style, attrs.into())))
5285                 }
5286                 // We used to incorrectly stop parsing macro-expanded statements here.
5287                 // If the next token will be an error anyway but could have parsed with the
5288                 // earlier behavior, stop parsing here and emit a warning to avoid breakage.
5289                 else if macro_legacy_warnings && self.token.can_begin_expr() && match self.token {
5290                     // These can continue an expression, so we can't stop parsing and warn.
5291                     token::OpenDelim(token::Paren) | token::OpenDelim(token::Bracket) |
5292                     token::BinOp(token::Minus) | token::BinOp(token::Star) |
5293                     token::BinOp(token::And) | token::BinOp(token::Or) |
5294                     token::AndAnd | token::OrOr |
5295                     token::DotDot | token::DotDotDot | token::DotDotEq => false,
5296                     _ => true,
5297                 } {
5298                     self.warn_missing_semicolon();
5299                     StmtKind::Mac(P((mac, style, attrs.into())))
5300                 } else {
5301                     let e = self.mk_expr(mac.span, ExprKind::Mac(mac), ThinVec::new());
5302                     let e = self.maybe_recover_from_bad_qpath(e, true)?;
5303                     let e = self.parse_dot_or_call_expr_with(e, lo, attrs.into())?;
5304                     let e = self.parse_assoc_expr_with(0, LhsExpr::AlreadyParsed(e))?;
5305                     StmtKind::Expr(e)
5306                 };
5307                 Stmt {
5308                     id: ast::DUMMY_NODE_ID,
5309                     span: lo.to(hi),
5310                     node,
5311                 }
5312             } else {
5313                 // if it has a special ident, it's definitely an item
5314                 //
5315                 // Require a semicolon or braces.
5316                 if style != MacStmtStyle::Braces && !self.eat(&token::Semi) {
5317                     self.report_invalid_macro_expansion_item();
5318                 }
5319                 let span = lo.to(hi);
5320                 Stmt {
5321                     id: ast::DUMMY_NODE_ID,
5322                     span,
5323                     node: StmtKind::Item({
5324                         self.mk_item(
5325                             span, id /*id is good here*/,
5326                             ItemKind::Mac(respan(span, Mac_ { path: pth, tts, delim })),
5327                             respan(lo, VisibilityKind::Inherited),
5328                             attrs)
5329                     }),
5330                 }
5331             }
5332         } else {
5333             // FIXME: Bad copy of attrs
5334             let old_directory_ownership =
5335                 mem::replace(&mut self.directory.ownership, DirectoryOwnership::UnownedViaBlock);
5336             let item = self.parse_item_(attrs.clone(), false, true)?;
5337             self.directory.ownership = old_directory_ownership;
5338
5339             match item {
5340                 Some(i) => Stmt {
5341                     id: ast::DUMMY_NODE_ID,
5342                     span: lo.to(i.span),
5343                     node: StmtKind::Item(i),
5344                 },
5345                 None => {
5346                     let unused_attrs = |attrs: &[Attribute], s: &mut Self| {
5347                         if !attrs.is_empty() {
5348                             if s.prev_token_kind == PrevTokenKind::DocComment {
5349                                 s.span_fatal_err(s.prev_span, Error::UselessDocComment).emit();
5350                             } else if attrs.iter().any(|a| a.style == AttrStyle::Outer) {
5351                                 s.span_err(s.span, "expected statement after outer attribute");
5352                             }
5353                         }
5354                     };
5355
5356                     // Do not attempt to parse an expression if we're done here.
5357                     if self.token == token::Semi {
5358                         unused_attrs(&attrs, self);
5359                         self.bump();
5360                         return Ok(None);
5361                     }
5362
5363                     if self.token == token::CloseDelim(token::Brace) {
5364                         unused_attrs(&attrs, self);
5365                         return Ok(None);
5366                     }
5367
5368                     // Remainder are line-expr stmts.
5369                     let e = self.parse_expr_res(
5370                         Restrictions::STMT_EXPR, Some(attrs.into()))?;
5371                     Stmt {
5372                         id: ast::DUMMY_NODE_ID,
5373                         span: lo.to(e.span),
5374                         node: StmtKind::Expr(e),
5375                     }
5376                 }
5377             }
5378         }))
5379     }
5380
5381     /// Checks if this expression is a successfully parsed statement.
5382     fn expr_is_complete(&mut self, e: &Expr) -> bool {
5383         self.restrictions.contains(Restrictions::STMT_EXPR) &&
5384             !classify::expr_requires_semi_to_be_stmt(e)
5385     }
5386
5387     /// Parses a block. No inner attributes are allowed.
5388     pub fn parse_block(&mut self) -> PResult<'a, P<Block>> {
5389         maybe_whole!(self, NtBlock, |x| x);
5390
5391         let lo = self.span;
5392
5393         if !self.eat(&token::OpenDelim(token::Brace)) {
5394             let sp = self.span;
5395             let tok = self.this_token_descr();
5396             let mut e = self.span_fatal(sp, &format!("expected `{{`, found {}", tok));
5397             let do_not_suggest_help =
5398                 self.token.is_keyword(keywords::In) || self.token == token::Colon;
5399
5400             if self.token.is_ident_named("and") {
5401                 e.span_suggestion_short(
5402                     self.span,
5403                     "use `&&` instead of `and` for the boolean operator",
5404                     "&&".to_string(),
5405                     Applicability::MaybeIncorrect,
5406                 );
5407             }
5408             if self.token.is_ident_named("or") {
5409                 e.span_suggestion_short(
5410                     self.span,
5411                     "use `||` instead of `or` for the boolean operator",
5412                     "||".to_string(),
5413                     Applicability::MaybeIncorrect,
5414                 );
5415             }
5416
5417             // Check to see if the user has written something like
5418             //
5419             //    if (cond)
5420             //      bar;
5421             //
5422             // Which is valid in other languages, but not Rust.
5423             match self.parse_stmt_without_recovery(false) {
5424                 Ok(Some(stmt)) => {
5425                     if self.look_ahead(1, |t| t == &token::OpenDelim(token::Brace))
5426                         || do_not_suggest_help {
5427                         // if the next token is an open brace (e.g., `if a b {`), the place-
5428                         // inside-a-block suggestion would be more likely wrong than right
5429                         e.span_label(sp, "expected `{`");
5430                         return Err(e);
5431                     }
5432                     let mut stmt_span = stmt.span;
5433                     // expand the span to include the semicolon, if it exists
5434                     if self.eat(&token::Semi) {
5435                         stmt_span = stmt_span.with_hi(self.prev_span.hi());
5436                     }
5437                     let sugg = pprust::to_string(|s| {
5438                         use crate::print::pprust::{PrintState, INDENT_UNIT};
5439                         s.ibox(INDENT_UNIT)?;
5440                         s.bopen()?;
5441                         s.print_stmt(&stmt)?;
5442                         s.bclose_maybe_open(stmt.span, INDENT_UNIT, false)
5443                     });
5444                     e.span_suggestion(
5445                         stmt_span,
5446                         "try placing this code inside a block",
5447                         sugg,
5448                         // speculative, has been misleading in the past (closed Issue #46836)
5449                         Applicability::MaybeIncorrect
5450                     );
5451                 }
5452                 Err(mut e) => {
5453                     self.recover_stmt_(SemiColonMode::Break, BlockMode::Ignore);
5454                     self.cancel(&mut e);
5455                 }
5456                 _ => ()
5457             }
5458             e.span_label(sp, "expected `{`");
5459             return Err(e);
5460         }
5461
5462         self.parse_block_tail(lo, BlockCheckMode::Default)
5463     }
5464
5465     /// Parses a block. Inner attributes are allowed.
5466     fn parse_inner_attrs_and_block(&mut self) -> PResult<'a, (Vec<Attribute>, P<Block>)> {
5467         maybe_whole!(self, NtBlock, |x| (Vec::new(), x));
5468
5469         let lo = self.span;
5470         self.expect(&token::OpenDelim(token::Brace))?;
5471         Ok((self.parse_inner_attributes()?,
5472             self.parse_block_tail(lo, BlockCheckMode::Default)?))
5473     }
5474
5475     /// Parses the rest of a block expression or function body.
5476     /// Precondition: already parsed the '{'.
5477     fn parse_block_tail(&mut self, lo: Span, s: BlockCheckMode) -> PResult<'a, P<Block>> {
5478         let mut stmts = vec![];
5479         while !self.eat(&token::CloseDelim(token::Brace)) {
5480             let stmt = match self.parse_full_stmt(false) {
5481                 Err(mut err) => {
5482                     err.emit();
5483                     self.recover_stmt_(SemiColonMode::Ignore, BlockMode::Ignore);
5484                     Some(Stmt {
5485                         id: ast::DUMMY_NODE_ID,
5486                         node: StmtKind::Expr(DummyResult::raw_expr(self.span, true)),
5487                         span: self.span,
5488                     })
5489                 }
5490                 Ok(stmt) => stmt,
5491             };
5492             if let Some(stmt) = stmt {
5493                 stmts.push(stmt);
5494             } else if self.token == token::Eof {
5495                 break;
5496             } else {
5497                 // Found only `;` or `}`.
5498                 continue;
5499             };
5500         }
5501         Ok(P(ast::Block {
5502             stmts,
5503             id: ast::DUMMY_NODE_ID,
5504             rules: s,
5505             span: lo.to(self.prev_span),
5506         }))
5507     }
5508
5509     /// Parses a statement, including the trailing semicolon.
5510     crate fn parse_full_stmt(&mut self, macro_legacy_warnings: bool) -> PResult<'a, Option<Stmt>> {
5511         // skip looking for a trailing semicolon when we have an interpolated statement
5512         maybe_whole!(self, NtStmt, |x| Some(x));
5513
5514         let mut stmt = match self.parse_stmt_without_recovery(macro_legacy_warnings)? {
5515             Some(stmt) => stmt,
5516             None => return Ok(None),
5517         };
5518
5519         match stmt.node {
5520             StmtKind::Expr(ref expr) if self.token != token::Eof => {
5521                 // expression without semicolon
5522                 if classify::expr_requires_semi_to_be_stmt(expr) {
5523                     // Just check for errors and recover; do not eat semicolon yet.
5524                     if let Err(mut e) =
5525                         self.expect_one_of(&[], &[token::Semi, token::CloseDelim(token::Brace)])
5526                     {
5527                         e.emit();
5528                         self.recover_stmt();
5529                     }
5530                 }
5531             }
5532             StmtKind::Local(..) => {
5533                 // We used to incorrectly allow a macro-expanded let statement to lack a semicolon.
5534                 if macro_legacy_warnings && self.token != token::Semi {
5535                     self.warn_missing_semicolon();
5536                 } else {
5537                     self.expect_one_of(&[], &[token::Semi])?;
5538                 }
5539             }
5540             _ => {}
5541         }
5542
5543         if self.eat(&token::Semi) {
5544             stmt = stmt.add_trailing_semicolon();
5545         }
5546
5547         stmt.span = stmt.span.with_hi(self.prev_span.hi());
5548         Ok(Some(stmt))
5549     }
5550
5551     fn warn_missing_semicolon(&self) {
5552         self.diagnostic().struct_span_warn(self.span, {
5553             &format!("expected `;`, found {}", self.this_token_descr())
5554         }).note({
5555             "This was erroneously allowed and will become a hard error in a future release"
5556         }).emit();
5557     }
5558
5559     fn err_dotdotdot_syntax(&self, span: Span) {
5560         self.diagnostic().struct_span_err(span, {
5561             "unexpected token: `...`"
5562         }).span_suggestion(
5563             span, "use `..` for an exclusive range", "..".to_owned(),
5564             Applicability::MaybeIncorrect
5565         ).span_suggestion(
5566             span, "or `..=` for an inclusive range", "..=".to_owned(),
5567             Applicability::MaybeIncorrect
5568         ).emit();
5569     }
5570
5571     /// Parses bounds of a type parameter `BOUND + BOUND + ...`, possibly with trailing `+`.
5572     ///
5573     /// ```
5574     /// BOUND = TY_BOUND | LT_BOUND
5575     /// LT_BOUND = LIFETIME (e.g., `'a`)
5576     /// TY_BOUND = TY_BOUND_NOPAREN | (TY_BOUND_NOPAREN)
5577     /// TY_BOUND_NOPAREN = [?] [for<LT_PARAM_DEFS>] SIMPLE_PATH (e.g., `?for<'a: 'b> m::Trait<'a>`)
5578     /// ```
5579     fn parse_generic_bounds_common(&mut self,
5580                                    allow_plus: bool,
5581                                    colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5582         let mut bounds = Vec::new();
5583         let mut negative_bounds = Vec::new();
5584         let mut last_plus_span = None;
5585         let mut was_negative = false;
5586         loop {
5587             // This needs to be synchronized with `Token::can_begin_bound`.
5588             let is_bound_start = self.check_path() || self.check_lifetime() ||
5589                                  self.check(&token::Not) || // used for error reporting only
5590                                  self.check(&token::Question) ||
5591                                  self.check_keyword(keywords::For) ||
5592                                  self.check(&token::OpenDelim(token::Paren));
5593             if is_bound_start {
5594                 let lo = self.span;
5595                 let has_parens = self.eat(&token::OpenDelim(token::Paren));
5596                 let inner_lo = self.span;
5597                 let is_negative = self.eat(&token::Not);
5598                 let question = if self.eat(&token::Question) { Some(self.prev_span) } else { None };
5599                 if self.token.is_lifetime() {
5600                     if let Some(question_span) = question {
5601                         self.span_err(question_span,
5602                                       "`?` may only modify trait bounds, not lifetime bounds");
5603                     }
5604                     bounds.push(GenericBound::Outlives(self.expect_lifetime()));
5605                     if has_parens {
5606                         let inner_span = inner_lo.to(self.prev_span);
5607                         self.expect(&token::CloseDelim(token::Paren))?;
5608                         let mut err = self.struct_span_err(
5609                             lo.to(self.prev_span),
5610                             "parenthesized lifetime bounds are not supported"
5611                         );
5612                         if let Ok(snippet) = self.sess.source_map().span_to_snippet(inner_span) {
5613                             err.span_suggestion_short(
5614                                 lo.to(self.prev_span),
5615                                 "remove the parentheses",
5616                                 snippet.to_owned(),
5617                                 Applicability::MachineApplicable
5618                             );
5619                         }
5620                         err.emit();
5621                     }
5622                 } else {
5623                     let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
5624                     let path = self.parse_path(PathStyle::Type)?;
5625                     if has_parens {
5626                         self.expect(&token::CloseDelim(token::Paren))?;
5627                     }
5628                     let poly_span = lo.to(self.prev_span);
5629                     if is_negative {
5630                         was_negative = true;
5631                         if let Some(sp) = last_plus_span.or(colon_span) {
5632                             negative_bounds.push(sp.to(poly_span));
5633                         }
5634                     } else {
5635                         let poly_trait = PolyTraitRef::new(lifetime_defs, path, poly_span);
5636                         let modifier = if question.is_some() {
5637                             TraitBoundModifier::Maybe
5638                         } else {
5639                             TraitBoundModifier::None
5640                         };
5641                         bounds.push(GenericBound::Trait(poly_trait, modifier));
5642                     }
5643                 }
5644             } else {
5645                 break
5646             }
5647
5648             if !allow_plus || !self.eat_plus() {
5649                 break
5650             } else {
5651                 last_plus_span = Some(self.prev_span);
5652             }
5653         }
5654
5655         if !negative_bounds.is_empty() || was_negative {
5656             let plural = negative_bounds.len() > 1;
5657             let last_span = negative_bounds.last().map(|sp| *sp);
5658             let mut err = self.struct_span_err(
5659                 negative_bounds,
5660                 "negative trait bounds are not supported",
5661             );
5662             if let Some(sp) = last_span {
5663                 err.span_label(sp, "negative trait bounds are not supported");
5664             }
5665             if let Some(bound_list) = colon_span {
5666                 let bound_list = bound_list.to(self.prev_span);
5667                 let mut new_bound_list = String::new();
5668                 if !bounds.is_empty() {
5669                     let mut snippets = bounds.iter().map(|bound| bound.span())
5670                         .map(|span| self.sess.source_map().span_to_snippet(span));
5671                     while let Some(Ok(snippet)) = snippets.next() {
5672                         new_bound_list.push_str(" + ");
5673                         new_bound_list.push_str(&snippet);
5674                     }
5675                     new_bound_list = new_bound_list.replacen(" +", ":", 1);
5676                 }
5677                 err.span_suggestion_hidden(
5678                     bound_list,
5679                     &format!("remove the trait bound{}", if plural { "s" } else { "" }),
5680                     new_bound_list,
5681                     Applicability::MachineApplicable,
5682                 );
5683             }
5684             err.emit();
5685         }
5686
5687         return Ok(bounds);
5688     }
5689
5690     crate fn parse_generic_bounds(&mut self,
5691                                   colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5692         self.parse_generic_bounds_common(true, colon_span)
5693     }
5694
5695     /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5696     ///
5697     /// ```
5698     /// BOUND = LT_BOUND (e.g., `'a`)
5699     /// ```
5700     fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5701         let mut lifetimes = Vec::new();
5702         while self.check_lifetime() {
5703             lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5704
5705             if !self.eat_plus() {
5706                 break
5707             }
5708         }
5709         lifetimes
5710     }
5711
5712     /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
5713     fn parse_ty_param(&mut self,
5714                       preceding_attrs: Vec<Attribute>)
5715                       -> PResult<'a, GenericParam> {
5716         let ident = self.parse_ident()?;
5717
5718         // Parse optional colon and param bounds.
5719         let bounds = if self.eat(&token::Colon) {
5720             self.parse_generic_bounds(Some(self.prev_span))?
5721         } else {
5722             Vec::new()
5723         };
5724
5725         let default = if self.eat(&token::Eq) {
5726             Some(self.parse_ty()?)
5727         } else {
5728             None
5729         };
5730
5731         Ok(GenericParam {
5732             ident,
5733             id: ast::DUMMY_NODE_ID,
5734             attrs: preceding_attrs.into(),
5735             bounds,
5736             kind: GenericParamKind::Type {
5737                 default,
5738             }
5739         })
5740     }
5741
5742     /// Parses the following grammar:
5743     ///
5744     ///     TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5745     fn parse_trait_item_assoc_ty(&mut self)
5746         -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5747         let ident = self.parse_ident()?;
5748         let mut generics = self.parse_generics()?;
5749
5750         // Parse optional colon and param bounds.
5751         let bounds = if self.eat(&token::Colon) {
5752             self.parse_generic_bounds(None)?
5753         } else {
5754             Vec::new()
5755         };
5756         generics.where_clause = self.parse_where_clause()?;
5757
5758         let default = if self.eat(&token::Eq) {
5759             Some(self.parse_ty()?)
5760         } else {
5761             None
5762         };
5763         self.expect(&token::Semi)?;
5764
5765         Ok((ident, TraitItemKind::Type(bounds, default), generics))
5766     }
5767
5768     fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
5769         self.expect_keyword(keywords::Const)?;
5770         let ident = self.parse_ident()?;
5771         self.expect(&token::Colon)?;
5772         let ty = self.parse_ty()?;
5773
5774         Ok(GenericParam {
5775             ident,
5776             id: ast::DUMMY_NODE_ID,
5777             attrs: preceding_attrs.into(),
5778             bounds: Vec::new(),
5779             kind: GenericParamKind::Const {
5780                 ty,
5781             }
5782         })
5783     }
5784
5785     /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
5786     /// a trailing comma and erroneous trailing attributes.
5787     crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5788         let mut params = Vec::new();
5789         loop {
5790             let attrs = self.parse_outer_attributes()?;
5791             if self.check_lifetime() {
5792                 let lifetime = self.expect_lifetime();
5793                 // Parse lifetime parameter.
5794                 let bounds = if self.eat(&token::Colon) {
5795                     self.parse_lt_param_bounds()
5796                 } else {
5797                     Vec::new()
5798                 };
5799                 params.push(ast::GenericParam {
5800                     ident: lifetime.ident,
5801                     id: lifetime.id,
5802                     attrs: attrs.into(),
5803                     bounds,
5804                     kind: ast::GenericParamKind::Lifetime,
5805                 });
5806             } else if self.check_keyword(keywords::Const) {
5807                 // Parse const parameter.
5808                 params.push(self.parse_const_param(attrs)?);
5809             } else if self.check_ident() {
5810                 // Parse type parameter.
5811                 params.push(self.parse_ty_param(attrs)?);
5812             } else {
5813                 // Check for trailing attributes and stop parsing.
5814                 if !attrs.is_empty() {
5815                     if !params.is_empty() {
5816                         self.struct_span_err(
5817                             attrs[0].span,
5818                             &format!("trailing attribute after generic parameter"),
5819                         )
5820                         .span_label(attrs[0].span, "attributes must go before parameters")
5821                         .emit();
5822                     } else {
5823                         self.struct_span_err(
5824                             attrs[0].span,
5825                             &format!("attribute without generic parameters"),
5826                         )
5827                         .span_label(
5828                             attrs[0].span,
5829                             "attributes are only permitted when preceding parameters",
5830                         )
5831                         .emit();
5832                     }
5833                 }
5834                 break
5835             }
5836
5837             if !self.eat(&token::Comma) {
5838                 break
5839             }
5840         }
5841         Ok(params)
5842     }
5843
5844     /// Parses a set of optional generic type parameter declarations. Where
5845     /// clauses are not parsed here, and must be added later via
5846     /// `parse_where_clause()`.
5847     ///
5848     /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5849     ///                  | ( < lifetimes , typaramseq ( , )? > )
5850     /// where   typaramseq = ( typaram ) | ( typaram , typaramseq )
5851     fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5852         maybe_whole!(self, NtGenerics, |x| x);
5853
5854         let span_lo = self.span;
5855         if self.eat_lt() {
5856             let params = self.parse_generic_params()?;
5857             self.expect_gt()?;
5858             Ok(ast::Generics {
5859                 params,
5860                 where_clause: WhereClause {
5861                     id: ast::DUMMY_NODE_ID,
5862                     predicates: Vec::new(),
5863                     span: syntax_pos::DUMMY_SP,
5864                 },
5865                 span: span_lo.to(self.prev_span),
5866             })
5867         } else {
5868             Ok(ast::Generics::default())
5869         }
5870     }
5871
5872     /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5873     /// For the purposes of understanding the parsing logic of generic arguments, this function
5874     /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5875     /// had the correct amount of leading angle brackets.
5876     ///
5877     /// ```ignore (diagnostics)
5878     /// bar::<<<<T as Foo>::Output>();
5879     ///      ^^ help: remove extra angle brackets
5880     /// ```
5881     fn parse_generic_args_with_leaning_angle_bracket_recovery(
5882         &mut self,
5883         style: PathStyle,
5884         lo: Span,
5885     ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5886         // We need to detect whether there are extra leading left angle brackets and produce an
5887         // appropriate error and suggestion. This cannot be implemented by looking ahead at
5888         // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5889         // then there won't be matching `>` tokens to find.
5890         //
5891         // To explain how this detection works, consider the following example:
5892         //
5893         // ```ignore (diagnostics)
5894         // bar::<<<<T as Foo>::Output>();
5895         //      ^^ help: remove extra angle brackets
5896         // ```
5897         //
5898         // Parsing of the left angle brackets starts in this function. We start by parsing the
5899         // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5900         // `eat_lt`):
5901         //
5902         // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5903         // *Unmatched count:* 1
5904         // *`parse_path_segment` calls deep:* 0
5905         //
5906         // This has the effect of recursing as this function is called if a `<` character
5907         // is found within the expected generic arguments:
5908         //
5909         // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5910         // *Unmatched count:* 2
5911         // *`parse_path_segment` calls deep:* 1
5912         //
5913         // Eventually we will have recursed until having consumed all of the `<` tokens and
5914         // this will be reflected in the count:
5915         //
5916         // *Upcoming tokens:* `T as Foo>::Output>;`
5917         // *Unmatched count:* 4
5918         // `parse_path_segment` calls deep:* 3
5919         //
5920         // The parser will continue until reaching the first `>` - this will decrement the
5921         // unmatched angle bracket count and return to the parent invocation of this function
5922         // having succeeded in parsing:
5923         //
5924         // *Upcoming tokens:* `::Output>;`
5925         // *Unmatched count:* 3
5926         // *`parse_path_segment` calls deep:* 2
5927         //
5928         // This will continue until the next `>` character which will also return successfully
5929         // to the parent invocation of this function and decrement the count:
5930         //
5931         // *Upcoming tokens:* `;`
5932         // *Unmatched count:* 2
5933         // *`parse_path_segment` calls deep:* 1
5934         //
5935         // At this point, this function will expect to find another matching `>` character but
5936         // won't be able to and will return an error. This will continue all the way up the
5937         // call stack until the first invocation:
5938         //
5939         // *Upcoming tokens:* `;`
5940         // *Unmatched count:* 2
5941         // *`parse_path_segment` calls deep:* 0
5942         //
5943         // In doing this, we have managed to work out how many unmatched leading left angle
5944         // brackets there are, but we cannot recover as the unmatched angle brackets have
5945         // already been consumed. To remedy this, we keep a snapshot of the parser state
5946         // before we do the above. We can then inspect whether we ended up with a parsing error
5947         // and unmatched left angle brackets and if so, restore the parser state before we
5948         // consumed any `<` characters to emit an error and consume the erroneous tokens to
5949         // recover by attempting to parse again.
5950         //
5951         // In practice, the recursion of this function is indirect and there will be other
5952         // locations that consume some `<` characters - as long as we update the count when
5953         // this happens, it isn't an issue.
5954
5955         let is_first_invocation = style == PathStyle::Expr;
5956         // Take a snapshot before attempting to parse - we can restore this later.
5957         let snapshot = if is_first_invocation {
5958             Some(self.clone())
5959         } else {
5960             None
5961         };
5962
5963         debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
5964         match self.parse_generic_args() {
5965             Ok(value) => Ok(value),
5966             Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
5967                 // Cancel error from being unable to find `>`. We know the error
5968                 // must have been this due to a non-zero unmatched angle bracket
5969                 // count.
5970                 e.cancel();
5971
5972                 // Swap `self` with our backup of the parser state before attempting to parse
5973                 // generic arguments.
5974                 let snapshot = mem::replace(self, snapshot.unwrap());
5975
5976                 debug!(
5977                     "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
5978                      snapshot.count={:?}",
5979                     snapshot.unmatched_angle_bracket_count,
5980                 );
5981
5982                 // Eat the unmatched angle brackets.
5983                 for _ in 0..snapshot.unmatched_angle_bracket_count {
5984                     self.eat_lt();
5985                 }
5986
5987                 // Make a span over ${unmatched angle bracket count} characters.
5988                 let span = lo.with_hi(
5989                     lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
5990                 );
5991                 let plural = snapshot.unmatched_angle_bracket_count > 1;
5992                 self.diagnostic()
5993                     .struct_span_err(
5994                         span,
5995                         &format!(
5996                             "unmatched angle bracket{}",
5997                             if plural { "s" } else { "" }
5998                         ),
5999                     )
6000                     .span_suggestion(
6001                         span,
6002                         &format!(
6003                             "remove extra angle bracket{}",
6004                             if plural { "s" } else { "" }
6005                         ),
6006                         String::new(),
6007                         Applicability::MachineApplicable,
6008                     )
6009                     .emit();
6010
6011                 // Try again without unmatched angle bracket characters.
6012                 self.parse_generic_args()
6013             },
6014             Err(e) => Err(e),
6015         }
6016     }
6017
6018     /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
6019     /// possibly including trailing comma.
6020     fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
6021         let mut args = Vec::new();
6022         let mut bindings = Vec::new();
6023         let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new();
6024         let mut assoc_ty_bindings: Vec<Span> = Vec::new();
6025
6026         let args_lo = self.span;
6027
6028         loop {
6029             if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6030                 // Parse lifetime argument.
6031                 args.push(GenericArg::Lifetime(self.expect_lifetime()));
6032                 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6033             } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
6034                 // Parse associated type binding.
6035                 let lo = self.span;
6036                 let ident = self.parse_ident()?;
6037                 self.bump();
6038                 let ty = self.parse_ty()?;
6039                 let span = lo.to(self.prev_span);
6040                 bindings.push(TypeBinding {
6041                     id: ast::DUMMY_NODE_ID,
6042                     ident,
6043                     ty,
6044                     span,
6045                 });
6046                 assoc_ty_bindings.push(span);
6047             } else if self.check_const_arg() {
6048                 // FIXME(const_generics): to distinguish between idents for types and consts,
6049                 // we should introduce a GenericArg::Ident in the AST and distinguish when
6050                 // lowering to the HIR. For now, idents for const args are not permitted.
6051
6052                 // Parse const argument.
6053                 let expr = if let token::OpenDelim(token::Brace) = self.token {
6054                     self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
6055                 } else if self.token.is_ident() {
6056                     // FIXME(const_generics): to distinguish between idents for types and consts,
6057                     // we should introduce a GenericArg::Ident in the AST and distinguish when
6058                     // lowering to the HIR. For now, idents for const args are not permitted.
6059                     return Err(
6060                         self.fatal("identifiers may currently not be used for const generics")
6061                     );
6062                 } else {
6063                     // FIXME(const_generics): this currently conflicts with emplacement syntax
6064                     // with negative integer literals.
6065                     self.parse_literal_maybe_minus()?
6066                 };
6067                 let value = AnonConst {
6068                     id: ast::DUMMY_NODE_ID,
6069                     value: expr,
6070                 };
6071                 args.push(GenericArg::Const(value));
6072                 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6073             } else if self.check_type() {
6074                 // Parse type argument.
6075                 args.push(GenericArg::Type(self.parse_ty()?));
6076                 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6077             } else {
6078                 break
6079             }
6080
6081             if !self.eat(&token::Comma) {
6082                 break
6083             }
6084         }
6085
6086         // FIXME: we would like to report this in ast_validation instead, but we currently do not
6087         // preserve ordering of generic parameters with respect to associated type binding, so we
6088         // lose that information after parsing.
6089         if misplaced_assoc_ty_bindings.len() > 0 {
6090             let mut err = self.struct_span_err(
6091                 args_lo.to(self.prev_span),
6092                 "associated type bindings must be declared after generic parameters",
6093             );
6094             for span in misplaced_assoc_ty_bindings {
6095                 err.span_label(
6096                     span,
6097                     "this associated type binding should be moved after the generic parameters",
6098                 );
6099             }
6100             err.emit();
6101         }
6102
6103         Ok((args, bindings))
6104     }
6105
6106     /// Parses an optional where-clause and places it in `generics`.
6107     ///
6108     /// ```ignore (only-for-syntax-highlight)
6109     /// where T : Trait<U, V> + 'b, 'a : 'b
6110     /// ```
6111     fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
6112         maybe_whole!(self, NtWhereClause, |x| x);
6113
6114         let mut where_clause = WhereClause {
6115             id: ast::DUMMY_NODE_ID,
6116             predicates: Vec::new(),
6117             span: syntax_pos::DUMMY_SP,
6118         };
6119
6120         if !self.eat_keyword(keywords::Where) {
6121             return Ok(where_clause);
6122         }
6123         let lo = self.prev_span;
6124
6125         // We are considering adding generics to the `where` keyword as an alternative higher-rank
6126         // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
6127         // change we parse those generics now, but report an error.
6128         if self.choose_generics_over_qpath() {
6129             let generics = self.parse_generics()?;
6130             self.struct_span_err(
6131                 generics.span,
6132                 "generic parameters on `where` clauses are reserved for future use",
6133             )
6134                 .span_label(generics.span, "currently unsupported")
6135                 .emit();
6136         }
6137
6138         loop {
6139             let lo = self.span;
6140             if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6141                 let lifetime = self.expect_lifetime();
6142                 // Bounds starting with a colon are mandatory, but possibly empty.
6143                 self.expect(&token::Colon)?;
6144                 let bounds = self.parse_lt_param_bounds();
6145                 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
6146                     ast::WhereRegionPredicate {
6147                         span: lo.to(self.prev_span),
6148                         lifetime,
6149                         bounds,
6150                     }
6151                 ));
6152             } else if self.check_type() {
6153                 // Parse optional `for<'a, 'b>`.
6154                 // This `for` is parsed greedily and applies to the whole predicate,
6155                 // the bounded type can have its own `for` applying only to it.
6156                 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
6157                 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
6158                 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
6159                 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
6160
6161                 // Parse type with mandatory colon and (possibly empty) bounds,
6162                 // or with mandatory equality sign and the second type.
6163                 let ty = self.parse_ty()?;
6164                 if self.eat(&token::Colon) {
6165                     let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6166                     where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
6167                         ast::WhereBoundPredicate {
6168                             span: lo.to(self.prev_span),
6169                             bound_generic_params: lifetime_defs,
6170                             bounded_ty: ty,
6171                             bounds,
6172                         }
6173                     ));
6174                 // FIXME: Decide what should be used here, `=` or `==`.
6175                 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
6176                 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
6177                     let rhs_ty = self.parse_ty()?;
6178                     where_clause.predicates.push(ast::WherePredicate::EqPredicate(
6179                         ast::WhereEqPredicate {
6180                             span: lo.to(self.prev_span),
6181                             lhs_ty: ty,
6182                             rhs_ty,
6183                             id: ast::DUMMY_NODE_ID,
6184                         }
6185                     ));
6186                 } else {
6187                     return self.unexpected();
6188                 }
6189             } else {
6190                 break
6191             }
6192
6193             if !self.eat(&token::Comma) {
6194                 break
6195             }
6196         }
6197
6198         where_clause.span = lo.to(self.prev_span);
6199         Ok(where_clause)
6200     }
6201
6202     fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
6203                      -> PResult<'a, (Vec<Arg> , bool)> {
6204         self.expect(&token::OpenDelim(token::Paren))?;
6205
6206         let sp = self.span;
6207         let mut c_variadic = false;
6208         let (args, recovered): (Vec<Option<Arg>>, bool) =
6209             self.parse_seq_to_before_end(
6210                 &token::CloseDelim(token::Paren),
6211                 SeqSep::trailing_allowed(token::Comma),
6212                 |p| {
6213                     // If the argument is a C-variadic argument we should not
6214                     // enforce named arguments.
6215                     let enforce_named_args = if p.token == token::DotDotDot {
6216                         false
6217                     } else {
6218                         named_args
6219                     };
6220                     match p.parse_arg_general(enforce_named_args, false,
6221                                               allow_c_variadic) {
6222                         Ok(arg) => {
6223                             if let TyKind::CVarArgs = arg.ty.node {
6224                                 c_variadic = true;
6225                                 if p.token != token::CloseDelim(token::Paren) {
6226                                     let span = p.span;
6227                                     p.span_err(span,
6228                                         "`...` must be the last argument of a C-variadic function");
6229                                     Ok(None)
6230                                 } else {
6231                                     Ok(Some(arg))
6232                                 }
6233                             } else {
6234                                 Ok(Some(arg))
6235                             }
6236                         },
6237                         Err(mut e) => {
6238                             e.emit();
6239                             let lo = p.prev_span;
6240                             // Skip every token until next possible arg or end.
6241                             p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
6242                             // Create a placeholder argument for proper arg count (issue #34264).
6243                             let span = lo.to(p.prev_span);
6244                             Ok(Some(dummy_arg(span)))
6245                         }
6246                     }
6247                 }
6248             )?;
6249
6250         if !recovered {
6251             self.eat(&token::CloseDelim(token::Paren));
6252         }
6253
6254         let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
6255
6256         if c_variadic && args.is_empty() {
6257             self.span_err(sp,
6258                           "C-variadic function must be declared with at least one named argument");
6259         }
6260
6261         Ok((args, c_variadic))
6262     }
6263
6264     /// Parses the argument list and result type of a function declaration.
6265     fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
6266
6267         let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
6268         let ret_ty = self.parse_ret_ty(true)?;
6269
6270         Ok(P(FnDecl {
6271             inputs: args,
6272             output: ret_ty,
6273             c_variadic,
6274         }))
6275     }
6276
6277     /// Returns the parsed optional self argument and whether a self shortcut was used.
6278     fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
6279         let expect_ident = |this: &mut Self| match this.token {
6280             // Preserve hygienic context.
6281             token::Ident(ident, _) =>
6282                 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
6283             _ => unreachable!()
6284         };
6285         let isolated_self = |this: &mut Self, n| {
6286             this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) &&
6287             this.look_ahead(n + 1, |t| t != &token::ModSep)
6288         };
6289
6290         // Parse optional self parameter of a method.
6291         // Only a limited set of initial token sequences is considered self parameters, anything
6292         // else is parsed as a normal function parameter list, so some lookahead is required.
6293         let eself_lo = self.span;
6294         let (eself, eself_ident, eself_hi) = match self.token {
6295             token::BinOp(token::And) => {
6296                 // &self
6297                 // &mut self
6298                 // &'lt self
6299                 // &'lt mut self
6300                 // &not_self
6301                 (if isolated_self(self, 1) {
6302                     self.bump();
6303                     SelfKind::Region(None, Mutability::Immutable)
6304                 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
6305                           isolated_self(self, 2) {
6306                     self.bump();
6307                     self.bump();
6308                     SelfKind::Region(None, Mutability::Mutable)
6309                 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6310                           isolated_self(self, 2) {
6311                     self.bump();
6312                     let lt = self.expect_lifetime();
6313                     SelfKind::Region(Some(lt), Mutability::Immutable)
6314                 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6315                           self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
6316                           isolated_self(self, 3) {
6317                     self.bump();
6318                     let lt = self.expect_lifetime();
6319                     self.bump();
6320                     SelfKind::Region(Some(lt), Mutability::Mutable)
6321                 } else {
6322                     return Ok(None);
6323                 }, expect_ident(self), self.prev_span)
6324             }
6325             token::BinOp(token::Star) => {
6326                 // *self
6327                 // *const self
6328                 // *mut self
6329                 // *not_self
6330                 // Emit special error for `self` cases.
6331                 let msg = "cannot pass `self` by raw pointer";
6332                 (if isolated_self(self, 1) {
6333                     self.bump();
6334                     self.struct_span_err(self.span, msg)
6335                         .span_label(self.span, msg)
6336                         .emit();
6337                     SelfKind::Value(Mutability::Immutable)
6338                 } else if self.look_ahead(1, |t| t.is_mutability()) &&
6339                           isolated_self(self, 2) {
6340                     self.bump();
6341                     self.bump();
6342                     self.struct_span_err(self.span, msg)
6343                         .span_label(self.span, msg)
6344                         .emit();
6345                     SelfKind::Value(Mutability::Immutable)
6346                 } else {
6347                     return Ok(None);
6348                 }, expect_ident(self), self.prev_span)
6349             }
6350             token::Ident(..) => {
6351                 if isolated_self(self, 0) {
6352                     // self
6353                     // self: TYPE
6354                     let eself_ident = expect_ident(self);
6355                     let eself_hi = self.prev_span;
6356                     (if self.eat(&token::Colon) {
6357                         let ty = self.parse_ty()?;
6358                         SelfKind::Explicit(ty, Mutability::Immutable)
6359                     } else {
6360                         SelfKind::Value(Mutability::Immutable)
6361                     }, eself_ident, eself_hi)
6362                 } else if self.token.is_keyword(keywords::Mut) &&
6363                           isolated_self(self, 1) {
6364                     // mut self
6365                     // mut self: TYPE
6366                     self.bump();
6367                     let eself_ident = expect_ident(self);
6368                     let eself_hi = self.prev_span;
6369                     (if self.eat(&token::Colon) {
6370                         let ty = self.parse_ty()?;
6371                         SelfKind::Explicit(ty, Mutability::Mutable)
6372                     } else {
6373                         SelfKind::Value(Mutability::Mutable)
6374                     }, eself_ident, eself_hi)
6375                 } else {
6376                     return Ok(None);
6377                 }
6378             }
6379             _ => return Ok(None),
6380         };
6381
6382         let eself = source_map::respan(eself_lo.to(eself_hi), eself);
6383         Ok(Some(Arg::from_self(eself, eself_ident)))
6384     }
6385
6386     /// Parses the parameter list and result type of a function that may have a `self` parameter.
6387     fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
6388         where F: FnMut(&mut Parser<'a>) -> PResult<'a,  Arg>,
6389     {
6390         self.expect(&token::OpenDelim(token::Paren))?;
6391
6392         // Parse optional self argument
6393         let self_arg = self.parse_self_arg()?;
6394
6395         // Parse the rest of the function parameter list.
6396         let sep = SeqSep::trailing_allowed(token::Comma);
6397         let (fn_inputs, recovered) = if let Some(self_arg) = self_arg {
6398             if self.check(&token::CloseDelim(token::Paren)) {
6399                 (vec![self_arg], false)
6400             } else if self.eat(&token::Comma) {
6401                 let mut fn_inputs = vec![self_arg];
6402                 let (mut input, recovered) = self.parse_seq_to_before_end(
6403                     &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
6404                 fn_inputs.append(&mut input);
6405                 (fn_inputs, recovered)
6406             } else {
6407                 match self.expect_one_of(&[], &[]) {
6408                     Err(err) => return Err(err),
6409                     Ok(recovered) => (vec![self_arg], recovered),
6410                 }
6411             }
6412         } else {
6413             self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
6414         };
6415
6416         if !recovered {
6417             // Parse closing paren and return type.
6418             self.expect(&token::CloseDelim(token::Paren))?;
6419         }
6420         Ok(P(FnDecl {
6421             inputs: fn_inputs,
6422             output: self.parse_ret_ty(true)?,
6423             c_variadic: false
6424         }))
6425     }
6426
6427     /// Parses the `|arg, arg|` header of a closure.
6428     fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
6429         let inputs_captures = {
6430             if self.eat(&token::OrOr) {
6431                 Vec::new()
6432             } else {
6433                 self.expect(&token::BinOp(token::Or))?;
6434                 let args = self.parse_seq_to_before_tokens(
6435                     &[&token::BinOp(token::Or), &token::OrOr],
6436                     SeqSep::trailing_allowed(token::Comma),
6437                     TokenExpectType::NoExpect,
6438                     |p| p.parse_fn_block_arg()
6439                 )?.0;
6440                 self.expect_or()?;
6441                 args
6442             }
6443         };
6444         let output = self.parse_ret_ty(true)?;
6445
6446         Ok(P(FnDecl {
6447             inputs: inputs_captures,
6448             output,
6449             c_variadic: false
6450         }))
6451     }
6452
6453     /// Parses the name and optional generic types of a function header.
6454     fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
6455         let id = self.parse_ident()?;
6456         let generics = self.parse_generics()?;
6457         Ok((id, generics))
6458     }
6459
6460     fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
6461                attrs: Vec<Attribute>) -> P<Item> {
6462         P(Item {
6463             ident,
6464             attrs,
6465             id: ast::DUMMY_NODE_ID,
6466             node,
6467             vis,
6468             span,
6469             tokens: None,
6470         })
6471     }
6472
6473     /// Parses an item-position function declaration.
6474     fn parse_item_fn(&mut self,
6475                      unsafety: Unsafety,
6476                      mut asyncness: Spanned<IsAsync>,
6477                      constness: Spanned<Constness>,
6478                      abi: Abi)
6479                      -> PResult<'a, ItemInfo> {
6480         let (ident, mut generics) = self.parse_fn_header()?;
6481         let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
6482         let decl = self.parse_fn_decl(allow_c_variadic)?;
6483         generics.where_clause = self.parse_where_clause()?;
6484         let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6485         self.construct_async_arguments(&mut asyncness, &decl);
6486         let header = FnHeader { unsafety, asyncness, constness, abi };
6487         Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
6488     }
6489
6490     /// Returns `true` if we are looking at `const ID`
6491     /// (returns `false` for things like `const fn`, etc.).
6492     fn is_const_item(&mut self) -> bool {
6493         self.token.is_keyword(keywords::Const) &&
6494             !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
6495             !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
6496     }
6497
6498     /// Parses all the "front matter" for a `fn` declaration, up to
6499     /// and including the `fn` keyword:
6500     ///
6501     /// - `const fn`
6502     /// - `unsafe fn`
6503     /// - `const unsafe fn`
6504     /// - `extern fn`
6505     /// - etc.
6506     fn parse_fn_front_matter(&mut self)
6507         -> PResult<'a, (
6508             Spanned<Constness>,
6509             Unsafety,
6510             Spanned<IsAsync>,
6511             Abi
6512         )>
6513     {
6514         let is_const_fn = self.eat_keyword(keywords::Const);
6515         let const_span = self.prev_span;
6516         let unsafety = self.parse_unsafety();
6517         let asyncness = self.parse_asyncness();
6518         let asyncness = respan(self.prev_span, asyncness);
6519         let (constness, unsafety, abi) = if is_const_fn {
6520             (respan(const_span, Constness::Const), unsafety, Abi::Rust)
6521         } else {
6522             let abi = if self.eat_keyword(keywords::Extern) {
6523                 self.parse_opt_abi()?.unwrap_or(Abi::C)
6524             } else {
6525                 Abi::Rust
6526             };
6527             (respan(self.prev_span, Constness::NotConst), unsafety, abi)
6528         };
6529         if !self.eat_keyword(keywords::Fn) {
6530             // It is possible for `expect_one_of` to recover given the contents of
6531             // `self.expected_tokens`, therefore, do not use `self.unexpected()` which doesn't
6532             // account for this.
6533             if !self.expect_one_of(&[], &[])? { unreachable!() }
6534         }
6535         Ok((constness, unsafety, asyncness, abi))
6536     }
6537
6538     /// Parses an impl item.
6539     pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
6540         maybe_whole!(self, NtImplItem, |x| x);
6541         let attrs = self.parse_outer_attributes()?;
6542         let mut unclosed_delims = vec![];
6543         let (mut item, tokens) = self.collect_tokens(|this| {
6544             let item = this.parse_impl_item_(at_end, attrs);
6545             unclosed_delims.append(&mut this.unclosed_delims);
6546             item
6547         })?;
6548         self.unclosed_delims.append(&mut unclosed_delims);
6549
6550         // See `parse_item` for why this clause is here.
6551         if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6552             item.tokens = Some(tokens);
6553         }
6554         Ok(item)
6555     }
6556
6557     fn parse_impl_item_(&mut self,
6558                         at_end: &mut bool,
6559                         mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
6560         let lo = self.span;
6561         let vis = self.parse_visibility(false)?;
6562         let defaultness = self.parse_defaultness();
6563         let (name, node, generics) = if let Some(type_) = self.eat_type() {
6564             let (name, alias, generics) = type_?;
6565             let kind = match alias {
6566                 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
6567                 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
6568             };
6569             (name, kind, generics)
6570         } else if self.is_const_item() {
6571             // This parses the grammar:
6572             //     ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
6573             self.expect_keyword(keywords::Const)?;
6574             let name = self.parse_ident()?;
6575             self.expect(&token::Colon)?;
6576             let typ = self.parse_ty()?;
6577             self.expect(&token::Eq)?;
6578             let expr = self.parse_expr()?;
6579             self.expect(&token::Semi)?;
6580             (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
6581         } else {
6582             let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
6583             attrs.extend(inner_attrs);
6584             (name, node, generics)
6585         };
6586
6587         Ok(ImplItem {
6588             id: ast::DUMMY_NODE_ID,
6589             span: lo.to(self.prev_span),
6590             ident: name,
6591             vis,
6592             defaultness,
6593             attrs,
6594             generics,
6595             node,
6596             tokens: None,
6597         })
6598     }
6599
6600     fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
6601         match *vis {
6602             VisibilityKind::Inherited => {}
6603             _ => {
6604                 let is_macro_rules: bool = match self.token {
6605                     token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
6606                     _ => false,
6607                 };
6608                 let mut err = if is_macro_rules {
6609                     let mut err = self.diagnostic()
6610                         .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
6611                     err.span_suggestion(
6612                         sp,
6613                         "try exporting the macro",
6614                         "#[macro_export]".to_owned(),
6615                         Applicability::MaybeIncorrect // speculative
6616                     );
6617                     err
6618                 } else {
6619                     let mut err = self.diagnostic()
6620                         .struct_span_err(sp, "can't qualify macro invocation with `pub`");
6621                     err.help("try adjusting the macro to put `pub` inside the invocation");
6622                     err
6623                 };
6624                 err.emit();
6625             }
6626         }
6627     }
6628
6629     fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
6630                                    -> DiagnosticBuilder<'a>
6631     {
6632         let expected_kinds = if item_type == "extern" {
6633             "missing `fn`, `type`, or `static`"
6634         } else {
6635             "missing `fn`, `type`, or `const`"
6636         };
6637
6638         // Given this code `path(`, it seems like this is not
6639         // setting the visibility of a macro invocation, but rather
6640         // a mistyped method declaration.
6641         // Create a diagnostic pointing out that `fn` is missing.
6642         //
6643         // x |     pub path(&self) {
6644         //   |        ^ missing `fn`, `type`, or `const`
6645         //     pub  path(
6646         //        ^^ `sp` below will point to this
6647         let sp = prev_span.between(self.prev_span);
6648         let mut err = self.diagnostic().struct_span_err(
6649             sp,
6650             &format!("{} for {}-item declaration",
6651                      expected_kinds, item_type));
6652         err.span_label(sp, expected_kinds);
6653         err
6654     }
6655
6656     /// Parse a method or a macro invocation in a trait impl.
6657     fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
6658                          -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
6659                              ast::ImplItemKind)> {
6660         // code copied from parse_macro_use_or_failure... abstraction!
6661         if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
6662             // method macro
6663             Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
6664                 ast::ImplItemKind::Macro(mac)))
6665         } else {
6666             let (constness, unsafety, mut asyncness, abi) = self.parse_fn_front_matter()?;
6667             let ident = self.parse_ident()?;
6668             let mut generics = self.parse_generics()?;
6669             let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
6670             generics.where_clause = self.parse_where_clause()?;
6671             self.construct_async_arguments(&mut asyncness, &decl);
6672             *at_end = true;
6673             let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6674             let header = ast::FnHeader { abi, unsafety, constness, asyncness };
6675             Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
6676                 ast::MethodSig { header, decl },
6677                 body
6678             )))
6679         }
6680     }
6681
6682     /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
6683     fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
6684         let ident = self.parse_ident()?;
6685         let mut tps = self.parse_generics()?;
6686
6687         // Parse optional colon and supertrait bounds.
6688         let bounds = if self.eat(&token::Colon) {
6689             self.parse_generic_bounds(Some(self.prev_span))?
6690         } else {
6691             Vec::new()
6692         };
6693
6694         if self.eat(&token::Eq) {
6695             // it's a trait alias
6696             let bounds = self.parse_generic_bounds(None)?;
6697             tps.where_clause = self.parse_where_clause()?;
6698             self.expect(&token::Semi)?;
6699             if is_auto == IsAuto::Yes {
6700                 let msg = "trait aliases cannot be `auto`";
6701                 self.struct_span_err(self.prev_span, msg)
6702                     .span_label(self.prev_span, msg)
6703                     .emit();
6704             }
6705             if unsafety != Unsafety::Normal {
6706                 let msg = "trait aliases cannot be `unsafe`";
6707                 self.struct_span_err(self.prev_span, msg)
6708                     .span_label(self.prev_span, msg)
6709                     .emit();
6710             }
6711             Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
6712         } else {
6713             // it's a normal trait
6714             tps.where_clause = self.parse_where_clause()?;
6715             self.expect(&token::OpenDelim(token::Brace))?;
6716             let mut trait_items = vec![];
6717             while !self.eat(&token::CloseDelim(token::Brace)) {
6718                 if let token::DocComment(_) = self.token {
6719                     if self.look_ahead(1,
6720                     |tok| tok == &token::Token::CloseDelim(token::Brace)) {
6721                         let mut err = self.diagnostic().struct_span_err_with_code(
6722                             self.span,
6723                             "found a documentation comment that doesn't document anything",
6724                             DiagnosticId::Error("E0584".into()),
6725                         );
6726                         err.help("doc comments must come before what they document, maybe a \
6727                             comment was intended with `//`?",
6728                         );
6729                         err.emit();
6730                         self.bump();
6731                         continue;
6732                     }
6733                 }
6734                 let mut at_end = false;
6735                 match self.parse_trait_item(&mut at_end) {
6736                     Ok(item) => trait_items.push(item),
6737                     Err(mut e) => {
6738                         e.emit();
6739                         if !at_end {
6740                             self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6741                         }
6742                     }
6743                 }
6744             }
6745             Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
6746         }
6747     }
6748
6749     fn choose_generics_over_qpath(&self) -> bool {
6750         // There's an ambiguity between generic parameters and qualified paths in impls.
6751         // If we see `<` it may start both, so we have to inspect some following tokens.
6752         // The following combinations can only start generics,
6753         // but not qualified paths (with one exception):
6754         //     `<` `>` - empty generic parameters
6755         //     `<` `#` - generic parameters with attributes
6756         //     `<` (LIFETIME|IDENT) `>` - single generic parameter
6757         //     `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
6758         //     `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
6759         //     `<` (LIFETIME|IDENT) `=` - generic parameter with a default
6760         //     `<` const                - generic const parameter
6761         // The only truly ambiguous case is
6762         //     `<` IDENT `>` `::` IDENT ...
6763         // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
6764         // because this is what almost always expected in practice, qualified paths in impls
6765         // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
6766         self.token == token::Lt &&
6767             (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
6768              self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
6769                 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
6770                                        t == &token::Colon || t == &token::Eq) ||
6771              self.look_ahead(1, |t| t.is_keyword(keywords::Const)))
6772     }
6773
6774     fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6775         self.expect(&token::OpenDelim(token::Brace))?;
6776         let attrs = self.parse_inner_attributes()?;
6777
6778         let mut impl_items = Vec::new();
6779         while !self.eat(&token::CloseDelim(token::Brace)) {
6780             let mut at_end = false;
6781             match self.parse_impl_item(&mut at_end) {
6782                 Ok(impl_item) => impl_items.push(impl_item),
6783                 Err(mut err) => {
6784                     err.emit();
6785                     if !at_end {
6786                         self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6787                     }
6788                 }
6789             }
6790         }
6791         Ok((impl_items, attrs))
6792     }
6793
6794     /// Parses an implementation item, `impl` keyword is already parsed.
6795     ///
6796     ///    impl<'a, T> TYPE { /* impl items */ }
6797     ///    impl<'a, T> TRAIT for TYPE { /* impl items */ }
6798     ///    impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6799     ///
6800     /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6801     ///     `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6802     ///     `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6803     fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6804                        -> PResult<'a, ItemInfo> {
6805         // First, parse generic parameters if necessary.
6806         let mut generics = if self.choose_generics_over_qpath() {
6807             self.parse_generics()?
6808         } else {
6809             ast::Generics::default()
6810         };
6811
6812         // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6813         let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6814             self.bump(); // `!`
6815             ast::ImplPolarity::Negative
6816         } else {
6817             ast::ImplPolarity::Positive
6818         };
6819
6820         // Parse both types and traits as a type, then reinterpret if necessary.
6821         let err_path = |span| ast::Path::from_ident(Ident::new(keywords::Invalid.name(), span));
6822         let ty_first = if self.token.is_keyword(keywords::For) &&
6823                           self.look_ahead(1, |t| t != &token::Lt) {
6824             let span = self.prev_span.between(self.span);
6825             self.struct_span_err(span, "missing trait in a trait impl").emit();
6826             P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6827         } else {
6828             self.parse_ty()?
6829         };
6830
6831         // If `for` is missing we try to recover.
6832         let has_for = self.eat_keyword(keywords::For);
6833         let missing_for_span = self.prev_span.between(self.span);
6834
6835         let ty_second = if self.token == token::DotDot {
6836             // We need to report this error after `cfg` expansion for compatibility reasons
6837             self.bump(); // `..`, do not add it to expected tokens
6838             Some(DummyResult::raw_ty(self.prev_span, true))
6839         } else if has_for || self.token.can_begin_type() {
6840             Some(self.parse_ty()?)
6841         } else {
6842             None
6843         };
6844
6845         generics.where_clause = self.parse_where_clause()?;
6846
6847         let (impl_items, attrs) = self.parse_impl_body()?;
6848
6849         let item_kind = match ty_second {
6850             Some(ty_second) => {
6851                 // impl Trait for Type
6852                 if !has_for {
6853                     self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6854                         .span_suggestion_short(
6855                             missing_for_span,
6856                             "add `for` here",
6857                             " for ".to_string(),
6858                             Applicability::MachineApplicable,
6859                         ).emit();
6860                 }
6861
6862                 let ty_first = ty_first.into_inner();
6863                 let path = match ty_first.node {
6864                     // This notably includes paths passed through `ty` macro fragments (#46438).
6865                     TyKind::Path(None, path) => path,
6866                     _ => {
6867                         self.span_err(ty_first.span, "expected a trait, found type");
6868                         err_path(ty_first.span)
6869                     }
6870                 };
6871                 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6872
6873                 ItemKind::Impl(unsafety, polarity, defaultness,
6874                                generics, Some(trait_ref), ty_second, impl_items)
6875             }
6876             None => {
6877                 // impl Type
6878                 ItemKind::Impl(unsafety, polarity, defaultness,
6879                                generics, None, ty_first, impl_items)
6880             }
6881         };
6882
6883         Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
6884     }
6885
6886     fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6887         if self.eat_keyword(keywords::For) {
6888             self.expect_lt()?;
6889             let params = self.parse_generic_params()?;
6890             self.expect_gt()?;
6891             // We rely on AST validation to rule out invalid cases: There must not be type
6892             // parameters, and the lifetime parameters must not have bounds.
6893             Ok(params)
6894         } else {
6895             Ok(Vec::new())
6896         }
6897     }
6898
6899     /// Parses `struct Foo { ... }`.
6900     fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6901         let class_name = self.parse_ident()?;
6902
6903         let mut generics = self.parse_generics()?;
6904
6905         // There is a special case worth noting here, as reported in issue #17904.
6906         // If we are parsing a tuple struct it is the case that the where clause
6907         // should follow the field list. Like so:
6908         //
6909         // struct Foo<T>(T) where T: Copy;
6910         //
6911         // If we are parsing a normal record-style struct it is the case
6912         // that the where clause comes before the body, and after the generics.
6913         // So if we look ahead and see a brace or a where-clause we begin
6914         // parsing a record style struct.
6915         //
6916         // Otherwise if we look ahead and see a paren we parse a tuple-style
6917         // struct.
6918
6919         let vdata = if self.token.is_keyword(keywords::Where) {
6920             generics.where_clause = self.parse_where_clause()?;
6921             if self.eat(&token::Semi) {
6922                 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6923                 VariantData::Unit(ast::DUMMY_NODE_ID)
6924             } else {
6925                 // If we see: `struct Foo<T> where T: Copy { ... }`
6926                 let (fields, recovered) = self.parse_record_struct_body()?;
6927                 VariantData::Struct(fields, recovered)
6928             }
6929         // No `where` so: `struct Foo<T>;`
6930         } else if self.eat(&token::Semi) {
6931             VariantData::Unit(ast::DUMMY_NODE_ID)
6932         // Record-style struct definition
6933         } else if self.token == token::OpenDelim(token::Brace) {
6934             let (fields, recovered) = self.parse_record_struct_body()?;
6935             VariantData::Struct(fields, recovered)
6936         // Tuple-style struct definition with optional where-clause.
6937         } else if self.token == token::OpenDelim(token::Paren) {
6938             let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6939             generics.where_clause = self.parse_where_clause()?;
6940             self.expect(&token::Semi)?;
6941             body
6942         } else {
6943             let token_str = self.this_token_descr();
6944             let mut err = self.fatal(&format!(
6945                 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6946                 token_str
6947             ));
6948             err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6949             return Err(err);
6950         };
6951
6952         Ok((class_name, ItemKind::Struct(vdata, generics), None))
6953     }
6954
6955     /// Parses `union Foo { ... }`.
6956     fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6957         let class_name = self.parse_ident()?;
6958
6959         let mut generics = self.parse_generics()?;
6960
6961         let vdata = if self.token.is_keyword(keywords::Where) {
6962             generics.where_clause = self.parse_where_clause()?;
6963             let (fields, recovered) = self.parse_record_struct_body()?;
6964             VariantData::Struct(fields, recovered)
6965         } else if self.token == token::OpenDelim(token::Brace) {
6966             let (fields, recovered) = self.parse_record_struct_body()?;
6967             VariantData::Struct(fields, recovered)
6968         } else {
6969             let token_str = self.this_token_descr();
6970             let mut err = self.fatal(&format!(
6971                 "expected `where` or `{{` after union name, found {}", token_str));
6972             err.span_label(self.span, "expected `where` or `{` after union name");
6973             return Err(err);
6974         };
6975
6976         Ok((class_name, ItemKind::Union(vdata, generics), None))
6977     }
6978
6979     fn consume_block(&mut self, delim: token::DelimToken) {
6980         let mut brace_depth = 0;
6981         loop {
6982             if self.eat(&token::OpenDelim(delim)) {
6983                 brace_depth += 1;
6984             } else if self.eat(&token::CloseDelim(delim)) {
6985                 if brace_depth == 0 {
6986                     return;
6987                 } else {
6988                     brace_depth -= 1;
6989                     continue;
6990                 }
6991             } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
6992                 return;
6993             } else {
6994                 self.bump();
6995             }
6996         }
6997     }
6998
6999     fn parse_record_struct_body(
7000         &mut self,
7001     ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
7002         let mut fields = Vec::new();
7003         let mut recovered = false;
7004         if self.eat(&token::OpenDelim(token::Brace)) {
7005             while self.token != token::CloseDelim(token::Brace) {
7006                 let field = self.parse_struct_decl_field().map_err(|e| {
7007                     self.recover_stmt();
7008                     recovered = true;
7009                     e
7010                 });
7011                 match field {
7012                     Ok(field) => fields.push(field),
7013                     Err(mut err) => {
7014                         err.emit();
7015                     }
7016                 }
7017             }
7018             self.eat(&token::CloseDelim(token::Brace));
7019         } else {
7020             let token_str = self.this_token_descr();
7021             let mut err = self.fatal(&format!(
7022                     "expected `where`, or `{{` after struct name, found {}", token_str));
7023             err.span_label(self.span, "expected `where`, or `{` after struct name");
7024             return Err(err);
7025         }
7026
7027         Ok((fields, recovered))
7028     }
7029
7030     fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
7031         // This is the case where we find `struct Foo<T>(T) where T: Copy;`
7032         // Unit like structs are handled in parse_item_struct function
7033         let fields = self.parse_unspanned_seq(
7034             &token::OpenDelim(token::Paren),
7035             &token::CloseDelim(token::Paren),
7036             SeqSep::trailing_allowed(token::Comma),
7037             |p| {
7038                 let attrs = p.parse_outer_attributes()?;
7039                 let lo = p.span;
7040                 let vis = p.parse_visibility(true)?;
7041                 let ty = p.parse_ty()?;
7042                 Ok(StructField {
7043                     span: lo.to(ty.span),
7044                     vis,
7045                     ident: None,
7046                     id: ast::DUMMY_NODE_ID,
7047                     ty,
7048                     attrs,
7049                 })
7050             })?;
7051
7052         Ok(fields)
7053     }
7054
7055     /// Parses a structure field declaration.
7056     fn parse_single_struct_field(&mut self,
7057                                      lo: Span,
7058                                      vis: Visibility,
7059                                      attrs: Vec<Attribute> )
7060                                      -> PResult<'a, StructField> {
7061         let mut seen_comma: bool = false;
7062         let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
7063         if self.token == token::Comma {
7064             seen_comma = true;
7065         }
7066         match self.token {
7067             token::Comma => {
7068                 self.bump();
7069             }
7070             token::CloseDelim(token::Brace) => {}
7071             token::DocComment(_) => {
7072                 let previous_span = self.prev_span;
7073                 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
7074                 self.bump(); // consume the doc comment
7075                 let comma_after_doc_seen = self.eat(&token::Comma);
7076                 // `seen_comma` is always false, because we are inside doc block
7077                 // condition is here to make code more readable
7078                 if seen_comma == false && comma_after_doc_seen == true {
7079                     seen_comma = true;
7080                 }
7081                 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
7082                     err.emit();
7083                 } else {
7084                     if seen_comma == false {
7085                         let sp = self.sess.source_map().next_point(previous_span);
7086                         err.span_suggestion(
7087                             sp,
7088                             "missing comma here",
7089                             ",".into(),
7090                             Applicability::MachineApplicable
7091                         );
7092                     }
7093                     return Err(err);
7094                 }
7095             }
7096             _ => {
7097                 let sp = self.sess.source_map().next_point(self.prev_span);
7098                 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
7099                                                                 self.this_token_descr()));
7100                 if self.token.is_ident() {
7101                     // This is likely another field; emit the diagnostic and keep going
7102                     err.span_suggestion(
7103                         sp,
7104                         "try adding a comma",
7105                         ",".into(),
7106                         Applicability::MachineApplicable,
7107                     );
7108                     err.emit();
7109                 } else {
7110                     return Err(err)
7111                 }
7112             }
7113         }
7114         Ok(a_var)
7115     }
7116
7117     /// Parses an element of a struct declaration.
7118     fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
7119         let attrs = self.parse_outer_attributes()?;
7120         let lo = self.span;
7121         let vis = self.parse_visibility(false)?;
7122         self.parse_single_struct_field(lo, vis, attrs)
7123     }
7124
7125     /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
7126     /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
7127     /// If the following element can't be a tuple (i.e., it's a function definition), then
7128     /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
7129     /// so emit a proper diagnostic.
7130     pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
7131         maybe_whole!(self, NtVis, |x| x);
7132
7133         self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
7134         if self.is_crate_vis() {
7135             self.bump(); // `crate`
7136             return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
7137         }
7138
7139         if !self.eat_keyword(keywords::Pub) {
7140             // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
7141             // keyword to grab a span from for inherited visibility; an empty span at the
7142             // beginning of the current token would seem to be the "Schelling span".
7143             return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
7144         }
7145         let lo = self.prev_span;
7146
7147         if self.check(&token::OpenDelim(token::Paren)) {
7148             // We don't `self.bump()` the `(` yet because this might be a struct definition where
7149             // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
7150             // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
7151             // by the following tokens.
7152             if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) &&
7153                 self.look_ahead(2, |t| t != &token::ModSep) // account for `pub(crate::foo)`
7154             {
7155                 // `pub(crate)`
7156                 self.bump(); // `(`
7157                 self.bump(); // `crate`
7158                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7159                 let vis = respan(
7160                     lo.to(self.prev_span),
7161                     VisibilityKind::Crate(CrateSugar::PubCrate),
7162                 );
7163                 return Ok(vis)
7164             } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
7165                 // `pub(in path)`
7166                 self.bump(); // `(`
7167                 self.bump(); // `in`
7168                 let path = self.parse_path(PathStyle::Mod)?; // `path`
7169                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7170                 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7171                     path: P(path),
7172                     id: ast::DUMMY_NODE_ID,
7173                 });
7174                 return Ok(vis)
7175             } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
7176                       self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
7177                                              t.is_keyword(keywords::SelfLower))
7178             {
7179                 // `pub(self)` or `pub(super)`
7180                 self.bump(); // `(`
7181                 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
7182                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7183                 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7184                     path: P(path),
7185                     id: ast::DUMMY_NODE_ID,
7186                 });
7187                 return Ok(vis)
7188             } else if !can_take_tuple {  // Provide this diagnostic if this is not a tuple struct
7189                 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
7190                 self.bump(); // `(`
7191                 let msg = "incorrect visibility restriction";
7192                 let suggestion = r##"some possible visibility restrictions are:
7193 `pub(crate)`: visible only on the current crate
7194 `pub(super)`: visible only in the current module's parent
7195 `pub(in path::to::module)`: visible only on the specified path"##;
7196                 let path = self.parse_path(PathStyle::Mod)?;
7197                 let sp = path.span;
7198                 let help_msg = format!("make this visible only to module `{}` with `in`", path);
7199                 self.expect(&token::CloseDelim(token::Paren))?;  // `)`
7200                 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
7201                 err.help(suggestion);
7202                 err.span_suggestion(
7203                     sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
7204                 );
7205                 err.emit();  // emit diagnostic, but continue with public visibility
7206             }
7207         }
7208
7209         Ok(respan(lo, VisibilityKind::Public))
7210     }
7211
7212     /// Parses defaultness (i.e., `default` or nothing).
7213     fn parse_defaultness(&mut self) -> Defaultness {
7214         // `pub` is included for better error messages
7215         if self.check_keyword(keywords::Default) &&
7216            self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
7217                                   t.is_keyword(keywords::Const) ||
7218                                   t.is_keyword(keywords::Fn) ||
7219                                   t.is_keyword(keywords::Unsafe) ||
7220                                   t.is_keyword(keywords::Extern) ||
7221                                   t.is_keyword(keywords::Type) ||
7222                                   t.is_keyword(keywords::Pub)) {
7223             self.bump(); // `default`
7224             Defaultness::Default
7225         } else {
7226             Defaultness::Final
7227         }
7228     }
7229
7230     /// Given a termination token, parses all of the items in a module.
7231     fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
7232         let mut items = vec![];
7233         while let Some(item) = self.parse_item()? {
7234             items.push(item);
7235             self.maybe_consume_incorrect_semicolon(&items);
7236         }
7237
7238         if !self.eat(term) {
7239             let token_str = self.this_token_descr();
7240             if !self.maybe_consume_incorrect_semicolon(&items) {
7241                 let mut err = self.fatal(&format!("expected item, found {}", token_str));
7242                 err.span_label(self.span, "expected item");
7243                 return Err(err);
7244             }
7245         }
7246
7247         let hi = if self.span.is_dummy() {
7248             inner_lo
7249         } else {
7250             self.prev_span
7251         };
7252
7253         Ok(ast::Mod {
7254             inner: inner_lo.to(hi),
7255             items,
7256             inline: true
7257         })
7258     }
7259
7260     fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
7261         let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
7262         self.expect(&token::Colon)?;
7263         let ty = self.parse_ty()?;
7264         self.expect(&token::Eq)?;
7265         let e = self.parse_expr()?;
7266         self.expect(&token::Semi)?;
7267         let item = match m {
7268             Some(m) => ItemKind::Static(ty, m, e),
7269             None => ItemKind::Const(ty, e),
7270         };
7271         Ok((id, item, None))
7272     }
7273
7274     /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
7275     fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
7276         let (in_cfg, outer_attrs) = {
7277             let mut strip_unconfigured = crate::config::StripUnconfigured {
7278                 sess: self.sess,
7279                 features: None, // don't perform gated feature checking
7280             };
7281             let mut outer_attrs = outer_attrs.to_owned();
7282             strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
7283             (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
7284         };
7285
7286         let id_span = self.span;
7287         let id = self.parse_ident()?;
7288         if self.eat(&token::Semi) {
7289             if in_cfg && self.recurse_into_file_modules {
7290                 // This mod is in an external file. Let's go get it!
7291                 let ModulePathSuccess { path, directory_ownership, warn } =
7292                     self.submod_path(id, &outer_attrs, id_span)?;
7293                 let (module, mut attrs) =
7294                     self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
7295                 // Record that we fetched the mod from an external file
7296                 if warn {
7297                     let attr = Attribute {
7298                         id: attr::mk_attr_id(),
7299                         style: ast::AttrStyle::Outer,
7300                         path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
7301                         tokens: TokenStream::empty(),
7302                         is_sugared_doc: false,
7303                         span: syntax_pos::DUMMY_SP,
7304                     };
7305                     attr::mark_known(&attr);
7306                     attrs.push(attr);
7307                 }
7308                 Ok((id, ItemKind::Mod(module), Some(attrs)))
7309             } else {
7310                 let placeholder = ast::Mod {
7311                     inner: syntax_pos::DUMMY_SP,
7312                     items: Vec::new(),
7313                     inline: false
7314                 };
7315                 Ok((id, ItemKind::Mod(placeholder), None))
7316             }
7317         } else {
7318             let old_directory = self.directory.clone();
7319             self.push_directory(id, &outer_attrs);
7320
7321             self.expect(&token::OpenDelim(token::Brace))?;
7322             let mod_inner_lo = self.span;
7323             let attrs = self.parse_inner_attributes()?;
7324             let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
7325
7326             self.directory = old_directory;
7327             Ok((id, ItemKind::Mod(module), Some(attrs)))
7328         }
7329     }
7330
7331     fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
7332         if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
7333             self.directory.path.to_mut().push(&path.as_str());
7334             self.directory.ownership = DirectoryOwnership::Owned { relative: None };
7335         } else {
7336             // We have to push on the current module name in the case of relative
7337             // paths in order to ensure that any additional module paths from inline
7338             // `mod x { ... }` come after the relative extension.
7339             //
7340             // For example, a `mod z { ... }` inside `x/y.rs` should set the current
7341             // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
7342             if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
7343                 if let Some(ident) = relative.take() { // remove the relative offset
7344                     self.directory.path.to_mut().push(ident.as_str());
7345                 }
7346             }
7347             self.directory.path.to_mut().push(&id.as_str());
7348         }
7349     }
7350
7351     pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
7352         if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
7353             let s = s.as_str();
7354
7355             // On windows, the base path might have the form
7356             // `\\?\foo\bar` in which case it does not tolerate
7357             // mixed `/` and `\` separators, so canonicalize
7358             // `/` to `\`.
7359             #[cfg(windows)]
7360             let s = s.replace("/", "\\");
7361             Some(dir_path.join(s))
7362         } else {
7363             None
7364         }
7365     }
7366
7367     /// Returns a path to a module.
7368     pub fn default_submod_path(
7369         id: ast::Ident,
7370         relative: Option<ast::Ident>,
7371         dir_path: &Path,
7372         source_map: &SourceMap) -> ModulePath
7373     {
7374         // If we're in a foo.rs file instead of a mod.rs file,
7375         // we need to look for submodules in
7376         // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
7377         // `./<id>.rs` and `./<id>/mod.rs`.
7378         let relative_prefix_string;
7379         let relative_prefix = if let Some(ident) = relative {
7380             relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
7381             &relative_prefix_string
7382         } else {
7383             ""
7384         };
7385
7386         let mod_name = id.to_string();
7387         let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
7388         let secondary_path_str = format!("{}{}{}mod.rs",
7389                                          relative_prefix, mod_name, path::MAIN_SEPARATOR);
7390         let default_path = dir_path.join(&default_path_str);
7391         let secondary_path = dir_path.join(&secondary_path_str);
7392         let default_exists = source_map.file_exists(&default_path);
7393         let secondary_exists = source_map.file_exists(&secondary_path);
7394
7395         let result = match (default_exists, secondary_exists) {
7396             (true, false) => Ok(ModulePathSuccess {
7397                 path: default_path,
7398                 directory_ownership: DirectoryOwnership::Owned {
7399                     relative: Some(id),
7400                 },
7401                 warn: false,
7402             }),
7403             (false, true) => Ok(ModulePathSuccess {
7404                 path: secondary_path,
7405                 directory_ownership: DirectoryOwnership::Owned {
7406                     relative: None,
7407                 },
7408                 warn: false,
7409             }),
7410             (false, false) => Err(Error::FileNotFoundForModule {
7411                 mod_name: mod_name.clone(),
7412                 default_path: default_path_str,
7413                 secondary_path: secondary_path_str,
7414                 dir_path: dir_path.display().to_string(),
7415             }),
7416             (true, true) => Err(Error::DuplicatePaths {
7417                 mod_name: mod_name.clone(),
7418                 default_path: default_path_str,
7419                 secondary_path: secondary_path_str,
7420             }),
7421         };
7422
7423         ModulePath {
7424             name: mod_name,
7425             path_exists: default_exists || secondary_exists,
7426             result,
7427         }
7428     }
7429
7430     fn submod_path(&mut self,
7431                    id: ast::Ident,
7432                    outer_attrs: &[Attribute],
7433                    id_sp: Span)
7434                    -> PResult<'a, ModulePathSuccess> {
7435         if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
7436             return Ok(ModulePathSuccess {
7437                 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
7438                     // All `#[path]` files are treated as though they are a `mod.rs` file.
7439                     // This means that `mod foo;` declarations inside `#[path]`-included
7440                     // files are siblings,
7441                     //
7442                     // Note that this will produce weirdness when a file named `foo.rs` is
7443                     // `#[path]` included and contains a `mod foo;` declaration.
7444                     // If you encounter this, it's your own darn fault :P
7445                     Some(_) => DirectoryOwnership::Owned { relative: None },
7446                     _ => DirectoryOwnership::UnownedViaMod(true),
7447                 },
7448                 path,
7449                 warn: false,
7450             });
7451         }
7452
7453         let relative = match self.directory.ownership {
7454             DirectoryOwnership::Owned { relative } => relative,
7455             DirectoryOwnership::UnownedViaBlock |
7456             DirectoryOwnership::UnownedViaMod(_) => None,
7457         };
7458         let paths = Parser::default_submod_path(
7459                         id, relative, &self.directory.path, self.sess.source_map());
7460
7461         match self.directory.ownership {
7462             DirectoryOwnership::Owned { .. } => {
7463                 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
7464             },
7465             DirectoryOwnership::UnownedViaBlock => {
7466                 let msg =
7467                     "Cannot declare a non-inline module inside a block \
7468                     unless it has a path attribute";
7469                 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
7470                 if paths.path_exists {
7471                     let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
7472                                       paths.name);
7473                     err.span_note(id_sp, &msg);
7474                 }
7475                 Err(err)
7476             }
7477             DirectoryOwnership::UnownedViaMod(warn) => {
7478                 if warn {
7479                     if let Ok(result) = paths.result {
7480                         return Ok(ModulePathSuccess { warn: true, ..result });
7481                     }
7482                 }
7483                 let mut err = self.diagnostic().struct_span_err(id_sp,
7484                     "cannot declare a new module at this location");
7485                 if !id_sp.is_dummy() {
7486                     let src_path = self.sess.source_map().span_to_filename(id_sp);
7487                     if let FileName::Real(src_path) = src_path {
7488                         if let Some(stem) = src_path.file_stem() {
7489                             let mut dest_path = src_path.clone();
7490                             dest_path.set_file_name(stem);
7491                             dest_path.push("mod.rs");
7492                             err.span_note(id_sp,
7493                                     &format!("maybe move this module `{}` to its own \
7494                                                 directory via `{}`", src_path.display(),
7495                                             dest_path.display()));
7496                         }
7497                     }
7498                 }
7499                 if paths.path_exists {
7500                     err.span_note(id_sp,
7501                                   &format!("... or maybe `use` the module `{}` instead \
7502                                             of possibly redeclaring it",
7503                                            paths.name));
7504                 }
7505                 Err(err)
7506             }
7507         }
7508     }
7509
7510     /// Reads a module from a source file.
7511     fn eval_src_mod(&mut self,
7512                     path: PathBuf,
7513                     directory_ownership: DirectoryOwnership,
7514                     name: String,
7515                     id_sp: Span)
7516                     -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
7517         let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
7518         if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
7519             let mut err = String::from("circular modules: ");
7520             let len = included_mod_stack.len();
7521             for p in &included_mod_stack[i.. len] {
7522                 err.push_str(&p.to_string_lossy());
7523                 err.push_str(" -> ");
7524             }
7525             err.push_str(&path.to_string_lossy());
7526             return Err(self.span_fatal(id_sp, &err[..]));
7527         }
7528         included_mod_stack.push(path.clone());
7529         drop(included_mod_stack);
7530
7531         let mut p0 =
7532             new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
7533         p0.cfg_mods = self.cfg_mods;
7534         let mod_inner_lo = p0.span;
7535         let mod_attrs = p0.parse_inner_attributes()?;
7536         let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
7537         m0.inline = false;
7538         self.sess.included_mod_stack.borrow_mut().pop();
7539         Ok((m0, mod_attrs))
7540     }
7541
7542     /// Parses a function declaration from a foreign module.
7543     fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7544                              -> PResult<'a, ForeignItem> {
7545         self.expect_keyword(keywords::Fn)?;
7546
7547         let (ident, mut generics) = self.parse_fn_header()?;
7548         let decl = self.parse_fn_decl(true)?;
7549         generics.where_clause = self.parse_where_clause()?;
7550         let hi = self.span;
7551         self.expect(&token::Semi)?;
7552         Ok(ast::ForeignItem {
7553             ident,
7554             attrs,
7555             node: ForeignItemKind::Fn(decl, generics),
7556             id: ast::DUMMY_NODE_ID,
7557             span: lo.to(hi),
7558             vis,
7559         })
7560     }
7561
7562     /// Parses a static item from a foreign module.
7563     /// Assumes that the `static` keyword is already parsed.
7564     fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7565                                  -> PResult<'a, ForeignItem> {
7566         let mutbl = self.parse_mutability();
7567         let ident = self.parse_ident()?;
7568         self.expect(&token::Colon)?;
7569         let ty = self.parse_ty()?;
7570         let hi = self.span;
7571         self.expect(&token::Semi)?;
7572         Ok(ForeignItem {
7573             ident,
7574             attrs,
7575             node: ForeignItemKind::Static(ty, mutbl),
7576             id: ast::DUMMY_NODE_ID,
7577             span: lo.to(hi),
7578             vis,
7579         })
7580     }
7581
7582     /// Parses a type from a foreign module.
7583     fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7584                              -> PResult<'a, ForeignItem> {
7585         self.expect_keyword(keywords::Type)?;
7586
7587         let ident = self.parse_ident()?;
7588         let hi = self.span;
7589         self.expect(&token::Semi)?;
7590         Ok(ast::ForeignItem {
7591             ident: ident,
7592             attrs: attrs,
7593             node: ForeignItemKind::Ty,
7594             id: ast::DUMMY_NODE_ID,
7595             span: lo.to(hi),
7596             vis: vis
7597         })
7598     }
7599
7600     fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
7601         let error_msg = "crate name using dashes are not valid in `extern crate` statements";
7602         let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
7603                               in the code";
7604         let mut ident = if self.token.is_keyword(keywords::SelfLower) {
7605             self.parse_path_segment_ident()
7606         } else {
7607             self.parse_ident()
7608         }?;
7609         let mut idents = vec![];
7610         let mut replacement = vec![];
7611         let mut fixed_crate_name = false;
7612         // Accept `extern crate name-like-this` for better diagnostics
7613         let dash = token::Token::BinOp(token::BinOpToken::Minus);
7614         if self.token == dash {  // Do not include `-` as part of the expected tokens list
7615             while self.eat(&dash) {
7616                 fixed_crate_name = true;
7617                 replacement.push((self.prev_span, "_".to_string()));
7618                 idents.push(self.parse_ident()?);
7619             }
7620         }
7621         if fixed_crate_name {
7622             let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
7623             let mut fixed_name = format!("{}", ident.name);
7624             for part in idents {
7625                 fixed_name.push_str(&format!("_{}", part.name));
7626             }
7627             ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
7628
7629             let mut err = self.struct_span_err(fixed_name_sp, error_msg);
7630             err.span_label(fixed_name_sp, "dash-separated idents are not valid");
7631             err.multipart_suggestion(
7632                 suggestion_msg,
7633                 replacement,
7634                 Applicability::MachineApplicable,
7635             );
7636             err.emit();
7637         }
7638         Ok(ident)
7639     }
7640
7641     /// Parses `extern crate` links.
7642     ///
7643     /// # Examples
7644     ///
7645     /// ```
7646     /// extern crate foo;
7647     /// extern crate bar as foo;
7648     /// ```
7649     fn parse_item_extern_crate(&mut self,
7650                                lo: Span,
7651                                visibility: Visibility,
7652                                attrs: Vec<Attribute>)
7653                                -> PResult<'a, P<Item>> {
7654         // Accept `extern crate name-like-this` for better diagnostics
7655         let orig_name = self.parse_crate_name_with_dashes()?;
7656         let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
7657             (rename, Some(orig_name.name))
7658         } else {
7659             (orig_name, None)
7660         };
7661         self.expect(&token::Semi)?;
7662
7663         let span = lo.to(self.prev_span);
7664         Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
7665     }
7666
7667     /// Parses `extern` for foreign ABIs modules.
7668     ///
7669     /// `extern` is expected to have been
7670     /// consumed before calling this method.
7671     ///
7672     /// # Examples
7673     ///
7674     /// ```ignore (only-for-syntax-highlight)
7675     /// extern "C" {}
7676     /// extern {}
7677     /// ```
7678     fn parse_item_foreign_mod(&mut self,
7679                               lo: Span,
7680                               opt_abi: Option<Abi>,
7681                               visibility: Visibility,
7682                               mut attrs: Vec<Attribute>)
7683                               -> PResult<'a, P<Item>> {
7684         self.expect(&token::OpenDelim(token::Brace))?;
7685
7686         let abi = opt_abi.unwrap_or(Abi::C);
7687
7688         attrs.extend(self.parse_inner_attributes()?);
7689
7690         let mut foreign_items = vec![];
7691         while !self.eat(&token::CloseDelim(token::Brace)) {
7692             foreign_items.push(self.parse_foreign_item()?);
7693         }
7694
7695         let prev_span = self.prev_span;
7696         let m = ast::ForeignMod {
7697             abi,
7698             items: foreign_items
7699         };
7700         let invalid = keywords::Invalid.ident();
7701         Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
7702     }
7703
7704     /// Parses `type Foo = Bar;`
7705     /// or
7706     /// `existential type Foo: Bar;`
7707     /// or
7708     /// `return `None``
7709     /// without modifying the parser state.
7710     fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
7711         // This parses the grammar:
7712         //     Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
7713         if self.check_keyword(keywords::Type) ||
7714            self.check_keyword(keywords::Existential) &&
7715                 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
7716             let existential = self.eat_keyword(keywords::Existential);
7717             assert!(self.eat_keyword(keywords::Type));
7718             Some(self.parse_existential_or_alias(existential))
7719         } else {
7720             None
7721         }
7722     }
7723
7724     /// Parses a type alias or existential type.
7725     fn parse_existential_or_alias(
7726         &mut self,
7727         existential: bool,
7728     ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
7729         let ident = self.parse_ident()?;
7730         let mut tps = self.parse_generics()?;
7731         tps.where_clause = self.parse_where_clause()?;
7732         let alias = if existential {
7733             self.expect(&token::Colon)?;
7734             let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
7735             AliasKind::Existential(bounds)
7736         } else {
7737             self.expect(&token::Eq)?;
7738             let ty = self.parse_ty()?;
7739             AliasKind::Weak(ty)
7740         };
7741         self.expect(&token::Semi)?;
7742         Ok((ident, alias, tps))
7743     }
7744
7745     /// Parses the part of an enum declaration following the `{`.
7746     fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
7747         let mut variants = Vec::new();
7748         let mut all_nullary = true;
7749         let mut any_disr = vec![];
7750         while self.token != token::CloseDelim(token::Brace) {
7751             let variant_attrs = self.parse_outer_attributes()?;
7752             let vlo = self.span;
7753
7754             let struct_def;
7755             let mut disr_expr = None;
7756             self.eat_bad_pub();
7757             let ident = self.parse_ident()?;
7758             if self.check(&token::OpenDelim(token::Brace)) {
7759                 // Parse a struct variant.
7760                 all_nullary = false;
7761                 let (fields, recovered) = self.parse_record_struct_body()?;
7762                 struct_def = VariantData::Struct(fields, recovered);
7763             } else if self.check(&token::OpenDelim(token::Paren)) {
7764                 all_nullary = false;
7765                 struct_def = VariantData::Tuple(
7766                     self.parse_tuple_struct_body()?,
7767                     ast::DUMMY_NODE_ID,
7768                 );
7769             } else if self.eat(&token::Eq) {
7770                 disr_expr = Some(AnonConst {
7771                     id: ast::DUMMY_NODE_ID,
7772                     value: self.parse_expr()?,
7773                 });
7774                 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
7775                     any_disr.push(sp);
7776                 }
7777                 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7778             } else {
7779                 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7780             }
7781
7782             let vr = ast::Variant_ {
7783                 ident,
7784                 id: ast::DUMMY_NODE_ID,
7785                 attrs: variant_attrs,
7786                 data: struct_def,
7787                 disr_expr,
7788             };
7789             variants.push(respan(vlo.to(self.prev_span), vr));
7790
7791             if !self.eat(&token::Comma) {
7792                 if self.token.is_ident() && !self.token.is_reserved_ident() {
7793                     let sp = self.sess.source_map().next_point(self.prev_span);
7794                     let mut err = self.struct_span_err(sp, "missing comma");
7795                     err.span_suggestion_short(
7796                         sp,
7797                         "missing comma",
7798                         ",".to_owned(),
7799                         Applicability::MaybeIncorrect,
7800                     );
7801                     err.emit();
7802                 } else {
7803                     break;
7804                 }
7805             }
7806         }
7807         self.expect(&token::CloseDelim(token::Brace))?;
7808         if !any_disr.is_empty() && !all_nullary {
7809             let mut err = self.struct_span_err(
7810                 any_disr.clone(),
7811                 "discriminator values can only be used with a field-less enum",
7812             );
7813             for sp in any_disr {
7814                 err.span_label(sp, "only valid in field-less enums");
7815             }
7816             err.emit();
7817         }
7818
7819         Ok(ast::EnumDef { variants })
7820     }
7821
7822     /// Parses an enum declaration.
7823     fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7824         let id = self.parse_ident()?;
7825         let mut generics = self.parse_generics()?;
7826         generics.where_clause = self.parse_where_clause()?;
7827         self.expect(&token::OpenDelim(token::Brace))?;
7828
7829         let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7830             self.recover_stmt();
7831             self.eat(&token::CloseDelim(token::Brace));
7832             e
7833         })?;
7834         Ok((id, ItemKind::Enum(enum_definition, generics), None))
7835     }
7836
7837     /// Parses a string as an ABI spec on an extern type or module. Consumes
7838     /// the `extern` keyword, if one is found.
7839     fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7840         match self.token {
7841             token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
7842                 let sp = self.span;
7843                 self.expect_no_suffix(sp, "an ABI spec", suf);
7844                 self.bump();
7845                 match abi::lookup(&s.as_str()) {
7846                     Some(abi) => Ok(Some(abi)),
7847                     None => {
7848                         let prev_span = self.prev_span;
7849                         let mut err = struct_span_err!(
7850                             self.sess.span_diagnostic,
7851                             prev_span,
7852                             E0703,
7853                             "invalid ABI: found `{}`",
7854                             s);
7855                         err.span_label(prev_span, "invalid ABI");
7856                         err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7857                         err.emit();
7858                         Ok(None)
7859                     }
7860                 }
7861             }
7862
7863             _ => Ok(None),
7864         }
7865     }
7866
7867     fn is_static_global(&mut self) -> bool {
7868         if self.check_keyword(keywords::Static) {
7869             // Check if this could be a closure
7870             !self.look_ahead(1, |token| {
7871                 if token.is_keyword(keywords::Move) {
7872                     return true;
7873                 }
7874                 match *token {
7875                     token::BinOp(token::Or) | token::OrOr => true,
7876                     _ => false,
7877                 }
7878             })
7879         } else {
7880             false
7881         }
7882     }
7883
7884     fn parse_item_(
7885         &mut self,
7886         attrs: Vec<Attribute>,
7887         macros_allowed: bool,
7888         attributes_allowed: bool,
7889     ) -> PResult<'a, Option<P<Item>>> {
7890         let mut unclosed_delims = vec![];
7891         let (ret, tokens) = self.collect_tokens(|this| {
7892             let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7893             unclosed_delims.append(&mut this.unclosed_delims);
7894             item
7895         })?;
7896         self.unclosed_delims.append(&mut unclosed_delims);
7897
7898         // Once we've parsed an item and recorded the tokens we got while
7899         // parsing we may want to store `tokens` into the item we're about to
7900         // return. Note, though, that we specifically didn't capture tokens
7901         // related to outer attributes. The `tokens` field here may later be
7902         // used with procedural macros to convert this item back into a token
7903         // stream, but during expansion we may be removing attributes as we go
7904         // along.
7905         //
7906         // If we've got inner attributes then the `tokens` we've got above holds
7907         // these inner attributes. If an inner attribute is expanded we won't
7908         // actually remove it from the token stream, so we'll just keep yielding
7909         // it (bad!). To work around this case for now we just avoid recording
7910         // `tokens` if we detect any inner attributes. This should help keep
7911         // expansion correct, but we should fix this bug one day!
7912         Ok(ret.map(|item| {
7913             item.map(|mut i| {
7914                 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7915                     i.tokens = Some(tokens);
7916                 }
7917                 i
7918             })
7919         }))
7920     }
7921
7922     /// Parses one of the items allowed by the flags.
7923     fn parse_item_implementation(
7924         &mut self,
7925         attrs: Vec<Attribute>,
7926         macros_allowed: bool,
7927         attributes_allowed: bool,
7928     ) -> PResult<'a, Option<P<Item>>> {
7929         maybe_whole!(self, NtItem, |item| {
7930             let mut item = item.into_inner();
7931             let mut attrs = attrs;
7932             mem::swap(&mut item.attrs, &mut attrs);
7933             item.attrs.extend(attrs);
7934             Some(P(item))
7935         });
7936
7937         let lo = self.span;
7938
7939         let visibility = self.parse_visibility(false)?;
7940
7941         if self.eat_keyword(keywords::Use) {
7942             // USE ITEM
7943             let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7944             self.expect(&token::Semi)?;
7945
7946             let span = lo.to(self.prev_span);
7947             let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
7948             return Ok(Some(item));
7949         }
7950
7951         if self.eat_keyword(keywords::Extern) {
7952             if self.eat_keyword(keywords::Crate) {
7953                 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7954             }
7955
7956             let opt_abi = self.parse_opt_abi()?;
7957
7958             if self.eat_keyword(keywords::Fn) {
7959                 // EXTERN FUNCTION ITEM
7960                 let fn_span = self.prev_span;
7961                 let abi = opt_abi.unwrap_or(Abi::C);
7962                 let (ident, item_, extra_attrs) =
7963                     self.parse_item_fn(Unsafety::Normal,
7964                                        respan(fn_span, IsAsync::NotAsync),
7965                                        respan(fn_span, Constness::NotConst),
7966                                        abi)?;
7967                 let prev_span = self.prev_span;
7968                 let item = self.mk_item(lo.to(prev_span),
7969                                         ident,
7970                                         item_,
7971                                         visibility,
7972                                         maybe_append(attrs, extra_attrs));
7973                 return Ok(Some(item));
7974             } else if self.check(&token::OpenDelim(token::Brace)) {
7975                 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7976             }
7977
7978             self.unexpected()?;
7979         }
7980
7981         if self.is_static_global() {
7982             self.bump();
7983             // STATIC ITEM
7984             let m = if self.eat_keyword(keywords::Mut) {
7985                 Mutability::Mutable
7986             } else {
7987                 Mutability::Immutable
7988             };
7989             let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7990             let prev_span = self.prev_span;
7991             let item = self.mk_item(lo.to(prev_span),
7992                                     ident,
7993                                     item_,
7994                                     visibility,
7995                                     maybe_append(attrs, extra_attrs));
7996             return Ok(Some(item));
7997         }
7998         if self.eat_keyword(keywords::Const) {
7999             let const_span = self.prev_span;
8000             if self.check_keyword(keywords::Fn)
8001                 || (self.check_keyword(keywords::Unsafe)
8002                     && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
8003                 // CONST FUNCTION ITEM
8004                 let unsafety = self.parse_unsafety();
8005                 self.bump();
8006                 let (ident, item_, extra_attrs) =
8007                     self.parse_item_fn(unsafety,
8008                                        respan(const_span, IsAsync::NotAsync),
8009                                        respan(const_span, Constness::Const),
8010                                        Abi::Rust)?;
8011                 let prev_span = self.prev_span;
8012                 let item = self.mk_item(lo.to(prev_span),
8013                                         ident,
8014                                         item_,
8015                                         visibility,
8016                                         maybe_append(attrs, extra_attrs));
8017                 return Ok(Some(item));
8018             }
8019
8020             // CONST ITEM
8021             if self.eat_keyword(keywords::Mut) {
8022                 let prev_span = self.prev_span;
8023                 let mut err = self.diagnostic()
8024                     .struct_span_err(prev_span, "const globals cannot be mutable");
8025                 err.span_label(prev_span, "cannot be mutable");
8026                 err.span_suggestion(
8027                     const_span,
8028                     "you might want to declare a static instead",
8029                     "static".to_owned(),
8030                     Applicability::MaybeIncorrect,
8031                 );
8032                 err.emit();
8033             }
8034             let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
8035             let prev_span = self.prev_span;
8036             let item = self.mk_item(lo.to(prev_span),
8037                                     ident,
8038                                     item_,
8039                                     visibility,
8040                                     maybe_append(attrs, extra_attrs));
8041             return Ok(Some(item));
8042         }
8043
8044         // `unsafe async fn` or `async fn`
8045         if (
8046             self.check_keyword(keywords::Unsafe) &&
8047             self.look_ahead(1, |t| t.is_keyword(keywords::Async))
8048         ) || (
8049             self.check_keyword(keywords::Async) &&
8050             self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
8051         )
8052         {
8053             // ASYNC FUNCTION ITEM
8054             let unsafety = self.parse_unsafety();
8055             self.expect_keyword(keywords::Async)?;
8056             let async_span = self.prev_span;
8057             self.expect_keyword(keywords::Fn)?;
8058             let fn_span = self.prev_span;
8059             let (ident, item_, extra_attrs) =
8060                 self.parse_item_fn(unsafety,
8061                                    respan(async_span, IsAsync::Async {
8062                                        closure_id: ast::DUMMY_NODE_ID,
8063                                        return_impl_trait_id: ast::DUMMY_NODE_ID,
8064                                        arguments: Vec::new(),
8065                                    }),
8066                                    respan(fn_span, Constness::NotConst),
8067                                    Abi::Rust)?;
8068             let prev_span = self.prev_span;
8069             let item = self.mk_item(lo.to(prev_span),
8070                                     ident,
8071                                     item_,
8072                                     visibility,
8073                                     maybe_append(attrs, extra_attrs));
8074             if self.span.rust_2015() {
8075                 self.diagnostic().struct_span_err_with_code(
8076                     async_span,
8077                     "`async fn` is not permitted in the 2015 edition",
8078                     DiagnosticId::Error("E0670".into())
8079                 ).emit();
8080             }
8081             return Ok(Some(item));
8082         }
8083         if self.check_keyword(keywords::Unsafe) &&
8084             (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
8085             self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
8086         {
8087             // UNSAFE TRAIT ITEM
8088             self.bump(); // `unsafe`
8089             let is_auto = if self.eat_keyword(keywords::Trait) {
8090                 IsAuto::No
8091             } else {
8092                 self.expect_keyword(keywords::Auto)?;
8093                 self.expect_keyword(keywords::Trait)?;
8094                 IsAuto::Yes
8095             };
8096             let (ident, item_, extra_attrs) =
8097                 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
8098             let prev_span = self.prev_span;
8099             let item = self.mk_item(lo.to(prev_span),
8100                                     ident,
8101                                     item_,
8102                                     visibility,
8103                                     maybe_append(attrs, extra_attrs));
8104             return Ok(Some(item));
8105         }
8106         if self.check_keyword(keywords::Impl) ||
8107            self.check_keyword(keywords::Unsafe) &&
8108                 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8109            self.check_keyword(keywords::Default) &&
8110                 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8111            self.check_keyword(keywords::Default) &&
8112                 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
8113             // IMPL ITEM
8114             let defaultness = self.parse_defaultness();
8115             let unsafety = self.parse_unsafety();
8116             self.expect_keyword(keywords::Impl)?;
8117             let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
8118             let span = lo.to(self.prev_span);
8119             return Ok(Some(self.mk_item(span, ident, item, visibility,
8120                                         maybe_append(attrs, extra_attrs))));
8121         }
8122         if self.check_keyword(keywords::Fn) {
8123             // FUNCTION ITEM
8124             self.bump();
8125             let fn_span = self.prev_span;
8126             let (ident, item_, extra_attrs) =
8127                 self.parse_item_fn(Unsafety::Normal,
8128                                    respan(fn_span, IsAsync::NotAsync),
8129                                    respan(fn_span, Constness::NotConst),
8130                                    Abi::Rust)?;
8131             let prev_span = self.prev_span;
8132             let item = self.mk_item(lo.to(prev_span),
8133                                     ident,
8134                                     item_,
8135                                     visibility,
8136                                     maybe_append(attrs, extra_attrs));
8137             return Ok(Some(item));
8138         }
8139         if self.check_keyword(keywords::Unsafe)
8140             && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
8141             // UNSAFE FUNCTION ITEM
8142             self.bump(); // `unsafe`
8143             // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
8144             self.check(&token::OpenDelim(token::Brace));
8145             let abi = if self.eat_keyword(keywords::Extern) {
8146                 self.parse_opt_abi()?.unwrap_or(Abi::C)
8147             } else {
8148                 Abi::Rust
8149             };
8150             self.expect_keyword(keywords::Fn)?;
8151             let fn_span = self.prev_span;
8152             let (ident, item_, extra_attrs) =
8153                 self.parse_item_fn(Unsafety::Unsafe,
8154                                    respan(fn_span, IsAsync::NotAsync),
8155                                    respan(fn_span, Constness::NotConst),
8156                                    abi)?;
8157             let prev_span = self.prev_span;
8158             let item = self.mk_item(lo.to(prev_span),
8159                                     ident,
8160                                     item_,
8161                                     visibility,
8162                                     maybe_append(attrs, extra_attrs));
8163             return Ok(Some(item));
8164         }
8165         if self.eat_keyword(keywords::Mod) {
8166             // MODULE ITEM
8167             let (ident, item_, extra_attrs) =
8168                 self.parse_item_mod(&attrs[..])?;
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 let Some(type_) = self.eat_type() {
8178             let (ident, alias, generics) = type_?;
8179             // TYPE ITEM
8180             let item_ = match alias {
8181                 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
8182                 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
8183             };
8184             let prev_span = self.prev_span;
8185             let item = self.mk_item(lo.to(prev_span),
8186                                     ident,
8187                                     item_,
8188                                     visibility,
8189                                     attrs);
8190             return Ok(Some(item));
8191         }
8192         if self.eat_keyword(keywords::Enum) {
8193             // ENUM ITEM
8194             let (ident, item_, extra_attrs) = self.parse_item_enum()?;
8195             let prev_span = self.prev_span;
8196             let item = self.mk_item(lo.to(prev_span),
8197                                     ident,
8198                                     item_,
8199                                     visibility,
8200                                     maybe_append(attrs, extra_attrs));
8201             return Ok(Some(item));
8202         }
8203         if self.check_keyword(keywords::Trait)
8204             || (self.check_keyword(keywords::Auto)
8205                 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
8206         {
8207             let is_auto = if self.eat_keyword(keywords::Trait) {
8208                 IsAuto::No
8209             } else {
8210                 self.expect_keyword(keywords::Auto)?;
8211                 self.expect_keyword(keywords::Trait)?;
8212                 IsAuto::Yes
8213             };
8214             // TRAIT ITEM
8215             let (ident, item_, extra_attrs) =
8216                 self.parse_item_trait(is_auto, Unsafety::Normal)?;
8217             let prev_span = self.prev_span;
8218             let item = self.mk_item(lo.to(prev_span),
8219                                     ident,
8220                                     item_,
8221                                     visibility,
8222                                     maybe_append(attrs, extra_attrs));
8223             return Ok(Some(item));
8224         }
8225         if self.eat_keyword(keywords::Struct) {
8226             // STRUCT ITEM
8227             let (ident, item_, extra_attrs) = self.parse_item_struct()?;
8228             let prev_span = self.prev_span;
8229             let item = self.mk_item(lo.to(prev_span),
8230                                     ident,
8231                                     item_,
8232                                     visibility,
8233                                     maybe_append(attrs, extra_attrs));
8234             return Ok(Some(item));
8235         }
8236         if self.is_union_item() {
8237             // UNION ITEM
8238             self.bump();
8239             let (ident, item_, extra_attrs) = self.parse_item_union()?;
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 let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
8249             return Ok(Some(macro_def));
8250         }
8251
8252         // Verify whether we have encountered a struct or method definition where the user forgot to
8253         // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
8254         if visibility.node.is_pub() &&
8255             self.check_ident() &&
8256             self.look_ahead(1, |t| *t != token::Not)
8257         {
8258             // Space between `pub` keyword and the identifier
8259             //
8260             //     pub   S {}
8261             //        ^^^ `sp` points here
8262             let sp = self.prev_span.between(self.span);
8263             let full_sp = self.prev_span.to(self.span);
8264             let ident_sp = self.span;
8265             if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
8266                 // possible public struct definition where `struct` was forgotten
8267                 let ident = self.parse_ident().unwrap();
8268                 let msg = format!("add `struct` here to parse `{}` as a public struct",
8269                                   ident);
8270                 let mut err = self.diagnostic()
8271                     .struct_span_err(sp, "missing `struct` for struct definition");
8272                 err.span_suggestion_short(
8273                     sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
8274                 );
8275                 return Err(err);
8276             } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
8277                 let ident = self.parse_ident().unwrap();
8278                 self.bump();  // `(`
8279                 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
8280                     "method"
8281                 } else {
8282                     "function"
8283                 };
8284                 self.consume_block(token::Paren);
8285                 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
8286                     self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
8287                     self.bump();  // `{`
8288                     ("fn", kw_name, false)
8289                 } else if self.check(&token::OpenDelim(token::Brace)) {
8290                     self.bump();  // `{`
8291                     ("fn", kw_name, false)
8292                 } else if self.check(&token::Colon) {
8293                     let kw = "struct";
8294                     (kw, kw, false)
8295                 } else {
8296                     ("fn` or `struct", "function or struct", true)
8297                 };
8298
8299                 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8300                 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8301                 if !ambiguous {
8302                     self.consume_block(token::Brace);
8303                     let suggestion = format!("add `{}` here to parse `{}` as a public {}",
8304                                              kw,
8305                                              ident,
8306                                              kw_name);
8307                     err.span_suggestion_short(
8308                         sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
8309                     );
8310                 } else {
8311                     if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
8312                         err.span_suggestion(
8313                             full_sp,
8314                             "if you meant to call a macro, try",
8315                             format!("{}!", snippet),
8316                             // this is the `ambiguous` conditional branch
8317                             Applicability::MaybeIncorrect
8318                         );
8319                     } else {
8320                         err.help("if you meant to call a macro, remove the `pub` \
8321                                   and add a trailing `!` after the identifier");
8322                     }
8323                 }
8324                 return Err(err);
8325             } else if self.look_ahead(1, |t| *t == token::Lt) {
8326                 let ident = self.parse_ident().unwrap();
8327                 self.eat_to_tokens(&[&token::Gt]);
8328                 self.bump();  // `>`
8329                 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
8330                     if let Ok(Some(_)) = self.parse_self_arg() {
8331                         ("fn", "method", false)
8332                     } else {
8333                         ("fn", "function", false)
8334                     }
8335                 } else if self.check(&token::OpenDelim(token::Brace)) {
8336                     ("struct", "struct", false)
8337                 } else {
8338                     ("fn` or `struct", "function or struct", true)
8339                 };
8340                 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8341                 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8342                 if !ambiguous {
8343                     err.span_suggestion_short(
8344                         sp,
8345                         &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
8346                         format!(" {} ", kw),
8347                         Applicability::MachineApplicable,
8348                     );
8349                 }
8350                 return Err(err);
8351             }
8352         }
8353         self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
8354     }
8355
8356     /// Parses a foreign item.
8357     crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
8358         maybe_whole!(self, NtForeignItem, |ni| ni);
8359
8360         let attrs = self.parse_outer_attributes()?;
8361         let lo = self.span;
8362         let visibility = self.parse_visibility(false)?;
8363
8364         // FOREIGN STATIC ITEM
8365         // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
8366         if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
8367             if self.token.is_keyword(keywords::Const) {
8368                 self.diagnostic()
8369                     .struct_span_err(self.span, "extern items cannot be `const`")
8370                     .span_suggestion(
8371                         self.span,
8372                         "try using a static value",
8373                         "static".to_owned(),
8374                         Applicability::MachineApplicable
8375                     ).emit();
8376             }
8377             self.bump(); // `static` or `const`
8378             return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
8379         }
8380         // FOREIGN FUNCTION ITEM
8381         if self.check_keyword(keywords::Fn) {
8382             return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
8383         }
8384         // FOREIGN TYPE ITEM
8385         if self.check_keyword(keywords::Type) {
8386             return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
8387         }
8388
8389         match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
8390             Some(mac) => {
8391                 Ok(
8392                     ForeignItem {
8393                         ident: keywords::Invalid.ident(),
8394                         span: lo.to(self.prev_span),
8395                         id: ast::DUMMY_NODE_ID,
8396                         attrs,
8397                         vis: visibility,
8398                         node: ForeignItemKind::Macro(mac),
8399                     }
8400                 )
8401             }
8402             None => {
8403                 if !attrs.is_empty()  {
8404                     self.expected_item_err(&attrs)?;
8405                 }
8406
8407                 self.unexpected()
8408             }
8409         }
8410     }
8411
8412     /// This is the fall-through for parsing items.
8413     fn parse_macro_use_or_failure(
8414         &mut self,
8415         attrs: Vec<Attribute> ,
8416         macros_allowed: bool,
8417         attributes_allowed: bool,
8418         lo: Span,
8419         visibility: Visibility
8420     ) -> PResult<'a, Option<P<Item>>> {
8421         if macros_allowed && self.token.is_path_start() &&
8422                 !(self.is_async_fn() && self.span.rust_2015()) {
8423             // MACRO INVOCATION ITEM
8424
8425             let prev_span = self.prev_span;
8426             self.complain_if_pub_macro(&visibility.node, prev_span);
8427
8428             let mac_lo = self.span;
8429
8430             // item macro.
8431             let pth = self.parse_path(PathStyle::Mod)?;
8432             self.expect(&token::Not)?;
8433
8434             // a 'special' identifier (like what `macro_rules!` uses)
8435             // is optional. We should eventually unify invoc syntax
8436             // and remove this.
8437             let id = if self.token.is_ident() {
8438                 self.parse_ident()?
8439             } else {
8440                 keywords::Invalid.ident() // no special identifier
8441             };
8442             // eat a matched-delimiter token tree:
8443             let (delim, tts) = self.expect_delimited_token_tree()?;
8444             if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
8445                 self.report_invalid_macro_expansion_item();
8446             }
8447
8448             let hi = self.prev_span;
8449             let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
8450             let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
8451             return Ok(Some(item));
8452         }
8453
8454         // FAILURE TO PARSE ITEM
8455         match visibility.node {
8456             VisibilityKind::Inherited => {}
8457             _ => {
8458                 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
8459             }
8460         }
8461
8462         if !attributes_allowed && !attrs.is_empty() {
8463             self.expected_item_err(&attrs)?;
8464         }
8465         Ok(None)
8466     }
8467
8468     /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
8469     fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
8470                                at_end: &mut bool) -> PResult<'a, Option<Mac>>
8471     {
8472         if self.token.is_path_start() &&
8473                 !(self.is_async_fn() && self.span.rust_2015()) {
8474             let prev_span = self.prev_span;
8475             let lo = self.span;
8476             let pth = self.parse_path(PathStyle::Mod)?;
8477
8478             if pth.segments.len() == 1 {
8479                 if !self.eat(&token::Not) {
8480                     return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
8481                 }
8482             } else {
8483                 self.expect(&token::Not)?;
8484             }
8485
8486             if let Some(vis) = vis {
8487                 self.complain_if_pub_macro(&vis.node, prev_span);
8488             }
8489
8490             *at_end = true;
8491
8492             // eat a matched-delimiter token tree:
8493             let (delim, tts) = self.expect_delimited_token_tree()?;
8494             if delim != MacDelimiter::Brace {
8495                 self.expect(&token::Semi)?;
8496             }
8497
8498             Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
8499         } else {
8500             Ok(None)
8501         }
8502     }
8503
8504     fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
8505         where F: FnOnce(&mut Self) -> PResult<'a, R>
8506     {
8507         // Record all tokens we parse when parsing this item.
8508         let mut tokens = Vec::new();
8509         let prev_collecting = match self.token_cursor.frame.last_token {
8510             LastToken::Collecting(ref mut list) => {
8511                 Some(mem::replace(list, Vec::new()))
8512             }
8513             LastToken::Was(ref mut last) => {
8514                 tokens.extend(last.take());
8515                 None
8516             }
8517         };
8518         self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
8519         let prev = self.token_cursor.stack.len();
8520         let ret = f(self);
8521         let last_token = if self.token_cursor.stack.len() == prev {
8522             &mut self.token_cursor.frame.last_token
8523         } else {
8524             &mut self.token_cursor.stack[prev].last_token
8525         };
8526
8527         // Pull out the tokens that we've collected from the call to `f` above.
8528         let mut collected_tokens = match *last_token {
8529             LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
8530             LastToken::Was(_) => panic!("our vector went away?"),
8531         };
8532
8533         // If we're not at EOF our current token wasn't actually consumed by
8534         // `f`, but it'll still be in our list that we pulled out. In that case
8535         // put it back.
8536         let extra_token = if self.token != token::Eof {
8537             collected_tokens.pop()
8538         } else {
8539             None
8540         };
8541
8542         // If we were previously collecting tokens, then this was a recursive
8543         // call. In that case we need to record all the tokens we collected in
8544         // our parent list as well. To do that we push a clone of our stream
8545         // onto the previous list.
8546         match prev_collecting {
8547             Some(mut list) => {
8548                 list.extend(collected_tokens.iter().cloned());
8549                 list.extend(extra_token);
8550                 *last_token = LastToken::Collecting(list);
8551             }
8552             None => {
8553                 *last_token = LastToken::Was(extra_token);
8554             }
8555         }
8556
8557         Ok((ret?, TokenStream::new(collected_tokens)))
8558     }
8559
8560     pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
8561         let attrs = self.parse_outer_attributes()?;
8562         self.parse_item_(attrs, true, false)
8563     }
8564
8565     /// `::{` or `::*`
8566     fn is_import_coupler(&mut self) -> bool {
8567         self.check(&token::ModSep) &&
8568             self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
8569                                    *t == token::BinOp(token::Star))
8570     }
8571
8572     /// Parses a `UseTree`.
8573     ///
8574     /// ```
8575     /// USE_TREE = [`::`] `*` |
8576     ///            [`::`] `{` USE_TREE_LIST `}` |
8577     ///            PATH `::` `*` |
8578     ///            PATH `::` `{` USE_TREE_LIST `}` |
8579     ///            PATH [`as` IDENT]
8580     /// ```
8581     fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
8582         let lo = self.span;
8583
8584         let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
8585         let kind = if self.check(&token::OpenDelim(token::Brace)) ||
8586                       self.check(&token::BinOp(token::Star)) ||
8587                       self.is_import_coupler() {
8588             // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
8589             let mod_sep_ctxt = self.span.ctxt();
8590             if self.eat(&token::ModSep) {
8591                 prefix.segments.push(
8592                     PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
8593                 );
8594             }
8595
8596             if self.eat(&token::BinOp(token::Star)) {
8597                 UseTreeKind::Glob
8598             } else {
8599                 UseTreeKind::Nested(self.parse_use_tree_list()?)
8600             }
8601         } else {
8602             // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
8603             prefix = self.parse_path(PathStyle::Mod)?;
8604
8605             if self.eat(&token::ModSep) {
8606                 if self.eat(&token::BinOp(token::Star)) {
8607                     UseTreeKind::Glob
8608                 } else {
8609                     UseTreeKind::Nested(self.parse_use_tree_list()?)
8610                 }
8611             } else {
8612                 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
8613             }
8614         };
8615
8616         Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
8617     }
8618
8619     /// Parses a `UseTreeKind::Nested(list)`.
8620     ///
8621     /// ```
8622     /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
8623     /// ```
8624     fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
8625         self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
8626                                  &token::CloseDelim(token::Brace),
8627                                  SeqSep::trailing_allowed(token::Comma), |this| {
8628             Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
8629         })
8630     }
8631
8632     fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
8633         if self.eat_keyword(keywords::As) {
8634             self.parse_ident_or_underscore().map(Some)
8635         } else {
8636             Ok(None)
8637         }
8638     }
8639
8640     /// Parses a source module as a crate. This is the main entry point for the parser.
8641     pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
8642         let lo = self.span;
8643         let krate = Ok(ast::Crate {
8644             attrs: self.parse_inner_attributes()?,
8645             module: self.parse_mod_items(&token::Eof, lo)?,
8646             span: lo.to(self.span),
8647         });
8648         krate
8649     }
8650
8651     pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
8652         let ret = match self.token {
8653             token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
8654             token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
8655             _ => return None
8656         };
8657         self.bump();
8658         Some(ret)
8659     }
8660
8661     pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
8662         match self.parse_optional_str() {
8663             Some((s, style, suf)) => {
8664                 let sp = self.prev_span;
8665                 self.expect_no_suffix(sp, "a string literal", suf);
8666                 Ok((s, style))
8667             }
8668             _ => {
8669                 let msg = "expected string literal";
8670                 let mut err = self.fatal(msg);
8671                 err.span_label(self.span, msg);
8672                 Err(err)
8673             }
8674         }
8675     }
8676
8677     fn report_invalid_macro_expansion_item(&self) {
8678         self.struct_span_err(
8679             self.prev_span,
8680             "macros that expand to items must be delimited with braces or followed by a semicolon",
8681         ).multipart_suggestion(
8682             "change the delimiters to curly braces",
8683             vec![
8684                 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
8685                 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
8686             ],
8687             Applicability::MaybeIncorrect,
8688         ).span_suggestion(
8689             self.sess.source_map.next_point(self.prev_span),
8690             "add a semicolon",
8691             ';'.to_string(),
8692             Applicability::MaybeIncorrect,
8693         ).emit();
8694     }
8695
8696     /// Recover from `pub` keyword in places where it seems _reasonable_ but isn't valid.
8697     fn eat_bad_pub(&mut self) {
8698         if self.token.is_keyword(keywords::Pub) {
8699             match self.parse_visibility(false) {
8700                 Ok(vis) => {
8701                     let mut err = self.diagnostic()
8702                         .struct_span_err(vis.span, "unnecessary visibility qualifier");
8703                     err.span_label(vis.span, "`pub` not permitted here");
8704                     err.emit();
8705                 }
8706                 Err(mut err) => err.emit(),
8707             }
8708         }
8709     }
8710
8711     /// When lowering a `async fn` to the HIR, we need to move all of the arguments of the function
8712     /// into the generated closure so that they are dropped when the future is polled and not when
8713     /// it is created.
8714     ///
8715     /// The arguments of the function are replaced in HIR lowering with the arguments created by
8716     /// this function and the statements created here are inserted at the top of the closure body.
8717     fn construct_async_arguments(&mut self, asyncness: &mut Spanned<IsAsync>, decl: &FnDecl) {
8718         if let IsAsync::Async { ref mut arguments, .. } = asyncness.node {
8719             for (index, input) in decl.inputs.iter().enumerate() {
8720                 let id = ast::DUMMY_NODE_ID;
8721                 let span = input.pat.span;
8722
8723                 // Construct a name for our temporary argument.
8724                 let name = format!("__arg{}", index);
8725                 let ident = Ident::from_str(&name).gensym();
8726
8727                 // Check if this is a ident pattern, if so, we can optimize and avoid adding a
8728                 // `let <pat> = __argN;` statement, instead just adding a `let <pat> = <pat>;`
8729                 // statement.
8730                 let (binding_mode, ident, is_simple_pattern) = match input.pat.node {
8731                     PatKind::Ident(binding_mode, ident, _) => (binding_mode, ident, true),
8732                     _ => (BindingMode::ByValue(Mutability::Immutable), ident, false),
8733                 };
8734
8735                 // Construct an argument representing `__argN: <ty>` to replace the argument of the
8736                 // async function if it isn't a simple pattern.
8737                 let arg = if is_simple_pattern {
8738                     None
8739                 } else {
8740                     Some(Arg {
8741                         ty: input.ty.clone(),
8742                         id,
8743                         pat: P(Pat {
8744                             id,
8745                             node: PatKind::Ident(
8746                                 BindingMode::ByValue(Mutability::Immutable), ident, None,
8747                             ),
8748                             span,
8749                         }),
8750                         source: ArgSource::AsyncFn(input.pat.clone()),
8751                     })
8752                 };
8753
8754                 // Construct a `let __argN = __argN;` statement to insert at the top of the
8755                 // async closure. This makes sure that the argument is captured by the closure and
8756                 // that the drop order is correct.
8757                 let move_local = Local {
8758                     pat: P(Pat {
8759                         id,
8760                         node: PatKind::Ident(binding_mode, ident, None),
8761                         span,
8762                     }),
8763                     // We explicitly do not specify the type for this statement. When the user's
8764                     // argument type is `impl Trait` then this would require the
8765                     // `impl_trait_in_bindings` feature to also be present for that same type to
8766                     // be valid in this binding. At the time of writing (13 Mar 19),
8767                     // `impl_trait_in_bindings` is not stable.
8768                     ty: None,
8769                     init: Some(P(Expr {
8770                         id,
8771                         node: ExprKind::Path(None, ast::Path {
8772                             span,
8773                             segments: vec![PathSegment { ident, id, args: None }],
8774                         }),
8775                         span,
8776                         attrs: ThinVec::new(),
8777                     })),
8778                     id,
8779                     span,
8780                     attrs: ThinVec::new(),
8781                     source: LocalSource::AsyncFn,
8782                 };
8783
8784                 // Construct a `let <pat> = __argN;` statement to insert at the top of the
8785                 // async closure if this isn't a simple pattern.
8786                 let pat_stmt = if is_simple_pattern {
8787                     None
8788                 } else {
8789                     Some(Stmt {
8790                         id,
8791                         node: StmtKind::Local(P(Local {
8792                             pat: input.pat.clone(),
8793                             ..move_local.clone()
8794                         })),
8795                         span,
8796                     })
8797                 };
8798
8799                 let move_stmt = Stmt { id, node: StmtKind::Local(P(move_local)), span };
8800                 arguments.push(AsyncArgument { ident, arg, pat_stmt, move_stmt });
8801             }
8802         }
8803     }
8804 }
8805
8806 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
8807     for unmatched in unclosed_delims.iter() {
8808         let mut err = handler.struct_span_err(unmatched.found_span, &format!(
8809             "incorrect close delimiter: `{}`",
8810             pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
8811         ));
8812         err.span_label(unmatched.found_span, "incorrect close delimiter");
8813         if let Some(sp) = unmatched.candidate_span {
8814             err.span_label(sp, "close delimiter possibly meant for this");
8815         }
8816         if let Some(sp) = unmatched.unclosed_span {
8817             err.span_label(sp, "un-closed delimiter");
8818         }
8819         err.emit();
8820     }
8821     unclosed_delims.clear();
8822 }