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