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