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