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