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