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