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