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