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