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