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