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