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