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