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