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