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