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