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