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