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