]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/parse/parser.rs
Improve some compiletest documentation
[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 last_span = negative_bounds.last().map(|sp| *sp);
5602             let mut err = self.struct_span_err(
5603                 negative_bounds,
5604                 "negative trait bounds are not supported",
5605             );
5606             if let Some(sp) = last_span {
5607                 err.span_label(sp, "negative trait bounds are not supported");
5608             }
5609             if let Some(bound_list) = colon_span {
5610                 let bound_list = bound_list.to(self.prev_span);
5611                 let mut new_bound_list = String::new();
5612                 if !bounds.is_empty() {
5613                     let mut snippets = bounds.iter().map(|bound| bound.span())
5614                         .map(|span| self.sess.source_map().span_to_snippet(span));
5615                     while let Some(Ok(snippet)) = snippets.next() {
5616                         new_bound_list.push_str(" + ");
5617                         new_bound_list.push_str(&snippet);
5618                     }
5619                     new_bound_list = new_bound_list.replacen(" +", ":", 1);
5620                 }
5621                 err.span_suggestion_hidden(
5622                     bound_list,
5623                     &format!("remove the trait bound{}", if plural { "s" } else { "" }),
5624                     new_bound_list,
5625                     Applicability::MachineApplicable,
5626                 );
5627             }
5628             err.emit();
5629         }
5630
5631         return Ok(bounds);
5632     }
5633
5634     fn parse_generic_bounds(&mut self, colon_span: Option<Span>) -> PResult<'a, GenericBounds> {
5635         self.parse_generic_bounds_common(true, colon_span)
5636     }
5637
5638     /// Parses bounds of a lifetime parameter `BOUND + BOUND + BOUND`, possibly with trailing `+`.
5639     ///
5640     /// ```
5641     /// BOUND = LT_BOUND (e.g., `'a`)
5642     /// ```
5643     fn parse_lt_param_bounds(&mut self) -> GenericBounds {
5644         let mut lifetimes = Vec::new();
5645         while self.check_lifetime() {
5646             lifetimes.push(ast::GenericBound::Outlives(self.expect_lifetime()));
5647
5648             if !self.eat_plus() {
5649                 break
5650             }
5651         }
5652         lifetimes
5653     }
5654
5655     /// Matches `typaram = IDENT (`?` unbound)? optbounds ( EQ ty )?`.
5656     fn parse_ty_param(&mut self,
5657                       preceding_attrs: Vec<Attribute>)
5658                       -> PResult<'a, GenericParam> {
5659         let ident = self.parse_ident()?;
5660
5661         // Parse optional colon and param bounds.
5662         let bounds = if self.eat(&token::Colon) {
5663             self.parse_generic_bounds(Some(self.prev_span))?
5664         } else {
5665             Vec::new()
5666         };
5667
5668         let default = if self.eat(&token::Eq) {
5669             Some(self.parse_ty()?)
5670         } else {
5671             None
5672         };
5673
5674         Ok(GenericParam {
5675             ident,
5676             id: ast::DUMMY_NODE_ID,
5677             attrs: preceding_attrs.into(),
5678             bounds,
5679             kind: GenericParamKind::Type {
5680                 default,
5681             }
5682         })
5683     }
5684
5685     /// Parses the following grammar:
5686     ///
5687     ///     TraitItemAssocTy = Ident ["<"...">"] [":" [GenericBounds]] ["where" ...] ["=" Ty]
5688     fn parse_trait_item_assoc_ty(&mut self)
5689         -> PResult<'a, (Ident, TraitItemKind, ast::Generics)> {
5690         let ident = self.parse_ident()?;
5691         let mut generics = self.parse_generics()?;
5692
5693         // Parse optional colon and param bounds.
5694         let bounds = if self.eat(&token::Colon) {
5695             self.parse_generic_bounds(None)?
5696         } else {
5697             Vec::new()
5698         };
5699         generics.where_clause = self.parse_where_clause()?;
5700
5701         let default = if self.eat(&token::Eq) {
5702             Some(self.parse_ty()?)
5703         } else {
5704             None
5705         };
5706         self.expect(&token::Semi)?;
5707
5708         Ok((ident, TraitItemKind::Type(bounds, default), generics))
5709     }
5710
5711     fn parse_const_param(&mut self, preceding_attrs: Vec<Attribute>) -> PResult<'a, GenericParam> {
5712         self.expect_keyword(keywords::Const)?;
5713         let ident = self.parse_ident()?;
5714         self.expect(&token::Colon)?;
5715         let ty = self.parse_ty()?;
5716
5717         Ok(GenericParam {
5718             ident,
5719             id: ast::DUMMY_NODE_ID,
5720             attrs: preceding_attrs.into(),
5721             bounds: Vec::new(),
5722             kind: GenericParamKind::Const {
5723                 ty,
5724             }
5725         })
5726     }
5727
5728     /// Parses a (possibly empty) list of lifetime and type parameters, possibly including
5729     /// a trailing comma and erroneous trailing attributes.
5730     crate fn parse_generic_params(&mut self) -> PResult<'a, Vec<ast::GenericParam>> {
5731         let mut params = Vec::new();
5732         loop {
5733             let attrs = self.parse_outer_attributes()?;
5734             if self.check_lifetime() {
5735                 let lifetime = self.expect_lifetime();
5736                 // Parse lifetime parameter.
5737                 let bounds = if self.eat(&token::Colon) {
5738                     self.parse_lt_param_bounds()
5739                 } else {
5740                     Vec::new()
5741                 };
5742                 params.push(ast::GenericParam {
5743                     ident: lifetime.ident,
5744                     id: lifetime.id,
5745                     attrs: attrs.into(),
5746                     bounds,
5747                     kind: ast::GenericParamKind::Lifetime,
5748                 });
5749             } else if self.check_keyword(keywords::Const) {
5750                 // Parse const parameter.
5751                 params.push(self.parse_const_param(attrs)?);
5752             } else if self.check_ident() {
5753                 // Parse type parameter.
5754                 params.push(self.parse_ty_param(attrs)?);
5755             } else {
5756                 // Check for trailing attributes and stop parsing.
5757                 if !attrs.is_empty() {
5758                     if !params.is_empty() {
5759                         self.struct_span_err(
5760                             attrs[0].span,
5761                             &format!("trailing attribute after generic parameter"),
5762                         )
5763                         .span_label(attrs[0].span, "attributes must go before parameters")
5764                         .emit();
5765                     } else {
5766                         self.struct_span_err(
5767                             attrs[0].span,
5768                             &format!("attribute without generic parameters"),
5769                         )
5770                         .span_label(
5771                             attrs[0].span,
5772                             "attributes are only permitted when preceding parameters",
5773                         )
5774                         .emit();
5775                     }
5776                 }
5777                 break
5778             }
5779
5780             if !self.eat(&token::Comma) {
5781                 break
5782             }
5783         }
5784         Ok(params)
5785     }
5786
5787     /// Parses a set of optional generic type parameter declarations. Where
5788     /// clauses are not parsed here, and must be added later via
5789     /// `parse_where_clause()`.
5790     ///
5791     /// matches generics = ( ) | ( < > ) | ( < typaramseq ( , )? > ) | ( < lifetimes ( , )? > )
5792     ///                  | ( < lifetimes , typaramseq ( , )? > )
5793     /// where   typaramseq = ( typaram ) | ( typaram , typaramseq )
5794     fn parse_generics(&mut self) -> PResult<'a, ast::Generics> {
5795         maybe_whole!(self, NtGenerics, |x| x);
5796
5797         let span_lo = self.span;
5798         if self.eat_lt() {
5799             let params = self.parse_generic_params()?;
5800             self.expect_gt()?;
5801             Ok(ast::Generics {
5802                 params,
5803                 where_clause: WhereClause {
5804                     id: ast::DUMMY_NODE_ID,
5805                     predicates: Vec::new(),
5806                     span: syntax_pos::DUMMY_SP,
5807                 },
5808                 span: span_lo.to(self.prev_span),
5809             })
5810         } else {
5811             Ok(ast::Generics::default())
5812         }
5813     }
5814
5815     /// Parses generic args (within a path segment) with recovery for extra leading angle brackets.
5816     /// For the purposes of understanding the parsing logic of generic arguments, this function
5817     /// can be thought of being the same as just calling `self.parse_generic_args()` if the source
5818     /// had the correct amount of leading angle brackets.
5819     ///
5820     /// ```ignore (diagnostics)
5821     /// bar::<<<<T as Foo>::Output>();
5822     ///      ^^ help: remove extra angle brackets
5823     /// ```
5824     fn parse_generic_args_with_leaning_angle_bracket_recovery(
5825         &mut self,
5826         style: PathStyle,
5827         lo: Span,
5828     ) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5829         // We need to detect whether there are extra leading left angle brackets and produce an
5830         // appropriate error and suggestion. This cannot be implemented by looking ahead at
5831         // upcoming tokens for a matching `>` character - if there are unmatched `<` tokens
5832         // then there won't be matching `>` tokens to find.
5833         //
5834         // To explain how this detection works, consider the following example:
5835         //
5836         // ```ignore (diagnostics)
5837         // bar::<<<<T as Foo>::Output>();
5838         //      ^^ help: remove extra angle brackets
5839         // ```
5840         //
5841         // Parsing of the left angle brackets starts in this function. We start by parsing the
5842         // `<` token (incrementing the counter of unmatched angle brackets on `Parser` via
5843         // `eat_lt`):
5844         //
5845         // *Upcoming tokens:* `<<<<T as Foo>::Output>;`
5846         // *Unmatched count:* 1
5847         // *`parse_path_segment` calls deep:* 0
5848         //
5849         // This has the effect of recursing as this function is called if a `<` character
5850         // is found within the expected generic arguments:
5851         //
5852         // *Upcoming tokens:* `<<<T as Foo>::Output>;`
5853         // *Unmatched count:* 2
5854         // *`parse_path_segment` calls deep:* 1
5855         //
5856         // Eventually we will have recursed until having consumed all of the `<` tokens and
5857         // this will be reflected in the count:
5858         //
5859         // *Upcoming tokens:* `T as Foo>::Output>;`
5860         // *Unmatched count:* 4
5861         // `parse_path_segment` calls deep:* 3
5862         //
5863         // The parser will continue until reaching the first `>` - this will decrement the
5864         // unmatched angle bracket count and return to the parent invocation of this function
5865         // having succeeded in parsing:
5866         //
5867         // *Upcoming tokens:* `::Output>;`
5868         // *Unmatched count:* 3
5869         // *`parse_path_segment` calls deep:* 2
5870         //
5871         // This will continue until the next `>` character which will also return successfully
5872         // to the parent invocation of this function and decrement the count:
5873         //
5874         // *Upcoming tokens:* `;`
5875         // *Unmatched count:* 2
5876         // *`parse_path_segment` calls deep:* 1
5877         //
5878         // At this point, this function will expect to find another matching `>` character but
5879         // won't be able to and will return an error. This will continue all the way up the
5880         // call stack until the first invocation:
5881         //
5882         // *Upcoming tokens:* `;`
5883         // *Unmatched count:* 2
5884         // *`parse_path_segment` calls deep:* 0
5885         //
5886         // In doing this, we have managed to work out how many unmatched leading left angle
5887         // brackets there are, but we cannot recover as the unmatched angle brackets have
5888         // already been consumed. To remedy this, we keep a snapshot of the parser state
5889         // before we do the above. We can then inspect whether we ended up with a parsing error
5890         // and unmatched left angle brackets and if so, restore the parser state before we
5891         // consumed any `<` characters to emit an error and consume the erroneous tokens to
5892         // recover by attempting to parse again.
5893         //
5894         // In practice, the recursion of this function is indirect and there will be other
5895         // locations that consume some `<` characters - as long as we update the count when
5896         // this happens, it isn't an issue.
5897
5898         let is_first_invocation = style == PathStyle::Expr;
5899         // Take a snapshot before attempting to parse - we can restore this later.
5900         let snapshot = if is_first_invocation {
5901             Some(self.clone())
5902         } else {
5903             None
5904         };
5905
5906         debug!("parse_generic_args_with_leading_angle_bracket_recovery: (snapshotting)");
5907         match self.parse_generic_args() {
5908             Ok(value) => Ok(value),
5909             Err(ref mut e) if is_first_invocation && self.unmatched_angle_bracket_count > 0 => {
5910                 // Cancel error from being unable to find `>`. We know the error
5911                 // must have been this due to a non-zero unmatched angle bracket
5912                 // count.
5913                 e.cancel();
5914
5915                 // Swap `self` with our backup of the parser state before attempting to parse
5916                 // generic arguments.
5917                 let snapshot = mem::replace(self, snapshot.unwrap());
5918
5919                 debug!(
5920                     "parse_generic_args_with_leading_angle_bracket_recovery: (snapshot failure) \
5921                      snapshot.count={:?}",
5922                     snapshot.unmatched_angle_bracket_count,
5923                 );
5924
5925                 // Eat the unmatched angle brackets.
5926                 for _ in 0..snapshot.unmatched_angle_bracket_count {
5927                     self.eat_lt();
5928                 }
5929
5930                 // Make a span over ${unmatched angle bracket count} characters.
5931                 let span = lo.with_hi(
5932                     lo.lo() + BytePos(snapshot.unmatched_angle_bracket_count)
5933                 );
5934                 let plural = snapshot.unmatched_angle_bracket_count > 1;
5935                 self.diagnostic()
5936                     .struct_span_err(
5937                         span,
5938                         &format!(
5939                             "unmatched angle bracket{}",
5940                             if plural { "s" } else { "" }
5941                         ),
5942                     )
5943                     .span_suggestion(
5944                         span,
5945                         &format!(
5946                             "remove extra angle bracket{}",
5947                             if plural { "s" } else { "" }
5948                         ),
5949                         String::new(),
5950                         Applicability::MachineApplicable,
5951                     )
5952                     .emit();
5953
5954                 // Try again without unmatched angle bracket characters.
5955                 self.parse_generic_args()
5956             },
5957             Err(e) => Err(e),
5958         }
5959     }
5960
5961     /// Parses (possibly empty) list of lifetime and type arguments and associated type bindings,
5962     /// possibly including trailing comma.
5963     fn parse_generic_args(&mut self) -> PResult<'a, (Vec<GenericArg>, Vec<TypeBinding>)> {
5964         let mut args = Vec::new();
5965         let mut bindings = Vec::new();
5966         let mut misplaced_assoc_ty_bindings: Vec<Span> = Vec::new();
5967         let mut assoc_ty_bindings: Vec<Span> = Vec::new();
5968
5969         let args_lo = self.span;
5970
5971         loop {
5972             if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
5973                 // Parse lifetime argument.
5974                 args.push(GenericArg::Lifetime(self.expect_lifetime()));
5975                 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
5976             } else if self.check_ident() && self.look_ahead(1, |t| t == &token::Eq) {
5977                 // Parse associated type binding.
5978                 let lo = self.span;
5979                 let ident = self.parse_ident()?;
5980                 self.bump();
5981                 let ty = self.parse_ty()?;
5982                 let span = lo.to(self.prev_span);
5983                 bindings.push(TypeBinding {
5984                     id: ast::DUMMY_NODE_ID,
5985                     ident,
5986                     ty,
5987                     span,
5988                 });
5989                 assoc_ty_bindings.push(span);
5990             } else if self.check_const_arg() {
5991                 // FIXME(const_generics): to distinguish between idents for types and consts,
5992                 // we should introduce a GenericArg::Ident in the AST and distinguish when
5993                 // lowering to the HIR. For now, idents for const args are not permitted.
5994
5995                 // Parse const argument.
5996                 let expr = if let token::OpenDelim(token::Brace) = self.token {
5997                     self.parse_block_expr(None, self.span, BlockCheckMode::Default, ThinVec::new())?
5998                 } else if self.token.is_ident() {
5999                     // FIXME(const_generics): to distinguish between idents for types and consts,
6000                     // we should introduce a GenericArg::Ident in the AST and distinguish when
6001                     // lowering to the HIR. For now, idents for const args are not permitted.
6002                     return Err(
6003                         self.fatal("identifiers may currently not be used for const generics")
6004                     );
6005                 } else {
6006                     // FIXME(const_generics): this currently conflicts with emplacement syntax
6007                     // with negative integer literals.
6008                     self.parse_literal_maybe_minus()?
6009                 };
6010                 let value = AnonConst {
6011                     id: ast::DUMMY_NODE_ID,
6012                     value: expr,
6013                 };
6014                 args.push(GenericArg::Const(value));
6015                 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6016             } else if self.check_type() {
6017                 // Parse type argument.
6018                 args.push(GenericArg::Type(self.parse_ty()?));
6019                 misplaced_assoc_ty_bindings.append(&mut assoc_ty_bindings);
6020             } else {
6021                 break
6022             }
6023
6024             if !self.eat(&token::Comma) {
6025                 break
6026             }
6027         }
6028
6029         // FIXME: we would like to report this in ast_validation instead, but we currently do not
6030         // preserve ordering of generic parameters with respect to associated type binding, so we
6031         // lose that information after parsing.
6032         if misplaced_assoc_ty_bindings.len() > 0 {
6033             let mut err = self.struct_span_err(
6034                 args_lo.to(self.prev_span),
6035                 "associated type bindings must be declared after generic parameters",
6036             );
6037             for span in misplaced_assoc_ty_bindings {
6038                 err.span_label(
6039                     span,
6040                     "this associated type binding should be moved after the generic parameters",
6041                 );
6042             }
6043             err.emit();
6044         }
6045
6046         Ok((args, bindings))
6047     }
6048
6049     /// Parses an optional where-clause and places it in `generics`.
6050     ///
6051     /// ```ignore (only-for-syntax-highlight)
6052     /// where T : Trait<U, V> + 'b, 'a : 'b
6053     /// ```
6054     fn parse_where_clause(&mut self) -> PResult<'a, WhereClause> {
6055         maybe_whole!(self, NtWhereClause, |x| x);
6056
6057         let mut where_clause = WhereClause {
6058             id: ast::DUMMY_NODE_ID,
6059             predicates: Vec::new(),
6060             span: syntax_pos::DUMMY_SP,
6061         };
6062
6063         if !self.eat_keyword(keywords::Where) {
6064             return Ok(where_clause);
6065         }
6066         let lo = self.prev_span;
6067
6068         // We are considering adding generics to the `where` keyword as an alternative higher-rank
6069         // parameter syntax (as in `where<'a>` or `where<T>`. To avoid that being a breaking
6070         // change we parse those generics now, but report an error.
6071         if self.choose_generics_over_qpath() {
6072             let generics = self.parse_generics()?;
6073             self.struct_span_err(
6074                 generics.span,
6075                 "generic parameters on `where` clauses are reserved for future use",
6076             )
6077                 .span_label(generics.span, "currently unsupported")
6078                 .emit();
6079         }
6080
6081         loop {
6082             let lo = self.span;
6083             if self.check_lifetime() && self.look_ahead(1, |t| !t.is_like_plus()) {
6084                 let lifetime = self.expect_lifetime();
6085                 // Bounds starting with a colon are mandatory, but possibly empty.
6086                 self.expect(&token::Colon)?;
6087                 let bounds = self.parse_lt_param_bounds();
6088                 where_clause.predicates.push(ast::WherePredicate::RegionPredicate(
6089                     ast::WhereRegionPredicate {
6090                         span: lo.to(self.prev_span),
6091                         lifetime,
6092                         bounds,
6093                     }
6094                 ));
6095             } else if self.check_type() {
6096                 // Parse optional `for<'a, 'b>`.
6097                 // This `for` is parsed greedily and applies to the whole predicate,
6098                 // the bounded type can have its own `for` applying only to it.
6099                 // Example 1: for<'a> Trait1<'a>: Trait2<'a /*ok*/>
6100                 // Example 2: (for<'a> Trait1<'a>): Trait2<'a /*not ok*/>
6101                 // Example 3: for<'a> for<'b> Trait1<'a, 'b>: Trait2<'a /*ok*/, 'b /*not ok*/>
6102                 let lifetime_defs = self.parse_late_bound_lifetime_defs()?;
6103
6104                 // Parse type with mandatory colon and (possibly empty) bounds,
6105                 // or with mandatory equality sign and the second type.
6106                 let ty = self.parse_ty()?;
6107                 if self.eat(&token::Colon) {
6108                     let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
6109                     where_clause.predicates.push(ast::WherePredicate::BoundPredicate(
6110                         ast::WhereBoundPredicate {
6111                             span: lo.to(self.prev_span),
6112                             bound_generic_params: lifetime_defs,
6113                             bounded_ty: ty,
6114                             bounds,
6115                         }
6116                     ));
6117                 // FIXME: Decide what should be used here, `=` or `==`.
6118                 // FIXME: We are just dropping the binders in lifetime_defs on the floor here.
6119                 } else if self.eat(&token::Eq) || self.eat(&token::EqEq) {
6120                     let rhs_ty = self.parse_ty()?;
6121                     where_clause.predicates.push(ast::WherePredicate::EqPredicate(
6122                         ast::WhereEqPredicate {
6123                             span: lo.to(self.prev_span),
6124                             lhs_ty: ty,
6125                             rhs_ty,
6126                             id: ast::DUMMY_NODE_ID,
6127                         }
6128                     ));
6129                 } else {
6130                     return self.unexpected();
6131                 }
6132             } else {
6133                 break
6134             }
6135
6136             if !self.eat(&token::Comma) {
6137                 break
6138             }
6139         }
6140
6141         where_clause.span = lo.to(self.prev_span);
6142         Ok(where_clause)
6143     }
6144
6145     fn parse_fn_args(&mut self, named_args: bool, allow_c_variadic: bool)
6146                      -> PResult<'a, (Vec<Arg> , bool)> {
6147         self.expect(&token::OpenDelim(token::Paren))?;
6148
6149         let sp = self.span;
6150         let mut c_variadic = false;
6151         let (args, recovered): (Vec<Option<Arg>>, bool) =
6152             self.parse_seq_to_before_end(
6153                 &token::CloseDelim(token::Paren),
6154                 SeqSep::trailing_allowed(token::Comma),
6155                 |p| {
6156                     // If the argument is a C-variadic argument we should not
6157                     // enforce named arguments.
6158                     let enforce_named_args = if p.token == token::DotDotDot {
6159                         false
6160                     } else {
6161                         named_args
6162                     };
6163                     match p.parse_arg_general(enforce_named_args, false,
6164                                               allow_c_variadic) {
6165                         Ok(arg) => {
6166                             if let TyKind::CVarArgs = arg.ty.node {
6167                                 c_variadic = true;
6168                                 if p.token != token::CloseDelim(token::Paren) {
6169                                     let span = p.span;
6170                                     p.span_err(span,
6171                                         "`...` must be the last argument of a C-variadic function");
6172                                     Ok(None)
6173                                 } else {
6174                                     Ok(Some(arg))
6175                                 }
6176                             } else {
6177                                 Ok(Some(arg))
6178                             }
6179                         },
6180                         Err(mut e) => {
6181                             e.emit();
6182                             let lo = p.prev_span;
6183                             // Skip every token until next possible arg or end.
6184                             p.eat_to_tokens(&[&token::Comma, &token::CloseDelim(token::Paren)]);
6185                             // Create a placeholder argument for proper arg count (issue #34264).
6186                             let span = lo.to(p.prev_span);
6187                             Ok(Some(dummy_arg(span)))
6188                         }
6189                     }
6190                 }
6191             )?;
6192
6193         if !recovered {
6194             self.eat(&token::CloseDelim(token::Paren));
6195         }
6196
6197         let args: Vec<_> = args.into_iter().filter_map(|x| x).collect();
6198
6199         if c_variadic && args.is_empty() {
6200             self.span_err(sp,
6201                           "C-variadic function must be declared with at least one named argument");
6202         }
6203
6204         Ok((args, c_variadic))
6205     }
6206
6207     /// Parses the argument list and result type of a function declaration.
6208     fn parse_fn_decl(&mut self, allow_c_variadic: bool) -> PResult<'a, P<FnDecl>> {
6209
6210         let (args, c_variadic) = self.parse_fn_args(true, allow_c_variadic)?;
6211         let ret_ty = self.parse_ret_ty(true)?;
6212
6213         Ok(P(FnDecl {
6214             inputs: args,
6215             output: ret_ty,
6216             c_variadic,
6217         }))
6218     }
6219
6220     /// Returns the parsed optional self argument and whether a self shortcut was used.
6221     fn parse_self_arg(&mut self) -> PResult<'a, Option<Arg>> {
6222         let expect_ident = |this: &mut Self| match this.token {
6223             // Preserve hygienic context.
6224             token::Ident(ident, _) =>
6225                 { let span = this.span; this.bump(); Ident::new(ident.name, span) }
6226             _ => unreachable!()
6227         };
6228         let isolated_self = |this: &mut Self, n| {
6229             this.look_ahead(n, |t| t.is_keyword(keywords::SelfLower)) &&
6230             this.look_ahead(n + 1, |t| t != &token::ModSep)
6231         };
6232
6233         // Parse optional self parameter of a method.
6234         // Only a limited set of initial token sequences is considered self parameters, anything
6235         // else is parsed as a normal function parameter list, so some lookahead is required.
6236         let eself_lo = self.span;
6237         let (eself, eself_ident, eself_hi) = match self.token {
6238             token::BinOp(token::And) => {
6239                 // &self
6240                 // &mut self
6241                 // &'lt self
6242                 // &'lt mut self
6243                 // &not_self
6244                 (if isolated_self(self, 1) {
6245                     self.bump();
6246                     SelfKind::Region(None, Mutability::Immutable)
6247                 } else if self.look_ahead(1, |t| t.is_keyword(keywords::Mut)) &&
6248                           isolated_self(self, 2) {
6249                     self.bump();
6250                     self.bump();
6251                     SelfKind::Region(None, Mutability::Mutable)
6252                 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6253                           isolated_self(self, 2) {
6254                     self.bump();
6255                     let lt = self.expect_lifetime();
6256                     SelfKind::Region(Some(lt), Mutability::Immutable)
6257                 } else if self.look_ahead(1, |t| t.is_lifetime()) &&
6258                           self.look_ahead(2, |t| t.is_keyword(keywords::Mut)) &&
6259                           isolated_self(self, 3) {
6260                     self.bump();
6261                     let lt = self.expect_lifetime();
6262                     self.bump();
6263                     SelfKind::Region(Some(lt), Mutability::Mutable)
6264                 } else {
6265                     return Ok(None);
6266                 }, expect_ident(self), self.prev_span)
6267             }
6268             token::BinOp(token::Star) => {
6269                 // *self
6270                 // *const self
6271                 // *mut self
6272                 // *not_self
6273                 // Emit special error for `self` cases.
6274                 let msg = "cannot pass `self` by raw pointer";
6275                 (if isolated_self(self, 1) {
6276                     self.bump();
6277                     self.struct_span_err(self.span, msg)
6278                         .span_label(self.span, msg)
6279                         .emit();
6280                     SelfKind::Value(Mutability::Immutable)
6281                 } else if self.look_ahead(1, |t| t.is_mutability()) &&
6282                           isolated_self(self, 2) {
6283                     self.bump();
6284                     self.bump();
6285                     self.struct_span_err(self.span, msg)
6286                         .span_label(self.span, msg)
6287                         .emit();
6288                     SelfKind::Value(Mutability::Immutable)
6289                 } else {
6290                     return Ok(None);
6291                 }, expect_ident(self), self.prev_span)
6292             }
6293             token::Ident(..) => {
6294                 if isolated_self(self, 0) {
6295                     // self
6296                     // self: TYPE
6297                     let eself_ident = expect_ident(self);
6298                     let eself_hi = self.prev_span;
6299                     (if self.eat(&token::Colon) {
6300                         let ty = self.parse_ty()?;
6301                         SelfKind::Explicit(ty, Mutability::Immutable)
6302                     } else {
6303                         SelfKind::Value(Mutability::Immutable)
6304                     }, eself_ident, eself_hi)
6305                 } else if self.token.is_keyword(keywords::Mut) &&
6306                           isolated_self(self, 1) {
6307                     // mut self
6308                     // mut self: TYPE
6309                     self.bump();
6310                     let eself_ident = expect_ident(self);
6311                     let eself_hi = self.prev_span;
6312                     (if self.eat(&token::Colon) {
6313                         let ty = self.parse_ty()?;
6314                         SelfKind::Explicit(ty, Mutability::Mutable)
6315                     } else {
6316                         SelfKind::Value(Mutability::Mutable)
6317                     }, eself_ident, eself_hi)
6318                 } else {
6319                     return Ok(None);
6320                 }
6321             }
6322             _ => return Ok(None),
6323         };
6324
6325         let eself = source_map::respan(eself_lo.to(eself_hi), eself);
6326         Ok(Some(Arg::from_self(eself, eself_ident)))
6327     }
6328
6329     /// Parses the parameter list and result type of a function that may have a `self` parameter.
6330     fn parse_fn_decl_with_self<F>(&mut self, parse_arg_fn: F) -> PResult<'a, P<FnDecl>>
6331         where F: FnMut(&mut Parser<'a>) -> PResult<'a,  Arg>,
6332     {
6333         self.expect(&token::OpenDelim(token::Paren))?;
6334
6335         // Parse optional self argument
6336         let self_arg = self.parse_self_arg()?;
6337
6338         // Parse the rest of the function parameter list.
6339         let sep = SeqSep::trailing_allowed(token::Comma);
6340         let (fn_inputs, recovered) = if let Some(self_arg) = self_arg {
6341             if self.check(&token::CloseDelim(token::Paren)) {
6342                 (vec![self_arg], false)
6343             } else if self.eat(&token::Comma) {
6344                 let mut fn_inputs = vec![self_arg];
6345                 let (mut input, recovered) = self.parse_seq_to_before_end(
6346                     &token::CloseDelim(token::Paren), sep, parse_arg_fn)?;
6347                 fn_inputs.append(&mut input);
6348                 (fn_inputs, recovered)
6349             } else {
6350                 match self.expect_one_of(&[], &[]) {
6351                     Err(err) => return Err(err),
6352                     Ok(recovered) => (vec![self_arg], recovered),
6353                 }
6354             }
6355         } else {
6356             self.parse_seq_to_before_end(&token::CloseDelim(token::Paren), sep, parse_arg_fn)?
6357         };
6358
6359         if !recovered {
6360             // Parse closing paren and return type.
6361             self.expect(&token::CloseDelim(token::Paren))?;
6362         }
6363         Ok(P(FnDecl {
6364             inputs: fn_inputs,
6365             output: self.parse_ret_ty(true)?,
6366             c_variadic: false
6367         }))
6368     }
6369
6370     /// Parses the `|arg, arg|` header of a closure.
6371     fn parse_fn_block_decl(&mut self) -> PResult<'a, P<FnDecl>> {
6372         let inputs_captures = {
6373             if self.eat(&token::OrOr) {
6374                 Vec::new()
6375             } else {
6376                 self.expect(&token::BinOp(token::Or))?;
6377                 let args = self.parse_seq_to_before_tokens(
6378                     &[&token::BinOp(token::Or), &token::OrOr],
6379                     SeqSep::trailing_allowed(token::Comma),
6380                     TokenExpectType::NoExpect,
6381                     |p| p.parse_fn_block_arg()
6382                 )?.0;
6383                 self.expect_or()?;
6384                 args
6385             }
6386         };
6387         let output = self.parse_ret_ty(true)?;
6388
6389         Ok(P(FnDecl {
6390             inputs: inputs_captures,
6391             output,
6392             c_variadic: false
6393         }))
6394     }
6395
6396     /// Parses the name and optional generic types of a function header.
6397     fn parse_fn_header(&mut self) -> PResult<'a, (Ident, ast::Generics)> {
6398         let id = self.parse_ident()?;
6399         let generics = self.parse_generics()?;
6400         Ok((id, generics))
6401     }
6402
6403     fn mk_item(&mut self, span: Span, ident: Ident, node: ItemKind, vis: Visibility,
6404                attrs: Vec<Attribute>) -> P<Item> {
6405         P(Item {
6406             ident,
6407             attrs,
6408             id: ast::DUMMY_NODE_ID,
6409             node,
6410             vis,
6411             span,
6412             tokens: None,
6413         })
6414     }
6415
6416     /// Parses an item-position function declaration.
6417     fn parse_item_fn(&mut self,
6418                      unsafety: Unsafety,
6419                      asyncness: Spanned<IsAsync>,
6420                      constness: Spanned<Constness>,
6421                      abi: Abi)
6422                      -> PResult<'a, ItemInfo> {
6423         let (ident, mut generics) = self.parse_fn_header()?;
6424         let allow_c_variadic = abi == Abi::C && unsafety == Unsafety::Unsafe;
6425         let decl = self.parse_fn_decl(allow_c_variadic)?;
6426         generics.where_clause = self.parse_where_clause()?;
6427         let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6428         let header = FnHeader { unsafety, asyncness, constness, abi };
6429         Ok((ident, ItemKind::Fn(decl, header, generics, body), Some(inner_attrs)))
6430     }
6431
6432     /// Returns `true` if we are looking at `const ID`
6433     /// (returns `false` for things like `const fn`, etc.).
6434     fn is_const_item(&mut self) -> bool {
6435         self.token.is_keyword(keywords::Const) &&
6436             !self.look_ahead(1, |t| t.is_keyword(keywords::Fn)) &&
6437             !self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe))
6438     }
6439
6440     /// Parses all the "front matter" for a `fn` declaration, up to
6441     /// and including the `fn` keyword:
6442     ///
6443     /// - `const fn`
6444     /// - `unsafe fn`
6445     /// - `const unsafe fn`
6446     /// - `extern fn`
6447     /// - etc.
6448     fn parse_fn_front_matter(&mut self)
6449         -> PResult<'a, (
6450             Spanned<Constness>,
6451             Unsafety,
6452             Spanned<IsAsync>,
6453             Abi
6454         )>
6455     {
6456         let is_const_fn = self.eat_keyword(keywords::Const);
6457         let const_span = self.prev_span;
6458         let unsafety = self.parse_unsafety();
6459         let asyncness = self.parse_asyncness();
6460         let asyncness = respan(self.prev_span, asyncness);
6461         let (constness, unsafety, abi) = if is_const_fn {
6462             (respan(const_span, Constness::Const), unsafety, Abi::Rust)
6463         } else {
6464             let abi = if self.eat_keyword(keywords::Extern) {
6465                 self.parse_opt_abi()?.unwrap_or(Abi::C)
6466             } else {
6467                 Abi::Rust
6468             };
6469             (respan(self.prev_span, Constness::NotConst), unsafety, abi)
6470         };
6471         self.expect_keyword(keywords::Fn)?;
6472         Ok((constness, unsafety, asyncness, abi))
6473     }
6474
6475     /// Parses an impl item.
6476     pub fn parse_impl_item(&mut self, at_end: &mut bool) -> PResult<'a, ImplItem> {
6477         maybe_whole!(self, NtImplItem, |x| x);
6478         let attrs = self.parse_outer_attributes()?;
6479         let mut unclosed_delims = vec![];
6480         let (mut item, tokens) = self.collect_tokens(|this| {
6481             let item = this.parse_impl_item_(at_end, attrs);
6482             unclosed_delims.append(&mut this.unclosed_delims);
6483             item
6484         })?;
6485         self.unclosed_delims.append(&mut unclosed_delims);
6486
6487         // See `parse_item` for why this clause is here.
6488         if !item.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
6489             item.tokens = Some(tokens);
6490         }
6491         Ok(item)
6492     }
6493
6494     fn parse_impl_item_(&mut self,
6495                         at_end: &mut bool,
6496                         mut attrs: Vec<Attribute>) -> PResult<'a, ImplItem> {
6497         let lo = self.span;
6498         let vis = self.parse_visibility(false)?;
6499         let defaultness = self.parse_defaultness();
6500         let (name, node, generics) = if let Some(type_) = self.eat_type() {
6501             let (name, alias, generics) = type_?;
6502             let kind = match alias {
6503                 AliasKind::Weak(typ) => ast::ImplItemKind::Type(typ),
6504                 AliasKind::Existential(bounds) => ast::ImplItemKind::Existential(bounds),
6505             };
6506             (name, kind, generics)
6507         } else if self.is_const_item() {
6508             // This parses the grammar:
6509             //     ImplItemConst = "const" Ident ":" Ty "=" Expr ";"
6510             self.expect_keyword(keywords::Const)?;
6511             let name = self.parse_ident()?;
6512             self.expect(&token::Colon)?;
6513             let typ = self.parse_ty()?;
6514             self.expect(&token::Eq)?;
6515             let expr = self.parse_expr()?;
6516             self.expect(&token::Semi)?;
6517             (name, ast::ImplItemKind::Const(typ, expr), ast::Generics::default())
6518         } else {
6519             let (name, inner_attrs, generics, node) = self.parse_impl_method(&vis, at_end)?;
6520             attrs.extend(inner_attrs);
6521             (name, node, generics)
6522         };
6523
6524         Ok(ImplItem {
6525             id: ast::DUMMY_NODE_ID,
6526             span: lo.to(self.prev_span),
6527             ident: name,
6528             vis,
6529             defaultness,
6530             attrs,
6531             generics,
6532             node,
6533             tokens: None,
6534         })
6535     }
6536
6537     fn complain_if_pub_macro(&mut self, vis: &VisibilityKind, sp: Span) {
6538         match *vis {
6539             VisibilityKind::Inherited => {}
6540             _ => {
6541                 let is_macro_rules: bool = match self.token {
6542                     token::Ident(sid, _) => sid.name == Symbol::intern("macro_rules"),
6543                     _ => false,
6544                 };
6545                 let mut err = if is_macro_rules {
6546                     let mut err = self.diagnostic()
6547                         .struct_span_err(sp, "can't qualify macro_rules invocation with `pub`");
6548                     err.span_suggestion(
6549                         sp,
6550                         "try exporting the macro",
6551                         "#[macro_export]".to_owned(),
6552                         Applicability::MaybeIncorrect // speculative
6553                     );
6554                     err
6555                 } else {
6556                     let mut err = self.diagnostic()
6557                         .struct_span_err(sp, "can't qualify macro invocation with `pub`");
6558                     err.help("try adjusting the macro to put `pub` inside the invocation");
6559                     err
6560                 };
6561                 err.emit();
6562             }
6563         }
6564     }
6565
6566     fn missing_assoc_item_kind_err(&mut self, item_type: &str, prev_span: Span)
6567                                    -> DiagnosticBuilder<'a>
6568     {
6569         let expected_kinds = if item_type == "extern" {
6570             "missing `fn`, `type`, or `static`"
6571         } else {
6572             "missing `fn`, `type`, or `const`"
6573         };
6574
6575         // Given this code `path(`, it seems like this is not
6576         // setting the visibility of a macro invocation, but rather
6577         // a mistyped method declaration.
6578         // Create a diagnostic pointing out that `fn` is missing.
6579         //
6580         // x |     pub path(&self) {
6581         //   |        ^ missing `fn`, `type`, or `const`
6582         //     pub  path(
6583         //        ^^ `sp` below will point to this
6584         let sp = prev_span.between(self.prev_span);
6585         let mut err = self.diagnostic().struct_span_err(
6586             sp,
6587             &format!("{} for {}-item declaration",
6588                      expected_kinds, item_type));
6589         err.span_label(sp, expected_kinds);
6590         err
6591     }
6592
6593     /// Parse a method or a macro invocation in a trait impl.
6594     fn parse_impl_method(&mut self, vis: &Visibility, at_end: &mut bool)
6595                          -> PResult<'a, (Ident, Vec<Attribute>, ast::Generics,
6596                              ast::ImplItemKind)> {
6597         // code copied from parse_macro_use_or_failure... abstraction!
6598         if let Some(mac) = self.parse_assoc_macro_invoc("impl", Some(vis), at_end)? {
6599             // method macro
6600             Ok((keywords::Invalid.ident(), vec![], ast::Generics::default(),
6601                 ast::ImplItemKind::Macro(mac)))
6602         } else {
6603             let (constness, unsafety, asyncness, abi) = self.parse_fn_front_matter()?;
6604             let ident = self.parse_ident()?;
6605             let mut generics = self.parse_generics()?;
6606             let decl = self.parse_fn_decl_with_self(|p| p.parse_arg())?;
6607             generics.where_clause = self.parse_where_clause()?;
6608             *at_end = true;
6609             let (inner_attrs, body) = self.parse_inner_attrs_and_block()?;
6610             let header = ast::FnHeader { abi, unsafety, constness, asyncness };
6611             Ok((ident, inner_attrs, generics, ast::ImplItemKind::Method(
6612                 ast::MethodSig { header, decl },
6613                 body
6614             )))
6615         }
6616     }
6617
6618     /// Parses `trait Foo { ... }` or `trait Foo = Bar;`.
6619     fn parse_item_trait(&mut self, is_auto: IsAuto, unsafety: Unsafety) -> PResult<'a, ItemInfo> {
6620         let ident = self.parse_ident()?;
6621         let mut tps = self.parse_generics()?;
6622
6623         // Parse optional colon and supertrait bounds.
6624         let bounds = if self.eat(&token::Colon) {
6625             self.parse_generic_bounds(Some(self.prev_span))?
6626         } else {
6627             Vec::new()
6628         };
6629
6630         if self.eat(&token::Eq) {
6631             // it's a trait alias
6632             let bounds = self.parse_generic_bounds(None)?;
6633             tps.where_clause = self.parse_where_clause()?;
6634             self.expect(&token::Semi)?;
6635             if is_auto == IsAuto::Yes {
6636                 let msg = "trait aliases cannot be `auto`";
6637                 self.struct_span_err(self.prev_span, msg)
6638                     .span_label(self.prev_span, msg)
6639                     .emit();
6640             }
6641             if unsafety != Unsafety::Normal {
6642                 let msg = "trait aliases cannot be `unsafe`";
6643                 self.struct_span_err(self.prev_span, msg)
6644                     .span_label(self.prev_span, msg)
6645                     .emit();
6646             }
6647             Ok((ident, ItemKind::TraitAlias(tps, bounds), None))
6648         } else {
6649             // it's a normal trait
6650             tps.where_clause = self.parse_where_clause()?;
6651             self.expect(&token::OpenDelim(token::Brace))?;
6652             let mut trait_items = vec![];
6653             while !self.eat(&token::CloseDelim(token::Brace)) {
6654                 let mut at_end = false;
6655                 match self.parse_trait_item(&mut at_end) {
6656                     Ok(item) => trait_items.push(item),
6657                     Err(mut e) => {
6658                         e.emit();
6659                         if !at_end {
6660                             self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6661                         }
6662                     }
6663                 }
6664             }
6665             Ok((ident, ItemKind::Trait(is_auto, unsafety, tps, bounds, trait_items), None))
6666         }
6667     }
6668
6669     fn choose_generics_over_qpath(&self) -> bool {
6670         // There's an ambiguity between generic parameters and qualified paths in impls.
6671         // If we see `<` it may start both, so we have to inspect some following tokens.
6672         // The following combinations can only start generics,
6673         // but not qualified paths (with one exception):
6674         //     `<` `>` - empty generic parameters
6675         //     `<` `#` - generic parameters with attributes
6676         //     `<` (LIFETIME|IDENT) `>` - single generic parameter
6677         //     `<` (LIFETIME|IDENT) `,` - first generic parameter in a list
6678         //     `<` (LIFETIME|IDENT) `:` - generic parameter with bounds
6679         //     `<` (LIFETIME|IDENT) `=` - generic parameter with a default
6680         //     `<` const                - generic const parameter
6681         // The only truly ambiguous case is
6682         //     `<` IDENT `>` `::` IDENT ...
6683         // we disambiguate it in favor of generics (`impl<T> ::absolute::Path<T> { ... }`)
6684         // because this is what almost always expected in practice, qualified paths in impls
6685         // (`impl <Type>::AssocTy { ... }`) aren't even allowed by type checker at the moment.
6686         self.token == token::Lt &&
6687             (self.look_ahead(1, |t| t == &token::Pound || t == &token::Gt) ||
6688              self.look_ahead(1, |t| t.is_lifetime() || t.is_ident()) &&
6689                 self.look_ahead(2, |t| t == &token::Gt || t == &token::Comma ||
6690                                        t == &token::Colon || t == &token::Eq) ||
6691              self.look_ahead(1, |t| t.is_keyword(keywords::Const)))
6692     }
6693
6694     fn parse_impl_body(&mut self) -> PResult<'a, (Vec<ImplItem>, Vec<Attribute>)> {
6695         self.expect(&token::OpenDelim(token::Brace))?;
6696         let attrs = self.parse_inner_attributes()?;
6697
6698         let mut impl_items = Vec::new();
6699         while !self.eat(&token::CloseDelim(token::Brace)) {
6700             let mut at_end = false;
6701             match self.parse_impl_item(&mut at_end) {
6702                 Ok(impl_item) => impl_items.push(impl_item),
6703                 Err(mut err) => {
6704                     err.emit();
6705                     if !at_end {
6706                         self.recover_stmt_(SemiColonMode::Break, BlockMode::Break);
6707                     }
6708                 }
6709             }
6710         }
6711         Ok((impl_items, attrs))
6712     }
6713
6714     /// Parses an implementation item, `impl` keyword is already parsed.
6715     ///
6716     ///    impl<'a, T> TYPE { /* impl items */ }
6717     ///    impl<'a, T> TRAIT for TYPE { /* impl items */ }
6718     ///    impl<'a, T> !TRAIT for TYPE { /* impl items */ }
6719     ///
6720     /// We actually parse slightly more relaxed grammar for better error reporting and recovery.
6721     ///     `impl` GENERICS `!`? TYPE `for`? (TYPE | `..`) (`where` PREDICATES)? `{` BODY `}`
6722     ///     `impl` GENERICS `!`? TYPE (`where` PREDICATES)? `{` BODY `}`
6723     fn parse_item_impl(&mut self, unsafety: Unsafety, defaultness: Defaultness)
6724                        -> PResult<'a, ItemInfo> {
6725         // First, parse generic parameters if necessary.
6726         let mut generics = if self.choose_generics_over_qpath() {
6727             self.parse_generics()?
6728         } else {
6729             ast::Generics::default()
6730         };
6731
6732         // Disambiguate `impl !Trait for Type { ... }` and `impl ! { ... }` for the never type.
6733         let polarity = if self.check(&token::Not) && self.look_ahead(1, |t| t.can_begin_type()) {
6734             self.bump(); // `!`
6735             ast::ImplPolarity::Negative
6736         } else {
6737             ast::ImplPolarity::Positive
6738         };
6739
6740         // Parse both types and traits as a type, then reinterpret if necessary.
6741         let err_path = |span| ast::Path::from_ident(Ident::new(keywords::Invalid.name(), span));
6742         let ty_first = if self.token.is_keyword(keywords::For) &&
6743                           self.look_ahead(1, |t| t != &token::Lt) {
6744             let span = self.prev_span.between(self.span);
6745             self.struct_span_err(span, "missing trait in a trait impl").emit();
6746             P(Ty { node: TyKind::Path(None, err_path(span)), span, id: ast::DUMMY_NODE_ID })
6747         } else {
6748             self.parse_ty()?
6749         };
6750
6751         // If `for` is missing we try to recover.
6752         let has_for = self.eat_keyword(keywords::For);
6753         let missing_for_span = self.prev_span.between(self.span);
6754
6755         let ty_second = if self.token == token::DotDot {
6756             // We need to report this error after `cfg` expansion for compatibility reasons
6757             self.bump(); // `..`, do not add it to expected tokens
6758             Some(DummyResult::raw_ty(self.prev_span, true))
6759         } else if has_for || self.token.can_begin_type() {
6760             Some(self.parse_ty()?)
6761         } else {
6762             None
6763         };
6764
6765         generics.where_clause = self.parse_where_clause()?;
6766
6767         let (impl_items, attrs) = self.parse_impl_body()?;
6768
6769         let item_kind = match ty_second {
6770             Some(ty_second) => {
6771                 // impl Trait for Type
6772                 if !has_for {
6773                     self.struct_span_err(missing_for_span, "missing `for` in a trait impl")
6774                         .span_suggestion_short(
6775                             missing_for_span,
6776                             "add `for` here",
6777                             " for ".to_string(),
6778                             Applicability::MachineApplicable,
6779                         ).emit();
6780                 }
6781
6782                 let ty_first = ty_first.into_inner();
6783                 let path = match ty_first.node {
6784                     // This notably includes paths passed through `ty` macro fragments (#46438).
6785                     TyKind::Path(None, path) => path,
6786                     _ => {
6787                         self.span_err(ty_first.span, "expected a trait, found type");
6788                         err_path(ty_first.span)
6789                     }
6790                 };
6791                 let trait_ref = TraitRef { path, ref_id: ty_first.id };
6792
6793                 ItemKind::Impl(unsafety, polarity, defaultness,
6794                                generics, Some(trait_ref), ty_second, impl_items)
6795             }
6796             None => {
6797                 // impl Type
6798                 ItemKind::Impl(unsafety, polarity, defaultness,
6799                                generics, None, ty_first, impl_items)
6800             }
6801         };
6802
6803         Ok((keywords::Invalid.ident(), item_kind, Some(attrs)))
6804     }
6805
6806     fn parse_late_bound_lifetime_defs(&mut self) -> PResult<'a, Vec<GenericParam>> {
6807         if self.eat_keyword(keywords::For) {
6808             self.expect_lt()?;
6809             let params = self.parse_generic_params()?;
6810             self.expect_gt()?;
6811             // We rely on AST validation to rule out invalid cases: There must not be type
6812             // parameters, and the lifetime parameters must not have bounds.
6813             Ok(params)
6814         } else {
6815             Ok(Vec::new())
6816         }
6817     }
6818
6819     /// Parses `struct Foo { ... }`.
6820     fn parse_item_struct(&mut self) -> PResult<'a, ItemInfo> {
6821         let class_name = self.parse_ident()?;
6822
6823         let mut generics = self.parse_generics()?;
6824
6825         // There is a special case worth noting here, as reported in issue #17904.
6826         // If we are parsing a tuple struct it is the case that the where clause
6827         // should follow the field list. Like so:
6828         //
6829         // struct Foo<T>(T) where T: Copy;
6830         //
6831         // If we are parsing a normal record-style struct it is the case
6832         // that the where clause comes before the body, and after the generics.
6833         // So if we look ahead and see a brace or a where-clause we begin
6834         // parsing a record style struct.
6835         //
6836         // Otherwise if we look ahead and see a paren we parse a tuple-style
6837         // struct.
6838
6839         let vdata = if self.token.is_keyword(keywords::Where) {
6840             generics.where_clause = self.parse_where_clause()?;
6841             if self.eat(&token::Semi) {
6842                 // If we see a: `struct Foo<T> where T: Copy;` style decl.
6843                 VariantData::Unit(ast::DUMMY_NODE_ID)
6844             } else {
6845                 // If we see: `struct Foo<T> where T: Copy { ... }`
6846                 let (fields, recovered) = self.parse_record_struct_body()?;
6847                 VariantData::Struct(fields, ast::DUMMY_NODE_ID, recovered)
6848             }
6849         // No `where` so: `struct Foo<T>;`
6850         } else if self.eat(&token::Semi) {
6851             VariantData::Unit(ast::DUMMY_NODE_ID)
6852         // Record-style struct definition
6853         } else if self.token == token::OpenDelim(token::Brace) {
6854             let (fields, recovered) = self.parse_record_struct_body()?;
6855             VariantData::Struct(fields, ast::DUMMY_NODE_ID, recovered)
6856         // Tuple-style struct definition with optional where-clause.
6857         } else if self.token == token::OpenDelim(token::Paren) {
6858             let body = VariantData::Tuple(self.parse_tuple_struct_body()?, ast::DUMMY_NODE_ID);
6859             generics.where_clause = self.parse_where_clause()?;
6860             self.expect(&token::Semi)?;
6861             body
6862         } else {
6863             let token_str = self.this_token_descr();
6864             let mut err = self.fatal(&format!(
6865                 "expected `where`, `{{`, `(`, or `;` after struct name, found {}",
6866                 token_str
6867             ));
6868             err.span_label(self.span, "expected `where`, `{`, `(`, or `;` after struct name");
6869             return Err(err);
6870         };
6871
6872         Ok((class_name, ItemKind::Struct(vdata, generics), None))
6873     }
6874
6875     /// Parses `union Foo { ... }`.
6876     fn parse_item_union(&mut self) -> PResult<'a, ItemInfo> {
6877         let class_name = self.parse_ident()?;
6878
6879         let mut generics = self.parse_generics()?;
6880
6881         let vdata = if self.token.is_keyword(keywords::Where) {
6882             generics.where_clause = self.parse_where_clause()?;
6883             let (fields, recovered) = self.parse_record_struct_body()?;
6884             VariantData::Struct(fields, ast::DUMMY_NODE_ID, recovered)
6885         } else if self.token == token::OpenDelim(token::Brace) {
6886             let (fields, recovered) = self.parse_record_struct_body()?;
6887             VariantData::Struct(fields, ast::DUMMY_NODE_ID, recovered)
6888         } else {
6889             let token_str = self.this_token_descr();
6890             let mut err = self.fatal(&format!(
6891                 "expected `where` or `{{` after union name, found {}", token_str));
6892             err.span_label(self.span, "expected `where` or `{` after union name");
6893             return Err(err);
6894         };
6895
6896         Ok((class_name, ItemKind::Union(vdata, generics), None))
6897     }
6898
6899     fn consume_block(&mut self, delim: token::DelimToken) {
6900         let mut brace_depth = 0;
6901         loop {
6902             if self.eat(&token::OpenDelim(delim)) {
6903                 brace_depth += 1;
6904             } else if self.eat(&token::CloseDelim(delim)) {
6905                 if brace_depth == 0 {
6906                     return;
6907                 } else {
6908                     brace_depth -= 1;
6909                     continue;
6910                 }
6911             } else if self.token == token::Eof || self.eat(&token::CloseDelim(token::NoDelim)) {
6912                 return;
6913             } else {
6914                 self.bump();
6915             }
6916         }
6917     }
6918
6919     fn parse_record_struct_body(
6920         &mut self,
6921     ) -> PResult<'a, (Vec<StructField>, /* recovered */ bool)> {
6922         let mut fields = Vec::new();
6923         let mut recovered = false;
6924         if self.eat(&token::OpenDelim(token::Brace)) {
6925             while self.token != token::CloseDelim(token::Brace) {
6926                 let field = self.parse_struct_decl_field().map_err(|e| {
6927                     self.recover_stmt();
6928                     recovered = true;
6929                     e
6930                 });
6931                 match field {
6932                     Ok(field) => fields.push(field),
6933                     Err(mut err) => {
6934                         err.emit();
6935                     }
6936                 }
6937             }
6938             self.eat(&token::CloseDelim(token::Brace));
6939         } else {
6940             let token_str = self.this_token_descr();
6941             let mut err = self.fatal(&format!(
6942                     "expected `where`, or `{{` after struct name, found {}", token_str));
6943             err.span_label(self.span, "expected `where`, or `{` after struct name");
6944             return Err(err);
6945         }
6946
6947         Ok((fields, recovered))
6948     }
6949
6950     fn parse_tuple_struct_body(&mut self) -> PResult<'a, Vec<StructField>> {
6951         // This is the case where we find `struct Foo<T>(T) where T: Copy;`
6952         // Unit like structs are handled in parse_item_struct function
6953         let fields = self.parse_unspanned_seq(
6954             &token::OpenDelim(token::Paren),
6955             &token::CloseDelim(token::Paren),
6956             SeqSep::trailing_allowed(token::Comma),
6957             |p| {
6958                 let attrs = p.parse_outer_attributes()?;
6959                 let lo = p.span;
6960                 let vis = p.parse_visibility(true)?;
6961                 let ty = p.parse_ty()?;
6962                 Ok(StructField {
6963                     span: lo.to(ty.span),
6964                     vis,
6965                     ident: None,
6966                     id: ast::DUMMY_NODE_ID,
6967                     ty,
6968                     attrs,
6969                 })
6970             })?;
6971
6972         Ok(fields)
6973     }
6974
6975     /// Parses a structure field declaration.
6976     fn parse_single_struct_field(&mut self,
6977                                      lo: Span,
6978                                      vis: Visibility,
6979                                      attrs: Vec<Attribute> )
6980                                      -> PResult<'a, StructField> {
6981         let mut seen_comma: bool = false;
6982         let a_var = self.parse_name_and_ty(lo, vis, attrs)?;
6983         if self.token == token::Comma {
6984             seen_comma = true;
6985         }
6986         match self.token {
6987             token::Comma => {
6988                 self.bump();
6989             }
6990             token::CloseDelim(token::Brace) => {}
6991             token::DocComment(_) => {
6992                 let previous_span = self.prev_span;
6993                 let mut err = self.span_fatal_err(self.span, Error::UselessDocComment);
6994                 self.bump(); // consume the doc comment
6995                 let comma_after_doc_seen = self.eat(&token::Comma);
6996                 // `seen_comma` is always false, because we are inside doc block
6997                 // condition is here to make code more readable
6998                 if seen_comma == false && comma_after_doc_seen == true {
6999                     seen_comma = true;
7000                 }
7001                 if comma_after_doc_seen || self.token == token::CloseDelim(token::Brace) {
7002                     err.emit();
7003                 } else {
7004                     if seen_comma == false {
7005                         let sp = self.sess.source_map().next_point(previous_span);
7006                         err.span_suggestion(
7007                             sp,
7008                             "missing comma here",
7009                             ",".into(),
7010                             Applicability::MachineApplicable
7011                         );
7012                     }
7013                     return Err(err);
7014                 }
7015             }
7016             _ => {
7017                 let sp = self.sess.source_map().next_point(self.prev_span);
7018                 let mut err = self.struct_span_err(sp, &format!("expected `,`, or `}}`, found {}",
7019                                                                 self.this_token_descr()));
7020                 if self.token.is_ident() {
7021                     // This is likely another field; emit the diagnostic and keep going
7022                     err.span_suggestion(
7023                         sp,
7024                         "try adding a comma",
7025                         ",".into(),
7026                         Applicability::MachineApplicable,
7027                     );
7028                     err.emit();
7029                 } else {
7030                     return Err(err)
7031                 }
7032             }
7033         }
7034         Ok(a_var)
7035     }
7036
7037     /// Parses an element of a struct declaration.
7038     fn parse_struct_decl_field(&mut self) -> PResult<'a, StructField> {
7039         let attrs = self.parse_outer_attributes()?;
7040         let lo = self.span;
7041         let vis = self.parse_visibility(false)?;
7042         self.parse_single_struct_field(lo, vis, attrs)
7043     }
7044
7045     /// Parses `pub`, `pub(crate)` and `pub(in path)` plus shortcuts `crate` for `pub(crate)`,
7046     /// `pub(self)` for `pub(in self)` and `pub(super)` for `pub(in super)`.
7047     /// If the following element can't be a tuple (i.e., it's a function definition), then
7048     /// it's not a tuple struct field), and the contents within the parentheses isn't valid,
7049     /// so emit a proper diagnostic.
7050     pub fn parse_visibility(&mut self, can_take_tuple: bool) -> PResult<'a, Visibility> {
7051         maybe_whole!(self, NtVis, |x| x);
7052
7053         self.expected_tokens.push(TokenType::Keyword(keywords::Crate));
7054         if self.is_crate_vis() {
7055             self.bump(); // `crate`
7056             return Ok(respan(self.prev_span, VisibilityKind::Crate(CrateSugar::JustCrate)));
7057         }
7058
7059         if !self.eat_keyword(keywords::Pub) {
7060             // We need a span for our `Spanned<VisibilityKind>`, but there's inherently no
7061             // keyword to grab a span from for inherited visibility; an empty span at the
7062             // beginning of the current token would seem to be the "Schelling span".
7063             return Ok(respan(self.span.shrink_to_lo(), VisibilityKind::Inherited))
7064         }
7065         let lo = self.prev_span;
7066
7067         if self.check(&token::OpenDelim(token::Paren)) {
7068             // We don't `self.bump()` the `(` yet because this might be a struct definition where
7069             // `()` or a tuple might be allowed. For example, `struct Struct(pub (), pub (usize));`.
7070             // Because of this, we only `bump` the `(` if we're assured it is appropriate to do so
7071             // by the following tokens.
7072             if self.look_ahead(1, |t| t.is_keyword(keywords::Crate)) {
7073                 // `pub(crate)`
7074                 self.bump(); // `(`
7075                 self.bump(); // `crate`
7076                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7077                 let vis = respan(
7078                     lo.to(self.prev_span),
7079                     VisibilityKind::Crate(CrateSugar::PubCrate),
7080                 );
7081                 return Ok(vis)
7082             } else if self.look_ahead(1, |t| t.is_keyword(keywords::In)) {
7083                 // `pub(in path)`
7084                 self.bump(); // `(`
7085                 self.bump(); // `in`
7086                 let path = self.parse_path(PathStyle::Mod)?; // `path`
7087                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7088                 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7089                     path: P(path),
7090                     id: ast::DUMMY_NODE_ID,
7091                 });
7092                 return Ok(vis)
7093             } else if self.look_ahead(2, |t| t == &token::CloseDelim(token::Paren)) &&
7094                       self.look_ahead(1, |t| t.is_keyword(keywords::Super) ||
7095                                              t.is_keyword(keywords::SelfLower))
7096             {
7097                 // `pub(self)` or `pub(super)`
7098                 self.bump(); // `(`
7099                 let path = self.parse_path(PathStyle::Mod)?; // `super`/`self`
7100                 self.expect(&token::CloseDelim(token::Paren))?; // `)`
7101                 let vis = respan(lo.to(self.prev_span), VisibilityKind::Restricted {
7102                     path: P(path),
7103                     id: ast::DUMMY_NODE_ID,
7104                 });
7105                 return Ok(vis)
7106             } else if !can_take_tuple {  // Provide this diagnostic if this is not a tuple struct
7107                 // `pub(something) fn ...` or `struct X { pub(something) y: Z }`
7108                 self.bump(); // `(`
7109                 let msg = "incorrect visibility restriction";
7110                 let suggestion = r##"some possible visibility restrictions are:
7111 `pub(crate)`: visible only on the current crate
7112 `pub(super)`: visible only in the current module's parent
7113 `pub(in path::to::module)`: visible only on the specified path"##;
7114                 let path = self.parse_path(PathStyle::Mod)?;
7115                 let sp = self.prev_span;
7116                 let help_msg = format!("make this visible only to module `{}` with `in`", path);
7117                 self.expect(&token::CloseDelim(token::Paren))?;  // `)`
7118                 let mut err = struct_span_err!(self.sess.span_diagnostic, sp, E0704, "{}", msg);
7119                 err.help(suggestion);
7120                 err.span_suggestion(
7121                     sp, &help_msg, format!("in {}", path), Applicability::MachineApplicable
7122                 );
7123                 err.emit();  // emit diagnostic, but continue with public visibility
7124             }
7125         }
7126
7127         Ok(respan(lo, VisibilityKind::Public))
7128     }
7129
7130     /// Parses defaultness (i.e., `default` or nothing).
7131     fn parse_defaultness(&mut self) -> Defaultness {
7132         // `pub` is included for better error messages
7133         if self.check_keyword(keywords::Default) &&
7134            self.look_ahead(1, |t| t.is_keyword(keywords::Impl) ||
7135                                   t.is_keyword(keywords::Const) ||
7136                                   t.is_keyword(keywords::Fn) ||
7137                                   t.is_keyword(keywords::Unsafe) ||
7138                                   t.is_keyword(keywords::Extern) ||
7139                                   t.is_keyword(keywords::Type) ||
7140                                   t.is_keyword(keywords::Pub)) {
7141             self.bump(); // `default`
7142             Defaultness::Default
7143         } else {
7144             Defaultness::Final
7145         }
7146     }
7147
7148     fn maybe_consume_incorrect_semicolon(&mut self, items: &[P<Item>]) -> bool {
7149         if self.eat(&token::Semi) {
7150             let mut err = self.struct_span_err(self.prev_span, "expected item, found `;`");
7151             err.span_suggestion_short(
7152                 self.prev_span,
7153                 "remove this semicolon",
7154                 String::new(),
7155                 Applicability::MachineApplicable,
7156             );
7157             if !items.is_empty() {
7158                 let previous_item = &items[items.len()-1];
7159                 let previous_item_kind_name = match previous_item.node {
7160                     // say "braced struct" because tuple-structs and
7161                     // braceless-empty-struct declarations do take a semicolon
7162                     ItemKind::Struct(..) => Some("braced struct"),
7163                     ItemKind::Enum(..) => Some("enum"),
7164                     ItemKind::Trait(..) => Some("trait"),
7165                     ItemKind::Union(..) => Some("union"),
7166                     _ => None,
7167                 };
7168                 if let Some(name) = previous_item_kind_name {
7169                     err.help(&format!("{} declarations are not followed by a semicolon", name));
7170                 }
7171             }
7172             err.emit();
7173             true
7174         } else {
7175             false
7176         }
7177     }
7178
7179     /// Given a termination token, parses all of the items in a module.
7180     fn parse_mod_items(&mut self, term: &token::Token, inner_lo: Span) -> PResult<'a, Mod> {
7181         let mut items = vec![];
7182         while let Some(item) = self.parse_item()? {
7183             items.push(item);
7184             self.maybe_consume_incorrect_semicolon(&items);
7185         }
7186
7187         if !self.eat(term) {
7188             let token_str = self.this_token_descr();
7189             if !self.maybe_consume_incorrect_semicolon(&items) {
7190                 let mut err = self.fatal(&format!("expected item, found {}", token_str));
7191                 err.span_label(self.span, "expected item");
7192                 return Err(err);
7193             }
7194         }
7195
7196         let hi = if self.span.is_dummy() {
7197             inner_lo
7198         } else {
7199             self.prev_span
7200         };
7201
7202         Ok(ast::Mod {
7203             inner: inner_lo.to(hi),
7204             items,
7205             inline: true
7206         })
7207     }
7208
7209     fn parse_item_const(&mut self, m: Option<Mutability>) -> PResult<'a, ItemInfo> {
7210         let id = if m.is_none() { self.parse_ident_or_underscore() } else { self.parse_ident() }?;
7211         self.expect(&token::Colon)?;
7212         let ty = self.parse_ty()?;
7213         self.expect(&token::Eq)?;
7214         let e = self.parse_expr()?;
7215         self.expect(&token::Semi)?;
7216         let item = match m {
7217             Some(m) => ItemKind::Static(ty, m, e),
7218             None => ItemKind::Const(ty, e),
7219         };
7220         Ok((id, item, None))
7221     }
7222
7223     /// Parse a `mod <foo> { ... }` or `mod <foo>;` item
7224     fn parse_item_mod(&mut self, outer_attrs: &[Attribute]) -> PResult<'a, ItemInfo> {
7225         let (in_cfg, outer_attrs) = {
7226             let mut strip_unconfigured = crate::config::StripUnconfigured {
7227                 sess: self.sess,
7228                 features: None, // don't perform gated feature checking
7229             };
7230             let mut outer_attrs = outer_attrs.to_owned();
7231             strip_unconfigured.process_cfg_attrs(&mut outer_attrs);
7232             (!self.cfg_mods || strip_unconfigured.in_cfg(&outer_attrs), outer_attrs)
7233         };
7234
7235         let id_span = self.span;
7236         let id = self.parse_ident()?;
7237         if self.eat(&token::Semi) {
7238             if in_cfg && self.recurse_into_file_modules {
7239                 // This mod is in an external file. Let's go get it!
7240                 let ModulePathSuccess { path, directory_ownership, warn } =
7241                     self.submod_path(id, &outer_attrs, id_span)?;
7242                 let (module, mut attrs) =
7243                     self.eval_src_mod(path, directory_ownership, id.to_string(), id_span)?;
7244                 // Record that we fetched the mod from an external file
7245                 if warn {
7246                     let attr = Attribute {
7247                         id: attr::mk_attr_id(),
7248                         style: ast::AttrStyle::Outer,
7249                         path: ast::Path::from_ident(Ident::from_str("warn_directory_ownership")),
7250                         tokens: TokenStream::empty(),
7251                         is_sugared_doc: false,
7252                         span: syntax_pos::DUMMY_SP,
7253                     };
7254                     attr::mark_known(&attr);
7255                     attrs.push(attr);
7256                 }
7257                 Ok((id, ItemKind::Mod(module), Some(attrs)))
7258             } else {
7259                 let placeholder = ast::Mod {
7260                     inner: syntax_pos::DUMMY_SP,
7261                     items: Vec::new(),
7262                     inline: false
7263                 };
7264                 Ok((id, ItemKind::Mod(placeholder), None))
7265             }
7266         } else {
7267             let old_directory = self.directory.clone();
7268             self.push_directory(id, &outer_attrs);
7269
7270             self.expect(&token::OpenDelim(token::Brace))?;
7271             let mod_inner_lo = self.span;
7272             let attrs = self.parse_inner_attributes()?;
7273             let module = self.parse_mod_items(&token::CloseDelim(token::Brace), mod_inner_lo)?;
7274
7275             self.directory = old_directory;
7276             Ok((id, ItemKind::Mod(module), Some(attrs)))
7277         }
7278     }
7279
7280     fn push_directory(&mut self, id: Ident, attrs: &[Attribute]) {
7281         if let Some(path) = attr::first_attr_value_str_by_name(attrs, "path") {
7282             self.directory.path.to_mut().push(&path.as_str());
7283             self.directory.ownership = DirectoryOwnership::Owned { relative: None };
7284         } else {
7285             // We have to push on the current module name in the case of relative
7286             // paths in order to ensure that any additional module paths from inline
7287             // `mod x { ... }` come after the relative extension.
7288             //
7289             // For example, a `mod z { ... }` inside `x/y.rs` should set the current
7290             // directory path to `/x/y/z`, not `/x/z` with a relative offset of `y`.
7291             if let DirectoryOwnership::Owned { relative } = &mut self.directory.ownership {
7292                 if let Some(ident) = relative.take() { // remove the relative offset
7293                     self.directory.path.to_mut().push(ident.as_str());
7294                 }
7295             }
7296             self.directory.path.to_mut().push(&id.as_str());
7297         }
7298     }
7299
7300     pub fn submod_path_from_attr(attrs: &[Attribute], dir_path: &Path) -> Option<PathBuf> {
7301         if let Some(s) = attr::first_attr_value_str_by_name(attrs, "path") {
7302             let s = s.as_str();
7303
7304             // On windows, the base path might have the form
7305             // `\\?\foo\bar` in which case it does not tolerate
7306             // mixed `/` and `\` separators, so canonicalize
7307             // `/` to `\`.
7308             #[cfg(windows)]
7309             let s = s.replace("/", "\\");
7310             Some(dir_path.join(s))
7311         } else {
7312             None
7313         }
7314     }
7315
7316     /// Returns a path to a module.
7317     pub fn default_submod_path(
7318         id: ast::Ident,
7319         relative: Option<ast::Ident>,
7320         dir_path: &Path,
7321         source_map: &SourceMap) -> ModulePath
7322     {
7323         // If we're in a foo.rs file instead of a mod.rs file,
7324         // we need to look for submodules in
7325         // `./foo/<id>.rs` and `./foo/<id>/mod.rs` rather than
7326         // `./<id>.rs` and `./<id>/mod.rs`.
7327         let relative_prefix_string;
7328         let relative_prefix = if let Some(ident) = relative {
7329             relative_prefix_string = format!("{}{}", ident.as_str(), path::MAIN_SEPARATOR);
7330             &relative_prefix_string
7331         } else {
7332             ""
7333         };
7334
7335         let mod_name = id.to_string();
7336         let default_path_str = format!("{}{}.rs", relative_prefix, mod_name);
7337         let secondary_path_str = format!("{}{}{}mod.rs",
7338                                          relative_prefix, mod_name, path::MAIN_SEPARATOR);
7339         let default_path = dir_path.join(&default_path_str);
7340         let secondary_path = dir_path.join(&secondary_path_str);
7341         let default_exists = source_map.file_exists(&default_path);
7342         let secondary_exists = source_map.file_exists(&secondary_path);
7343
7344         let result = match (default_exists, secondary_exists) {
7345             (true, false) => Ok(ModulePathSuccess {
7346                 path: default_path,
7347                 directory_ownership: DirectoryOwnership::Owned {
7348                     relative: Some(id),
7349                 },
7350                 warn: false,
7351             }),
7352             (false, true) => Ok(ModulePathSuccess {
7353                 path: secondary_path,
7354                 directory_ownership: DirectoryOwnership::Owned {
7355                     relative: None,
7356                 },
7357                 warn: false,
7358             }),
7359             (false, false) => Err(Error::FileNotFoundForModule {
7360                 mod_name: mod_name.clone(),
7361                 default_path: default_path_str,
7362                 secondary_path: secondary_path_str,
7363                 dir_path: dir_path.display().to_string(),
7364             }),
7365             (true, true) => Err(Error::DuplicatePaths {
7366                 mod_name: mod_name.clone(),
7367                 default_path: default_path_str,
7368                 secondary_path: secondary_path_str,
7369             }),
7370         };
7371
7372         ModulePath {
7373             name: mod_name,
7374             path_exists: default_exists || secondary_exists,
7375             result,
7376         }
7377     }
7378
7379     fn submod_path(&mut self,
7380                    id: ast::Ident,
7381                    outer_attrs: &[Attribute],
7382                    id_sp: Span)
7383                    -> PResult<'a, ModulePathSuccess> {
7384         if let Some(path) = Parser::submod_path_from_attr(outer_attrs, &self.directory.path) {
7385             return Ok(ModulePathSuccess {
7386                 directory_ownership: match path.file_name().and_then(|s| s.to_str()) {
7387                     // All `#[path]` files are treated as though they are a `mod.rs` file.
7388                     // This means that `mod foo;` declarations inside `#[path]`-included
7389                     // files are siblings,
7390                     //
7391                     // Note that this will produce weirdness when a file named `foo.rs` is
7392                     // `#[path]` included and contains a `mod foo;` declaration.
7393                     // If you encounter this, it's your own darn fault :P
7394                     Some(_) => DirectoryOwnership::Owned { relative: None },
7395                     _ => DirectoryOwnership::UnownedViaMod(true),
7396                 },
7397                 path,
7398                 warn: false,
7399             });
7400         }
7401
7402         let relative = match self.directory.ownership {
7403             DirectoryOwnership::Owned { relative } => relative,
7404             DirectoryOwnership::UnownedViaBlock |
7405             DirectoryOwnership::UnownedViaMod(_) => None,
7406         };
7407         let paths = Parser::default_submod_path(
7408                         id, relative, &self.directory.path, self.sess.source_map());
7409
7410         match self.directory.ownership {
7411             DirectoryOwnership::Owned { .. } => {
7412                 paths.result.map_err(|err| self.span_fatal_err(id_sp, err))
7413             },
7414             DirectoryOwnership::UnownedViaBlock => {
7415                 let msg =
7416                     "Cannot declare a non-inline module inside a block \
7417                     unless it has a path attribute";
7418                 let mut err = self.diagnostic().struct_span_err(id_sp, msg);
7419                 if paths.path_exists {
7420                     let msg = format!("Maybe `use` the module `{}` instead of redeclaring it",
7421                                       paths.name);
7422                     err.span_note(id_sp, &msg);
7423                 }
7424                 Err(err)
7425             }
7426             DirectoryOwnership::UnownedViaMod(warn) => {
7427                 if warn {
7428                     if let Ok(result) = paths.result {
7429                         return Ok(ModulePathSuccess { warn: true, ..result });
7430                     }
7431                 }
7432                 let mut err = self.diagnostic().struct_span_err(id_sp,
7433                     "cannot declare a new module at this location");
7434                 if !id_sp.is_dummy() {
7435                     let src_path = self.sess.source_map().span_to_filename(id_sp);
7436                     if let FileName::Real(src_path) = src_path {
7437                         if let Some(stem) = src_path.file_stem() {
7438                             let mut dest_path = src_path.clone();
7439                             dest_path.set_file_name(stem);
7440                             dest_path.push("mod.rs");
7441                             err.span_note(id_sp,
7442                                     &format!("maybe move this module `{}` to its own \
7443                                                 directory via `{}`", src_path.display(),
7444                                             dest_path.display()));
7445                         }
7446                     }
7447                 }
7448                 if paths.path_exists {
7449                     err.span_note(id_sp,
7450                                   &format!("... or maybe `use` the module `{}` instead \
7451                                             of possibly redeclaring it",
7452                                            paths.name));
7453                 }
7454                 Err(err)
7455             }
7456         }
7457     }
7458
7459     /// Reads a module from a source file.
7460     fn eval_src_mod(&mut self,
7461                     path: PathBuf,
7462                     directory_ownership: DirectoryOwnership,
7463                     name: String,
7464                     id_sp: Span)
7465                     -> PResult<'a, (ast::Mod, Vec<Attribute> )> {
7466         let mut included_mod_stack = self.sess.included_mod_stack.borrow_mut();
7467         if let Some(i) = included_mod_stack.iter().position(|p| *p == path) {
7468             let mut err = String::from("circular modules: ");
7469             let len = included_mod_stack.len();
7470             for p in &included_mod_stack[i.. len] {
7471                 err.push_str(&p.to_string_lossy());
7472                 err.push_str(" -> ");
7473             }
7474             err.push_str(&path.to_string_lossy());
7475             return Err(self.span_fatal(id_sp, &err[..]));
7476         }
7477         included_mod_stack.push(path.clone());
7478         drop(included_mod_stack);
7479
7480         let mut p0 =
7481             new_sub_parser_from_file(self.sess, &path, directory_ownership, Some(name), id_sp);
7482         p0.cfg_mods = self.cfg_mods;
7483         let mod_inner_lo = p0.span;
7484         let mod_attrs = p0.parse_inner_attributes()?;
7485         let mut m0 = p0.parse_mod_items(&token::Eof, mod_inner_lo)?;
7486         m0.inline = false;
7487         self.sess.included_mod_stack.borrow_mut().pop();
7488         Ok((m0, mod_attrs))
7489     }
7490
7491     /// Parses a function declaration from a foreign module.
7492     fn parse_item_foreign_fn(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7493                              -> PResult<'a, ForeignItem> {
7494         self.expect_keyword(keywords::Fn)?;
7495
7496         let (ident, mut generics) = self.parse_fn_header()?;
7497         let decl = self.parse_fn_decl(true)?;
7498         generics.where_clause = self.parse_where_clause()?;
7499         let hi = self.span;
7500         self.expect(&token::Semi)?;
7501         Ok(ast::ForeignItem {
7502             ident,
7503             attrs,
7504             node: ForeignItemKind::Fn(decl, generics),
7505             id: ast::DUMMY_NODE_ID,
7506             span: lo.to(hi),
7507             vis,
7508         })
7509     }
7510
7511     /// Parses a static item from a foreign module.
7512     /// Assumes that the `static` keyword is already parsed.
7513     fn parse_item_foreign_static(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7514                                  -> PResult<'a, ForeignItem> {
7515         let mutbl = self.eat_keyword(keywords::Mut);
7516         let ident = self.parse_ident()?;
7517         self.expect(&token::Colon)?;
7518         let ty = self.parse_ty()?;
7519         let hi = self.span;
7520         self.expect(&token::Semi)?;
7521         Ok(ForeignItem {
7522             ident,
7523             attrs,
7524             node: ForeignItemKind::Static(ty, mutbl),
7525             id: ast::DUMMY_NODE_ID,
7526             span: lo.to(hi),
7527             vis,
7528         })
7529     }
7530
7531     /// Parses a type from a foreign module.
7532     fn parse_item_foreign_type(&mut self, vis: ast::Visibility, lo: Span, attrs: Vec<Attribute>)
7533                              -> PResult<'a, ForeignItem> {
7534         self.expect_keyword(keywords::Type)?;
7535
7536         let ident = self.parse_ident()?;
7537         let hi = self.span;
7538         self.expect(&token::Semi)?;
7539         Ok(ast::ForeignItem {
7540             ident: ident,
7541             attrs: attrs,
7542             node: ForeignItemKind::Ty,
7543             id: ast::DUMMY_NODE_ID,
7544             span: lo.to(hi),
7545             vis: vis
7546         })
7547     }
7548
7549     fn parse_crate_name_with_dashes(&mut self) -> PResult<'a, ast::Ident> {
7550         let error_msg = "crate name using dashes are not valid in `extern crate` statements";
7551         let suggestion_msg = "if the original crate name uses dashes you need to use underscores \
7552                               in the code";
7553         let mut ident = if self.token.is_keyword(keywords::SelfLower) {
7554             self.parse_path_segment_ident()
7555         } else {
7556             self.parse_ident()
7557         }?;
7558         let mut idents = vec![];
7559         let mut replacement = vec![];
7560         let mut fixed_crate_name = false;
7561         // Accept `extern crate name-like-this` for better diagnostics
7562         let dash = token::Token::BinOp(token::BinOpToken::Minus);
7563         if self.token == dash {  // Do not include `-` as part of the expected tokens list
7564             while self.eat(&dash) {
7565                 fixed_crate_name = true;
7566                 replacement.push((self.prev_span, "_".to_string()));
7567                 idents.push(self.parse_ident()?);
7568             }
7569         }
7570         if fixed_crate_name {
7571             let fixed_name_sp = ident.span.to(idents.last().unwrap().span);
7572             let mut fixed_name = format!("{}", ident.name);
7573             for part in idents {
7574                 fixed_name.push_str(&format!("_{}", part.name));
7575             }
7576             ident = Ident::from_str(&fixed_name).with_span_pos(fixed_name_sp);
7577
7578             let mut err = self.struct_span_err(fixed_name_sp, error_msg);
7579             err.span_label(fixed_name_sp, "dash-separated idents are not valid");
7580             err.multipart_suggestion(
7581                 suggestion_msg,
7582                 replacement,
7583                 Applicability::MachineApplicable,
7584             );
7585             err.emit();
7586         }
7587         Ok(ident)
7588     }
7589
7590     /// Parses `extern crate` links.
7591     ///
7592     /// # Examples
7593     ///
7594     /// ```
7595     /// extern crate foo;
7596     /// extern crate bar as foo;
7597     /// ```
7598     fn parse_item_extern_crate(&mut self,
7599                                lo: Span,
7600                                visibility: Visibility,
7601                                attrs: Vec<Attribute>)
7602                                -> PResult<'a, P<Item>> {
7603         // Accept `extern crate name-like-this` for better diagnostics
7604         let orig_name = self.parse_crate_name_with_dashes()?;
7605         let (item_name, orig_name) = if let Some(rename) = self.parse_rename()? {
7606             (rename, Some(orig_name.name))
7607         } else {
7608             (orig_name, None)
7609         };
7610         self.expect(&token::Semi)?;
7611
7612         let span = lo.to(self.prev_span);
7613         Ok(self.mk_item(span, item_name, ItemKind::ExternCrate(orig_name), visibility, attrs))
7614     }
7615
7616     /// Parses `extern` for foreign ABIs modules.
7617     ///
7618     /// `extern` is expected to have been
7619     /// consumed before calling this method.
7620     ///
7621     /// # Examples
7622     ///
7623     /// ```ignore (only-for-syntax-highlight)
7624     /// extern "C" {}
7625     /// extern {}
7626     /// ```
7627     fn parse_item_foreign_mod(&mut self,
7628                               lo: Span,
7629                               opt_abi: Option<Abi>,
7630                               visibility: Visibility,
7631                               mut attrs: Vec<Attribute>)
7632                               -> PResult<'a, P<Item>> {
7633         self.expect(&token::OpenDelim(token::Brace))?;
7634
7635         let abi = opt_abi.unwrap_or(Abi::C);
7636
7637         attrs.extend(self.parse_inner_attributes()?);
7638
7639         let mut foreign_items = vec![];
7640         while !self.eat(&token::CloseDelim(token::Brace)) {
7641             foreign_items.push(self.parse_foreign_item()?);
7642         }
7643
7644         let prev_span = self.prev_span;
7645         let m = ast::ForeignMod {
7646             abi,
7647             items: foreign_items
7648         };
7649         let invalid = keywords::Invalid.ident();
7650         Ok(self.mk_item(lo.to(prev_span), invalid, ItemKind::ForeignMod(m), visibility, attrs))
7651     }
7652
7653     /// Parses `type Foo = Bar;`
7654     /// or
7655     /// `existential type Foo: Bar;`
7656     /// or
7657     /// `return `None``
7658     /// without modifying the parser state.
7659     fn eat_type(&mut self) -> Option<PResult<'a, (Ident, AliasKind, ast::Generics)>> {
7660         // This parses the grammar:
7661         //     Ident ["<"...">"] ["where" ...] ("=" | ":") Ty ";"
7662         if self.check_keyword(keywords::Type) ||
7663            self.check_keyword(keywords::Existential) &&
7664                 self.look_ahead(1, |t| t.is_keyword(keywords::Type)) {
7665             let existential = self.eat_keyword(keywords::Existential);
7666             assert!(self.eat_keyword(keywords::Type));
7667             Some(self.parse_existential_or_alias(existential))
7668         } else {
7669             None
7670         }
7671     }
7672
7673     /// Parses a type alias or existential type.
7674     fn parse_existential_or_alias(
7675         &mut self,
7676         existential: bool,
7677     ) -> PResult<'a, (Ident, AliasKind, ast::Generics)> {
7678         let ident = self.parse_ident()?;
7679         let mut tps = self.parse_generics()?;
7680         tps.where_clause = self.parse_where_clause()?;
7681         let alias = if existential {
7682             self.expect(&token::Colon)?;
7683             let bounds = self.parse_generic_bounds(Some(self.prev_span))?;
7684             AliasKind::Existential(bounds)
7685         } else {
7686             self.expect(&token::Eq)?;
7687             let ty = self.parse_ty()?;
7688             AliasKind::Weak(ty)
7689         };
7690         self.expect(&token::Semi)?;
7691         Ok((ident, alias, tps))
7692     }
7693
7694     /// Parses the part of an enum declaration following the `{`.
7695     fn parse_enum_def(&mut self, _generics: &ast::Generics) -> PResult<'a, EnumDef> {
7696         let mut variants = Vec::new();
7697         let mut all_nullary = true;
7698         let mut any_disr = vec![];
7699         while self.token != token::CloseDelim(token::Brace) {
7700             let variant_attrs = self.parse_outer_attributes()?;
7701             let vlo = self.span;
7702
7703             let struct_def;
7704             let mut disr_expr = None;
7705             self.eat_bad_pub();
7706             let ident = self.parse_ident()?;
7707             if self.check(&token::OpenDelim(token::Brace)) {
7708                 // Parse a struct variant.
7709                 all_nullary = false;
7710                 let (fields, recovered) = self.parse_record_struct_body()?;
7711                 struct_def = VariantData::Struct(fields, ast::DUMMY_NODE_ID, recovered);
7712             } else if self.check(&token::OpenDelim(token::Paren)) {
7713                 all_nullary = false;
7714                 struct_def = VariantData::Tuple(
7715                     self.parse_tuple_struct_body()?,
7716                     ast::DUMMY_NODE_ID,
7717                 );
7718             } else if self.eat(&token::Eq) {
7719                 disr_expr = Some(AnonConst {
7720                     id: ast::DUMMY_NODE_ID,
7721                     value: self.parse_expr()?,
7722                 });
7723                 if let Some(sp) = disr_expr.as_ref().map(|c| c.value.span) {
7724                     any_disr.push(sp);
7725                 }
7726                 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7727             } else {
7728                 struct_def = VariantData::Unit(ast::DUMMY_NODE_ID);
7729             }
7730
7731             let vr = ast::Variant_ {
7732                 ident,
7733                 attrs: variant_attrs,
7734                 data: struct_def,
7735                 disr_expr,
7736             };
7737             variants.push(respan(vlo.to(self.prev_span), vr));
7738
7739             if !self.eat(&token::Comma) {
7740                 if self.token.is_ident() && !self.token.is_reserved_ident() {
7741                     let sp = self.sess.source_map().next_point(self.prev_span);
7742                     let mut err = self.struct_span_err(sp, "missing comma");
7743                     err.span_suggestion_short(
7744                         sp,
7745                         "missing comma",
7746                         ",".to_owned(),
7747                         Applicability::MaybeIncorrect,
7748                     );
7749                     err.emit();
7750                 } else {
7751                     break;
7752                 }
7753             }
7754         }
7755         self.expect(&token::CloseDelim(token::Brace))?;
7756         if !any_disr.is_empty() && !all_nullary {
7757             let mut err = self.struct_span_err(
7758                 any_disr.clone(),
7759                 "discriminator values can only be used with a field-less enum",
7760             );
7761             for sp in any_disr {
7762                 err.span_label(sp, "only valid in field-less enums");
7763             }
7764             err.emit();
7765         }
7766
7767         Ok(ast::EnumDef { variants })
7768     }
7769
7770     /// Parses an enum declaration.
7771     fn parse_item_enum(&mut self) -> PResult<'a, ItemInfo> {
7772         let id = self.parse_ident()?;
7773         let mut generics = self.parse_generics()?;
7774         generics.where_clause = self.parse_where_clause()?;
7775         self.expect(&token::OpenDelim(token::Brace))?;
7776
7777         let enum_definition = self.parse_enum_def(&generics).map_err(|e| {
7778             self.recover_stmt();
7779             self.eat(&token::CloseDelim(token::Brace));
7780             e
7781         })?;
7782         Ok((id, ItemKind::Enum(enum_definition, generics), None))
7783     }
7784
7785     /// Parses a string as an ABI spec on an extern type or module. Consumes
7786     /// the `extern` keyword, if one is found.
7787     fn parse_opt_abi(&mut self) -> PResult<'a, Option<Abi>> {
7788         match self.token {
7789             token::Literal(token::Str_(s), suf) | token::Literal(token::StrRaw(s, _), suf) => {
7790                 let sp = self.span;
7791                 self.expect_no_suffix(sp, "ABI spec", suf);
7792                 self.bump();
7793                 match abi::lookup(&s.as_str()) {
7794                     Some(abi) => Ok(Some(abi)),
7795                     None => {
7796                         let prev_span = self.prev_span;
7797                         let mut err = struct_span_err!(
7798                             self.sess.span_diagnostic,
7799                             prev_span,
7800                             E0703,
7801                             "invalid ABI: found `{}`",
7802                             s);
7803                         err.span_label(prev_span, "invalid ABI");
7804                         err.help(&format!("valid ABIs: {}", abi::all_names().join(", ")));
7805                         err.emit();
7806                         Ok(None)
7807                     }
7808                 }
7809             }
7810
7811             _ => Ok(None),
7812         }
7813     }
7814
7815     fn is_static_global(&mut self) -> bool {
7816         if self.check_keyword(keywords::Static) {
7817             // Check if this could be a closure
7818             !self.look_ahead(1, |token| {
7819                 if token.is_keyword(keywords::Move) {
7820                     return true;
7821                 }
7822                 match *token {
7823                     token::BinOp(token::Or) | token::OrOr => true,
7824                     _ => false,
7825                 }
7826             })
7827         } else {
7828             false
7829         }
7830     }
7831
7832     fn parse_item_(
7833         &mut self,
7834         attrs: Vec<Attribute>,
7835         macros_allowed: bool,
7836         attributes_allowed: bool,
7837     ) -> PResult<'a, Option<P<Item>>> {
7838         let mut unclosed_delims = vec![];
7839         let (ret, tokens) = self.collect_tokens(|this| {
7840             let item = this.parse_item_implementation(attrs, macros_allowed, attributes_allowed);
7841             unclosed_delims.append(&mut this.unclosed_delims);
7842             item
7843         })?;
7844         self.unclosed_delims.append(&mut unclosed_delims);
7845
7846         // Once we've parsed an item and recorded the tokens we got while
7847         // parsing we may want to store `tokens` into the item we're about to
7848         // return. Note, though, that we specifically didn't capture tokens
7849         // related to outer attributes. The `tokens` field here may later be
7850         // used with procedural macros to convert this item back into a token
7851         // stream, but during expansion we may be removing attributes as we go
7852         // along.
7853         //
7854         // If we've got inner attributes then the `tokens` we've got above holds
7855         // these inner attributes. If an inner attribute is expanded we won't
7856         // actually remove it from the token stream, so we'll just keep yielding
7857         // it (bad!). To work around this case for now we just avoid recording
7858         // `tokens` if we detect any inner attributes. This should help keep
7859         // expansion correct, but we should fix this bug one day!
7860         Ok(ret.map(|item| {
7861             item.map(|mut i| {
7862                 if !i.attrs.iter().any(|attr| attr.style == AttrStyle::Inner) {
7863                     i.tokens = Some(tokens);
7864                 }
7865                 i
7866             })
7867         }))
7868     }
7869
7870     /// Parses one of the items allowed by the flags.
7871     fn parse_item_implementation(
7872         &mut self,
7873         attrs: Vec<Attribute>,
7874         macros_allowed: bool,
7875         attributes_allowed: bool,
7876     ) -> PResult<'a, Option<P<Item>>> {
7877         maybe_whole!(self, NtItem, |item| {
7878             let mut item = item.into_inner();
7879             let mut attrs = attrs;
7880             mem::swap(&mut item.attrs, &mut attrs);
7881             item.attrs.extend(attrs);
7882             Some(P(item))
7883         });
7884
7885         let lo = self.span;
7886
7887         let visibility = self.parse_visibility(false)?;
7888
7889         if self.eat_keyword(keywords::Use) {
7890             // USE ITEM
7891             let item_ = ItemKind::Use(P(self.parse_use_tree()?));
7892             self.expect(&token::Semi)?;
7893
7894             let span = lo.to(self.prev_span);
7895             let item = self.mk_item(span, keywords::Invalid.ident(), item_, visibility, attrs);
7896             return Ok(Some(item));
7897         }
7898
7899         if self.eat_keyword(keywords::Extern) {
7900             if self.eat_keyword(keywords::Crate) {
7901                 return Ok(Some(self.parse_item_extern_crate(lo, visibility, attrs)?));
7902             }
7903
7904             let opt_abi = self.parse_opt_abi()?;
7905
7906             if self.eat_keyword(keywords::Fn) {
7907                 // EXTERN FUNCTION ITEM
7908                 let fn_span = self.prev_span;
7909                 let abi = opt_abi.unwrap_or(Abi::C);
7910                 let (ident, item_, extra_attrs) =
7911                     self.parse_item_fn(Unsafety::Normal,
7912                                        respan(fn_span, IsAsync::NotAsync),
7913                                        respan(fn_span, Constness::NotConst),
7914                                        abi)?;
7915                 let prev_span = self.prev_span;
7916                 let item = self.mk_item(lo.to(prev_span),
7917                                         ident,
7918                                         item_,
7919                                         visibility,
7920                                         maybe_append(attrs, extra_attrs));
7921                 return Ok(Some(item));
7922             } else if self.check(&token::OpenDelim(token::Brace)) {
7923                 return Ok(Some(self.parse_item_foreign_mod(lo, opt_abi, visibility, attrs)?));
7924             }
7925
7926             self.unexpected()?;
7927         }
7928
7929         if self.is_static_global() {
7930             self.bump();
7931             // STATIC ITEM
7932             let m = if self.eat_keyword(keywords::Mut) {
7933                 Mutability::Mutable
7934             } else {
7935                 Mutability::Immutable
7936             };
7937             let (ident, item_, extra_attrs) = self.parse_item_const(Some(m))?;
7938             let prev_span = self.prev_span;
7939             let item = self.mk_item(lo.to(prev_span),
7940                                     ident,
7941                                     item_,
7942                                     visibility,
7943                                     maybe_append(attrs, extra_attrs));
7944             return Ok(Some(item));
7945         }
7946         if self.eat_keyword(keywords::Const) {
7947             let const_span = self.prev_span;
7948             if self.check_keyword(keywords::Fn)
7949                 || (self.check_keyword(keywords::Unsafe)
7950                     && self.look_ahead(1, |t| t.is_keyword(keywords::Fn))) {
7951                 // CONST FUNCTION ITEM
7952                 let unsafety = self.parse_unsafety();
7953                 self.bump();
7954                 let (ident, item_, extra_attrs) =
7955                     self.parse_item_fn(unsafety,
7956                                        respan(const_span, IsAsync::NotAsync),
7957                                        respan(const_span, Constness::Const),
7958                                        Abi::Rust)?;
7959                 let prev_span = self.prev_span;
7960                 let item = self.mk_item(lo.to(prev_span),
7961                                         ident,
7962                                         item_,
7963                                         visibility,
7964                                         maybe_append(attrs, extra_attrs));
7965                 return Ok(Some(item));
7966             }
7967
7968             // CONST ITEM
7969             if self.eat_keyword(keywords::Mut) {
7970                 let prev_span = self.prev_span;
7971                 let mut err = self.diagnostic()
7972                     .struct_span_err(prev_span, "const globals cannot be mutable");
7973                 err.span_label(prev_span, "cannot be mutable");
7974                 err.span_suggestion(
7975                     const_span,
7976                     "you might want to declare a static instead",
7977                     "static".to_owned(),
7978                     Applicability::MaybeIncorrect,
7979                 );
7980                 err.emit();
7981             }
7982             let (ident, item_, extra_attrs) = self.parse_item_const(None)?;
7983             let prev_span = self.prev_span;
7984             let item = self.mk_item(lo.to(prev_span),
7985                                     ident,
7986                                     item_,
7987                                     visibility,
7988                                     maybe_append(attrs, extra_attrs));
7989             return Ok(Some(item));
7990         }
7991
7992         // `unsafe async fn` or `async fn`
7993         if (
7994             self.check_keyword(keywords::Unsafe) &&
7995             self.look_ahead(1, |t| t.is_keyword(keywords::Async))
7996         ) || (
7997             self.check_keyword(keywords::Async) &&
7998             self.look_ahead(1, |t| t.is_keyword(keywords::Fn))
7999         )
8000         {
8001             // ASYNC FUNCTION ITEM
8002             let unsafety = self.parse_unsafety();
8003             self.expect_keyword(keywords::Async)?;
8004             let async_span = self.prev_span;
8005             self.expect_keyword(keywords::Fn)?;
8006             let fn_span = self.prev_span;
8007             let (ident, item_, extra_attrs) =
8008                 self.parse_item_fn(unsafety,
8009                                    respan(async_span, IsAsync::Async {
8010                                        closure_id: ast::DUMMY_NODE_ID,
8011                                        return_impl_trait_id: ast::DUMMY_NODE_ID,
8012                                    }),
8013                                    respan(fn_span, Constness::NotConst),
8014                                    Abi::Rust)?;
8015             let prev_span = self.prev_span;
8016             let item = self.mk_item(lo.to(prev_span),
8017                                     ident,
8018                                     item_,
8019                                     visibility,
8020                                     maybe_append(attrs, extra_attrs));
8021             if self.span.rust_2015() {
8022                 self.diagnostic().struct_span_err_with_code(
8023                     async_span,
8024                     "`async fn` is not permitted in the 2015 edition",
8025                     DiagnosticId::Error("E0670".into())
8026                 ).emit();
8027             }
8028             return Ok(Some(item));
8029         }
8030         if self.check_keyword(keywords::Unsafe) &&
8031             (self.look_ahead(1, |t| t.is_keyword(keywords::Trait)) ||
8032             self.look_ahead(1, |t| t.is_keyword(keywords::Auto)))
8033         {
8034             // UNSAFE TRAIT ITEM
8035             self.bump(); // `unsafe`
8036             let is_auto = if self.eat_keyword(keywords::Trait) {
8037                 IsAuto::No
8038             } else {
8039                 self.expect_keyword(keywords::Auto)?;
8040                 self.expect_keyword(keywords::Trait)?;
8041                 IsAuto::Yes
8042             };
8043             let (ident, item_, extra_attrs) =
8044                 self.parse_item_trait(is_auto, Unsafety::Unsafe)?;
8045             let prev_span = self.prev_span;
8046             let item = self.mk_item(lo.to(prev_span),
8047                                     ident,
8048                                     item_,
8049                                     visibility,
8050                                     maybe_append(attrs, extra_attrs));
8051             return Ok(Some(item));
8052         }
8053         if self.check_keyword(keywords::Impl) ||
8054            self.check_keyword(keywords::Unsafe) &&
8055                 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8056            self.check_keyword(keywords::Default) &&
8057                 self.look_ahead(1, |t| t.is_keyword(keywords::Impl)) ||
8058            self.check_keyword(keywords::Default) &&
8059                 self.look_ahead(1, |t| t.is_keyword(keywords::Unsafe)) {
8060             // IMPL ITEM
8061             let defaultness = self.parse_defaultness();
8062             let unsafety = self.parse_unsafety();
8063             self.expect_keyword(keywords::Impl)?;
8064             let (ident, item, extra_attrs) = self.parse_item_impl(unsafety, defaultness)?;
8065             let span = lo.to(self.prev_span);
8066             return Ok(Some(self.mk_item(span, ident, item, visibility,
8067                                         maybe_append(attrs, extra_attrs))));
8068         }
8069         if self.check_keyword(keywords::Fn) {
8070             // FUNCTION ITEM
8071             self.bump();
8072             let fn_span = self.prev_span;
8073             let (ident, item_, extra_attrs) =
8074                 self.parse_item_fn(Unsafety::Normal,
8075                                    respan(fn_span, IsAsync::NotAsync),
8076                                    respan(fn_span, Constness::NotConst),
8077                                    Abi::Rust)?;
8078             let prev_span = self.prev_span;
8079             let item = self.mk_item(lo.to(prev_span),
8080                                     ident,
8081                                     item_,
8082                                     visibility,
8083                                     maybe_append(attrs, extra_attrs));
8084             return Ok(Some(item));
8085         }
8086         if self.check_keyword(keywords::Unsafe)
8087             && self.look_ahead(1, |t| *t != token::OpenDelim(token::Brace)) {
8088             // UNSAFE FUNCTION ITEM
8089             self.bump(); // `unsafe`
8090             // `{` is also expected after `unsafe`, in case of error, include it in the diagnostic
8091             self.check(&token::OpenDelim(token::Brace));
8092             let abi = if self.eat_keyword(keywords::Extern) {
8093                 self.parse_opt_abi()?.unwrap_or(Abi::C)
8094             } else {
8095                 Abi::Rust
8096             };
8097             self.expect_keyword(keywords::Fn)?;
8098             let fn_span = self.prev_span;
8099             let (ident, item_, extra_attrs) =
8100                 self.parse_item_fn(Unsafety::Unsafe,
8101                                    respan(fn_span, IsAsync::NotAsync),
8102                                    respan(fn_span, Constness::NotConst),
8103                                    abi)?;
8104             let prev_span = self.prev_span;
8105             let item = self.mk_item(lo.to(prev_span),
8106                                     ident,
8107                                     item_,
8108                                     visibility,
8109                                     maybe_append(attrs, extra_attrs));
8110             return Ok(Some(item));
8111         }
8112         if self.eat_keyword(keywords::Mod) {
8113             // MODULE ITEM
8114             let (ident, item_, extra_attrs) =
8115                 self.parse_item_mod(&attrs[..])?;
8116             let prev_span = self.prev_span;
8117             let item = self.mk_item(lo.to(prev_span),
8118                                     ident,
8119                                     item_,
8120                                     visibility,
8121                                     maybe_append(attrs, extra_attrs));
8122             return Ok(Some(item));
8123         }
8124         if let Some(type_) = self.eat_type() {
8125             let (ident, alias, generics) = type_?;
8126             // TYPE ITEM
8127             let item_ = match alias {
8128                 AliasKind::Weak(ty) => ItemKind::Ty(ty, generics),
8129                 AliasKind::Existential(bounds) => ItemKind::Existential(bounds, generics),
8130             };
8131             let prev_span = self.prev_span;
8132             let item = self.mk_item(lo.to(prev_span),
8133                                     ident,
8134                                     item_,
8135                                     visibility,
8136                                     attrs);
8137             return Ok(Some(item));
8138         }
8139         if self.eat_keyword(keywords::Enum) {
8140             // ENUM ITEM
8141             let (ident, item_, extra_attrs) = self.parse_item_enum()?;
8142             let prev_span = self.prev_span;
8143             let item = self.mk_item(lo.to(prev_span),
8144                                     ident,
8145                                     item_,
8146                                     visibility,
8147                                     maybe_append(attrs, extra_attrs));
8148             return Ok(Some(item));
8149         }
8150         if self.check_keyword(keywords::Trait)
8151             || (self.check_keyword(keywords::Auto)
8152                 && self.look_ahead(1, |t| t.is_keyword(keywords::Trait)))
8153         {
8154             let is_auto = if self.eat_keyword(keywords::Trait) {
8155                 IsAuto::No
8156             } else {
8157                 self.expect_keyword(keywords::Auto)?;
8158                 self.expect_keyword(keywords::Trait)?;
8159                 IsAuto::Yes
8160             };
8161             // TRAIT ITEM
8162             let (ident, item_, extra_attrs) =
8163                 self.parse_item_trait(is_auto, Unsafety::Normal)?;
8164             let prev_span = self.prev_span;
8165             let item = self.mk_item(lo.to(prev_span),
8166                                     ident,
8167                                     item_,
8168                                     visibility,
8169                                     maybe_append(attrs, extra_attrs));
8170             return Ok(Some(item));
8171         }
8172         if self.eat_keyword(keywords::Struct) {
8173             // STRUCT ITEM
8174             let (ident, item_, extra_attrs) = self.parse_item_struct()?;
8175             let prev_span = self.prev_span;
8176             let item = self.mk_item(lo.to(prev_span),
8177                                     ident,
8178                                     item_,
8179                                     visibility,
8180                                     maybe_append(attrs, extra_attrs));
8181             return Ok(Some(item));
8182         }
8183         if self.is_union_item() {
8184             // UNION ITEM
8185             self.bump();
8186             let (ident, item_, extra_attrs) = self.parse_item_union()?;
8187             let prev_span = self.prev_span;
8188             let item = self.mk_item(lo.to(prev_span),
8189                                     ident,
8190                                     item_,
8191                                     visibility,
8192                                     maybe_append(attrs, extra_attrs));
8193             return Ok(Some(item));
8194         }
8195         if let Some(macro_def) = self.eat_macro_def(&attrs, &visibility, lo)? {
8196             return Ok(Some(macro_def));
8197         }
8198
8199         // Verify whether we have encountered a struct or method definition where the user forgot to
8200         // add the `struct` or `fn` keyword after writing `pub`: `pub S {}`
8201         if visibility.node.is_pub() &&
8202             self.check_ident() &&
8203             self.look_ahead(1, |t| *t != token::Not)
8204         {
8205             // Space between `pub` keyword and the identifier
8206             //
8207             //     pub   S {}
8208             //        ^^^ `sp` points here
8209             let sp = self.prev_span.between(self.span);
8210             let full_sp = self.prev_span.to(self.span);
8211             let ident_sp = self.span;
8212             if self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace)) {
8213                 // possible public struct definition where `struct` was forgotten
8214                 let ident = self.parse_ident().unwrap();
8215                 let msg = format!("add `struct` here to parse `{}` as a public struct",
8216                                   ident);
8217                 let mut err = self.diagnostic()
8218                     .struct_span_err(sp, "missing `struct` for struct definition");
8219                 err.span_suggestion_short(
8220                     sp, &msg, " struct ".into(), Applicability::MaybeIncorrect // speculative
8221                 );
8222                 return Err(err);
8223             } else if self.look_ahead(1, |t| *t == token::OpenDelim(token::Paren)) {
8224                 let ident = self.parse_ident().unwrap();
8225                 self.bump();  // `(`
8226                 let kw_name = if let Ok(Some(_)) = self.parse_self_arg() {
8227                     "method"
8228                 } else {
8229                     "function"
8230                 };
8231                 self.consume_block(token::Paren);
8232                 let (kw, kw_name, ambiguous) = if self.check(&token::RArrow) {
8233                     self.eat_to_tokens(&[&token::OpenDelim(token::Brace)]);
8234                     self.bump();  // `{`
8235                     ("fn", kw_name, false)
8236                 } else if self.check(&token::OpenDelim(token::Brace)) {
8237                     self.bump();  // `{`
8238                     ("fn", kw_name, false)
8239                 } else if self.check(&token::Colon) {
8240                     let kw = "struct";
8241                     (kw, kw, false)
8242                 } else {
8243                     ("fn` or `struct", "function or struct", true)
8244                 };
8245                 self.consume_block(token::Brace);
8246
8247                 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8248                 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8249                 if !ambiguous {
8250                     let suggestion = format!("add `{}` here to parse `{}` as a public {}",
8251                                              kw,
8252                                              ident,
8253                                              kw_name);
8254                     err.span_suggestion_short(
8255                         sp, &suggestion, format!(" {} ", kw), Applicability::MachineApplicable
8256                     );
8257                 } else {
8258                     if let Ok(snippet) = self.sess.source_map().span_to_snippet(ident_sp) {
8259                         err.span_suggestion(
8260                             full_sp,
8261                             "if you meant to call a macro, try",
8262                             format!("{}!", snippet),
8263                             // this is the `ambiguous` conditional branch
8264                             Applicability::MaybeIncorrect
8265                         );
8266                     } else {
8267                         err.help("if you meant to call a macro, remove the `pub` \
8268                                   and add a trailing `!` after the identifier");
8269                     }
8270                 }
8271                 return Err(err);
8272             } else if self.look_ahead(1, |t| *t == token::Lt) {
8273                 let ident = self.parse_ident().unwrap();
8274                 self.eat_to_tokens(&[&token::Gt]);
8275                 self.bump();  // `>`
8276                 let (kw, kw_name, ambiguous) = if self.eat(&token::OpenDelim(token::Paren)) {
8277                     if let Ok(Some(_)) = self.parse_self_arg() {
8278                         ("fn", "method", false)
8279                     } else {
8280                         ("fn", "function", false)
8281                     }
8282                 } else if self.check(&token::OpenDelim(token::Brace)) {
8283                     ("struct", "struct", false)
8284                 } else {
8285                     ("fn` or `struct", "function or struct", true)
8286                 };
8287                 let msg = format!("missing `{}` for {} definition", kw, kw_name);
8288                 let mut err = self.diagnostic().struct_span_err(sp, &msg);
8289                 if !ambiguous {
8290                     err.span_suggestion_short(
8291                         sp,
8292                         &format!("add `{}` here to parse `{}` as a public {}", kw, ident, kw_name),
8293                         format!(" {} ", kw),
8294                         Applicability::MachineApplicable,
8295                     );
8296                 }
8297                 return Err(err);
8298             }
8299         }
8300         self.parse_macro_use_or_failure(attrs, macros_allowed, attributes_allowed, lo, visibility)
8301     }
8302
8303     /// Parses a foreign item.
8304     crate fn parse_foreign_item(&mut self) -> PResult<'a, ForeignItem> {
8305         maybe_whole!(self, NtForeignItem, |ni| ni);
8306
8307         let attrs = self.parse_outer_attributes()?;
8308         let lo = self.span;
8309         let visibility = self.parse_visibility(false)?;
8310
8311         // FOREIGN STATIC ITEM
8312         // Treat `const` as `static` for error recovery, but don't add it to expected tokens.
8313         if self.check_keyword(keywords::Static) || self.token.is_keyword(keywords::Const) {
8314             if self.token.is_keyword(keywords::Const) {
8315                 self.diagnostic()
8316                     .struct_span_err(self.span, "extern items cannot be `const`")
8317                     .span_suggestion(
8318                         self.span,
8319                         "try using a static value",
8320                         "static".to_owned(),
8321                         Applicability::MachineApplicable
8322                     ).emit();
8323             }
8324             self.bump(); // `static` or `const`
8325             return Ok(self.parse_item_foreign_static(visibility, lo, attrs)?);
8326         }
8327         // FOREIGN FUNCTION ITEM
8328         if self.check_keyword(keywords::Fn) {
8329             return Ok(self.parse_item_foreign_fn(visibility, lo, attrs)?);
8330         }
8331         // FOREIGN TYPE ITEM
8332         if self.check_keyword(keywords::Type) {
8333             return Ok(self.parse_item_foreign_type(visibility, lo, attrs)?);
8334         }
8335
8336         match self.parse_assoc_macro_invoc("extern", Some(&visibility), &mut false)? {
8337             Some(mac) => {
8338                 Ok(
8339                     ForeignItem {
8340                         ident: keywords::Invalid.ident(),
8341                         span: lo.to(self.prev_span),
8342                         id: ast::DUMMY_NODE_ID,
8343                         attrs,
8344                         vis: visibility,
8345                         node: ForeignItemKind::Macro(mac),
8346                     }
8347                 )
8348             }
8349             None => {
8350                 if !attrs.is_empty()  {
8351                     self.expected_item_err(&attrs)?;
8352                 }
8353
8354                 self.unexpected()
8355             }
8356         }
8357     }
8358
8359     /// This is the fall-through for parsing items.
8360     fn parse_macro_use_or_failure(
8361         &mut self,
8362         attrs: Vec<Attribute> ,
8363         macros_allowed: bool,
8364         attributes_allowed: bool,
8365         lo: Span,
8366         visibility: Visibility
8367     ) -> PResult<'a, Option<P<Item>>> {
8368         if macros_allowed && self.token.is_path_start() &&
8369                 !(self.is_async_fn() && self.span.rust_2015()) {
8370             // MACRO INVOCATION ITEM
8371
8372             let prev_span = self.prev_span;
8373             self.complain_if_pub_macro(&visibility.node, prev_span);
8374
8375             let mac_lo = self.span;
8376
8377             // item macro.
8378             let pth = self.parse_path(PathStyle::Mod)?;
8379             self.expect(&token::Not)?;
8380
8381             // a 'special' identifier (like what `macro_rules!` uses)
8382             // is optional. We should eventually unify invoc syntax
8383             // and remove this.
8384             let id = if self.token.is_ident() {
8385                 self.parse_ident()?
8386             } else {
8387                 keywords::Invalid.ident() // no special identifier
8388             };
8389             // eat a matched-delimiter token tree:
8390             let (delim, tts) = self.expect_delimited_token_tree()?;
8391             if delim != MacDelimiter::Brace && !self.eat(&token::Semi) {
8392                 self.report_invalid_macro_expansion_item();
8393             }
8394
8395             let hi = self.prev_span;
8396             let mac = respan(mac_lo.to(hi), Mac_ { path: pth, tts, delim });
8397             let item = self.mk_item(lo.to(hi), id, ItemKind::Mac(mac), visibility, attrs);
8398             return Ok(Some(item));
8399         }
8400
8401         // FAILURE TO PARSE ITEM
8402         match visibility.node {
8403             VisibilityKind::Inherited => {}
8404             _ => {
8405                 return Err(self.span_fatal(self.prev_span, "unmatched visibility `pub`"));
8406             }
8407         }
8408
8409         if !attributes_allowed && !attrs.is_empty() {
8410             self.expected_item_err(&attrs)?;
8411         }
8412         Ok(None)
8413     }
8414
8415     /// Parses a macro invocation inside a `trait`, `impl` or `extern` block.
8416     fn parse_assoc_macro_invoc(&mut self, item_kind: &str, vis: Option<&Visibility>,
8417                                at_end: &mut bool) -> PResult<'a, Option<Mac>>
8418     {
8419         if self.token.is_path_start() &&
8420                 !(self.is_async_fn() && self.span.rust_2015()) {
8421             let prev_span = self.prev_span;
8422             let lo = self.span;
8423             let pth = self.parse_path(PathStyle::Mod)?;
8424
8425             if pth.segments.len() == 1 {
8426                 if !self.eat(&token::Not) {
8427                     return Err(self.missing_assoc_item_kind_err(item_kind, prev_span));
8428                 }
8429             } else {
8430                 self.expect(&token::Not)?;
8431             }
8432
8433             if let Some(vis) = vis {
8434                 self.complain_if_pub_macro(&vis.node, prev_span);
8435             }
8436
8437             *at_end = true;
8438
8439             // eat a matched-delimiter token tree:
8440             let (delim, tts) = self.expect_delimited_token_tree()?;
8441             if delim != MacDelimiter::Brace {
8442                 self.expect(&token::Semi)?;
8443             }
8444
8445             Ok(Some(respan(lo.to(self.prev_span), Mac_ { path: pth, tts, delim })))
8446         } else {
8447             Ok(None)
8448         }
8449     }
8450
8451     fn collect_tokens<F, R>(&mut self, f: F) -> PResult<'a, (R, TokenStream)>
8452         where F: FnOnce(&mut Self) -> PResult<'a, R>
8453     {
8454         // Record all tokens we parse when parsing this item.
8455         let mut tokens = Vec::new();
8456         let prev_collecting = match self.token_cursor.frame.last_token {
8457             LastToken::Collecting(ref mut list) => {
8458                 Some(mem::replace(list, Vec::new()))
8459             }
8460             LastToken::Was(ref mut last) => {
8461                 tokens.extend(last.take());
8462                 None
8463             }
8464         };
8465         self.token_cursor.frame.last_token = LastToken::Collecting(tokens);
8466         let prev = self.token_cursor.stack.len();
8467         let ret = f(self);
8468         let last_token = if self.token_cursor.stack.len() == prev {
8469             &mut self.token_cursor.frame.last_token
8470         } else {
8471             &mut self.token_cursor.stack[prev].last_token
8472         };
8473
8474         // Pull out the tokens that we've collected from the call to `f` above.
8475         let mut collected_tokens = match *last_token {
8476             LastToken::Collecting(ref mut v) => mem::replace(v, Vec::new()),
8477             LastToken::Was(_) => panic!("our vector went away?"),
8478         };
8479
8480         // If we're not at EOF our current token wasn't actually consumed by
8481         // `f`, but it'll still be in our list that we pulled out. In that case
8482         // put it back.
8483         let extra_token = if self.token != token::Eof {
8484             collected_tokens.pop()
8485         } else {
8486             None
8487         };
8488
8489         // If we were previously collecting tokens, then this was a recursive
8490         // call. In that case we need to record all the tokens we collected in
8491         // our parent list as well. To do that we push a clone of our stream
8492         // onto the previous list.
8493         match prev_collecting {
8494             Some(mut list) => {
8495                 list.extend(collected_tokens.iter().cloned());
8496                 list.extend(extra_token);
8497                 *last_token = LastToken::Collecting(list);
8498             }
8499             None => {
8500                 *last_token = LastToken::Was(extra_token);
8501             }
8502         }
8503
8504         Ok((ret?, TokenStream::new(collected_tokens)))
8505     }
8506
8507     pub fn parse_item(&mut self) -> PResult<'a, Option<P<Item>>> {
8508         let attrs = self.parse_outer_attributes()?;
8509         self.parse_item_(attrs, true, false)
8510     }
8511
8512     /// `::{` or `::*`
8513     fn is_import_coupler(&mut self) -> bool {
8514         self.check(&token::ModSep) &&
8515             self.look_ahead(1, |t| *t == token::OpenDelim(token::Brace) ||
8516                                    *t == token::BinOp(token::Star))
8517     }
8518
8519     /// Parses a `UseTree`.
8520     ///
8521     /// ```
8522     /// USE_TREE = [`::`] `*` |
8523     ///            [`::`] `{` USE_TREE_LIST `}` |
8524     ///            PATH `::` `*` |
8525     ///            PATH `::` `{` USE_TREE_LIST `}` |
8526     ///            PATH [`as` IDENT]
8527     /// ```
8528     fn parse_use_tree(&mut self) -> PResult<'a, UseTree> {
8529         let lo = self.span;
8530
8531         let mut prefix = ast::Path { segments: Vec::new(), span: lo.shrink_to_lo() };
8532         let kind = if self.check(&token::OpenDelim(token::Brace)) ||
8533                       self.check(&token::BinOp(token::Star)) ||
8534                       self.is_import_coupler() {
8535             // `use *;` or `use ::*;` or `use {...};` or `use ::{...};`
8536             let mod_sep_ctxt = self.span.ctxt();
8537             if self.eat(&token::ModSep) {
8538                 prefix.segments.push(
8539                     PathSegment::path_root(lo.shrink_to_lo().with_ctxt(mod_sep_ctxt))
8540                 );
8541             }
8542
8543             if self.eat(&token::BinOp(token::Star)) {
8544                 UseTreeKind::Glob
8545             } else {
8546                 UseTreeKind::Nested(self.parse_use_tree_list()?)
8547             }
8548         } else {
8549             // `use path::*;` or `use path::{...};` or `use path;` or `use path as bar;`
8550             prefix = self.parse_path(PathStyle::Mod)?;
8551
8552             if self.eat(&token::ModSep) {
8553                 if self.eat(&token::BinOp(token::Star)) {
8554                     UseTreeKind::Glob
8555                 } else {
8556                     UseTreeKind::Nested(self.parse_use_tree_list()?)
8557                 }
8558             } else {
8559                 UseTreeKind::Simple(self.parse_rename()?, ast::DUMMY_NODE_ID, ast::DUMMY_NODE_ID)
8560             }
8561         };
8562
8563         Ok(UseTree { prefix, kind, span: lo.to(self.prev_span) })
8564     }
8565
8566     /// Parses a `UseTreeKind::Nested(list)`.
8567     ///
8568     /// ```
8569     /// USE_TREE_LIST = Ø | (USE_TREE `,`)* USE_TREE [`,`]
8570     /// ```
8571     fn parse_use_tree_list(&mut self) -> PResult<'a, Vec<(UseTree, ast::NodeId)>> {
8572         self.parse_unspanned_seq(&token::OpenDelim(token::Brace),
8573                                  &token::CloseDelim(token::Brace),
8574                                  SeqSep::trailing_allowed(token::Comma), |this| {
8575             Ok((this.parse_use_tree()?, ast::DUMMY_NODE_ID))
8576         })
8577     }
8578
8579     fn parse_rename(&mut self) -> PResult<'a, Option<Ident>> {
8580         if self.eat_keyword(keywords::As) {
8581             self.parse_ident_or_underscore().map(Some)
8582         } else {
8583             Ok(None)
8584         }
8585     }
8586
8587     /// Parses a source module as a crate. This is the main entry point for the parser.
8588     pub fn parse_crate_mod(&mut self) -> PResult<'a, Crate> {
8589         let lo = self.span;
8590         let krate = Ok(ast::Crate {
8591             attrs: self.parse_inner_attributes()?,
8592             module: self.parse_mod_items(&token::Eof, lo)?,
8593             span: lo.to(self.span),
8594         });
8595         krate
8596     }
8597
8598     pub fn parse_optional_str(&mut self) -> Option<(Symbol, ast::StrStyle, Option<ast::Name>)> {
8599         let ret = match self.token {
8600             token::Literal(token::Str_(s), suf) => (s, ast::StrStyle::Cooked, suf),
8601             token::Literal(token::StrRaw(s, n), suf) => (s, ast::StrStyle::Raw(n), suf),
8602             _ => return None
8603         };
8604         self.bump();
8605         Some(ret)
8606     }
8607
8608     pub fn parse_str(&mut self) -> PResult<'a, (Symbol, StrStyle)> {
8609         match self.parse_optional_str() {
8610             Some((s, style, suf)) => {
8611                 let sp = self.prev_span;
8612                 self.expect_no_suffix(sp, "string literal", suf);
8613                 Ok((s, style))
8614             }
8615             _ => {
8616                 let msg = "expected string literal";
8617                 let mut err = self.fatal(msg);
8618                 err.span_label(self.span, msg);
8619                 Err(err)
8620             }
8621         }
8622     }
8623
8624     fn report_invalid_macro_expansion_item(&self) {
8625         self.struct_span_err(
8626             self.prev_span,
8627             "macros that expand to items must be delimited with braces or followed by a semicolon",
8628         ).multipart_suggestion(
8629             "change the delimiters to curly braces",
8630             vec![
8631                 (self.prev_span.with_hi(self.prev_span.lo() + BytePos(1)), String::from(" {")),
8632                 (self.prev_span.with_lo(self.prev_span.hi() - BytePos(1)), '}'.to_string()),
8633             ],
8634             Applicability::MaybeIncorrect,
8635         ).span_suggestion(
8636             self.sess.source_map.next_point(self.prev_span),
8637             "add a semicolon",
8638             ';'.to_string(),
8639             Applicability::MaybeIncorrect,
8640         ).emit();
8641     }
8642
8643     /// Recover from `pub` keyword in places where it seems _reasonable_ but isn't valid.
8644     fn eat_bad_pub(&mut self) {
8645         if self.token.is_keyword(keywords::Pub) {
8646             match self.parse_visibility(false) {
8647                 Ok(vis) => {
8648                     let mut err = self.diagnostic()
8649                         .struct_span_err(vis.span, "unnecessary visibility qualifier");
8650                     err.span_label(vis.span, "`pub` not permitted here");
8651                     err.emit();
8652                 }
8653                 Err(mut err) => err.emit(),
8654             }
8655         }
8656     }
8657 }
8658
8659 pub fn emit_unclosed_delims(unclosed_delims: &mut Vec<UnmatchedBrace>, handler: &errors::Handler) {
8660     for unmatched in unclosed_delims.iter() {
8661         let mut err = handler.struct_span_err(unmatched.found_span, &format!(
8662             "incorrect close delimiter: `{}`",
8663             pprust::token_to_string(&token::Token::CloseDelim(unmatched.found_delim)),
8664         ));
8665         err.span_label(unmatched.found_span, "incorrect close delimiter");
8666         if let Some(sp) = unmatched.candidate_span {
8667             err.span_label(sp, "close delimiter possibly meant for this");
8668         }
8669         if let Some(sp) = unmatched.unclosed_span {
8670             err.span_label(sp, "un-closed delimiter");
8671         }
8672         err.emit();
8673     }
8674     unclosed_delims.clear();
8675 }