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