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