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