]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/expand.rs
auto merge of #17182 : luqmana/rust/rnp, r=alexcrichton
[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::{P, Block, Crate, DeclLocal, ExprMac, PatMac};
12 use ast::{Local, Ident, MacInvocTT};
13 use ast::{ItemMac, Mrk, Stmt, StmtDecl, StmtMac, StmtExpr, StmtSemi};
14 use ast::TokenTree;
15 use ast;
16 use ext::mtwt;
17 use ext::build::AstBuilder;
18 use attr;
19 use attr::AttrMetaMethods;
20 use codemap;
21 use codemap::{Span, Spanned, ExpnInfo, NameAndSpan, MacroBang, MacroAttribute};
22 use ext::base::*;
23 use fold;
24 use fold::*;
25 use parse;
26 use parse::token::{fresh_mark, fresh_name, intern};
27 use parse::token;
28 use visit;
29 use visit::Visitor;
30 use util::small_vector::SmallVector;
31
32 use std::gc::{Gc, GC};
33
34 enum Either<L,R> {
35     Left(L),
36     Right(R)
37 }
38
39 fn expand_expr(e: Gc<ast::Expr>, fld: &mut MacroExpander) -> Gc<ast::Expr> {
40     match e.node {
41         // expr_mac should really be expr_ext or something; it's the
42         // entry-point for all syntax extensions.
43         ExprMac(ref mac) => {
44             let expanded_expr = match expand_mac_invoc(mac,&e.span,
45                                                        |r|{r.make_expr()},
46                                                        |expr,fm|{mark_expr(expr,fm)},
47                                                        fld) {
48                 Some(expr) => expr,
49                 None => {
50                     return DummyResult::raw_expr(e.span);
51                 }
52             };
53
54             // Keep going, outside-in.
55             //
56             // FIXME(pcwalton): Is it necessary to clone the
57             // node here?
58             let fully_expanded =
59                 fld.fold_expr(expanded_expr).node.clone();
60             fld.cx.bt_pop();
61
62             box(GC) ast::Expr {
63                 id: ast::DUMMY_NODE_ID,
64                 node: fully_expanded,
65                 span: e.span,
66             }
67         }
68
69         ast::ExprWhile(cond, body, opt_ident) => {
70             let cond = fld.fold_expr(cond);
71             let (body, opt_ident) = expand_loop_block(body, opt_ident, fld);
72             fld.cx.expr(e.span, ast::ExprWhile(cond, body, opt_ident))
73         }
74
75         ast::ExprLoop(loop_block, opt_ident) => {
76             let (loop_block, opt_ident) = expand_loop_block(loop_block, opt_ident, fld);
77             fld.cx.expr(e.span, ast::ExprLoop(loop_block, opt_ident))
78         }
79
80         ast::ExprForLoop(pat, head, body, opt_ident) => {
81             let pat = fld.fold_pat(pat);
82             let head = fld.fold_expr(head);
83             let (body, opt_ident) = expand_loop_block(body, opt_ident, fld);
84             fld.cx.expr(e.span, ast::ExprForLoop(pat, head, body, opt_ident))
85         }
86
87         ast::ExprFnBlock(capture_clause, fn_decl, block) => {
88             let (rewritten_fn_decl, rewritten_block)
89                 = expand_and_rename_fn_decl_and_block(&*fn_decl, block, fld);
90             let new_node = ast::ExprFnBlock(capture_clause,
91                                             rewritten_fn_decl,
92                                             rewritten_block);
93             box(GC) ast::Expr{id:e.id, node: new_node, span: fld.new_span(e.span)}
94         }
95
96         ast::ExprProc(fn_decl, block) => {
97             let (rewritten_fn_decl, rewritten_block)
98                 = expand_and_rename_fn_decl_and_block(&*fn_decl, block, fld);
99             let new_node = ast::ExprProc(rewritten_fn_decl, rewritten_block);
100             box(GC) ast::Expr{id:e.id, node: new_node, span: fld.new_span(e.span)}
101         }
102
103         _ => noop_fold_expr(e, fld)
104     }
105 }
106
107 /// Expand a (not-ident-style) macro invocation. Returns the result
108 /// of expansion and the mark which must be applied to the result.
109 /// Our current interface doesn't allow us to apply the mark to the
110 /// result until after calling make_expr, make_items, etc.
111 fn expand_mac_invoc<T>(mac: &ast::Mac, span: &codemap::Span,
112                        parse_thunk: |Box<MacResult>|->Option<T>,
113                        mark_thunk: |T,Mrk|->T,
114                        fld: &mut MacroExpander)
115                        -> Option<T>
116 {
117     match (*mac).node {
118         // it would almost certainly be cleaner to pass the whole
119         // macro invocation in, rather than pulling it apart and
120         // marking the tts and the ctxt separately. This also goes
121         // for the other three macro invocation chunks of code
122         // in this file.
123         // Token-tree macros:
124         MacInvocTT(ref pth, ref tts, _) => {
125             if pth.segments.len() > 1u {
126                 fld.cx.span_err(pth.span,
127                                 "expected macro name without module \
128                                 separators");
129                 // let compilation continue
130                 return None;
131             }
132             let extname = pth.segments.get(0).identifier;
133             let extnamestr = token::get_ident(extname);
134             match fld.cx.syntax_env.find(&extname.name) {
135                 None => {
136                     fld.cx.span_err(
137                         pth.span,
138                         format!("macro undefined: '{}!'",
139                                 extnamestr.get()).as_slice());
140
141                     // let compilation continue
142                     None
143                 }
144                 Some(rc) => match *rc {
145                     NormalTT(ref expandfun, exp_span) => {
146                         fld.cx.bt_push(ExpnInfo {
147                                 call_site: *span,
148                                 callee: NameAndSpan {
149                                     name: extnamestr.get().to_string(),
150                                     format: MacroBang,
151                                     span: exp_span,
152                                 },
153                             });
154                         let fm = fresh_mark();
155                         let marked_before = mark_tts(tts.as_slice(), fm);
156
157                         // The span that we pass to the expanders we want to
158                         // be the root of the call stack. That's the most
159                         // relevant span and it's the actual invocation of
160                         // the macro.
161                         let mac_span = original_span(fld.cx);
162
163                         let opt_parsed = {
164                             let expanded = expandfun.expand(fld.cx,
165                                                             mac_span.call_site,
166                                                             marked_before.as_slice());
167                             parse_thunk(expanded)
168                         };
169                         let parsed = match opt_parsed {
170                             Some(e) => e,
171                             None => {
172                                 fld.cx.span_err(
173                                     pth.span,
174                                     format!("non-expression macro in expression position: {}",
175                                             extnamestr.get().as_slice()
176                                             ).as_slice());
177                                 return None;
178                             }
179                         };
180                         Some(mark_thunk(parsed,fm))
181                     }
182                     _ => {
183                         fld.cx.span_err(
184                             pth.span,
185                             format!("'{}' is not a tt-style macro",
186                                     extnamestr.get()).as_slice());
187                         None
188                     }
189                 }
190             }
191         }
192     }
193 }
194
195 /// Rename loop label and expand its loop body
196 ///
197 /// The renaming procedure for loop is different in the sense that the loop
198 /// body is in a block enclosed by loop head so the renaming of loop label
199 /// must be propagated to the enclosed context.
200 fn expand_loop_block(loop_block: P<Block>,
201                      opt_ident: Option<Ident>,
202                      fld: &mut MacroExpander) -> (P<Block>, Option<Ident>) {
203     match opt_ident {
204         Some(label) => {
205             let new_label = fresh_name(&label);
206             let rename = (label, new_label);
207
208             // The rename *must not* be added to the pending list of current
209             // syntax context otherwise an unrelated `break` or `continue` in
210             // the same context will pick that up in the deferred renaming pass
211             // and be renamed incorrectly.
212             let mut rename_list = vec!(rename);
213             let mut rename_fld = IdentRenamer{renames: &mut rename_list};
214             let renamed_ident = rename_fld.fold_ident(label);
215
216             // The rename *must* be added to the enclosed syntax context for
217             // `break` or `continue` to pick up because by definition they are
218             // in a block enclosed by loop head.
219             fld.cx.syntax_env.push_frame();
220             fld.cx.syntax_env.info().pending_renames.push(rename);
221             let expanded_block = expand_block_elts(&*loop_block, fld);
222             fld.cx.syntax_env.pop_frame();
223
224             (expanded_block, Some(renamed_ident))
225         }
226         None => (fld.fold_block(loop_block), opt_ident)
227     }
228 }
229
230 // eval $e with a new exts frame.
231 // must be a macro so that $e isn't evaluated too early.
232 macro_rules! with_exts_frame (
233     ($extsboxexpr:expr,$macros_escape:expr,$e:expr) =>
234     ({$extsboxexpr.push_frame();
235       $extsboxexpr.info().macros_escape = $macros_escape;
236       let result = $e;
237       $extsboxexpr.pop_frame();
238       result
239      })
240 )
241
242 // When we enter a module, record it, for the sake of `module!`
243 fn expand_item(it: Gc<ast::Item>, fld: &mut MacroExpander)
244                    -> SmallVector<Gc<ast::Item>> {
245     let it = expand_item_modifiers(it, fld);
246
247     let mut decorator_items = SmallVector::zero();
248     let mut new_attrs = Vec::new();
249     for attr in it.attrs.iter() {
250         let mname = attr.name();
251
252         match fld.cx.syntax_env.find(&intern(mname.get())) {
253             Some(rc) => match *rc {
254                 ItemDecorator(ref dec) => {
255                     attr::mark_used(attr);
256
257                     fld.cx.bt_push(ExpnInfo {
258                         call_site: attr.span,
259                         callee: NameAndSpan {
260                             name: mname.get().to_string(),
261                             format: MacroAttribute,
262                             span: None
263                         }
264                     });
265
266                     // we'd ideally decorator_items.push_all(expand_item(item, fld)),
267                     // but that double-mut-borrows fld
268                     let mut items: SmallVector<Gc<ast::Item>> = SmallVector::zero();
269                     dec.expand(fld.cx, attr.span, attr.node.value, it, |item| items.push(item));
270                     decorator_items.extend(items.move_iter()
271                         .flat_map(|item| expand_item(item, fld).move_iter()));
272
273                     fld.cx.bt_pop();
274                 }
275                 _ => new_attrs.push((*attr).clone()),
276             },
277             _ => new_attrs.push((*attr).clone()),
278         }
279     }
280
281     let mut new_items = match it.node {
282         ast::ItemMac(..) => expand_item_mac(it, fld),
283         ast::ItemMod(_) | ast::ItemForeignMod(_) => {
284             fld.cx.mod_push(it.ident);
285             let macro_escape = contains_macro_escape(new_attrs.as_slice());
286             let result = with_exts_frame!(fld.cx.syntax_env,
287                                           macro_escape,
288                                           noop_fold_item(&*it, fld));
289             fld.cx.mod_pop();
290             result
291         },
292         _ => {
293             let it = box(GC) ast::Item {
294                 attrs: new_attrs,
295                 ..(*it).clone()
296
297             };
298             noop_fold_item(&*it, fld)
299         }
300     };
301
302     new_items.push_all(decorator_items);
303     new_items
304 }
305
306 fn expand_item_modifiers(mut it: Gc<ast::Item>, fld: &mut MacroExpander)
307                          -> Gc<ast::Item> {
308     // partition the attributes into ItemModifiers and others
309     let (modifiers, other_attrs) = it.attrs.partitioned(|attr| {
310         match fld.cx.syntax_env.find(&intern(attr.name().get())) {
311             Some(rc) => match *rc { ItemModifier(_) => true, _ => false },
312             _ => false
313         }
314     });
315     // update the attrs, leave everything else alone. Is this mutation really a good idea?
316     it = box(GC) ast::Item {
317         attrs: other_attrs,
318         ..(*it).clone()
319     };
320
321     if modifiers.is_empty() {
322         return it;
323     }
324
325     for attr in modifiers.iter() {
326         let mname = attr.name();
327
328         match fld.cx.syntax_env.find(&intern(mname.get())) {
329             Some(rc) => match *rc {
330                 ItemModifier(ref mac) => {
331                     attr::mark_used(attr);
332                     fld.cx.bt_push(ExpnInfo {
333                         call_site: attr.span,
334                         callee: NameAndSpan {
335                             name: mname.get().to_string(),
336                             format: MacroAttribute,
337                             span: None,
338                         }
339                     });
340                     it = mac.expand(fld.cx, attr.span, attr.node.value, it);
341                     fld.cx.bt_pop();
342                 }
343                 _ => unreachable!()
344             },
345             _ => unreachable!()
346         }
347     }
348
349     // expansion may have added new ItemModifiers
350     expand_item_modifiers(it, fld)
351 }
352
353 /// Expand item_underscore
354 fn expand_item_underscore(item: &ast::Item_, fld: &mut MacroExpander) -> ast::Item_ {
355     match *item {
356         ast::ItemFn(decl, fn_style, abi, ref generics, body) => {
357             let (rewritten_fn_decl, rewritten_body)
358                 = expand_and_rename_fn_decl_and_block(&*decl, body, fld);
359             let expanded_generics = fold::noop_fold_generics(generics,fld);
360             ast::ItemFn(rewritten_fn_decl, fn_style, abi, expanded_generics, rewritten_body)
361         }
362         _ => noop_fold_item_underscore(&*item, fld)
363     }
364 }
365
366 // does this attribute list contain "macro_escape" ?
367 fn contains_macro_escape(attrs: &[ast::Attribute]) -> bool {
368     attr::contains_name(attrs, "macro_escape")
369 }
370
371 // Support for item-position macro invocations, exactly the same
372 // logic as for expression-position macro invocations.
373 fn expand_item_mac(it: Gc<ast::Item>, fld: &mut MacroExpander)
374                    -> SmallVector<Gc<ast::Item>>
375 {
376     let (pth, tts) = match it.node {
377         ItemMac(codemap::Spanned {
378             node: MacInvocTT(ref pth, ref tts, _),
379             ..
380         }) => {
381             (pth, (*tts).clone())
382         }
383         _ => fld.cx.span_bug(it.span, "invalid item macro invocation")
384     };
385
386     let extname = pth.segments.get(0).identifier;
387     let extnamestr = token::get_ident(extname);
388     let fm = fresh_mark();
389     let def_or_items = {
390         let expanded = match fld.cx.syntax_env.find(&extname.name) {
391             None => {
392                 fld.cx.span_err(pth.span,
393                                 format!("macro undefined: '{}!'",
394                                         extnamestr).as_slice());
395                 // let compilation continue
396                 return SmallVector::zero();
397             }
398
399             Some(rc) => match *rc {
400                 NormalTT(ref expander, span) => {
401                     if it.ident.name != parse::token::special_idents::invalid.name {
402                         fld.cx
403                             .span_err(pth.span,
404                                       format!("macro {}! expects no ident argument, \
405                                         given '{}'",
406                                       extnamestr,
407                                       token::get_ident(it.ident)).as_slice());
408                         return SmallVector::zero();
409                     }
410                     fld.cx.bt_push(ExpnInfo {
411                         call_site: it.span,
412                         callee: NameAndSpan {
413                             name: extnamestr.get().to_string(),
414                             format: MacroBang,
415                             span: span
416                         }
417                     });
418                     // mark before expansion:
419                     let marked_before = mark_tts(tts.as_slice(), fm);
420                     expander.expand(fld.cx, it.span, marked_before.as_slice())
421                 }
422                 IdentTT(ref expander, span) => {
423                     if it.ident.name == parse::token::special_idents::invalid.name {
424                         fld.cx.span_err(pth.span,
425                                         format!("macro {}! expects an ident argument",
426                                                 extnamestr.get()).as_slice());
427                         return SmallVector::zero();
428                     }
429                     fld.cx.bt_push(ExpnInfo {
430                         call_site: it.span,
431                         callee: NameAndSpan {
432                             name: extnamestr.get().to_string(),
433                             format: MacroBang,
434                             span: span
435                         }
436                     });
437                     // mark before expansion:
438                     let marked_tts = mark_tts(tts.as_slice(), fm);
439                     expander.expand(fld.cx, it.span, it.ident, marked_tts)
440                 }
441                 LetSyntaxTT(ref expander, span) => {
442                     if it.ident.name == parse::token::special_idents::invalid.name {
443                         fld.cx.span_err(pth.span,
444                                         format!("macro {}! expects an ident argument",
445                                                 extnamestr.get()).as_slice());
446                         return SmallVector::zero();
447                     }
448                     fld.cx.bt_push(ExpnInfo {
449                         call_site: it.span,
450                         callee: NameAndSpan {
451                             name: extnamestr.get().to_string(),
452                             format: MacroBang,
453                             span: span
454                         }
455                     });
456                     // DON'T mark before expansion:
457                     expander.expand(fld.cx, it.span, it.ident, tts)
458                 }
459                 _ => {
460                     fld.cx.span_err(it.span,
461                                     format!("{}! is not legal in item position",
462                                             extnamestr.get()).as_slice());
463                     return SmallVector::zero();
464                 }
465             }
466         };
467
468         match expanded.make_def() {
469             Some(def) => Left(def),
470             None => Right(expanded.make_items())
471         }
472     };
473
474     let items = match def_or_items {
475         Left(MacroDef { name, ext }) => {
476             // hidden invariant: this should only be possible as the
477             // result of expanding a LetSyntaxTT, and thus doesn't
478             // need to be marked. Not that it could be marked anyway.
479             // create issue to recommend refactoring here?
480             fld.cx.syntax_env.insert(intern(name.as_slice()), ext);
481             if attr::contains_name(it.attrs.as_slice(), "macro_export") {
482                 fld.cx.exported_macros.push(it);
483             }
484             SmallVector::zero()
485         }
486         Right(Some(items)) => {
487             items.move_iter()
488                 .map(|i| mark_item(i, fm))
489                 .flat_map(|i| fld.fold_item(i).move_iter())
490                 .collect()
491         }
492         Right(None) => {
493             fld.cx.span_err(pth.span,
494                             format!("non-item macro in item position: {}",
495                                     extnamestr.get()).as_slice());
496             return SmallVector::zero();
497         }
498     };
499
500     fld.cx.bt_pop();
501     return items;
502 }
503
504 /// Expand a stmt
505 //
506 // I don't understand why this returns a vector... it looks like we're
507 // half done adding machinery to allow macros to expand into multiple statements.
508 fn expand_stmt(s: &Stmt, fld: &mut MacroExpander) -> SmallVector<Gc<Stmt>> {
509     let (mac, semi) = match s.node {
510         StmtMac(ref mac, semi) => (mac, semi),
511         _ => return expand_non_macro_stmt(s, fld)
512     };
513     let expanded_stmt = match expand_mac_invoc(mac,&s.span,
514                                                 |r|{r.make_stmt()},
515                                                 |sts,mrk| {
516                                                     mark_stmt(&*sts,mrk)
517                                                 },
518                                                 fld) {
519         Some(stmt) => stmt,
520         None => {
521             return SmallVector::zero();
522         }
523     };
524
525     // Keep going, outside-in.
526     let fully_expanded = fld.fold_stmt(&*expanded_stmt);
527     fld.cx.bt_pop();
528     let fully_expanded: SmallVector<Gc<Stmt>> = fully_expanded.move_iter()
529             .map(|s| box(GC) Spanned { span: s.span, node: s.node.clone() })
530             .collect();
531
532     fully_expanded.move_iter().map(|s| {
533         match s.node {
534             StmtExpr(e, stmt_id) if semi => {
535                 box(GC) Spanned {
536                     span: s.span,
537                     node: StmtSemi(e, stmt_id)
538                 }
539             }
540             _ => s /* might already have a semi */
541         }
542     }).collect()
543 }
544
545 // expand a non-macro stmt. this is essentially the fallthrough for
546 // expand_stmt, above.
547 fn expand_non_macro_stmt(s: &Stmt, fld: &mut MacroExpander)
548                          -> SmallVector<Gc<Stmt>> {
549     // is it a let?
550     match s.node {
551         StmtDecl(decl, node_id) => {
552             match *decl {
553                 Spanned {
554                     node: DeclLocal(ref local),
555                     span: stmt_span
556                 } => {
557                     // take it apart:
558                     let Local {
559                         ty: ty,
560                         pat: pat,
561                         init: init,
562                         id: id,
563                         span: span,
564                         source: source,
565                     } = **local;
566                     // expand the ty since TyFixedLengthVec contains an Expr
567                     // and thus may have a macro use
568                     let expanded_ty = fld.fold_ty(ty);
569                     // expand the pat (it might contain macro uses):
570                     let expanded_pat = fld.fold_pat(pat);
571                     // find the PatIdents in the pattern:
572                     // oh dear heaven... this is going to include the enum
573                     // names, as well... but that should be okay, as long as
574                     // the new names are gensyms for the old ones.
575                     // generate fresh names, push them to a new pending list
576                     let idents = pattern_bindings(&*expanded_pat);
577                     let mut new_pending_renames =
578                         idents.iter().map(|ident| (*ident, fresh_name(ident))).collect();
579                     // rewrite the pattern using the new names (the old
580                     // ones have already been applied):
581                     let rewritten_pat = {
582                         // nested binding to allow borrow to expire:
583                         let mut rename_fld = IdentRenamer{renames: &mut new_pending_renames};
584                         rename_fld.fold_pat(expanded_pat)
585                     };
586                     // add them to the existing pending renames:
587                     fld.cx.syntax_env.info().pending_renames.push_all_move(new_pending_renames);
588                     // also, don't forget to expand the init:
589                     let new_init_opt = init.map(|e| fld.fold_expr(e));
590                     let rewritten_local =
591                         box(GC) Local {
592                             ty: expanded_ty,
593                             pat: rewritten_pat,
594                             init: new_init_opt,
595                             id: id,
596                             span: span,
597                             source: source
598                         };
599                     SmallVector::one(box(GC) Spanned {
600                         node: StmtDecl(box(GC) Spanned {
601                                 node: DeclLocal(rewritten_local),
602                                 span: stmt_span
603                             },
604                             node_id),
605                         span: span
606                     })
607                 }
608                 _ => noop_fold_stmt(s, fld),
609             }
610         },
611         _ => noop_fold_stmt(s, fld),
612     }
613 }
614
615 // expand the arm of a 'match', renaming for macro hygiene
616 fn expand_arm(arm: &ast::Arm, fld: &mut MacroExpander) -> ast::Arm {
617     // expand pats... they might contain macro uses:
618     let expanded_pats : Vec<Gc<ast::Pat>> = arm.pats.iter().map(|pat| fld.fold_pat(*pat)).collect();
619     if expanded_pats.len() == 0 {
620         fail!("encountered match arm with 0 patterns");
621     }
622     // all of the pats must have the same set of bindings, so use the
623     // first one to extract them and generate new names:
624     let first_pat = expanded_pats.get(0);
625     let idents = pattern_bindings(&**first_pat);
626     let new_renames =
627         idents.iter().map(|id| (*id,fresh_name(id))).collect();
628     // apply the renaming, but only to the PatIdents:
629     let mut rename_pats_fld = PatIdentRenamer{renames:&new_renames};
630     let rewritten_pats =
631         expanded_pats.iter().map(|pat| rename_pats_fld.fold_pat(*pat)).collect();
632     // apply renaming and then expansion to the guard and the body:
633     let mut rename_fld = IdentRenamer{renames:&new_renames};
634     let rewritten_guard =
635         arm.guard.map(|g| fld.fold_expr(rename_fld.fold_expr(g)));
636     let rewritten_body = fld.fold_expr(rename_fld.fold_expr(arm.body));
637     ast::Arm {
638         attrs: arm.attrs.iter().map(|x| fld.fold_attribute(*x)).collect(),
639         pats: rewritten_pats,
640         guard: rewritten_guard,
641         body: rewritten_body,
642     }
643 }
644
645 /// A visitor that extracts the PatIdent (binding) paths
646 /// from a given thingy and puts them in a mutable
647 /// array
648 #[deriving(Clone)]
649 struct PatIdentFinder {
650     ident_accumulator: Vec<ast::Ident>
651 }
652
653 impl<'v> Visitor<'v> for PatIdentFinder {
654     fn visit_pat(&mut self, pattern: &ast::Pat) {
655         match *pattern {
656             ast::Pat { id: _, node: ast::PatIdent(_, ref path1, ref inner), span: _ } => {
657                 self.ident_accumulator.push(path1.node);
658                 // visit optional subpattern of PatIdent:
659                 for subpat in inner.iter() {
660                     self.visit_pat(&**subpat)
661                 }
662             }
663             // use the default traversal for non-PatIdents
664             _ => visit::walk_pat(self, pattern)
665         }
666     }
667 }
668
669 /// find the PatIdent paths in a pattern
670 fn pattern_bindings(pat: &ast::Pat) -> Vec<ast::Ident> {
671     let mut name_finder = PatIdentFinder{ident_accumulator:Vec::new()};
672     name_finder.visit_pat(pat);
673     name_finder.ident_accumulator
674 }
675
676 /// find the PatIdent paths in a
677 fn fn_decl_arg_bindings(fn_decl: &ast::FnDecl) -> Vec<ast::Ident> {
678     let mut pat_idents = PatIdentFinder{ident_accumulator:Vec::new()};
679     for arg in fn_decl.inputs.iter() {
680         pat_idents.visit_pat(&*arg.pat);
681     }
682     pat_idents.ident_accumulator
683 }
684
685 // expand a block. pushes a new exts_frame, then calls expand_block_elts
686 fn expand_block(blk: &Block, fld: &mut MacroExpander) -> P<Block> {
687     // see note below about treatment of exts table
688     with_exts_frame!(fld.cx.syntax_env,false,
689                      expand_block_elts(blk, fld))
690 }
691
692 // expand the elements of a block.
693 fn expand_block_elts(b: &Block, fld: &mut MacroExpander) -> P<Block> {
694     let new_view_items = b.view_items.iter().map(|x| fld.fold_view_item(x)).collect();
695     let new_stmts =
696         b.stmts.iter().flat_map(|x| {
697             // perform all pending renames
698             let renamed_stmt = {
699                 let pending_renames = &mut fld.cx.syntax_env.info().pending_renames;
700                 let mut rename_fld = IdentRenamer{renames:pending_renames};
701                 rename_fld.fold_stmt(&**x).expect_one("rename_fold didn't return one value")
702             };
703             // expand macros in the statement
704             fld.fold_stmt(&*renamed_stmt).move_iter()
705         }).collect();
706     let new_expr = b.expr.map(|x| {
707         let expr = {
708             let pending_renames = &mut fld.cx.syntax_env.info().pending_renames;
709             let mut rename_fld = IdentRenamer{renames:pending_renames};
710             rename_fld.fold_expr(x)
711         };
712         fld.fold_expr(expr)
713     });
714     P(Block {
715         view_items: new_view_items,
716         stmts: new_stmts,
717         expr: new_expr,
718         id: fld.new_id(b.id),
719         rules: b.rules,
720         span: b.span,
721     })
722 }
723
724 fn expand_pat(p: Gc<ast::Pat>, fld: &mut MacroExpander) -> Gc<ast::Pat> {
725     let (pth, tts) = match p.node {
726         PatMac(ref mac) => {
727             match mac.node {
728                 MacInvocTT(ref pth, ref tts, _) => {
729                     (pth, (*tts).clone())
730                 }
731             }
732         }
733         _ => return noop_fold_pat(p, fld),
734     };
735     if pth.segments.len() > 1u {
736         fld.cx.span_err(pth.span, "expected macro name without module separators");
737         return DummyResult::raw_pat(p.span);
738     }
739     let extname = pth.segments.get(0).identifier;
740     let extnamestr = token::get_ident(extname);
741     let marked_after = match fld.cx.syntax_env.find(&extname.name) {
742         None => {
743             fld.cx.span_err(pth.span,
744                             format!("macro undefined: '{}!'",
745                                     extnamestr).as_slice());
746             // let compilation continue
747             return DummyResult::raw_pat(p.span);
748         }
749
750         Some(rc) => match *rc {
751             NormalTT(ref expander, span) => {
752                 fld.cx.bt_push(ExpnInfo {
753                     call_site: p.span,
754                     callee: NameAndSpan {
755                         name: extnamestr.get().to_string(),
756                         format: MacroBang,
757                         span: span
758                     }
759                 });
760
761                 let fm = fresh_mark();
762                 let marked_before = mark_tts(tts.as_slice(), fm);
763                 let mac_span = original_span(fld.cx);
764                 let expanded = match expander.expand(fld.cx,
765                                     mac_span.call_site,
766                                     marked_before.as_slice()).make_pat() {
767                     Some(e) => e,
768                     None => {
769                         fld.cx.span_err(
770                             pth.span,
771                             format!(
772                                 "non-pattern macro in pattern position: {}",
773                                 extnamestr.get()
774                             ).as_slice()
775                         );
776                         return DummyResult::raw_pat(p.span);
777                     }
778                 };
779
780                 // mark after:
781                 mark_pat(expanded,fm)
782             }
783             _ => {
784                 fld.cx.span_err(p.span,
785                                 format!("{}! is not legal in pattern position",
786                                         extnamestr.get()).as_slice());
787                 return DummyResult::raw_pat(p.span);
788             }
789         }
790     };
791
792     let fully_expanded =
793         fld.fold_pat(marked_after).node.clone();
794     fld.cx.bt_pop();
795
796     box(GC) ast::Pat {
797         id: ast::DUMMY_NODE_ID,
798         node: fully_expanded,
799         span: p.span,
800     }
801 }
802
803 /// A tree-folder that applies every rename in its (mutable) list
804 /// to every identifier, including both bindings and varrefs
805 /// (and lots of things that will turn out to be neither)
806 pub struct IdentRenamer<'a> {
807     renames: &'a mtwt::RenameList,
808 }
809
810 impl<'a> Folder for IdentRenamer<'a> {
811     fn fold_ident(&mut self, id: Ident) -> Ident {
812         Ident {
813             name: id.name,
814             ctxt: mtwt::apply_renames(self.renames, id.ctxt),
815         }
816     }
817     fn fold_mac(&mut self, macro: &ast::Mac) -> ast::Mac {
818         fold::noop_fold_mac(macro, self)
819     }
820 }
821
822 /// A tree-folder that applies every rename in its list to
823 /// the idents that are in PatIdent patterns. This is more narrowly
824 /// focused than IdentRenamer, and is needed for FnDecl,
825 /// where we want to rename the args but not the fn name or the generics etc.
826 pub struct PatIdentRenamer<'a> {
827     renames: &'a mtwt::RenameList,
828 }
829
830 impl<'a> Folder for PatIdentRenamer<'a> {
831     fn fold_pat(&mut self, pat: Gc<ast::Pat>) -> Gc<ast::Pat> {
832         match pat.node {
833             ast::PatIdent(binding_mode, Spanned{span: ref sp, node: id}, ref sub) => {
834                 let new_ident = Ident{name: id.name,
835                                       ctxt: mtwt::apply_renames(self.renames, id.ctxt)};
836                 let new_node =
837                     ast::PatIdent(binding_mode,
838                                   Spanned{span: self.new_span(*sp), node: new_ident},
839                                   sub.map(|p| self.fold_pat(p)));
840                 box(GC) ast::Pat {
841                     id: pat.id,
842                     span: self.new_span(pat.span),
843                     node: new_node,
844                 }
845             },
846             _ => noop_fold_pat(pat, self)
847         }
848     }
849     fn fold_mac(&mut self, macro: &ast::Mac) -> ast::Mac {
850         fold::noop_fold_mac(macro, self)
851     }
852 }
853
854 // expand a method
855 fn expand_method(m: &ast::Method, fld: &mut MacroExpander) -> SmallVector<Gc<ast::Method>> {
856     let id = fld.new_id(m.id);
857     match m.node {
858         ast::MethDecl(ident,
859                       ref generics,
860                       abi,
861                       ref explicit_self,
862                       fn_style,
863                       decl,
864                       body,
865                       vis) => {
866             let (rewritten_fn_decl, rewritten_body)
867                 = expand_and_rename_fn_decl_and_block(&*decl,body,fld);
868             SmallVector::one(box(GC) ast::Method {
869                     attrs: m.attrs.iter().map(|a| fld.fold_attribute(*a)).collect(),
870                     id: id,
871                     span: fld.new_span(m.span),
872                     node: ast::MethDecl(fld.fold_ident(ident),
873                                         noop_fold_generics(generics, fld),
874                                         abi,
875                                         fld.fold_explicit_self(explicit_self),
876                                         fn_style,
877                                         rewritten_fn_decl,
878                                         rewritten_body,
879                                         vis)
880                 })
881         },
882         ast::MethMac(ref mac) => {
883             let maybe_new_methods =
884                 expand_mac_invoc(mac, &m.span,
885                                  |r|{r.make_methods()},
886                                  |meths,mark|{
887                     meths.move_iter().map(|m|{mark_method(m,mark)})
888                         .collect()},
889                                  fld);
890
891             let new_methods = match maybe_new_methods {
892                 Some(methods) => methods,
893                 None => SmallVector::zero()
894             };
895
896             // expand again if necessary
897             new_methods.move_iter().flat_map(|m| fld.fold_method(m).move_iter()).collect()
898         }
899     }
900 }
901
902 /// Given a fn_decl and a block and a MacroExpander, expand the fn_decl, then use the
903 /// PatIdents in its arguments to perform renaming in the FnDecl and
904 /// the block, returning both the new FnDecl and the new Block.
905 fn expand_and_rename_fn_decl_and_block(fn_decl: &ast::FnDecl, block: Gc<ast::Block>,
906                                        fld: &mut MacroExpander)
907     -> (Gc<ast::FnDecl>, Gc<ast::Block>) {
908     let expanded_decl = fld.fold_fn_decl(fn_decl);
909     let idents = fn_decl_arg_bindings(&*expanded_decl);
910     let renames =
911         idents.iter().map(|id : &ast::Ident| (*id,fresh_name(id))).collect();
912     // first, a renamer for the PatIdents, for the fn_decl:
913     let mut rename_pat_fld = PatIdentRenamer{renames: &renames};
914     let rewritten_fn_decl = rename_pat_fld.fold_fn_decl(&*expanded_decl);
915     // now, a renamer for *all* idents, for the body:
916     let mut rename_fld = IdentRenamer{renames: &renames};
917     let rewritten_body = fld.fold_block(rename_fld.fold_block(block));
918     (rewritten_fn_decl,rewritten_body)
919 }
920
921 /// A tree-folder that performs macro expansion
922 pub struct MacroExpander<'a, 'b:'a> {
923     pub cx: &'a mut ExtCtxt<'b>,
924 }
925
926 impl<'a, 'b> Folder for MacroExpander<'a, 'b> {
927     fn fold_expr(&mut self, expr: Gc<ast::Expr>) -> Gc<ast::Expr> {
928         expand_expr(expr, self)
929     }
930
931     fn fold_pat(&mut self, pat: Gc<ast::Pat>) -> Gc<ast::Pat> {
932         expand_pat(pat, self)
933     }
934
935     fn fold_item(&mut self, item: Gc<ast::Item>) -> SmallVector<Gc<ast::Item>> {
936         expand_item(item, self)
937     }
938
939     fn fold_item_underscore(&mut self, item: &ast::Item_) -> ast::Item_ {
940         expand_item_underscore(item, self)
941     }
942
943     fn fold_stmt(&mut self, stmt: &ast::Stmt) -> SmallVector<Gc<ast::Stmt>> {
944         expand_stmt(stmt, self)
945     }
946
947     fn fold_block(&mut self, block: P<Block>) -> P<Block> {
948         expand_block(&*block, self)
949     }
950
951     fn fold_arm(&mut self, arm: &ast::Arm) -> ast::Arm {
952         expand_arm(arm, self)
953     }
954
955     fn fold_method(&mut self, method: Gc<ast::Method>) -> SmallVector<Gc<ast::Method>> {
956         expand_method(&*method, self)
957     }
958
959     fn new_span(&mut self, span: Span) -> Span {
960         new_span(self.cx, span)
961     }
962 }
963
964 fn new_span(cx: &ExtCtxt, sp: Span) -> Span {
965     /* this discards information in the case of macro-defining macros */
966     Span {
967         lo: sp.lo,
968         hi: sp.hi,
969         expn_info: cx.backtrace(),
970     }
971 }
972
973 pub struct ExpansionConfig {
974     pub deriving_hash_type_parameter: bool,
975     pub crate_name: String,
976 }
977
978 pub struct ExportedMacros {
979     pub crate_name: Ident,
980     pub macros: Vec<String>,
981 }
982
983 pub fn expand_crate(parse_sess: &parse::ParseSess,
984                     cfg: ExpansionConfig,
985                     // these are the macros being imported to this crate:
986                     imported_macros: Vec<ExportedMacros>,
987                     user_exts: Vec<NamedSyntaxExtension>,
988                     c: Crate) -> Crate {
989     let mut cx = ExtCtxt::new(parse_sess, c.config.clone(), cfg);
990     let mut expander = MacroExpander {
991         cx: &mut cx,
992     };
993
994     for ExportedMacros { crate_name, macros } in imported_macros.move_iter() {
995         let name = format!("<{} macros>", token::get_ident(crate_name))
996             .into_string();
997
998         for source in macros.move_iter() {
999             let item = parse::parse_item_from_source_str(name.clone(),
1000                                                          source,
1001                                                          expander.cx.cfg(),
1002                                                          expander.cx.parse_sess())
1003                     .expect("expected a serialized item");
1004             expand_item_mac(item, &mut expander);
1005         }
1006     }
1007
1008     for (name, extension) in user_exts.move_iter() {
1009         expander.cx.syntax_env.insert(name, extension);
1010     }
1011
1012     let mut ret = expander.fold_crate(c);
1013     ret.exported_macros = expander.cx.exported_macros.clone();
1014     parse_sess.span_diagnostic.handler().abort_if_errors();
1015     return ret;
1016 }
1017
1018 // HYGIENIC CONTEXT EXTENSION:
1019 // all of these functions are for walking over
1020 // ASTs and making some change to the context of every
1021 // element that has one. a CtxtFn is a trait-ified
1022 // version of a closure in (SyntaxContext -> SyntaxContext).
1023 // the ones defined here include:
1024 // Marker - add a mark to a context
1025
1026 // A Marker adds the given mark to the syntax context
1027 struct Marker { mark: Mrk }
1028
1029 impl Folder for Marker {
1030     fn fold_ident(&mut self, id: Ident) -> Ident {
1031         ast::Ident {
1032             name: id.name,
1033             ctxt: mtwt::apply_mark(self.mark, id.ctxt)
1034         }
1035     }
1036     fn fold_mac(&mut self, m: &ast::Mac) -> ast::Mac {
1037         let macro = match m.node {
1038             MacInvocTT(ref path, ref tts, ctxt) => {
1039                 MacInvocTT(self.fold_path(path),
1040                            self.fold_tts(tts.as_slice()),
1041                            mtwt::apply_mark(self.mark, ctxt))
1042             }
1043         };
1044         Spanned {
1045             node: macro,
1046             span: m.span,
1047         }
1048     }
1049 }
1050
1051 // apply a given mark to the given token trees. Used prior to expansion of a macro.
1052 fn mark_tts(tts: &[TokenTree], m: Mrk) -> Vec<TokenTree> {
1053     noop_fold_tts(tts, &mut Marker{mark:m})
1054 }
1055
1056 // apply a given mark to the given expr. Used following the expansion of a macro.
1057 fn mark_expr(expr: Gc<ast::Expr>, m: Mrk) -> Gc<ast::Expr> {
1058     Marker{mark:m}.fold_expr(expr)
1059 }
1060
1061 // apply a given mark to the given pattern. Used following the expansion of a macro.
1062 fn mark_pat(pat: Gc<ast::Pat>, m: Mrk) -> Gc<ast::Pat> {
1063     Marker{mark:m}.fold_pat(pat)
1064 }
1065
1066 // apply a given mark to the given stmt. Used following the expansion of a macro.
1067 fn mark_stmt(expr: &ast::Stmt, m: Mrk) -> Gc<ast::Stmt> {
1068     Marker{mark:m}.fold_stmt(expr)
1069         .expect_one("marking a stmt didn't return exactly one stmt")
1070 }
1071
1072 // apply a given mark to the given item. Used following the expansion of a macro.
1073 fn mark_item(expr: Gc<ast::Item>, m: Mrk) -> Gc<ast::Item> {
1074     Marker{mark:m}.fold_item(expr)
1075         .expect_one("marking an item didn't return exactly one item")
1076 }
1077
1078 // apply a given mark to the given item. Used following the expansion of a macro.
1079 fn mark_method(expr: Gc<ast::Method>, m: Mrk) -> Gc<ast::Method> {
1080     Marker{mark:m}.fold_method(expr)
1081         .expect_one("marking an item didn't return exactly one method")
1082 }
1083
1084 fn original_span(cx: &ExtCtxt) -> Gc<codemap::ExpnInfo> {
1085     let mut relevant_info = cx.backtrace();
1086     let mut einfo = relevant_info.unwrap();
1087     loop {
1088         match relevant_info {
1089             None => { break }
1090             Some(e) => {
1091                 einfo = e;
1092                 relevant_info = einfo.call_site.expn_info;
1093             }
1094         }
1095     }
1096     return einfo;
1097 }
1098
1099 /// Check that there are no macro invocations left in the AST:
1100 pub fn check_for_macros(sess: &parse::ParseSess, krate: &ast::Crate) {
1101     visit::walk_crate(&mut MacroExterminator{sess:sess}, krate);
1102 }
1103
1104 /// A visitor that ensures that no macro invocations remain in an AST.
1105 struct MacroExterminator<'a>{
1106     sess: &'a parse::ParseSess
1107 }
1108
1109 impl<'a, 'v> Visitor<'v> for MacroExterminator<'a> {
1110     fn visit_mac(&mut self, macro: &ast::Mac) {
1111         self.sess.span_diagnostic.span_bug(macro.span,
1112                                            "macro exterminator: expected AST \
1113                                            with no macro invocations");
1114     }
1115 }
1116
1117
1118 #[cfg(test)]
1119 mod test {
1120     use super::{pattern_bindings, expand_crate, contains_macro_escape};
1121     use super::{PatIdentFinder, IdentRenamer, PatIdentRenamer};
1122     use ast;
1123     use ast::{Attribute_, AttrOuter, MetaWord, Name};
1124     use attr;
1125     use codemap;
1126     use codemap::Spanned;
1127     use ext::mtwt;
1128     use fold::Folder;
1129     use parse;
1130     use parse::token;
1131     use util::parser_testing::{string_to_parser};
1132     use util::parser_testing::{string_to_pat, string_to_crate, strs_to_idents};
1133     use visit;
1134     use visit::Visitor;
1135
1136     use std::gc::GC;
1137
1138     // a visitor that extracts the paths
1139     // from a given thingy and puts them in a mutable
1140     // array (passed in to the traversal)
1141     #[deriving(Clone)]
1142     struct PathExprFinderContext {
1143         path_accumulator: Vec<ast::Path> ,
1144     }
1145
1146     impl<'v> Visitor<'v> for PathExprFinderContext {
1147         fn visit_expr(&mut self, expr: &ast::Expr) {
1148             match expr.node {
1149                 ast::ExprPath(ref p) => {
1150                     self.path_accumulator.push(p.clone());
1151                     // not calling visit_path, but it should be fine.
1152                 }
1153                 _ => visit::walk_expr(self, expr)
1154             }
1155         }
1156     }
1157
1158     // find the variable references in a crate
1159     fn crate_varrefs(the_crate : &ast::Crate) -> Vec<ast::Path> {
1160         let mut path_finder = PathExprFinderContext{path_accumulator:Vec::new()};
1161         visit::walk_crate(&mut path_finder, the_crate);
1162         path_finder.path_accumulator
1163     }
1164
1165     /// A Visitor that extracts the identifiers from a thingy.
1166     // as a side note, I'm starting to want to abstract over these....
1167     struct IdentFinder {
1168         ident_accumulator: Vec<ast::Ident>
1169     }
1170
1171     impl<'v> Visitor<'v> for IdentFinder {
1172         fn visit_ident(&mut self, _: codemap::Span, id: ast::Ident){
1173             self.ident_accumulator.push(id);
1174         }
1175     }
1176
1177     /// Find the idents in a crate
1178     fn crate_idents(the_crate: &ast::Crate) -> Vec<ast::Ident> {
1179         let mut ident_finder = IdentFinder{ident_accumulator: Vec::new()};
1180         visit::walk_crate(&mut ident_finder, the_crate);
1181         ident_finder.ident_accumulator
1182     }
1183
1184     // these following tests are quite fragile, in that they don't test what
1185     // *kind* of failure occurs.
1186
1187     // make sure that macros can't escape fns
1188     #[should_fail]
1189     #[test] fn macros_cant_escape_fns_test () {
1190         let src = "fn bogus() {macro_rules! z (() => (3+4))}\
1191                    fn inty() -> int { z!() }".to_string();
1192         let sess = parse::new_parse_sess();
1193         let crate_ast = parse::parse_crate_from_source_str(
1194             "<test>".to_string(),
1195             src,
1196             Vec::new(), &sess);
1197         // should fail:
1198         let cfg = ::syntax::ext::expand::ExpansionConfig {
1199             deriving_hash_type_parameter: false,
1200             crate_name: "test".to_string(),
1201         };
1202         expand_crate(&sess,cfg,vec!(),vec!(),crate_ast);
1203     }
1204
1205     // make sure that macros can't escape modules
1206     #[should_fail]
1207     #[test] fn macros_cant_escape_mods_test () {
1208         let src = "mod foo {macro_rules! z (() => (3+4))}\
1209                    fn inty() -> int { z!() }".to_string();
1210         let sess = parse::new_parse_sess();
1211         let crate_ast = parse::parse_crate_from_source_str(
1212             "<test>".to_string(),
1213             src,
1214             Vec::new(), &sess);
1215         let cfg = ::syntax::ext::expand::ExpansionConfig {
1216             deriving_hash_type_parameter: false,
1217             crate_name: "test".to_string(),
1218         };
1219         expand_crate(&sess,cfg,vec!(),vec!(),crate_ast);
1220     }
1221
1222     // macro_escape modules should allow macros to escape
1223     #[test] fn macros_can_escape_flattened_mods_test () {
1224         let src = "#[macro_escape] mod foo {macro_rules! z (() => (3+4))}\
1225                    fn inty() -> int { z!() }".to_string();
1226         let sess = parse::new_parse_sess();
1227         let crate_ast = parse::parse_crate_from_source_str(
1228             "<test>".to_string(),
1229             src,
1230             Vec::new(), &sess);
1231         let cfg = ::syntax::ext::expand::ExpansionConfig {
1232             deriving_hash_type_parameter: false,
1233             crate_name: "test".to_string(),
1234         };
1235         expand_crate(&sess, cfg, vec!(), vec!(), crate_ast);
1236     }
1237
1238     #[test] fn test_contains_flatten (){
1239         let attr1 = make_dummy_attr ("foo");
1240         let attr2 = make_dummy_attr ("bar");
1241         let escape_attr = make_dummy_attr ("macro_escape");
1242         let attrs1 = vec!(attr1, escape_attr, attr2);
1243         assert_eq!(contains_macro_escape(attrs1.as_slice()),true);
1244         let attrs2 = vec!(attr1,attr2);
1245         assert_eq!(contains_macro_escape(attrs2.as_slice()),false);
1246     }
1247
1248     // make a MetaWord outer attribute with the given name
1249     fn make_dummy_attr(s: &str) -> ast::Attribute {
1250         Spanned {
1251             span:codemap::DUMMY_SP,
1252             node: Attribute_ {
1253                 id: attr::mk_attr_id(),
1254                 style: AttrOuter,
1255                 value: box(GC) Spanned {
1256                     node: MetaWord(token::intern_and_get_ident(s)),
1257                     span: codemap::DUMMY_SP,
1258                 },
1259                 is_sugared_doc: false,
1260             }
1261         }
1262     }
1263
1264     fn expand_crate_str(crate_str: String) -> ast::Crate {
1265         let ps = parse::new_parse_sess();
1266         let crate_ast = string_to_parser(&ps, crate_str).parse_crate_mod();
1267         // the cfg argument actually does matter, here...
1268         let cfg = ::syntax::ext::expand::ExpansionConfig {
1269             deriving_hash_type_parameter: false,
1270             crate_name: "test".to_string(),
1271         };
1272         expand_crate(&ps,cfg,vec!(),vec!(),crate_ast)
1273     }
1274
1275     // find the pat_ident paths in a crate
1276     fn crate_bindings(the_crate : &ast::Crate) -> Vec<ast::Ident> {
1277         let mut name_finder = PatIdentFinder{ident_accumulator:Vec::new()};
1278         visit::walk_crate(&mut name_finder, the_crate);
1279         name_finder.ident_accumulator
1280     }
1281
1282     #[test] fn macro_tokens_should_match(){
1283         expand_crate_str(
1284             "macro_rules! m((a)=>(13)) fn main(){m!(a);}".to_string());
1285     }
1286
1287     // should be able to use a bound identifier as a literal in a macro definition:
1288     #[test] fn self_macro_parsing(){
1289         expand_crate_str(
1290             "macro_rules! foo ((zz) => (287u;))
1291             fn f(zz : int) {foo!(zz);}".to_string()
1292             );
1293     }
1294
1295     // renaming tests expand a crate and then check that the bindings match
1296     // the right varrefs. The specification of the test case includes the
1297     // text of the crate, and also an array of arrays.  Each element in the
1298     // outer array corresponds to a binding in the traversal of the AST
1299     // induced by visit.  Each of these arrays contains a list of indexes,
1300     // interpreted as the varrefs in the varref traversal that this binding
1301     // should match.  So, for instance, in a program with two bindings and
1302     // three varrefs, the array ~[~[1,2],~[0]] would indicate that the first
1303     // binding should match the second two varrefs, and the second binding
1304     // should match the first varref.
1305     //
1306     // Put differently; this is a sparse representation of a boolean matrix
1307     // indicating which bindings capture which identifiers.
1308     //
1309     // Note also that this matrix is dependent on the implicit ordering of
1310     // the bindings and the varrefs discovered by the name-finder and the path-finder.
1311     //
1312     // The comparisons are done post-mtwt-resolve, so we're comparing renamed
1313     // names; differences in marks don't matter any more.
1314     //
1315     // oog... I also want tests that check "bound-identifier-=?". That is,
1316     // not just "do these have the same name", but "do they have the same
1317     // name *and* the same marks"? Understanding this is really pretty painful.
1318     // in principle, you might want to control this boolean on a per-varref basis,
1319     // but that would make things even harder to understand, and might not be
1320     // necessary for thorough testing.
1321     type RenamingTest = (&'static str, Vec<Vec<uint>>, bool);
1322
1323     #[test]
1324     fn automatic_renaming () {
1325         let tests: Vec<RenamingTest> =
1326             vec!(// b & c should get new names throughout, in the expr too:
1327                 ("fn a() -> int { let b = 13; let c = b; b+c }",
1328                  vec!(vec!(0,1),vec!(2)), false),
1329                 // both x's should be renamed (how is this causing a bug?)
1330                 ("fn main () {let x: int = 13;x;}",
1331                  vec!(vec!(0)), false),
1332                 // the use of b after the + should be renamed, the other one not:
1333                 ("macro_rules! f (($x:ident) => (b + $x)) fn a() -> int { let b = 13; f!(b)}",
1334                  vec!(vec!(1)), false),
1335                 // the b before the plus should not be renamed (requires marks)
1336                 ("macro_rules! f (($x:ident) => ({let b=9; ($x + b)})) fn a() -> int { f!(b)}",
1337                  vec!(vec!(1)), false),
1338                 // the marks going in and out of letty should cancel, allowing that $x to
1339                 // capture the one following the semicolon.
1340                 // this was an awesome test case, and caught a *lot* of bugs.
1341                 ("macro_rules! letty(($x:ident) => (let $x = 15;))
1342                   macro_rules! user(($x:ident) => ({letty!($x); $x}))
1343                   fn main() -> int {user!(z)}",
1344                  vec!(vec!(0)), false)
1345                 );
1346         for (idx,s) in tests.iter().enumerate() {
1347             run_renaming_test(s,idx);
1348         }
1349     }
1350
1351     // no longer a fixme #8062: this test exposes a *potential* bug; our system does
1352     // not behave exactly like MTWT, but a conversation with Matthew Flatt
1353     // suggests that this can only occur in the presence of local-expand, which
1354     // we have no plans to support. ... unless it's needed for item hygiene....
1355     #[ignore]
1356     #[test] fn issue_8062(){
1357         run_renaming_test(
1358             &("fn main() {let hrcoo = 19; macro_rules! getx(()=>(hrcoo)); getx!();}",
1359               vec!(vec!(0)), true), 0)
1360     }
1361
1362     // FIXME #6994:
1363     // the z flows into and out of two macros (g & f) along one path, and one
1364     // (just g) along the other, so the result of the whole thing should
1365     // be "let z_123 = 3; z_123"
1366     #[ignore]
1367     #[test] fn issue_6994(){
1368         run_renaming_test(
1369             &("macro_rules! g (($x:ident) =>
1370               ({macro_rules! f(($y:ident)=>({let $y=3;$x}));f!($x)}))
1371               fn a(){g!(z)}",
1372               vec!(vec!(0)),false),
1373             0)
1374     }
1375
1376     // match variable hygiene. Should expand into
1377     // fn z() {match 8 {x_1 => {match 9 {x_2 | x_2 if x_2 == x_1 => x_2 + x_1}}}}
1378     #[test] fn issue_9384(){
1379         run_renaming_test(
1380             &("macro_rules! bad_macro (($ex:expr) => ({match 9 {x | x if x == $ex => x + $ex}}))
1381               fn z() {match 8 {x => bad_macro!(x)}}",
1382               // NB: the third "binding" is the repeat of the second one.
1383               vec!(vec!(1,3),vec!(0,2),vec!(0,2)),
1384               true),
1385             0)
1386     }
1387
1388     // interpolated nodes weren't getting labeled.
1389     // should expand into
1390     // fn main(){let g1_1 = 13; g1_1}}
1391     #[test] fn pat_expand_issue_15221(){
1392         run_renaming_test(
1393             &("macro_rules! inner ( ($e:pat ) => ($e))
1394               macro_rules! outer ( ($e:pat ) => (inner!($e)))
1395               fn main() { let outer!(g) = 13; g;}",
1396               vec!(vec!(0)),
1397               true),
1398             0)
1399     }
1400
1401     // create a really evil test case where a $x appears inside a binding of $x
1402     // but *shouldn't* bind because it was inserted by a different macro....
1403     // can't write this test case until we have macro-generating macros.
1404
1405     // method arg hygiene
1406     // method expands to fn get_x(&self_0, x_1:int) {self_0 + self_2 + x_3 + x_1}
1407     #[test] fn method_arg_hygiene(){
1408         run_renaming_test(
1409             &("macro_rules! inject_x (()=>(x))
1410               macro_rules! inject_self (()=>(self))
1411               struct A;
1412               impl A{fn get_x(&self, x: int) {self + inject_self!() + inject_x!() + x;} }",
1413               vec!(vec!(0),vec!(3)),
1414               true),
1415             0)
1416     }
1417
1418     // ooh, got another bite?
1419     // expands to struct A; impl A {fn thingy(&self_1) {self_1;}}
1420     #[test] fn method_arg_hygiene_2(){
1421         run_renaming_test(
1422             &("struct A;
1423               macro_rules! add_method (($T:ty) =>
1424               (impl $T {  fn thingy(&self) {self;} }))
1425               add_method!(A)",
1426               vec!(vec!(0)),
1427               true),
1428             0)
1429     }
1430
1431     // item fn hygiene
1432     // expands to fn q(x_1:int){fn g(x_2:int){x_2 + x_1};}
1433     #[test] fn issue_9383(){
1434         run_renaming_test(
1435             &("macro_rules! bad_macro (($ex:expr) => (fn g(x:int){ x + $ex }))
1436               fn q(x:int) { bad_macro!(x); }",
1437               vec!(vec!(1),vec!(0)),true),
1438             0)
1439     }
1440
1441     // closure arg hygiene (ExprFnBlock)
1442     // expands to fn f(){(|x_1 : int| {(x_2 + x_1)})(3);}
1443     #[test] fn closure_arg_hygiene(){
1444         run_renaming_test(
1445             &("macro_rules! inject_x (()=>(x))
1446             fn f(){(|x : int| {(inject_x!() + x)})(3);}",
1447               vec!(vec!(1)),
1448               true),
1449             0)
1450     }
1451
1452     // closure arg hygiene (ExprProc)
1453     // expands to fn f(){(proc(x_1 : int) {(x_2 + x_1)})(3);}
1454     #[test] fn closure_arg_hygiene_2(){
1455         run_renaming_test(
1456             &("macro_rules! inject_x (()=>(x))
1457               fn f(){ (proc(x : int){(inject_x!() + x)})(3); }",
1458               vec!(vec!(1)),
1459               true),
1460             0)
1461     }
1462
1463     // macro_rules in method position. Sadly, unimplemented.
1464     #[test] fn macro_in_method_posn(){
1465         expand_crate_str(
1466             "macro_rules! my_method (() => (fn thirteen(&self) -> int {13}))
1467             struct A;
1468             impl A{ my_method!()}
1469             fn f(){A.thirteen;}".to_string());
1470     }
1471
1472     // another nested macro
1473     // expands to impl Entries {fn size_hint(&self_1) {self_1;}
1474     #[test] fn item_macro_workaround(){
1475         run_renaming_test(
1476             &("macro_rules! item { ($i:item) => {$i}}
1477               struct Entries;
1478               macro_rules! iterator_impl {
1479               () => { item!( impl Entries { fn size_hint(&self) { self;}})}}
1480               iterator_impl! { }",
1481               vec!(vec!(0)), true),
1482             0)
1483     }
1484
1485     // run one of the renaming tests
1486     fn run_renaming_test(t: &RenamingTest, test_idx: uint) {
1487         let invalid_name = token::special_idents::invalid.name;
1488         let (teststr, bound_connections, bound_ident_check) = match *t {
1489             (ref str,ref conns, bic) => (str.to_string(), conns.clone(), bic)
1490         };
1491         let cr = expand_crate_str(teststr.to_string());
1492         let bindings = crate_bindings(&cr);
1493         let varrefs = crate_varrefs(&cr);
1494
1495         // must be one check clause for each binding:
1496         assert_eq!(bindings.len(),bound_connections.len());
1497         for (binding_idx,shouldmatch) in bound_connections.iter().enumerate() {
1498             let binding_name = mtwt::resolve(*bindings.get(binding_idx));
1499             let binding_marks = mtwt::marksof(bindings.get(binding_idx).ctxt, invalid_name);
1500             // shouldmatch can't name varrefs that don't exist:
1501             assert!((shouldmatch.len() == 0) ||
1502                     (varrefs.len() > *shouldmatch.iter().max().unwrap()));
1503             for (idx,varref) in varrefs.iter().enumerate() {
1504                 let print_hygiene_debug_info = || {
1505                     // good lord, you can't make a path with 0 segments, can you?
1506                     let final_varref_ident = match varref.segments.last() {
1507                         Some(pathsegment) => pathsegment.identifier,
1508                         None => fail!("varref with 0 path segments?")
1509                     };
1510                     let varref_name = mtwt::resolve(final_varref_ident);
1511                     let varref_idents : Vec<ast::Ident>
1512                         = varref.segments.iter().map(|s| s.identifier)
1513                         .collect();
1514                     println!("varref #{}: {}, resolves to {}",idx, varref_idents, varref_name);
1515                     let string = token::get_ident(final_varref_ident);
1516                     println!("varref's first segment's string: \"{}\"", string.get());
1517                     println!("binding #{}: {}, resolves to {}",
1518                              binding_idx, *bindings.get(binding_idx), binding_name);
1519                     mtwt::with_sctable(|x| mtwt::display_sctable(x));
1520                 };
1521                 if shouldmatch.contains(&idx) {
1522                     // it should be a path of length 1, and it should
1523                     // be free-identifier=? or bound-identifier=? to the given binding
1524                     assert_eq!(varref.segments.len(),1);
1525                     let varref_name = mtwt::resolve(varref.segments.get(0).identifier);
1526                     let varref_marks = mtwt::marksof(varref.segments
1527                                                            .get(0)
1528                                                            .identifier
1529                                                            .ctxt,
1530                                                      invalid_name);
1531                     if !(varref_name==binding_name) {
1532                         println!("uh oh, should match but doesn't:");
1533                         print_hygiene_debug_info();
1534                     }
1535                     assert_eq!(varref_name,binding_name);
1536                     if bound_ident_check {
1537                         // we're checking bound-identifier=?, and the marks
1538                         // should be the same, too:
1539                         assert_eq!(varref_marks,binding_marks.clone());
1540                     }
1541                 } else {
1542                     let varref_name = mtwt::resolve(varref.segments.get(0).identifier);
1543                     let fail = (varref.segments.len() == 1)
1544                         && (varref_name == binding_name);
1545                     // temp debugging:
1546                     if fail {
1547                         println!("failure on test {}",test_idx);
1548                         println!("text of test case: \"{}\"", teststr);
1549                         println!("");
1550                         println!("uh oh, matches but shouldn't:");
1551                         print_hygiene_debug_info();
1552                     }
1553                     assert!(!fail);
1554                 }
1555             }
1556         }
1557     }
1558
1559     #[test] fn fmt_in_macro_used_inside_module_macro() {
1560         let crate_str = "macro_rules! fmt_wrap(($b:expr)=>($b.to_string()))
1561 macro_rules! foo_module (() => (mod generated { fn a() { let xx = 147; fmt_wrap!(xx);}}))
1562 foo_module!()
1563 ".to_string();
1564         let cr = expand_crate_str(crate_str);
1565         // find the xx binding
1566         let bindings = crate_bindings(&cr);
1567         let cxbinds: Vec<&ast::Ident> =
1568             bindings.iter().filter(|b| {
1569                 let ident = token::get_ident(**b);
1570                 let string = ident.get();
1571                 "xx" == string
1572             }).collect();
1573         let cxbinds: &[&ast::Ident] = cxbinds.as_slice();
1574         let cxbind = match cxbinds {
1575             [b] => b,
1576             _ => fail!("expected just one binding for ext_cx")
1577         };
1578         let resolved_binding = mtwt::resolve(*cxbind);
1579         let varrefs = crate_varrefs(&cr);
1580
1581         // the xx binding should bind all of the xx varrefs:
1582         for (idx,v) in varrefs.iter().filter(|p| {
1583             p.segments.len() == 1
1584             && "xx" == token::get_ident(p.segments.get(0).identifier).get()
1585         }).enumerate() {
1586             if mtwt::resolve(v.segments.get(0).identifier) != resolved_binding {
1587                 println!("uh oh, xx binding didn't match xx varref:");
1588                 println!("this is xx varref \\# {:?}",idx);
1589                 println!("binding: {:?}",cxbind);
1590                 println!("resolves to: {:?}",resolved_binding);
1591                 println!("varref: {:?}",v.segments.get(0).identifier);
1592                 println!("resolves to: {:?}",
1593                          mtwt::resolve(v.segments.get(0).identifier));
1594                 mtwt::with_sctable(|x| mtwt::display_sctable(x));
1595             }
1596             assert_eq!(mtwt::resolve(v.segments.get(0).identifier),
1597                        resolved_binding);
1598         };
1599     }
1600
1601     #[test]
1602     fn pat_idents(){
1603         let pat = string_to_pat(
1604             "(a,Foo{x:c @ (b,9),y:Bar(4,d)})".to_string());
1605         let idents = pattern_bindings(&*pat);
1606         assert_eq!(idents, strs_to_idents(vec!("a","c","b","d")));
1607     }
1608
1609     // test the list of identifier patterns gathered by the visitor. Note that
1610     // 'None' is listed as an identifier pattern because we don't yet know that
1611     // it's the name of a 0-ary variant, and that 'i' appears twice in succession.
1612     #[test]
1613     fn crate_bindings_test(){
1614         let the_crate = string_to_crate("fn main (a : int) -> int {|b| {
1615         match 34 {None => 3, Some(i) | i => j, Foo{k:z,l:y} => \"banana\"}} }".to_string());
1616         let idents = crate_bindings(&the_crate);
1617         assert_eq!(idents, strs_to_idents(vec!("a","b","None","i","i","z","y")));
1618     }
1619
1620     // test the IdentRenamer directly
1621     #[test]
1622     fn ident_renamer_test () {
1623         let the_crate = string_to_crate("fn f(x : int){let x = x; x}".to_string());
1624         let f_ident = token::str_to_ident("f");
1625         let x_ident = token::str_to_ident("x");
1626         let int_ident = token::str_to_ident("int");
1627         let renames = vec!((x_ident,Name(16)));
1628         let mut renamer = IdentRenamer{renames: &renames};
1629         let renamed_crate = renamer.fold_crate(the_crate);
1630         let idents = crate_idents(&renamed_crate);
1631         let resolved : Vec<ast::Name> = idents.iter().map(|id| mtwt::resolve(*id)).collect();
1632         assert_eq!(resolved,vec!(f_ident.name,Name(16),int_ident.name,Name(16),Name(16),Name(16)));
1633     }
1634
1635     // test the PatIdentRenamer; only PatIdents get renamed
1636     #[test]
1637     fn pat_ident_renamer_test () {
1638         let the_crate = string_to_crate("fn f(x : int){let x = x; x}".to_string());
1639         let f_ident = token::str_to_ident("f");
1640         let x_ident = token::str_to_ident("x");
1641         let int_ident = token::str_to_ident("int");
1642         let renames = vec!((x_ident,Name(16)));
1643         let mut renamer = PatIdentRenamer{renames: &renames};
1644         let renamed_crate = renamer.fold_crate(the_crate);
1645         let idents = crate_idents(&renamed_crate);
1646         let resolved : Vec<ast::Name> = idents.iter().map(|id| mtwt::resolve(*id)).collect();
1647         let x_name = x_ident.name;
1648         assert_eq!(resolved,vec!(f_ident.name,Name(16),int_ident.name,Name(16),x_name,x_name));
1649     }
1650
1651
1652 }