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