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