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