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