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