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