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