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