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