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