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