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