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