]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/expand.rs
save-analysis: API-ify paths
[rust.git] / src / libsyntax / ext / expand.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 ast::{Block, Crate, DeclLocal, ExprMac, PatMac};
12 use ast::{Local, Ident, MacInvocTT};
13 use ast::{ItemMac, MacStmtWithSemicolon, Mrk, Stmt, StmtDecl, StmtMac};
14 use ast::{StmtExpr, StmtSemi};
15 use ast::TokenTree;
16 use ast;
17 use ext::mtwt;
18 use ext::build::AstBuilder;
19 use attr;
20 use attr::AttrMetaMethods;
21 use codemap;
22 use codemap::{Span, Spanned, ExpnInfo, NameAndSpan, MacroBang, MacroAttribute, CompilerExpansion};
23 use ext::base::*;
24 use feature_gate::{self, Features};
25 use fold;
26 use fold::*;
27 use parse;
28 use parse::token::{fresh_mark, fresh_name, intern};
29 use parse::token;
30 use ptr::P;
31 use util::small_vector::SmallVector;
32 use visit;
33 use visit::Visitor;
34 use std_inject;
35
36 pub fn expand_expr(e: P<ast::Expr>, fld: &mut MacroExpander) -> P<ast::Expr> {
37     fn push_compiler_expansion(fld: &mut MacroExpander, span: Span, expansion_desc: &str) {
38         fld.cx.bt_push(ExpnInfo {
39             call_site: span,
40             callee: NameAndSpan {
41                 name: expansion_desc.to_string(),
42                 format: CompilerExpansion,
43                 allow_internal_unstable: true,
44                 span: None,
45             },
46         });
47     }
48
49     e.and_then(|ast::Expr {id, node, span}| match node {
50         // expr_mac should really be expr_ext or something; it's the
51         // entry-point for all syntax extensions.
52         ast::ExprMac(mac) => {
53             let expanded_expr = match expand_mac_invoc(mac, span,
54                                                        |r| r.make_expr(),
55                                                        mark_expr, fld) {
56                 Some(expr) => expr,
57                 None => {
58                     return DummyResult::raw_expr(span);
59                 }
60             };
61
62             // Keep going, outside-in.
63             let fully_expanded = fld.fold_expr(expanded_expr);
64             let span = fld.new_span(span);
65             fld.cx.bt_pop();
66
67             fully_expanded.map(|e| ast::Expr {
68                 id: ast::DUMMY_NODE_ID,
69                 node: e.node,
70                 span: span,
71             })
72         }
73
74         ast::ExprWhile(cond, body, opt_ident) => {
75             let cond = fld.fold_expr(cond);
76             let (body, opt_ident) = expand_loop_block(body, opt_ident, fld);
77             fld.cx.expr(span, ast::ExprWhile(cond, body, opt_ident))
78         }
79
80         // Desugar ExprWhileLet
81         // From: `[opt_ident]: while let <pat> = <expr> <body>`
82         ast::ExprWhileLet(pat, expr, body, opt_ident) => {
83             // to:
84             //
85             //   [opt_ident]: loop {
86             //     match <expr> {
87             //       <pat> => <body>,
88             //       _ => break
89             //     }
90             //   }
91
92             push_compiler_expansion(fld, span, "while let expansion");
93
94             // `<pat> => <body>`
95             let pat_arm = {
96                 let body_expr = fld.cx.expr_block(body);
97                 fld.cx.arm(pat.span, vec![pat], body_expr)
98             };
99
100             // `_ => break`
101             let break_arm = {
102                 let pat_under = fld.cx.pat_wild(span);
103                 let break_expr = fld.cx.expr_break(span);
104                 fld.cx.arm(span, vec![pat_under], break_expr)
105             };
106
107             // `match <expr> { ... }`
108             let arms = vec![pat_arm, break_arm];
109             let match_expr = fld.cx.expr(span,
110                                     ast::ExprMatch(expr, arms, ast::MatchSource::WhileLetDesugar));
111
112             // `[opt_ident]: loop { ... }`
113             let loop_block = fld.cx.block_expr(match_expr);
114             let (loop_block, opt_ident) = expand_loop_block(loop_block, opt_ident, fld);
115             let result = fld.cx.expr(span, ast::ExprLoop(loop_block, opt_ident));
116             fld.cx.bt_pop();
117             result
118         }
119
120         // Desugar ExprIfLet
121         // From: `if let <pat> = <expr> <body> [<elseopt>]`
122         ast::ExprIfLet(pat, expr, body, mut elseopt) => {
123             // to:
124             //
125             //   match <expr> {
126             //     <pat> => <body>,
127             //     [_ if <elseopt_if_cond> => <elseopt_if_body>,]
128             //     _ => [<elseopt> | ()]
129             //   }
130
131             push_compiler_expansion(fld, span, "if let expansion");
132
133             // `<pat> => <body>`
134             let pat_arm = {
135                 let body_expr = fld.cx.expr_block(body);
136                 fld.cx.arm(pat.span, vec![pat], body_expr)
137             };
138
139             // `[_ if <elseopt_if_cond> => <elseopt_if_body>,]`
140             let else_if_arms = {
141                 let mut arms = vec![];
142                 loop {
143                     let elseopt_continue = elseopt
144                         .and_then(|els| els.and_then(|els| match els.node {
145                         // else if
146                         ast::ExprIf(cond, then, elseopt) => {
147                             let pat_under = fld.cx.pat_wild(span);
148                             arms.push(ast::Arm {
149                                 attrs: vec![],
150                                 pats: vec![pat_under],
151                                 guard: Some(cond),
152                                 body: fld.cx.expr_block(then)
153                             });
154                             elseopt.map(|elseopt| (elseopt, true))
155                         }
156                         _ => Some((P(els), false))
157                     }));
158                     match elseopt_continue {
159                         Some((e, true)) => {
160                             elseopt = Some(e);
161                         }
162                         Some((e, false)) => {
163                             elseopt = Some(e);
164                             break;
165                         }
166                         None => {
167                             elseopt = None;
168                             break;
169                         }
170                     }
171                 }
172                 arms
173             };
174
175             let contains_else_clause = elseopt.is_some();
176
177             // `_ => [<elseopt> | ()]`
178             let else_arm = {
179                 let pat_under = fld.cx.pat_wild(span);
180                 let else_expr = elseopt.unwrap_or_else(|| fld.cx.expr_tuple(span, vec![]));
181                 fld.cx.arm(span, vec![pat_under], else_expr)
182             };
183
184             let mut arms = Vec::with_capacity(else_if_arms.len() + 2);
185             arms.push(pat_arm);
186             arms.extend(else_if_arms);
187             arms.push(else_arm);
188
189             let match_expr = fld.cx.expr(span,
190                                          ast::ExprMatch(expr, arms,
191                                                 ast::MatchSource::IfLetDesugar {
192                                                     contains_else_clause: contains_else_clause,
193                                                 }));
194             let result = fld.fold_expr(match_expr);
195             fld.cx.bt_pop();
196             result
197         }
198
199         // Desugar support for ExprIfLet in the ExprIf else position
200         ast::ExprIf(cond, blk, elseopt) => {
201             let elseopt = elseopt.map(|els| els.and_then(|els| match els.node {
202                 ast::ExprIfLet(..) => {
203                     push_compiler_expansion(fld, span, "if let expansion");
204                     // wrap the if-let expr in a block
205                     let span = els.span;
206                     let blk = P(ast::Block {
207                         stmts: vec![],
208                         expr: Some(P(els)),
209                         id: ast::DUMMY_NODE_ID,
210                         rules: ast::DefaultBlock,
211                         span: span
212                     });
213                     let result = fld.cx.expr_block(blk);
214                     fld.cx.bt_pop();
215                     result
216                 }
217                 _ => P(els)
218             }));
219             let if_expr = fld.cx.expr(span, ast::ExprIf(cond, blk, elseopt));
220             if_expr.map(|e| noop_fold_expr(e, fld))
221         }
222
223         ast::ExprLoop(loop_block, opt_ident) => {
224             let (loop_block, opt_ident) = expand_loop_block(loop_block, opt_ident, fld);
225             fld.cx.expr(span, ast::ExprLoop(loop_block, opt_ident))
226         }
227
228         // Desugar ExprForLoop
229         // From: `[opt_ident]: for <pat> in <head> <body>`
230         ast::ExprForLoop(pat, head, body, opt_ident) => {
231             // to:
232             //
233             //   {
234             //     let result = match ::std::iter::IntoIterator::into_iter(<head>) {
235             //       mut iter => {
236             //         [opt_ident]: loop {
237             //           match ::std::iter::Iterator::next(&mut iter) {
238             //             ::std::option::Option::Some(<pat>) => <body>,
239             //             ::std::option::Option::None => break
240             //           }
241             //         }
242             //       }
243             //     };
244             //     result
245             //   }
246
247             push_compiler_expansion(fld, span, "for loop expansion");
248
249             let span = fld.new_span(span);
250
251             // expand <head>
252             let head = fld.fold_expr(head);
253
254             // create an hygienic ident
255             let iter = {
256                 let ident = fld.cx.ident_of("iter");
257                 let new_ident = fresh_name(&ident);
258                 let rename = (ident, new_ident);
259                 let mut rename_list = vec![rename];
260                 let mut rename_fld = IdentRenamer{ renames: &mut rename_list };
261
262                 rename_fld.fold_ident(ident)
263             };
264
265             let pat_span = fld.new_span(pat.span);
266             // `::std::option::Option::Some(<pat>) => <body>`
267             let pat_arm = {
268                 let body_expr = fld.cx.expr_block(body);
269                 let pat = noop_fold_pat(pat, fld);
270                 let some_pat = fld.cx.pat_some(pat_span, pat);
271
272                 fld.cx.arm(pat_span, vec![some_pat], body_expr)
273             };
274
275             // `::std::option::Option::None => break`
276             let break_arm = {
277                 let break_expr = fld.cx.expr_break(span);
278
279                 fld.cx.arm(span, vec![fld.cx.pat_none(span)], break_expr)
280             };
281
282             // `match ::std::iter::Iterator::next(&mut iter) { ... }`
283             let match_expr = {
284                 let next_path = {
285                     let strs = vec![
286                         fld.cx.ident_of_std("core"),
287                         fld.cx.ident_of("iter"),
288                         fld.cx.ident_of("Iterator"),
289                         fld.cx.ident_of("next"),
290                     ];
291
292                     fld.cx.path_global(span, strs)
293                 };
294                 let ref_mut_iter = fld.cx.expr_mut_addr_of(span, fld.cx.expr_ident(span, iter));
295                 let next_expr =
296                     fld.cx.expr_call(span, fld.cx.expr_path(next_path), vec![ref_mut_iter]);
297                 let arms = vec![pat_arm, break_arm];
298
299                 fld.cx.expr(pat_span,
300                             ast::ExprMatch(next_expr, arms, ast::MatchSource::ForLoopDesugar))
301             };
302
303             // `[opt_ident]: loop { ... }`
304             let loop_block = fld.cx.block_expr(match_expr);
305             let (loop_block, opt_ident) = expand_loop_block(loop_block, opt_ident, fld);
306             let loop_expr = fld.cx.expr(span, ast::ExprLoop(loop_block, opt_ident));
307
308             // `mut iter => { ... }`
309             let iter_arm = {
310                 let iter_pat =
311                     fld.cx.pat_ident_binding_mode(span, iter, ast::BindByValue(ast::MutMutable));
312                 fld.cx.arm(span, vec![iter_pat], loop_expr)
313             };
314
315             // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
316             let into_iter_expr = {
317                 let into_iter_path = {
318                     let strs = vec![
319                         fld.cx.ident_of_std("core"),
320                         fld.cx.ident_of("iter"),
321                         fld.cx.ident_of("IntoIterator"),
322                         fld.cx.ident_of("into_iter"),
323                     ];
324
325                     fld.cx.path_global(span, strs)
326                 };
327
328                 fld.cx.expr_call(span, fld.cx.expr_path(into_iter_path), vec![head])
329             };
330
331             let match_expr = fld.cx.expr_match(span, into_iter_expr, vec![iter_arm]);
332
333             // `{ let result = ...; result }`
334             let result_ident = token::gensym_ident("result");
335             let result = fld.cx.expr_block(
336                 fld.cx.block_all(
337                     span,
338                     vec![fld.cx.stmt_let(span, false, result_ident, match_expr)],
339                     Some(fld.cx.expr_ident(span, result_ident))));
340             fld.cx.bt_pop();
341             result
342         }
343
344         ast::ExprClosure(capture_clause, fn_decl, block) => {
345             push_compiler_expansion(fld, span, "closure expansion");
346             let (rewritten_fn_decl, rewritten_block)
347                 = expand_and_rename_fn_decl_and_block(fn_decl, block, fld);
348             let new_node = ast::ExprClosure(capture_clause,
349                                             rewritten_fn_decl,
350                                             rewritten_block);
351             let result = P(ast::Expr{id:id, node: new_node, span: fld.new_span(span)});
352             fld.cx.bt_pop();
353             result
354         }
355
356         _ => {
357             P(noop_fold_expr(ast::Expr {
358                 id: id,
359                 node: node,
360                 span: span
361             }, fld))
362         }
363     })
364 }
365
366 /// Expand a (not-ident-style) macro invocation. Returns the result
367 /// of expansion and the mark which must be applied to the result.
368 /// Our current interface doesn't allow us to apply the mark to the
369 /// result until after calling make_expr, make_items, etc.
370 fn expand_mac_invoc<T, F, G>(mac: ast::Mac,
371                              span: codemap::Span,
372                              parse_thunk: F,
373                              mark_thunk: G,
374                              fld: &mut MacroExpander)
375                              -> Option<T> where
376     F: for<'a> FnOnce(Box<MacResult+'a>) -> Option<T>,
377     G: FnOnce(T, Mrk) -> T,
378 {
379     match mac.node {
380         // it would almost certainly be cleaner to pass the whole
381         // macro invocation in, rather than pulling it apart and
382         // marking the tts and the ctxt separately. This also goes
383         // for the other three macro invocation chunks of code
384         // in this file.
385         // Token-tree macros:
386         MacInvocTT(pth, tts, _) => {
387             if pth.segments.len() > 1 {
388                 fld.cx.span_err(pth.span,
389                                 "expected macro name without module \
390                                 separators");
391                 // let compilation continue
392                 return None;
393             }
394             let extname = pth.segments[0].identifier;
395             let extnamestr = token::get_ident(extname);
396             match fld.cx.syntax_env.find(&extname.name) {
397                 None => {
398                     fld.cx.span_err(
399                         pth.span,
400                         &format!("macro undefined: '{}!'",
401                                 &extnamestr));
402
403                     // let compilation continue
404                     None
405                 }
406                 Some(rc) => match *rc {
407                     NormalTT(ref expandfun, exp_span, allow_internal_unstable) => {
408                         fld.cx.bt_push(ExpnInfo {
409                                 call_site: span,
410                                 callee: NameAndSpan {
411                                     name: extnamestr.to_string(),
412                                     format: MacroBang,
413                                     span: exp_span,
414                                     allow_internal_unstable: allow_internal_unstable,
415                                 },
416                             });
417                         let fm = fresh_mark();
418                         let marked_before = mark_tts(&tts[..], fm);
419
420                         // The span that we pass to the expanders we want to
421                         // be the root of the call stack. That's the most
422                         // relevant span and it's the actual invocation of
423                         // the macro.
424                         let mac_span = fld.cx.original_span();
425
426                         let opt_parsed = {
427                             let expanded = expandfun.expand(fld.cx,
428                                                             mac_span,
429                                                             &marked_before[..]);
430                             parse_thunk(expanded)
431                         };
432                         let parsed = match opt_parsed {
433                             Some(e) => e,
434                             None => {
435                                 fld.cx.span_err(
436                                     pth.span,
437                                     &format!("non-expression macro in expression position: {}",
438                                             &extnamestr[..]
439                                             ));
440                                 return None;
441                             }
442                         };
443                         Some(mark_thunk(parsed,fm))
444                     }
445                     _ => {
446                         fld.cx.span_err(
447                             pth.span,
448                             &format!("'{}' is not a tt-style macro",
449                                     &extnamestr));
450                         None
451                     }
452                 }
453             }
454         }
455     }
456 }
457
458 /// Rename loop label and expand its loop body
459 ///
460 /// The renaming procedure for loop is different in the sense that the loop
461 /// body is in a block enclosed by loop head so the renaming of loop label
462 /// must be propagated to the enclosed context.
463 fn expand_loop_block(loop_block: P<Block>,
464                      opt_ident: Option<Ident>,
465                      fld: &mut MacroExpander) -> (P<Block>, Option<Ident>) {
466     match opt_ident {
467         Some(label) => {
468             let new_label = fresh_name(&label);
469             let rename = (label, new_label);
470
471             // The rename *must not* be added to the pending list of current
472             // syntax context otherwise an unrelated `break` or `continue` in
473             // the same context will pick that up in the deferred renaming pass
474             // and be renamed incorrectly.
475             let mut rename_list = vec!(rename);
476             let mut rename_fld = IdentRenamer{renames: &mut rename_list};
477             let renamed_ident = rename_fld.fold_ident(label);
478
479             // The rename *must* be added to the enclosed syntax context for
480             // `break` or `continue` to pick up because by definition they are
481             // in a block enclosed by loop head.
482             fld.cx.syntax_env.push_frame();
483             fld.cx.syntax_env.info().pending_renames.push(rename);
484             let expanded_block = expand_block_elts(loop_block, fld);
485             fld.cx.syntax_env.pop_frame();
486
487             (expanded_block, Some(renamed_ident))
488         }
489         None => (fld.fold_block(loop_block), opt_ident)
490     }
491 }
492
493 // eval $e with a new exts frame.
494 // must be a macro so that $e isn't evaluated too early.
495 macro_rules! with_exts_frame {
496     ($extsboxexpr:expr,$macros_escape:expr,$e:expr) =>
497     ({$extsboxexpr.push_frame();
498       $extsboxexpr.info().macros_escape = $macros_escape;
499       let result = $e;
500       $extsboxexpr.pop_frame();
501       result
502      })
503 }
504
505 // When we enter a module, record it, for the sake of `module!`
506 pub fn expand_item(it: P<ast::Item>, fld: &mut MacroExpander)
507                    -> SmallVector<P<ast::Item>> {
508     let it = expand_item_modifiers(it, fld);
509
510     expand_annotatable(Annotatable::Item(it), fld)
511         .into_iter().map(|i| i.expect_item()).collect()
512 }
513
514 /// Expand item_underscore
515 fn expand_item_underscore(item: ast::Item_, fld: &mut MacroExpander) -> ast::Item_ {
516     match item {
517         ast::ItemFn(decl, unsafety, constness, abi, generics, body) => {
518             let (rewritten_fn_decl, rewritten_body)
519                 = expand_and_rename_fn_decl_and_block(decl, body, fld);
520             let expanded_generics = fold::noop_fold_generics(generics,fld);
521             ast::ItemFn(rewritten_fn_decl, unsafety, constness, abi,
522                         expanded_generics, rewritten_body)
523         }
524         _ => noop_fold_item_underscore(item, fld)
525     }
526 }
527
528 // does this attribute list contain "macro_use" ?
529 fn contains_macro_use(fld: &mut MacroExpander, attrs: &[ast::Attribute]) -> bool {
530     for attr in attrs {
531         let mut is_use = attr.check_name("macro_use");
532         if attr.check_name("macro_escape") {
533             fld.cx.span_warn(attr.span, "macro_escape is a deprecated synonym for macro_use");
534             is_use = true;
535             if let ast::AttrInner = attr.node.style {
536                 fld.cx.fileline_help(attr.span, "consider an outer attribute, \
537                                              #[macro_use] mod ...");
538             }
539         };
540
541         if is_use {
542             match attr.node.value.node {
543                 ast::MetaWord(..) => (),
544                 _ => fld.cx.span_err(attr.span, "arguments to macro_use are not allowed here"),
545             }
546             return true;
547         }
548     }
549     false
550 }
551
552 // Support for item-position macro invocations, exactly the same
553 // logic as for expression-position macro invocations.
554 pub fn expand_item_mac(it: P<ast::Item>,
555                        fld: &mut MacroExpander) -> SmallVector<P<ast::Item>> {
556     let (extname, path_span, tts) = match it.node {
557         ItemMac(codemap::Spanned {
558             node: MacInvocTT(ref pth, ref tts, _),
559             ..
560         }) => {
561             (pth.segments[0].identifier, pth.span, (*tts).clone())
562         }
563         _ => fld.cx.span_bug(it.span, "invalid item macro invocation")
564     };
565
566     let extnamestr = token::get_ident(extname);
567     let fm = fresh_mark();
568     let items = {
569         let expanded = match fld.cx.syntax_env.find(&extname.name) {
570             None => {
571                 fld.cx.span_err(path_span,
572                                 &format!("macro undefined: '{}!'",
573                                         extnamestr));
574                 // let compilation continue
575                 return SmallVector::zero();
576             }
577
578             Some(rc) => match *rc {
579                 NormalTT(ref expander, span, allow_internal_unstable) => {
580                     if it.ident.name != parse::token::special_idents::invalid.name {
581                         fld.cx
582                             .span_err(path_span,
583                                       &format!("macro {}! expects no ident argument, given '{}'",
584                                                extnamestr,
585                                                token::get_ident(it.ident)));
586                         return SmallVector::zero();
587                     }
588                     fld.cx.bt_push(ExpnInfo {
589                         call_site: it.span,
590                         callee: NameAndSpan {
591                             name: extnamestr.to_string(),
592                             format: MacroBang,
593                             span: span,
594                             allow_internal_unstable: allow_internal_unstable,
595                         }
596                     });
597                     // mark before expansion:
598                     let marked_before = mark_tts(&tts[..], fm);
599                     expander.expand(fld.cx, it.span, &marked_before[..])
600                 }
601                 IdentTT(ref expander, span, allow_internal_unstable) => {
602                     if it.ident.name == parse::token::special_idents::invalid.name {
603                         fld.cx.span_err(path_span,
604                                         &format!("macro {}! expects an ident argument",
605                                                 &extnamestr));
606                         return SmallVector::zero();
607                     }
608                     fld.cx.bt_push(ExpnInfo {
609                         call_site: it.span,
610                         callee: NameAndSpan {
611                             name: extnamestr.to_string(),
612                             format: MacroBang,
613                             span: span,
614                             allow_internal_unstable: allow_internal_unstable,
615                         }
616                     });
617                     // mark before expansion:
618                     let marked_tts = mark_tts(&tts[..], fm);
619                     expander.expand(fld.cx, it.span, it.ident, marked_tts)
620                 }
621                 MacroRulesTT => {
622                     if it.ident.name == parse::token::special_idents::invalid.name {
623                         fld.cx.span_err(path_span,
624                                         &format!("macro_rules! expects an ident argument")
625                                         );
626                         return SmallVector::zero();
627                     }
628
629                     fld.cx.bt_push(ExpnInfo {
630                         call_site: it.span,
631                         callee: NameAndSpan {
632                             name: extnamestr.to_string(),
633                             format: MacroBang,
634                             span: None,
635                             // `macro_rules!` doesn't directly allow
636                             // unstable (this is orthogonal to whether
637                             // the macro it creates allows it)
638                             allow_internal_unstable: false,
639                         }
640                     });
641                     // DON'T mark before expansion.
642
643                     let allow_internal_unstable = attr::contains_name(&it.attrs,
644                                                                       "allow_internal_unstable");
645
646                     // ensure any #[allow_internal_unstable]s are
647                     // detected (including nested macro definitions
648                     // etc.)
649                     if allow_internal_unstable && !fld.cx.ecfg.enable_allow_internal_unstable() {
650                         feature_gate::emit_feature_err(
651                             &fld.cx.parse_sess.span_diagnostic,
652                             "allow_internal_unstable",
653                             it.span,
654                             feature_gate::EXPLAIN_ALLOW_INTERNAL_UNSTABLE)
655                     }
656
657                     let def = ast::MacroDef {
658                         ident: it.ident,
659                         attrs: it.attrs.clone(),
660                         id: ast::DUMMY_NODE_ID,
661                         span: it.span,
662                         imported_from: None,
663                         export: attr::contains_name(&it.attrs, "macro_export"),
664                         use_locally: true,
665                         allow_internal_unstable: allow_internal_unstable,
666                         body: tts,
667                     };
668                     fld.cx.insert_macro(def);
669
670                     // macro_rules! has a side effect but expands to nothing.
671                     fld.cx.bt_pop();
672                     return SmallVector::zero();
673                 }
674                 _ => {
675                     fld.cx.span_err(it.span,
676                                     &format!("{}! is not legal in item position",
677                                             &extnamestr));
678                     return SmallVector::zero();
679                 }
680             }
681         };
682
683         expanded.make_items()
684     };
685
686     let items = match items {
687         Some(items) => {
688             items.into_iter()
689                 .map(|i| mark_item(i, fm))
690                 .flat_map(|i| fld.fold_item(i).into_iter())
691                 .collect()
692         }
693         None => {
694             fld.cx.span_err(path_span,
695                             &format!("non-item macro in item position: {}",
696                                     &extnamestr));
697             return SmallVector::zero();
698         }
699     };
700
701     fld.cx.bt_pop();
702     items
703 }
704
705 /// Expand a stmt
706 fn expand_stmt(stmt: P<Stmt>, fld: &mut MacroExpander) -> SmallVector<P<Stmt>> {
707     let stmt = stmt.and_then(|stmt| stmt);
708     let (mac, style) = match stmt.node {
709         StmtMac(mac, style) => (mac, style),
710         _ => return expand_non_macro_stmt(stmt, fld)
711     };
712
713     let maybe_new_items =
714         expand_mac_invoc(mac.and_then(|m| m), stmt.span,
715                          |r| r.make_stmts(),
716                          |stmts, mark| stmts.move_map(|m| mark_stmt(m, mark)),
717                          fld);
718
719     let mut fully_expanded = match maybe_new_items {
720         Some(stmts) => {
721             // Keep going, outside-in.
722             let new_items = stmts.into_iter().flat_map(|s| {
723                 fld.fold_stmt(s).into_iter()
724             }).collect();
725             fld.cx.bt_pop();
726             new_items
727         }
728         None => SmallVector::zero()
729     };
730
731     // If this is a macro invocation with a semicolon, then apply that
732     // semicolon to the final statement produced by expansion.
733     if style == MacStmtWithSemicolon {
734         if let Some(stmt) = fully_expanded.pop() {
735             let new_stmt = stmt.map(|Spanned {node, span}| {
736                 Spanned {
737                     node: match node {
738                         StmtExpr(e, stmt_id) => StmtSemi(e, stmt_id),
739                         _ => node /* might already have a semi */
740                     },
741                     span: span
742                 }
743             });
744             fully_expanded.push(new_stmt);
745         }
746     }
747
748     fully_expanded
749 }
750
751 // expand a non-macro stmt. this is essentially the fallthrough for
752 // expand_stmt, above.
753 fn expand_non_macro_stmt(Spanned {node, span: stmt_span}: Stmt, fld: &mut MacroExpander)
754                          -> SmallVector<P<Stmt>> {
755     // is it a let?
756     match node {
757         StmtDecl(decl, node_id) => decl.and_then(|Spanned {node: decl, span}| match decl {
758             DeclLocal(local) => {
759                 // take it apart:
760                 let rewritten_local = local.map(|Local {id, pat, ty, init, source, span}| {
761                     // expand the ty since TyFixedLengthVec contains an Expr
762                     // and thus may have a macro use
763                     let expanded_ty = ty.map(|t| fld.fold_ty(t));
764                     // expand the pat (it might contain macro uses):
765                     let expanded_pat = fld.fold_pat(pat);
766                     // find the PatIdents in the pattern:
767                     // oh dear heaven... this is going to include the enum
768                     // names, as well... but that should be okay, as long as
769                     // the new names are gensyms for the old ones.
770                     // generate fresh names, push them to a new pending list
771                     let idents = pattern_bindings(&*expanded_pat);
772                     let mut new_pending_renames =
773                         idents.iter().map(|ident| (*ident, fresh_name(ident))).collect();
774                     // rewrite the pattern using the new names (the old
775                     // ones have already been applied):
776                     let rewritten_pat = {
777                         // nested binding to allow borrow to expire:
778                         let mut rename_fld = IdentRenamer{renames: &mut new_pending_renames};
779                         rename_fld.fold_pat(expanded_pat)
780                     };
781                     // add them to the existing pending renames:
782                     fld.cx.syntax_env.info().pending_renames
783                           .extend(new_pending_renames);
784                     Local {
785                         id: id,
786                         ty: expanded_ty,
787                         pat: rewritten_pat,
788                         // also, don't forget to expand the init:
789                         init: init.map(|e| fld.fold_expr(e)),
790                         source: source,
791                         span: span
792                     }
793                 });
794                 SmallVector::one(P(Spanned {
795                     node: StmtDecl(P(Spanned {
796                             node: DeclLocal(rewritten_local),
797                             span: span
798                         }),
799                         node_id),
800                     span: stmt_span
801                 }))
802             }
803             _ => {
804                 noop_fold_stmt(Spanned {
805                     node: StmtDecl(P(Spanned {
806                             node: decl,
807                             span: span
808                         }),
809                         node_id),
810                     span: stmt_span
811                 }, fld)
812             }
813         }),
814         _ => {
815             noop_fold_stmt(Spanned {
816                 node: node,
817                 span: stmt_span
818             }, fld)
819         }
820     }
821 }
822
823 // expand the arm of a 'match', renaming for macro hygiene
824 fn expand_arm(arm: ast::Arm, fld: &mut MacroExpander) -> ast::Arm {
825     // expand pats... they might contain macro uses:
826     let expanded_pats = arm.pats.move_map(|pat| fld.fold_pat(pat));
827     if expanded_pats.is_empty() {
828         panic!("encountered match arm with 0 patterns");
829     }
830     // all of the pats must have the same set of bindings, so use the
831     // first one to extract them and generate new names:
832     let idents = pattern_bindings(&*expanded_pats[0]);
833     let new_renames = idents.into_iter().map(|id| (id, fresh_name(&id))).collect();
834     // apply the renaming, but only to the PatIdents:
835     let mut rename_pats_fld = PatIdentRenamer{renames:&new_renames};
836     let rewritten_pats = expanded_pats.move_map(|pat| rename_pats_fld.fold_pat(pat));
837     // apply renaming and then expansion to the guard and the body:
838     let mut rename_fld = IdentRenamer{renames:&new_renames};
839     let rewritten_guard =
840         arm.guard.map(|g| fld.fold_expr(rename_fld.fold_expr(g)));
841     let rewritten_body = fld.fold_expr(rename_fld.fold_expr(arm.body));
842     ast::Arm {
843         attrs: fold::fold_attrs(arm.attrs, fld),
844         pats: rewritten_pats,
845         guard: rewritten_guard,
846         body: rewritten_body,
847     }
848 }
849
850 /// A visitor that extracts the PatIdent (binding) paths
851 /// from a given thingy and puts them in a mutable
852 /// array
853 #[derive(Clone)]
854 struct PatIdentFinder {
855     ident_accumulator: Vec<ast::Ident>
856 }
857
858 impl<'v> Visitor<'v> for PatIdentFinder {
859     fn visit_pat(&mut self, pattern: &ast::Pat) {
860         match *pattern {
861             ast::Pat { id: _, node: ast::PatIdent(_, ref path1, ref inner), span: _ } => {
862                 self.ident_accumulator.push(path1.node);
863                 // visit optional subpattern of PatIdent:
864                 if let Some(ref subpat) = *inner {
865                     self.visit_pat(&**subpat)
866                 }
867             }
868             // use the default traversal for non-PatIdents
869             _ => visit::walk_pat(self, pattern)
870         }
871     }
872 }
873
874 /// find the PatIdent paths in a pattern
875 fn pattern_bindings(pat: &ast::Pat) -> Vec<ast::Ident> {
876     let mut name_finder = PatIdentFinder{ident_accumulator:Vec::new()};
877     name_finder.visit_pat(pat);
878     name_finder.ident_accumulator
879 }
880
881 /// find the PatIdent paths in a
882 fn fn_decl_arg_bindings(fn_decl: &ast::FnDecl) -> Vec<ast::Ident> {
883     let mut pat_idents = PatIdentFinder{ident_accumulator:Vec::new()};
884     for arg in &fn_decl.inputs {
885         pat_idents.visit_pat(&*arg.pat);
886     }
887     pat_idents.ident_accumulator
888 }
889
890 // expand a block. pushes a new exts_frame, then calls expand_block_elts
891 pub fn expand_block(blk: P<Block>, fld: &mut MacroExpander) -> P<Block> {
892     // see note below about treatment of exts table
893     with_exts_frame!(fld.cx.syntax_env,false,
894                      expand_block_elts(blk, fld))
895 }
896
897 // expand the elements of a block.
898 pub fn expand_block_elts(b: P<Block>, fld: &mut MacroExpander) -> P<Block> {
899     b.map(|Block {id, stmts, expr, rules, span}| {
900         let new_stmts = stmts.into_iter().flat_map(|x| {
901             // perform all pending renames
902             let renamed_stmt = {
903                 let pending_renames = &mut fld.cx.syntax_env.info().pending_renames;
904                 let mut rename_fld = IdentRenamer{renames:pending_renames};
905                 rename_fld.fold_stmt(x).expect_one("rename_fold didn't return one value")
906             };
907             // expand macros in the statement
908             fld.fold_stmt(renamed_stmt).into_iter()
909         }).collect();
910         let new_expr = expr.map(|x| {
911             let expr = {
912                 let pending_renames = &mut fld.cx.syntax_env.info().pending_renames;
913                 let mut rename_fld = IdentRenamer{renames:pending_renames};
914                 rename_fld.fold_expr(x)
915             };
916             fld.fold_expr(expr)
917         });
918         Block {
919             id: fld.new_id(id),
920             stmts: new_stmts,
921             expr: new_expr,
922             rules: rules,
923             span: span
924         }
925     })
926 }
927
928 fn expand_pat(p: P<ast::Pat>, fld: &mut MacroExpander) -> P<ast::Pat> {
929     match p.node {
930         PatMac(_) => {}
931         _ => return noop_fold_pat(p, fld)
932     }
933     p.map(|ast::Pat {node, span, ..}| {
934         let (pth, tts) = match node {
935             PatMac(mac) => match mac.node {
936                 MacInvocTT(pth, tts, _) => {
937                     (pth, tts)
938                 }
939             },
940             _ => unreachable!()
941         };
942         if pth.segments.len() > 1 {
943             fld.cx.span_err(pth.span, "expected macro name without module separators");
944             return DummyResult::raw_pat(span);
945         }
946         let extname = pth.segments[0].identifier;
947         let extnamestr = token::get_ident(extname);
948         let marked_after = match fld.cx.syntax_env.find(&extname.name) {
949             None => {
950                 fld.cx.span_err(pth.span,
951                                 &format!("macro undefined: '{}!'",
952                                         extnamestr));
953                 // let compilation continue
954                 return DummyResult::raw_pat(span);
955             }
956
957             Some(rc) => match *rc {
958                 NormalTT(ref expander, tt_span, allow_internal_unstable) => {
959                     fld.cx.bt_push(ExpnInfo {
960                         call_site: span,
961                         callee: NameAndSpan {
962                             name: extnamestr.to_string(),
963                             format: MacroBang,
964                             span: tt_span,
965                             allow_internal_unstable: allow_internal_unstable,
966                         }
967                     });
968
969                     let fm = fresh_mark();
970                     let marked_before = mark_tts(&tts[..], fm);
971                     let mac_span = fld.cx.original_span();
972                     let pat = expander.expand(fld.cx,
973                                               mac_span,
974                                               &marked_before[..]).make_pat();
975                     let expanded = match pat {
976                         Some(e) => e,
977                         None => {
978                             fld.cx.span_err(
979                                 pth.span,
980                                 &format!(
981                                     "non-pattern macro in pattern position: {}",
982                                     &extnamestr
983                                     )
984                             );
985                             return DummyResult::raw_pat(span);
986                         }
987                     };
988
989                     // mark after:
990                     mark_pat(expanded,fm)
991                 }
992                 _ => {
993                     fld.cx.span_err(span,
994                                     &format!("{}! is not legal in pattern position",
995                                             &extnamestr));
996                     return DummyResult::raw_pat(span);
997                 }
998             }
999         };
1000
1001         let fully_expanded =
1002             fld.fold_pat(marked_after).node.clone();
1003         fld.cx.bt_pop();
1004
1005         ast::Pat {
1006             id: ast::DUMMY_NODE_ID,
1007             node: fully_expanded,
1008             span: span
1009         }
1010     })
1011 }
1012
1013 /// A tree-folder that applies every rename in its (mutable) list
1014 /// to every identifier, including both bindings and varrefs
1015 /// (and lots of things that will turn out to be neither)
1016 pub struct IdentRenamer<'a> {
1017     renames: &'a mtwt::RenameList,
1018 }
1019
1020 impl<'a> Folder for IdentRenamer<'a> {
1021     fn fold_ident(&mut self, id: Ident) -> Ident {
1022         Ident {
1023             name: id.name,
1024             ctxt: mtwt::apply_renames(self.renames, id.ctxt),
1025         }
1026     }
1027     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
1028         fold::noop_fold_mac(mac, self)
1029     }
1030 }
1031
1032 /// A tree-folder that applies every rename in its list to
1033 /// the idents that are in PatIdent patterns. This is more narrowly
1034 /// focused than IdentRenamer, and is needed for FnDecl,
1035 /// where we want to rename the args but not the fn name or the generics etc.
1036 pub struct PatIdentRenamer<'a> {
1037     renames: &'a mtwt::RenameList,
1038 }
1039
1040 impl<'a> Folder for PatIdentRenamer<'a> {
1041     fn fold_pat(&mut self, pat: P<ast::Pat>) -> P<ast::Pat> {
1042         match pat.node {
1043             ast::PatIdent(..) => {},
1044             _ => return noop_fold_pat(pat, self)
1045         }
1046
1047         pat.map(|ast::Pat {id, node, span}| match node {
1048             ast::PatIdent(binding_mode, Spanned{span: sp, node: ident}, sub) => {
1049                 let new_ident = Ident{name: ident.name,
1050                                       ctxt: mtwt::apply_renames(self.renames, ident.ctxt)};
1051                 let new_node =
1052                     ast::PatIdent(binding_mode,
1053                                   Spanned{span: self.new_span(sp), node: new_ident},
1054                                   sub.map(|p| self.fold_pat(p)));
1055                 ast::Pat {
1056                     id: id,
1057                     node: new_node,
1058                     span: self.new_span(span)
1059                 }
1060             },
1061             _ => unreachable!()
1062         })
1063     }
1064     fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
1065         fold::noop_fold_mac(mac, self)
1066     }
1067 }
1068
1069 fn expand_annotatable(a: Annotatable,
1070                       fld: &mut MacroExpander)
1071                       -> SmallVector<Annotatable> {
1072     let a = expand_item_multi_modifier(a, fld);
1073
1074     let mut decorator_items = SmallVector::zero();
1075     let mut new_attrs = Vec::new();
1076     expand_decorators(a.clone(), fld, &mut decorator_items, &mut new_attrs);
1077
1078     let mut new_items: SmallVector<Annotatable> = match a {
1079         Annotatable::Item(it) => match it.node {
1080             ast::ItemMac(..) => {
1081                 expand_item_mac(it, fld).into_iter().map(|i| Annotatable::Item(i)).collect()
1082             }
1083             ast::ItemMod(_) | ast::ItemForeignMod(_) => {
1084                 let valid_ident =
1085                     it.ident.name != parse::token::special_idents::invalid.name;
1086
1087                 if valid_ident {
1088                     fld.cx.mod_push(it.ident);
1089                 }
1090                 let macro_use = contains_macro_use(fld, &new_attrs[..]);
1091                 let result = with_exts_frame!(fld.cx.syntax_env,
1092                                               macro_use,
1093                                               noop_fold_item(it, fld));
1094                 if valid_ident {
1095                     fld.cx.mod_pop();
1096                 }
1097                 result.into_iter().map(|i| Annotatable::Item(i)).collect()
1098             },
1099             _ => {
1100                 let it = P(ast::Item {
1101                     attrs: new_attrs,
1102                     ..(*it).clone()
1103                 });
1104                 noop_fold_item(it, fld).into_iter().map(|i| Annotatable::Item(i)).collect()
1105             }
1106         },
1107
1108         Annotatable::TraitItem(it) => match it.node {
1109             ast::MethodTraitItem(_, Some(_)) => SmallVector::one(it.map(|ti| ast::TraitItem {
1110                 id: ti.id,
1111                 ident: ti.ident,
1112                 attrs: ti.attrs,
1113                 node: match ti.node  {
1114                     ast::MethodTraitItem(sig, Some(body)) => {
1115                         let (sig, body) = expand_and_rename_method(sig, body, fld);
1116                         ast::MethodTraitItem(sig, Some(body))
1117                     }
1118                     _ => unreachable!()
1119                 },
1120                 span: fld.new_span(ti.span)
1121             })),
1122             _ => fold::noop_fold_trait_item(it, fld)
1123         }.into_iter().map(Annotatable::TraitItem).collect(),
1124
1125         Annotatable::ImplItem(ii) => {
1126             expand_impl_item(ii, fld).into_iter().map(Annotatable::ImplItem).collect()
1127         }
1128     };
1129
1130     new_items.push_all(decorator_items);
1131     new_items
1132 }
1133
1134 // Partition a set of attributes into one kind of attribute, and other kinds.
1135 macro_rules! partition {
1136     ($fn_name: ident, $variant: ident) => {
1137         #[allow(deprecated)] // The `allow` is needed because the `Modifier` variant might be used.
1138         fn $fn_name(attrs: &[ast::Attribute],
1139                     fld: &MacroExpander)
1140                      -> (Vec<ast::Attribute>, Vec<ast::Attribute>) {
1141             attrs.iter().cloned().partition(|attr| {
1142                 match fld.cx.syntax_env.find(&intern(&attr.name())) {
1143                     Some(rc) => match *rc {
1144                         $variant(..) => true,
1145                         _ => false
1146                     },
1147                     _ => false
1148                 }
1149             })
1150         }
1151     }
1152 }
1153
1154 partition!(modifiers, Modifier);
1155 partition!(multi_modifiers, MultiModifier);
1156
1157
1158 #[allow(deprecated)] // The `allow` is needed because the `Decorator` variant is used.
1159 fn expand_decorators(a: Annotatable,
1160                      fld: &mut MacroExpander,
1161                      decorator_items: &mut SmallVector<Annotatable>,
1162                      new_attrs: &mut Vec<ast::Attribute>)
1163 {
1164     for attr in a.attrs() {
1165         let mname = attr.name();
1166         match fld.cx.syntax_env.find(&intern(&mname)) {
1167             Some(rc) => match *rc {
1168                 Decorator(ref dec) => {
1169                     attr::mark_used(&attr);
1170
1171                     fld.cx.bt_push(ExpnInfo {
1172                         call_site: attr.span,
1173                         callee: NameAndSpan {
1174                             name: mname.to_string(),
1175                             format: MacroAttribute,
1176                             span: Some(attr.span),
1177                             // attributes can do whatever they like,
1178                             // for now.
1179                             allow_internal_unstable: true,
1180                         }
1181                     });
1182
1183                     // we'd ideally decorator_items.push_all(expand_item(item, fld)),
1184                     // but that double-mut-borrows fld
1185                     let mut items: SmallVector<Annotatable> = SmallVector::zero();
1186                     dec.expand(fld.cx,
1187                                attr.span,
1188                                &attr.node.value,
1189                                &a.clone().expect_item(),
1190                                &mut |item| items.push(Annotatable::Item(item)));
1191                     decorator_items.extend(items.into_iter()
1192                         .flat_map(|ann| expand_annotatable(ann, fld).into_iter()));
1193
1194                     fld.cx.bt_pop();
1195                 }
1196                 MultiDecorator(ref dec) => {
1197                     attr::mark_used(&attr);
1198
1199                     fld.cx.bt_push(ExpnInfo {
1200                         call_site: attr.span,
1201                         callee: NameAndSpan {
1202                             name: mname.to_string(),
1203                             format: MacroAttribute,
1204                             span: Some(attr.span),
1205                             // attributes can do whatever they like,
1206                             // for now.
1207                             allow_internal_unstable: true,
1208                         }
1209                     });
1210
1211                     // we'd ideally decorator_items.push_all(expand_annotatable(ann, fld)),
1212                     // but that double-mut-borrows fld
1213                     let mut items: SmallVector<Annotatable> = SmallVector::zero();
1214                     dec.expand(fld.cx,
1215                                attr.span,
1216                                &attr.node.value,
1217                                &a,
1218                                &mut |ann| items.push(ann));
1219                     decorator_items.extend(items.into_iter()
1220                         .flat_map(|ann| expand_annotatable(ann, fld).into_iter()));
1221
1222                     fld.cx.bt_pop();
1223                 }
1224                 _ => new_attrs.push((*attr).clone()),
1225             },
1226             _ => new_attrs.push((*attr).clone()),
1227         }
1228     }
1229 }
1230
1231 fn expand_item_multi_modifier(mut it: Annotatable,
1232                               fld: &mut MacroExpander)
1233                               -> Annotatable {
1234     let (modifiers, other_attrs) = multi_modifiers(it.attrs(), fld);
1235
1236     // Update the attrs, leave everything else alone. Is this mutation really a good idea?
1237     it = it.fold_attrs(other_attrs);
1238
1239     if modifiers.is_empty() {
1240         return it
1241     }
1242
1243     for attr in &modifiers {
1244         let mname = attr.name();
1245
1246         match fld.cx.syntax_env.find(&intern(&mname)) {
1247             Some(rc) => match *rc {
1248                 MultiModifier(ref mac) => {
1249                     attr::mark_used(attr);
1250                     fld.cx.bt_push(ExpnInfo {
1251                         call_site: attr.span,
1252                         callee: NameAndSpan {
1253                             name: mname.to_string(),
1254                             format: MacroAttribute,
1255                             span: Some(attr.span),
1256                             // attributes can do whatever they like,
1257                             // for now
1258                             allow_internal_unstable: true,
1259                         }
1260                     });
1261                     it = mac.expand(fld.cx, attr.span, &*attr.node.value, it);
1262                     fld.cx.bt_pop();
1263                 }
1264                 _ => unreachable!()
1265             },
1266             _ => unreachable!()
1267         }
1268     }
1269
1270     // Expansion may have added new ItemModifiers.
1271     expand_item_multi_modifier(it, fld)
1272 }
1273
1274 #[allow(deprecated)] // This is needed because the `ItemModifier` trait is used
1275 fn expand_item_modifiers(mut it: P<ast::Item>,
1276                          fld: &mut MacroExpander)
1277                          -> P<ast::Item> {
1278     // partition the attributes into ItemModifiers and others
1279     let (modifiers, other_attrs) = modifiers(&it.attrs, fld);
1280
1281     // update the attrs, leave everything else alone. Is this mutation really a good idea?
1282     it = P(ast::Item {
1283         attrs: other_attrs,
1284         ..(*it).clone()
1285     });
1286
1287     if modifiers.is_empty() {
1288         let it = expand_item_multi_modifier(Annotatable::Item(it), fld);
1289         return it.expect_item();
1290     }
1291
1292     for attr in &modifiers {
1293         let mname = attr.name();
1294
1295         match fld.cx.syntax_env.find(&intern(&mname)) {
1296             Some(rc) => match *rc {
1297                 Modifier(ref mac) => {
1298                     attr::mark_used(attr);
1299                     fld.cx.bt_push(ExpnInfo {
1300                         call_site: attr.span,
1301                         callee: NameAndSpan {
1302                             name: mname.to_string(),
1303                             format: MacroAttribute,
1304                             span: Some(attr.span),
1305                             // attributes can do whatever they like,
1306                             // for now
1307                             allow_internal_unstable: true,
1308                         }
1309                     });
1310                     it = mac.expand(fld.cx, attr.span, &*attr.node.value, it);
1311                     fld.cx.bt_pop();
1312                 }
1313                 _ => unreachable!()
1314             },
1315             _ => unreachable!()
1316         }
1317     }
1318
1319     // Expansion may have added new ItemModifiers.
1320     // It is possible, that an item modifier could expand to a multi-modifier or
1321     // vice versa. In this case we will expand all modifiers before multi-modifiers,
1322     // which might give an odd ordering. However, I think it is unlikely that the
1323     // two kinds will be mixed, and old-style multi-modifiers are deprecated.
1324     expand_item_modifiers(it, fld)
1325 }
1326
1327 fn expand_impl_item(ii: P<ast::ImplItem>, fld: &mut MacroExpander)
1328                  -> SmallVector<P<ast::ImplItem>> {
1329     match ii.node {
1330         ast::MethodImplItem(..) => SmallVector::one(ii.map(|ii| ast::ImplItem {
1331             id: ii.id,
1332             ident: ii.ident,
1333             attrs: ii.attrs,
1334             vis: ii.vis,
1335             node: match ii.node  {
1336                 ast::MethodImplItem(sig, body) => {
1337                     let (sig, body) = expand_and_rename_method(sig, body, fld);
1338                     ast::MethodImplItem(sig, body)
1339                 }
1340                 _ => unreachable!()
1341             },
1342             span: fld.new_span(ii.span)
1343         })),
1344         ast::MacImplItem(_) => {
1345             let (span, mac) = ii.and_then(|ii| match ii.node {
1346                 ast::MacImplItem(mac) => (ii.span, mac),
1347                 _ => unreachable!()
1348             });
1349             let maybe_new_items =
1350                 expand_mac_invoc(mac, span,
1351                                  |r| r.make_impl_items(),
1352                                  |meths, mark| meths.move_map(|m| mark_impl_item(m, mark)),
1353                                  fld);
1354
1355             match maybe_new_items {
1356                 Some(impl_items) => {
1357                     // expand again if necessary
1358                     let new_items = impl_items.into_iter().flat_map(|ii| {
1359                         expand_impl_item(ii, fld).into_iter()
1360                     }).collect();
1361                     fld.cx.bt_pop();
1362                     new_items
1363                 }
1364                 None => SmallVector::zero()
1365             }
1366         }
1367         _ => fold::noop_fold_impl_item(ii, fld)
1368     }
1369 }
1370
1371 /// Given a fn_decl and a block and a MacroExpander, expand the fn_decl, then use the
1372 /// PatIdents in its arguments to perform renaming in the FnDecl and
1373 /// the block, returning both the new FnDecl and the new Block.
1374 fn expand_and_rename_fn_decl_and_block(fn_decl: P<ast::FnDecl>, block: P<ast::Block>,
1375                                        fld: &mut MacroExpander)
1376                                        -> (P<ast::FnDecl>, P<ast::Block>) {
1377     let expanded_decl = fld.fold_fn_decl(fn_decl);
1378     let idents = fn_decl_arg_bindings(&*expanded_decl);
1379     let renames =
1380         idents.iter().map(|id : &ast::Ident| (*id,fresh_name(id))).collect();
1381     // first, a renamer for the PatIdents, for the fn_decl:
1382     let mut rename_pat_fld = PatIdentRenamer{renames: &renames};
1383     let rewritten_fn_decl = rename_pat_fld.fold_fn_decl(expanded_decl);
1384     // now, a renamer for *all* idents, for the body:
1385     let mut rename_fld = IdentRenamer{renames: &renames};
1386     let rewritten_body = fld.fold_block(rename_fld.fold_block(block));
1387     (rewritten_fn_decl,rewritten_body)
1388 }
1389
1390 fn expand_and_rename_method(sig: ast::MethodSig, body: P<ast::Block>,
1391                             fld: &mut MacroExpander)
1392                             -> (ast::MethodSig, P<ast::Block>) {
1393     let (rewritten_fn_decl, rewritten_body)
1394         = expand_and_rename_fn_decl_and_block(sig.decl, body, fld);
1395     (ast::MethodSig {
1396         generics: fld.fold_generics(sig.generics),
1397         abi: sig.abi,
1398         explicit_self: fld.fold_explicit_self(sig.explicit_self),
1399         unsafety: sig.unsafety,
1400         constness: sig.constness,
1401         decl: rewritten_fn_decl
1402     }, rewritten_body)
1403 }
1404
1405 /// A tree-folder that performs macro expansion
1406 pub struct MacroExpander<'a, 'b:'a> {
1407     pub cx: &'a mut ExtCtxt<'b>,
1408 }
1409
1410 impl<'a, 'b> MacroExpander<'a, 'b> {
1411     pub fn new(cx: &'a mut ExtCtxt<'b>) -> MacroExpander<'a, 'b> {
1412         MacroExpander { cx: cx }
1413     }
1414 }
1415
1416 impl<'a, 'b> Folder for MacroExpander<'a, 'b> {
1417     fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
1418         expand_expr(expr, self)
1419     }
1420
1421     fn fold_pat(&mut self, pat: P<ast::Pat>) -> P<ast::Pat> {
1422         expand_pat(pat, self)
1423     }
1424
1425     fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
1426         expand_item(item, self)
1427     }
1428
1429     fn fold_item_underscore(&mut self, item: ast::Item_) -> ast::Item_ {
1430         expand_item_underscore(item, self)
1431     }
1432
1433     fn fold_stmt(&mut self, stmt: P<ast::Stmt>) -> SmallVector<P<ast::Stmt>> {
1434         expand_stmt(stmt, self)
1435     }
1436
1437     fn fold_block(&mut self, block: P<Block>) -> P<Block> {
1438         expand_block(block, self)
1439     }
1440
1441     fn fold_arm(&mut self, arm: ast::Arm) -> ast::Arm {
1442         expand_arm(arm, self)
1443     }
1444
1445     fn fold_trait_item(&mut self, i: P<ast::TraitItem>) -> SmallVector<P<ast::TraitItem>> {
1446         expand_annotatable(Annotatable::TraitItem(i), self)
1447             .into_iter().map(|i| i.expect_trait_item()).collect()
1448     }
1449
1450     fn fold_impl_item(&mut self, i: P<ast::ImplItem>) -> SmallVector<P<ast::ImplItem>> {
1451         expand_annotatable(Annotatable::ImplItem(i), self)
1452             .into_iter().map(|i| i.expect_impl_item()).collect()
1453     }
1454
1455     fn new_span(&mut self, span: Span) -> Span {
1456         new_span(self.cx, span)
1457     }
1458 }
1459
1460 fn new_span(cx: &ExtCtxt, sp: Span) -> Span {
1461     /* this discards information in the case of macro-defining macros */
1462     Span {
1463         lo: sp.lo,
1464         hi: sp.hi,
1465         expn_id: cx.backtrace(),
1466     }
1467 }
1468
1469 pub struct ExpansionConfig<'feat> {
1470     pub crate_name: String,
1471     pub features: Option<&'feat Features>,
1472     pub recursion_limit: usize,
1473     pub trace_mac: bool,
1474 }
1475
1476 macro_rules! feature_tests {
1477     ($( fn $getter:ident = $field:ident, )*) => {
1478         $(
1479             pub fn $getter(&self) -> bool {
1480                 match self.features {
1481                     Some(&Features { $field: true, .. }) => true,
1482                     _ => false,
1483                 }
1484             }
1485         )*
1486     }
1487 }
1488
1489 impl<'feat> ExpansionConfig<'feat> {
1490     pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1491         ExpansionConfig {
1492             crate_name: crate_name,
1493             features: None,
1494             recursion_limit: 64,
1495             trace_mac: false,
1496         }
1497     }
1498
1499     feature_tests! {
1500         fn enable_quotes = allow_quote,
1501         fn enable_asm = allow_asm,
1502         fn enable_log_syntax = allow_log_syntax,
1503         fn enable_concat_idents = allow_concat_idents,
1504         fn enable_trace_macros = allow_trace_macros,
1505         fn enable_allow_internal_unstable = allow_internal_unstable,
1506         fn enable_custom_derive = allow_custom_derive,
1507     }
1508 }
1509
1510 pub fn expand_crate<'feat>(parse_sess: &parse::ParseSess,
1511                            cfg: ExpansionConfig<'feat>,
1512                            // these are the macros being imported to this crate:
1513                            imported_macros: Vec<ast::MacroDef>,
1514                            user_exts: Vec<NamedSyntaxExtension>,
1515                            c: Crate) -> Crate {
1516     let mut cx = ExtCtxt::new(parse_sess, c.config.clone(), cfg);
1517     cx.use_std = std_inject::use_std(&c);
1518
1519     let mut expander = MacroExpander::new(&mut cx);
1520
1521     for def in imported_macros {
1522         expander.cx.insert_macro(def);
1523     }
1524
1525     for (name, extension) in user_exts {
1526         expander.cx.syntax_env.insert(name, extension);
1527     }
1528
1529     let mut ret = expander.fold_crate(c);
1530     ret.exported_macros = expander.cx.exported_macros.clone();
1531     parse_sess.span_diagnostic.handler().abort_if_errors();
1532     return ret;
1533 }
1534
1535 // HYGIENIC CONTEXT EXTENSION:
1536 // all of these functions are for walking over
1537 // ASTs and making some change to the context of every
1538 // element that has one. a CtxtFn is a trait-ified
1539 // version of a closure in (SyntaxContext -> SyntaxContext).
1540 // the ones defined here include:
1541 // Marker - add a mark to a context
1542
1543 // A Marker adds the given mark to the syntax context
1544 struct Marker { mark: Mrk }
1545
1546 impl Folder for Marker {
1547     fn fold_ident(&mut self, id: Ident) -> Ident {
1548         ast::Ident {
1549             name: id.name,
1550             ctxt: mtwt::apply_mark(self.mark, id.ctxt)
1551         }
1552     }
1553     fn fold_mac(&mut self, Spanned {node, span}: ast::Mac) -> ast::Mac {
1554         Spanned {
1555             node: match node {
1556                 MacInvocTT(path, tts, ctxt) => {
1557                     MacInvocTT(self.fold_path(path),
1558                                self.fold_tts(&tts[..]),
1559                                mtwt::apply_mark(self.mark, ctxt))
1560                 }
1561             },
1562             span: span,
1563         }
1564     }
1565 }
1566
1567 // apply a given mark to the given token trees. Used prior to expansion of a macro.
1568 fn mark_tts(tts: &[TokenTree], m: Mrk) -> Vec<TokenTree> {
1569     noop_fold_tts(tts, &mut Marker{mark:m})
1570 }
1571
1572 // apply a given mark to the given expr. Used following the expansion of a macro.
1573 fn mark_expr(expr: P<ast::Expr>, m: Mrk) -> P<ast::Expr> {
1574     Marker{mark:m}.fold_expr(expr)
1575 }
1576
1577 // apply a given mark to the given pattern. Used following the expansion of a macro.
1578 fn mark_pat(pat: P<ast::Pat>, m: Mrk) -> P<ast::Pat> {
1579     Marker{mark:m}.fold_pat(pat)
1580 }
1581
1582 // apply a given mark to the given stmt. Used following the expansion of a macro.
1583 fn mark_stmt(stmt: P<ast::Stmt>, m: Mrk) -> P<ast::Stmt> {
1584     Marker{mark:m}.fold_stmt(stmt)
1585         .expect_one("marking a stmt didn't return exactly one stmt")
1586 }
1587
1588 // apply a given mark to the given item. Used following the expansion of a macro.
1589 fn mark_item(expr: P<ast::Item>, m: Mrk) -> P<ast::Item> {
1590     Marker{mark:m}.fold_item(expr)
1591         .expect_one("marking an item didn't return exactly one item")
1592 }
1593
1594 // apply a given mark to the given item. Used following the expansion of a macro.
1595 fn mark_impl_item(ii: P<ast::ImplItem>, m: Mrk) -> P<ast::ImplItem> {
1596     Marker{mark:m}.fold_impl_item(ii)
1597         .expect_one("marking an impl item didn't return exactly one impl item")
1598 }
1599
1600 /// Check that there are no macro invocations left in the AST:
1601 pub fn check_for_macros(sess: &parse::ParseSess, krate: &ast::Crate) {
1602     visit::walk_crate(&mut MacroExterminator{sess:sess}, krate);
1603 }
1604
1605 /// A visitor that ensures that no macro invocations remain in an AST.
1606 struct MacroExterminator<'a>{
1607     sess: &'a parse::ParseSess
1608 }
1609
1610 impl<'a, 'v> Visitor<'v> for MacroExterminator<'a> {
1611     fn visit_mac(&mut self, mac: &ast::Mac) {
1612         self.sess.span_diagnostic.span_bug(mac.span,
1613                                            "macro exterminator: expected AST \
1614                                            with no macro invocations");
1615     }
1616 }
1617
1618
1619 #[cfg(test)]
1620 mod tests {
1621     use super::{pattern_bindings, expand_crate};
1622     use super::{PatIdentFinder, IdentRenamer, PatIdentRenamer, ExpansionConfig};
1623     use ast;
1624     use ast::Name;
1625     use codemap;
1626     use ext::mtwt;
1627     use fold::Folder;
1628     use parse;
1629     use parse::token;
1630     use util::parser_testing::{string_to_parser};
1631     use util::parser_testing::{string_to_pat, string_to_crate, strs_to_idents};
1632     use visit;
1633     use visit::Visitor;
1634
1635     // a visitor that extracts the paths
1636     // from a given thingy and puts them in a mutable
1637     // array (passed in to the traversal)
1638     #[derive(Clone)]
1639     struct PathExprFinderContext {
1640         path_accumulator: Vec<ast::Path> ,
1641     }
1642
1643     impl<'v> Visitor<'v> for PathExprFinderContext {
1644         fn visit_expr(&mut self, expr: &ast::Expr) {
1645             if let ast::ExprPath(None, ref p) = expr.node {
1646                 self.path_accumulator.push(p.clone());
1647             }
1648             visit::walk_expr(self, expr);
1649         }
1650     }
1651
1652     // find the variable references in a crate
1653     fn crate_varrefs(the_crate : &ast::Crate) -> Vec<ast::Path> {
1654         let mut path_finder = PathExprFinderContext{path_accumulator:Vec::new()};
1655         visit::walk_crate(&mut path_finder, the_crate);
1656         path_finder.path_accumulator
1657     }
1658
1659     /// A Visitor that extracts the identifiers from a thingy.
1660     // as a side note, I'm starting to want to abstract over these....
1661     struct IdentFinder {
1662         ident_accumulator: Vec<ast::Ident>
1663     }
1664
1665     impl<'v> Visitor<'v> for IdentFinder {
1666         fn visit_ident(&mut self, _: codemap::Span, id: ast::Ident){
1667             self.ident_accumulator.push(id);
1668         }
1669     }
1670
1671     /// Find the idents in a crate
1672     fn crate_idents(the_crate: &ast::Crate) -> Vec<ast::Ident> {
1673         let mut ident_finder = IdentFinder{ident_accumulator: Vec::new()};
1674         visit::walk_crate(&mut ident_finder, the_crate);
1675         ident_finder.ident_accumulator
1676     }
1677
1678     // these following tests are quite fragile, in that they don't test what
1679     // *kind* of failure occurs.
1680
1681     fn test_ecfg() -> ExpansionConfig<'static> {
1682         ExpansionConfig::default("test".to_string())
1683     }
1684
1685     // make sure that macros can't escape fns
1686     #[should_panic]
1687     #[test] fn macros_cant_escape_fns_test () {
1688         let src = "fn bogus() {macro_rules! z (() => (3+4));}\
1689                    fn inty() -> i32 { z!() }".to_string();
1690         let sess = parse::ParseSess::new();
1691         let crate_ast = parse::parse_crate_from_source_str(
1692             "<test>".to_string(),
1693             src,
1694             Vec::new(), &sess);
1695         // should fail:
1696         expand_crate(&sess,test_ecfg(),vec!(),vec!(),crate_ast);
1697     }
1698
1699     // make sure that macros can't escape modules
1700     #[should_panic]
1701     #[test] fn macros_cant_escape_mods_test () {
1702         let src = "mod foo {macro_rules! z (() => (3+4));}\
1703                    fn inty() -> i32 { z!() }".to_string();
1704         let sess = parse::ParseSess::new();
1705         let crate_ast = parse::parse_crate_from_source_str(
1706             "<test>".to_string(),
1707             src,
1708             Vec::new(), &sess);
1709         expand_crate(&sess,test_ecfg(),vec!(),vec!(),crate_ast);
1710     }
1711
1712     // macro_use modules should allow macros to escape
1713     #[test] fn macros_can_escape_flattened_mods_test () {
1714         let src = "#[macro_use] mod foo {macro_rules! z (() => (3+4));}\
1715                    fn inty() -> i32 { z!() }".to_string();
1716         let sess = parse::ParseSess::new();
1717         let crate_ast = parse::parse_crate_from_source_str(
1718             "<test>".to_string(),
1719             src,
1720             Vec::new(), &sess);
1721         expand_crate(&sess, test_ecfg(), vec!(), vec!(), crate_ast);
1722     }
1723
1724     fn expand_crate_str(crate_str: String) -> ast::Crate {
1725         let ps = parse::ParseSess::new();
1726         let crate_ast = panictry!(string_to_parser(&ps, crate_str).parse_crate_mod());
1727         // the cfg argument actually does matter, here...
1728         expand_crate(&ps,test_ecfg(),vec!(),vec!(),crate_ast)
1729     }
1730
1731     // find the pat_ident paths in a crate
1732     fn crate_bindings(the_crate : &ast::Crate) -> Vec<ast::Ident> {
1733         let mut name_finder = PatIdentFinder{ident_accumulator:Vec::new()};
1734         visit::walk_crate(&mut name_finder, the_crate);
1735         name_finder.ident_accumulator
1736     }
1737
1738     #[test] fn macro_tokens_should_match(){
1739         expand_crate_str(
1740             "macro_rules! m((a)=>(13)) ;fn main(){m!(a);}".to_string());
1741     }
1742
1743     // should be able to use a bound identifier as a literal in a macro definition:
1744     #[test] fn self_macro_parsing(){
1745         expand_crate_str(
1746             "macro_rules! foo ((zz) => (287;));
1747             fn f(zz: i32) {foo!(zz);}".to_string()
1748             );
1749     }
1750
1751     // renaming tests expand a crate and then check that the bindings match
1752     // the right varrefs. The specification of the test case includes the
1753     // text of the crate, and also an array of arrays.  Each element in the
1754     // outer array corresponds to a binding in the traversal of the AST
1755     // induced by visit.  Each of these arrays contains a list of indexes,
1756     // interpreted as the varrefs in the varref traversal that this binding
1757     // should match.  So, for instance, in a program with two bindings and
1758     // three varrefs, the array [[1, 2], [0]] would indicate that the first
1759     // binding should match the second two varrefs, and the second binding
1760     // should match the first varref.
1761     //
1762     // Put differently; this is a sparse representation of a boolean matrix
1763     // indicating which bindings capture which identifiers.
1764     //
1765     // Note also that this matrix is dependent on the implicit ordering of
1766     // the bindings and the varrefs discovered by the name-finder and the path-finder.
1767     //
1768     // The comparisons are done post-mtwt-resolve, so we're comparing renamed
1769     // names; differences in marks don't matter any more.
1770     //
1771     // oog... I also want tests that check "bound-identifier-=?". That is,
1772     // not just "do these have the same name", but "do they have the same
1773     // name *and* the same marks"? Understanding this is really pretty painful.
1774     // in principle, you might want to control this boolean on a per-varref basis,
1775     // but that would make things even harder to understand, and might not be
1776     // necessary for thorough testing.
1777     type RenamingTest = (&'static str, Vec<Vec<usize>>, bool);
1778
1779     #[test]
1780     fn automatic_renaming () {
1781         let tests: Vec<RenamingTest> =
1782             vec!(// b & c should get new names throughout, in the expr too:
1783                 ("fn a() -> i32 { let b = 13; let c = b; b+c }",
1784                  vec!(vec!(0,1),vec!(2)), false),
1785                 // both x's should be renamed (how is this causing a bug?)
1786                 ("fn main () {let x: i32 = 13;x;}",
1787                  vec!(vec!(0)), false),
1788                 // the use of b after the + should be renamed, the other one not:
1789                 ("macro_rules! f (($x:ident) => (b + $x)); fn a() -> i32 { let b = 13; f!(b)}",
1790                  vec!(vec!(1)), false),
1791                 // the b before the plus should not be renamed (requires marks)
1792                 ("macro_rules! f (($x:ident) => ({let b=9; ($x + b)})); fn a() -> i32 { f!(b)}",
1793                  vec!(vec!(1)), false),
1794                 // the marks going in and out of letty should cancel, allowing that $x to
1795                 // capture the one following the semicolon.
1796                 // this was an awesome test case, and caught a *lot* of bugs.
1797                 ("macro_rules! letty(($x:ident) => (let $x = 15;));
1798                   macro_rules! user(($x:ident) => ({letty!($x); $x}));
1799                   fn main() -> i32 {user!(z)}",
1800                  vec!(vec!(0)), false)
1801                 );
1802         for (idx,s) in tests.iter().enumerate() {
1803             run_renaming_test(s,idx);
1804         }
1805     }
1806
1807     // no longer a fixme #8062: this test exposes a *potential* bug; our system does
1808     // not behave exactly like MTWT, but a conversation with Matthew Flatt
1809     // suggests that this can only occur in the presence of local-expand, which
1810     // we have no plans to support. ... unless it's needed for item hygiene....
1811     #[ignore]
1812     #[test]
1813     fn issue_8062(){
1814         run_renaming_test(
1815             &("fn main() {let hrcoo = 19; macro_rules! getx(()=>(hrcoo)); getx!();}",
1816               vec!(vec!(0)), true), 0)
1817     }
1818
1819     // FIXME #6994:
1820     // the z flows into and out of two macros (g & f) along one path, and one
1821     // (just g) along the other, so the result of the whole thing should
1822     // be "let z_123 = 3; z_123"
1823     #[ignore]
1824     #[test]
1825     fn issue_6994(){
1826         run_renaming_test(
1827             &("macro_rules! g (($x:ident) =>
1828               ({macro_rules! f(($y:ident)=>({let $y=3;$x}));f!($x)}));
1829               fn a(){g!(z)}",
1830               vec!(vec!(0)),false),
1831             0)
1832     }
1833
1834     // match variable hygiene. Should expand into
1835     // fn z() {match 8 {x_1 => {match 9 {x_2 | x_2 if x_2 == x_1 => x_2 + x_1}}}}
1836     #[test]
1837     fn issue_9384(){
1838         run_renaming_test(
1839             &("macro_rules! bad_macro (($ex:expr) => ({match 9 {x | x if x == $ex => x + $ex}}));
1840               fn z() {match 8 {x => bad_macro!(x)}}",
1841               // NB: the third "binding" is the repeat of the second one.
1842               vec!(vec!(1,3),vec!(0,2),vec!(0,2)),
1843               true),
1844             0)
1845     }
1846
1847     // interpolated nodes weren't getting labeled.
1848     // should expand into
1849     // fn main(){let g1_1 = 13; g1_1}}
1850     #[test]
1851     fn pat_expand_issue_15221(){
1852         run_renaming_test(
1853             &("macro_rules! inner ( ($e:pat ) => ($e));
1854               macro_rules! outer ( ($e:pat ) => (inner!($e)));
1855               fn main() { let outer!(g) = 13; g;}",
1856               vec!(vec!(0)),
1857               true),
1858             0)
1859     }
1860
1861     // create a really evil test case where a $x appears inside a binding of $x
1862     // but *shouldn't* bind because it was inserted by a different macro....
1863     // can't write this test case until we have macro-generating macros.
1864
1865     // method arg hygiene
1866     // method expands to fn get_x(&self_0, x_1: i32) {self_0 + self_2 + x_3 + x_1}
1867     #[test]
1868     fn method_arg_hygiene(){
1869         run_renaming_test(
1870             &("macro_rules! inject_x (()=>(x));
1871               macro_rules! inject_self (()=>(self));
1872               struct A;
1873               impl A{fn get_x(&self, x: i32) {self + inject_self!() + inject_x!() + x;} }",
1874               vec!(vec!(0),vec!(3)),
1875               true),
1876             0)
1877     }
1878
1879     // ooh, got another bite?
1880     // expands to struct A; impl A {fn thingy(&self_1) {self_1;}}
1881     #[test]
1882     fn method_arg_hygiene_2(){
1883         run_renaming_test(
1884             &("struct A;
1885               macro_rules! add_method (($T:ty) =>
1886               (impl $T {  fn thingy(&self) {self;} }));
1887               add_method!(A);",
1888               vec!(vec!(0)),
1889               true),
1890             0)
1891     }
1892
1893     // item fn hygiene
1894     // expands to fn q(x_1: i32){fn g(x_2: i32){x_2 + x_1};}
1895     #[test]
1896     fn issue_9383(){
1897         run_renaming_test(
1898             &("macro_rules! bad_macro (($ex:expr) => (fn g(x: i32){ x + $ex }));
1899               fn q(x: i32) { bad_macro!(x); }",
1900               vec!(vec!(1),vec!(0)),true),
1901             0)
1902     }
1903
1904     // closure arg hygiene (ExprClosure)
1905     // expands to fn f(){(|x_1 : i32| {(x_2 + x_1)})(3);}
1906     #[test]
1907     fn closure_arg_hygiene(){
1908         run_renaming_test(
1909             &("macro_rules! inject_x (()=>(x));
1910             fn f(){(|x : i32| {(inject_x!() + x)})(3);}",
1911               vec!(vec!(1)),
1912               true),
1913             0)
1914     }
1915
1916     // macro_rules in method position. Sadly, unimplemented.
1917     #[test]
1918     fn macro_in_method_posn(){
1919         expand_crate_str(
1920             "macro_rules! my_method (() => (fn thirteen(&self) -> i32 {13}));
1921             struct A;
1922             impl A{ my_method!(); }
1923             fn f(){A.thirteen;}".to_string());
1924     }
1925
1926     // another nested macro
1927     // expands to impl Entries {fn size_hint(&self_1) {self_1;}
1928     #[test]
1929     fn item_macro_workaround(){
1930         run_renaming_test(
1931             &("macro_rules! item { ($i:item) => {$i}}
1932               struct Entries;
1933               macro_rules! iterator_impl {
1934               () => { item!( impl Entries { fn size_hint(&self) { self;}});}}
1935               iterator_impl! { }",
1936               vec!(vec!(0)), true),
1937             0)
1938     }
1939
1940     // run one of the renaming tests
1941     fn run_renaming_test(t: &RenamingTest, test_idx: usize) {
1942         let invalid_name = token::special_idents::invalid.name;
1943         let (teststr, bound_connections, bound_ident_check) = match *t {
1944             (ref str,ref conns, bic) => (str.to_string(), conns.clone(), bic)
1945         };
1946         let cr = expand_crate_str(teststr.to_string());
1947         let bindings = crate_bindings(&cr);
1948         let varrefs = crate_varrefs(&cr);
1949
1950         // must be one check clause for each binding:
1951         assert_eq!(bindings.len(),bound_connections.len());
1952         for (binding_idx,shouldmatch) in bound_connections.iter().enumerate() {
1953             let binding_name = mtwt::resolve(bindings[binding_idx]);
1954             let binding_marks = mtwt::marksof(bindings[binding_idx].ctxt, invalid_name);
1955             // shouldmatch can't name varrefs that don't exist:
1956             assert!((shouldmatch.is_empty()) ||
1957                     (varrefs.len() > *shouldmatch.iter().max().unwrap()));
1958             for (idx,varref) in varrefs.iter().enumerate() {
1959                 let print_hygiene_debug_info = || {
1960                     // good lord, you can't make a path with 0 segments, can you?
1961                     let final_varref_ident = match varref.segments.last() {
1962                         Some(pathsegment) => pathsegment.identifier,
1963                         None => panic!("varref with 0 path segments?")
1964                     };
1965                     let varref_name = mtwt::resolve(final_varref_ident);
1966                     let varref_idents : Vec<ast::Ident>
1967                         = varref.segments.iter().map(|s| s.identifier)
1968                         .collect();
1969                     println!("varref #{}: {:?}, resolves to {}",idx, varref_idents, varref_name);
1970                     let string = token::get_ident(final_varref_ident);
1971                     println!("varref's first segment's string: \"{}\"", &string[..]);
1972                     println!("binding #{}: {}, resolves to {}",
1973                              binding_idx, bindings[binding_idx], binding_name);
1974                     mtwt::with_sctable(|x| mtwt::display_sctable(x));
1975                 };
1976                 if shouldmatch.contains(&idx) {
1977                     // it should be a path of length 1, and it should
1978                     // be free-identifier=? or bound-identifier=? to the given binding
1979                     assert_eq!(varref.segments.len(),1);
1980                     let varref_name = mtwt::resolve(varref.segments[0].identifier);
1981                     let varref_marks = mtwt::marksof(varref.segments[0]
1982                                                            .identifier
1983                                                            .ctxt,
1984                                                      invalid_name);
1985                     if !(varref_name==binding_name) {
1986                         println!("uh oh, should match but doesn't:");
1987                         print_hygiene_debug_info();
1988                     }
1989                     assert_eq!(varref_name,binding_name);
1990                     if bound_ident_check {
1991                         // we're checking bound-identifier=?, and the marks
1992                         // should be the same, too:
1993                         assert_eq!(varref_marks,binding_marks.clone());
1994                     }
1995                 } else {
1996                     let varref_name = mtwt::resolve(varref.segments[0].identifier);
1997                     let fail = (varref.segments.len() == 1)
1998                         && (varref_name == binding_name);
1999                     // temp debugging:
2000                     if fail {
2001                         println!("failure on test {}",test_idx);
2002                         println!("text of test case: \"{}\"", teststr);
2003                         println!("");
2004                         println!("uh oh, matches but shouldn't:");
2005                         print_hygiene_debug_info();
2006                     }
2007                     assert!(!fail);
2008                 }
2009             }
2010         }
2011     }
2012
2013     #[test]
2014     fn fmt_in_macro_used_inside_module_macro() {
2015         let crate_str = "macro_rules! fmt_wrap(($b:expr)=>($b.to_string()));
2016 macro_rules! foo_module (() => (mod generated { fn a() { let xx = 147; fmt_wrap!(xx);}}));
2017 foo_module!();
2018 ".to_string();
2019         let cr = expand_crate_str(crate_str);
2020         // find the xx binding
2021         let bindings = crate_bindings(&cr);
2022         let cxbinds: Vec<&ast::Ident> =
2023             bindings.iter().filter(|b| {
2024                 let ident = token::get_ident(**b);
2025                 let string = &ident[..];
2026                 "xx" == string
2027             }).collect();
2028         let cxbinds: &[&ast::Ident] = &cxbinds[..];
2029         let cxbind = match (cxbinds.len(), cxbinds.get(0)) {
2030             (1, Some(b)) => *b,
2031             _ => panic!("expected just one binding for ext_cx")
2032         };
2033         let resolved_binding = mtwt::resolve(*cxbind);
2034         let varrefs = crate_varrefs(&cr);
2035
2036         // the xx binding should bind all of the xx varrefs:
2037         for (idx,v) in varrefs.iter().filter(|p| {
2038             p.segments.len() == 1
2039             && "xx" == &*token::get_ident(p.segments[0].identifier)
2040         }).enumerate() {
2041             if mtwt::resolve(v.segments[0].identifier) != resolved_binding {
2042                 println!("uh oh, xx binding didn't match xx varref:");
2043                 println!("this is xx varref \\# {}", idx);
2044                 println!("binding: {}", cxbind);
2045                 println!("resolves to: {}", resolved_binding);
2046                 println!("varref: {}", v.segments[0].identifier);
2047                 println!("resolves to: {}",
2048                          mtwt::resolve(v.segments[0].identifier));
2049                 mtwt::with_sctable(|x| mtwt::display_sctable(x));
2050             }
2051             assert_eq!(mtwt::resolve(v.segments[0].identifier),
2052                        resolved_binding);
2053         };
2054     }
2055
2056     #[test]
2057     fn pat_idents(){
2058         let pat = string_to_pat(
2059             "(a,Foo{x:c @ (b,9),y:Bar(4,d)})".to_string());
2060         let idents = pattern_bindings(&*pat);
2061         assert_eq!(idents, strs_to_idents(vec!("a","c","b","d")));
2062     }
2063
2064     // test the list of identifier patterns gathered by the visitor. Note that
2065     // 'None' is listed as an identifier pattern because we don't yet know that
2066     // it's the name of a 0-ary variant, and that 'i' appears twice in succession.
2067     #[test]
2068     fn crate_bindings_test(){
2069         let the_crate = string_to_crate("fn main (a: i32) -> i32 {|b| {
2070         match 34 {None => 3, Some(i) | i => j, Foo{k:z,l:y} => \"banana\"}} }".to_string());
2071         let idents = crate_bindings(&the_crate);
2072         assert_eq!(idents, strs_to_idents(vec!("a","b","None","i","i","z","y")));
2073     }
2074
2075     // test the IdentRenamer directly
2076     #[test]
2077     fn ident_renamer_test () {
2078         let the_crate = string_to_crate("fn f(x: i32){let x = x; x}".to_string());
2079         let f_ident = token::str_to_ident("f");
2080         let x_ident = token::str_to_ident("x");
2081         let int_ident = token::str_to_ident("i32");
2082         let renames = vec!((x_ident,Name(16)));
2083         let mut renamer = IdentRenamer{renames: &renames};
2084         let renamed_crate = renamer.fold_crate(the_crate);
2085         let idents = crate_idents(&renamed_crate);
2086         let resolved : Vec<ast::Name> = idents.iter().map(|id| mtwt::resolve(*id)).collect();
2087         assert_eq!(resolved, [f_ident.name,Name(16),int_ident.name,Name(16),Name(16),Name(16)]);
2088     }
2089
2090     // test the PatIdentRenamer; only PatIdents get renamed
2091     #[test]
2092     fn pat_ident_renamer_test () {
2093         let the_crate = string_to_crate("fn f(x: i32){let x = x; x}".to_string());
2094         let f_ident = token::str_to_ident("f");
2095         let x_ident = token::str_to_ident("x");
2096         let int_ident = token::str_to_ident("i32");
2097         let renames = vec!((x_ident,Name(16)));
2098         let mut renamer = PatIdentRenamer{renames: &renames};
2099         let renamed_crate = renamer.fold_crate(the_crate);
2100         let idents = crate_idents(&renamed_crate);
2101         let resolved : Vec<ast::Name> = idents.iter().map(|id| mtwt::resolve(*id)).collect();
2102         let x_name = x_ident.name;
2103         assert_eq!(resolved, [f_ident.name,Name(16),int_ident.name,Name(16),x_name,x_name]);
2104     }
2105 }