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