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