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