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