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