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