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