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