]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/expand.rs
rollup merge of #17318 : nick29581/slice
[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                 ItemDecorator(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 { ItemModifier(_) => 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                 ItemModifier(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             new_methods.into_iter().flat_map(|m| fld.fold_method(m).into_iter()).collect()
899         }
900     })
901 }
902
903 /// Given a fn_decl and a block and a MacroExpander, expand the fn_decl, then use the
904 /// PatIdents in its arguments to perform renaming in the FnDecl and
905 /// the block, returning both the new FnDecl and the new Block.
906 fn expand_and_rename_fn_decl_and_block(fn_decl: P<ast::FnDecl>, block: P<ast::Block>,
907                                        fld: &mut MacroExpander)
908     -> (P<ast::FnDecl>, P<ast::Block>) {
909     let expanded_decl = fld.fold_fn_decl(fn_decl);
910     let idents = fn_decl_arg_bindings(&*expanded_decl);
911     let renames =
912         idents.iter().map(|id : &ast::Ident| (*id,fresh_name(id))).collect();
913     // first, a renamer for the PatIdents, for the fn_decl:
914     let mut rename_pat_fld = PatIdentRenamer{renames: &renames};
915     let rewritten_fn_decl = rename_pat_fld.fold_fn_decl(expanded_decl);
916     // now, a renamer for *all* idents, for the body:
917     let mut rename_fld = IdentRenamer{renames: &renames};
918     let rewritten_body = fld.fold_block(rename_fld.fold_block(block));
919     (rewritten_fn_decl,rewritten_body)
920 }
921
922 /// A tree-folder that performs macro expansion
923 pub struct MacroExpander<'a, 'b:'a> {
924     pub cx: &'a mut ExtCtxt<'b>,
925 }
926
927 impl<'a, 'b> Folder for MacroExpander<'a, 'b> {
928     fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
929         expand_expr(expr, self)
930     }
931
932     fn fold_pat(&mut self, pat: P<ast::Pat>) -> P<ast::Pat> {
933         expand_pat(pat, self)
934     }
935
936     fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
937         expand_item(item, self)
938     }
939
940     fn fold_item_underscore(&mut self, item: ast::Item_) -> ast::Item_ {
941         expand_item_underscore(item, self)
942     }
943
944     fn fold_stmt(&mut self, stmt: P<ast::Stmt>) -> SmallVector<P<ast::Stmt>> {
945         stmt.and_then(|stmt| expand_stmt(stmt, self))
946     }
947
948     fn fold_block(&mut self, block: P<Block>) -> P<Block> {
949         expand_block(block, self)
950     }
951
952     fn fold_arm(&mut self, arm: ast::Arm) -> ast::Arm {
953         expand_arm(arm, self)
954     }
955
956     fn fold_method(&mut self, method: P<ast::Method>) -> SmallVector<P<ast::Method>> {
957         expand_method(method, self)
958     }
959
960     fn new_span(&mut self, span: Span) -> Span {
961         new_span(self.cx, span)
962     }
963 }
964
965 fn new_span(cx: &ExtCtxt, sp: Span) -> Span {
966     /* this discards information in the case of macro-defining macros */
967     Span {
968         lo: sp.lo,
969         hi: sp.hi,
970         expn_id: cx.backtrace(),
971     }
972 }
973
974 pub struct ExpansionConfig {
975     pub deriving_hash_type_parameter: bool,
976     pub crate_name: String,
977 }
978
979 pub struct ExportedMacros {
980     pub crate_name: Ident,
981     pub macros: Vec<String>,
982 }
983
984 pub fn expand_crate(parse_sess: &parse::ParseSess,
985                     cfg: ExpansionConfig,
986                     // these are the macros being imported to this crate:
987                     imported_macros: Vec<ExportedMacros>,
988                     user_exts: Vec<NamedSyntaxExtension>,
989                     c: Crate) -> Crate {
990     let mut cx = ExtCtxt::new(parse_sess, c.config.clone(), cfg);
991     let mut expander = MacroExpander {
992         cx: &mut cx,
993     };
994
995     for ExportedMacros { crate_name, macros } in imported_macros.into_iter() {
996         let name = format!("<{} macros>", token::get_ident(crate_name))
997             .into_string();
998
999         for source in macros.into_iter() {
1000             let item = parse::parse_item_from_source_str(name.clone(),
1001                                                          source,
1002                                                          expander.cx.cfg(),
1003                                                          expander.cx.parse_sess())
1004                     .expect("expected a serialized item");
1005             expand_item_mac(item, &mut expander);
1006         }
1007     }
1008
1009     for (name, extension) in user_exts.into_iter() {
1010         expander.cx.syntax_env.insert(name, extension);
1011     }
1012
1013     let mut ret = expander.fold_crate(c);
1014     ret.exported_macros = expander.cx.exported_macros.clone();
1015     parse_sess.span_diagnostic.handler().abort_if_errors();
1016     return ret;
1017 }
1018
1019 // HYGIENIC CONTEXT EXTENSION:
1020 // all of these functions are for walking over
1021 // ASTs and making some change to the context of every
1022 // element that has one. a CtxtFn is a trait-ified
1023 // version of a closure in (SyntaxContext -> SyntaxContext).
1024 // the ones defined here include:
1025 // Marker - add a mark to a context
1026
1027 // A Marker adds the given mark to the syntax context
1028 struct Marker { mark: Mrk }
1029
1030 impl Folder for Marker {
1031     fn fold_ident(&mut self, id: Ident) -> Ident {
1032         ast::Ident {
1033             name: id.name,
1034             ctxt: mtwt::apply_mark(self.mark, id.ctxt)
1035         }
1036     }
1037     fn fold_mac(&mut self, Spanned {node, span}: ast::Mac) -> ast::Mac {
1038         Spanned {
1039             node: match node {
1040                 MacInvocTT(path, tts, ctxt) => {
1041                     MacInvocTT(self.fold_path(path),
1042                                self.fold_tts(tts.as_slice()),
1043                                mtwt::apply_mark(self.mark, ctxt))
1044                 }
1045             },
1046             span: span,
1047         }
1048     }
1049 }
1050
1051 // apply a given mark to the given token trees. Used prior to expansion of a macro.
1052 fn mark_tts(tts: &[TokenTree], m: Mrk) -> Vec<TokenTree> {
1053     noop_fold_tts(tts, &mut Marker{mark:m})
1054 }
1055
1056 // apply a given mark to the given expr. Used following the expansion of a macro.
1057 fn mark_expr(expr: P<ast::Expr>, m: Mrk) -> P<ast::Expr> {
1058     Marker{mark:m}.fold_expr(expr)
1059 }
1060
1061 // apply a given mark to the given pattern. Used following the expansion of a macro.
1062 fn mark_pat(pat: P<ast::Pat>, m: Mrk) -> P<ast::Pat> {
1063     Marker{mark:m}.fold_pat(pat)
1064 }
1065
1066 // apply a given mark to the given stmt. Used following the expansion of a macro.
1067 fn mark_stmt(expr: P<ast::Stmt>, m: Mrk) -> P<ast::Stmt> {
1068     Marker{mark:m}.fold_stmt(expr)
1069         .expect_one("marking a stmt didn't return exactly one stmt")
1070 }
1071
1072 // apply a given mark to the given item. Used following the expansion of a macro.
1073 fn mark_item(expr: P<ast::Item>, m: Mrk) -> P<ast::Item> {
1074     Marker{mark:m}.fold_item(expr)
1075         .expect_one("marking an item didn't return exactly one item")
1076 }
1077
1078 // apply a given mark to the given item. Used following the expansion of a macro.
1079 fn mark_method(expr: P<ast::Method>, m: Mrk) -> P<ast::Method> {
1080     Marker{mark:m}.fold_method(expr)
1081         .expect_one("marking an item didn't return exactly one method")
1082 }
1083
1084 /// Check that there are no macro invocations left in the AST:
1085 pub fn check_for_macros(sess: &parse::ParseSess, krate: &ast::Crate) {
1086     visit::walk_crate(&mut MacroExterminator{sess:sess}, krate);
1087 }
1088
1089 /// A visitor that ensures that no macro invocations remain in an AST.
1090 struct MacroExterminator<'a>{
1091     sess: &'a parse::ParseSess
1092 }
1093
1094 impl<'a, 'v> Visitor<'v> for MacroExterminator<'a> {
1095     fn visit_mac(&mut self, macro: &ast::Mac) {
1096         self.sess.span_diagnostic.span_bug(macro.span,
1097                                            "macro exterminator: expected AST \
1098                                            with no macro invocations");
1099     }
1100 }
1101
1102
1103 #[cfg(test)]
1104 mod test {
1105     use super::{pattern_bindings, expand_crate, contains_macro_escape};
1106     use super::{PatIdentFinder, IdentRenamer, PatIdentRenamer};
1107     use ast;
1108     use ast::{Attribute_, AttrOuter, MetaWord, Name};
1109     use attr;
1110     use codemap;
1111     use codemap::Spanned;
1112     use ext::mtwt;
1113     use fold::Folder;
1114     use parse;
1115     use parse::token;
1116     use ptr::P;
1117     use util::parser_testing::{string_to_parser};
1118     use util::parser_testing::{string_to_pat, string_to_crate, strs_to_idents};
1119     use visit;
1120     use visit::Visitor;
1121
1122     // a visitor that extracts the paths
1123     // from a given thingy and puts them in a mutable
1124     // array (passed in to the traversal)
1125     #[deriving(Clone)]
1126     struct PathExprFinderContext {
1127         path_accumulator: Vec<ast::Path> ,
1128     }
1129
1130     impl<'v> Visitor<'v> for PathExprFinderContext {
1131         fn visit_expr(&mut self, expr: &ast::Expr) {
1132             match expr.node {
1133                 ast::ExprPath(ref p) => {
1134                     self.path_accumulator.push(p.clone());
1135                     // not calling visit_path, but it should be fine.
1136                 }
1137                 _ => visit::walk_expr(self, expr)
1138             }
1139         }
1140     }
1141
1142     // find the variable references in a crate
1143     fn crate_varrefs(the_crate : &ast::Crate) -> Vec<ast::Path> {
1144         let mut path_finder = PathExprFinderContext{path_accumulator:Vec::new()};
1145         visit::walk_crate(&mut path_finder, the_crate);
1146         path_finder.path_accumulator
1147     }
1148
1149     /// A Visitor that extracts the identifiers from a thingy.
1150     // as a side note, I'm starting to want to abstract over these....
1151     struct IdentFinder {
1152         ident_accumulator: Vec<ast::Ident>
1153     }
1154
1155     impl<'v> Visitor<'v> for IdentFinder {
1156         fn visit_ident(&mut self, _: codemap::Span, id: ast::Ident){
1157             self.ident_accumulator.push(id);
1158         }
1159     }
1160
1161     /// Find the idents in a crate
1162     fn crate_idents(the_crate: &ast::Crate) -> Vec<ast::Ident> {
1163         let mut ident_finder = IdentFinder{ident_accumulator: Vec::new()};
1164         visit::walk_crate(&mut ident_finder, the_crate);
1165         ident_finder.ident_accumulator
1166     }
1167
1168     // these following tests are quite fragile, in that they don't test what
1169     // *kind* of failure occurs.
1170
1171     // make sure that macros can't escape fns
1172     #[should_fail]
1173     #[test] fn macros_cant_escape_fns_test () {
1174         let src = "fn bogus() {macro_rules! z (() => (3+4))}\
1175                    fn inty() -> int { z!() }".to_string();
1176         let sess = parse::new_parse_sess();
1177         let crate_ast = parse::parse_crate_from_source_str(
1178             "<test>".to_string(),
1179             src,
1180             Vec::new(), &sess);
1181         // should fail:
1182         let cfg = ::syntax::ext::expand::ExpansionConfig {
1183             deriving_hash_type_parameter: false,
1184             crate_name: "test".to_string(),
1185         };
1186         expand_crate(&sess,cfg,vec!(),vec!(),crate_ast);
1187     }
1188
1189     // make sure that macros can't escape modules
1190     #[should_fail]
1191     #[test] fn macros_cant_escape_mods_test () {
1192         let src = "mod foo {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         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     // macro_escape modules should allow macros to escape
1207     #[test] fn macros_can_escape_flattened_mods_test () {
1208         let src = "#[macro_escape] mod foo {macro_rules! z (() => (3+4))}\
1209                    fn inty() -> int { z!() }".to_string();
1210         let sess = parse::new_parse_sess();
1211         let crate_ast = parse::parse_crate_from_source_str(
1212             "<test>".to_string(),
1213             src,
1214             Vec::new(), &sess);
1215         let cfg = ::syntax::ext::expand::ExpansionConfig {
1216             deriving_hash_type_parameter: false,
1217             crate_name: "test".to_string(),
1218         };
1219         expand_crate(&sess, cfg, vec!(), vec!(), crate_ast);
1220     }
1221
1222     #[test] fn test_contains_flatten (){
1223         let attr1 = make_dummy_attr ("foo");
1224         let attr2 = make_dummy_attr ("bar");
1225         let escape_attr = make_dummy_attr ("macro_escape");
1226         let attrs1 = vec!(attr1.clone(), escape_attr, attr2.clone());
1227         assert_eq!(contains_macro_escape(attrs1.as_slice()),true);
1228         let attrs2 = vec!(attr1,attr2);
1229         assert_eq!(contains_macro_escape(attrs2.as_slice()),false);
1230     }
1231
1232     // make a MetaWord outer attribute with the given name
1233     fn make_dummy_attr(s: &str) -> ast::Attribute {
1234         Spanned {
1235             span:codemap::DUMMY_SP,
1236             node: Attribute_ {
1237                 id: attr::mk_attr_id(),
1238                 style: AttrOuter,
1239                 value: P(Spanned {
1240                     node: MetaWord(token::intern_and_get_ident(s)),
1241                     span: codemap::DUMMY_SP,
1242                 }),
1243                 is_sugared_doc: false,
1244             }
1245         }
1246     }
1247
1248     fn expand_crate_str(crate_str: String) -> ast::Crate {
1249         let ps = parse::new_parse_sess();
1250         let crate_ast = string_to_parser(&ps, crate_str).parse_crate_mod();
1251         // the cfg argument actually does matter, here...
1252         let cfg = ::syntax::ext::expand::ExpansionConfig {
1253             deriving_hash_type_parameter: false,
1254             crate_name: "test".to_string(),
1255         };
1256         expand_crate(&ps,cfg,vec!(),vec!(),crate_ast)
1257     }
1258
1259     // find the pat_ident paths in a crate
1260     fn crate_bindings(the_crate : &ast::Crate) -> Vec<ast::Ident> {
1261         let mut name_finder = PatIdentFinder{ident_accumulator:Vec::new()};
1262         visit::walk_crate(&mut name_finder, the_crate);
1263         name_finder.ident_accumulator
1264     }
1265
1266     #[test] fn macro_tokens_should_match(){
1267         expand_crate_str(
1268             "macro_rules! m((a)=>(13)) fn main(){m!(a);}".to_string());
1269     }
1270
1271     // should be able to use a bound identifier as a literal in a macro definition:
1272     #[test] fn self_macro_parsing(){
1273         expand_crate_str(
1274             "macro_rules! foo ((zz) => (287u;))
1275             fn f(zz : int) {foo!(zz);}".to_string()
1276             );
1277     }
1278
1279     // renaming tests expand a crate and then check that the bindings match
1280     // the right varrefs. The specification of the test case includes the
1281     // text of the crate, and also an array of arrays.  Each element in the
1282     // outer array corresponds to a binding in the traversal of the AST
1283     // induced by visit.  Each of these arrays contains a list of indexes,
1284     // interpreted as the varrefs in the varref traversal that this binding
1285     // should match.  So, for instance, in a program with two bindings and
1286     // three varrefs, the array ~[~[1,2],~[0]] would indicate that the first
1287     // binding should match the second two varrefs, and the second binding
1288     // should match the first varref.
1289     //
1290     // Put differently; this is a sparse representation of a boolean matrix
1291     // indicating which bindings capture which identifiers.
1292     //
1293     // Note also that this matrix is dependent on the implicit ordering of
1294     // the bindings and the varrefs discovered by the name-finder and the path-finder.
1295     //
1296     // The comparisons are done post-mtwt-resolve, so we're comparing renamed
1297     // names; differences in marks don't matter any more.
1298     //
1299     // oog... I also want tests that check "bound-identifier-=?". That is,
1300     // not just "do these have the same name", but "do they have the same
1301     // name *and* the same marks"? Understanding this is really pretty painful.
1302     // in principle, you might want to control this boolean on a per-varref basis,
1303     // but that would make things even harder to understand, and might not be
1304     // necessary for thorough testing.
1305     type RenamingTest = (&'static str, Vec<Vec<uint>>, bool);
1306
1307     #[test]
1308     fn automatic_renaming () {
1309         let tests: Vec<RenamingTest> =
1310             vec!(// b & c should get new names throughout, in the expr too:
1311                 ("fn a() -> int { let b = 13; let c = b; b+c }",
1312                  vec!(vec!(0,1),vec!(2)), false),
1313                 // both x's should be renamed (how is this causing a bug?)
1314                 ("fn main () {let x: int = 13;x;}",
1315                  vec!(vec!(0)), false),
1316                 // the use of b after the + should be renamed, the other one not:
1317                 ("macro_rules! f (($x:ident) => (b + $x)) fn a() -> int { let b = 13; f!(b)}",
1318                  vec!(vec!(1)), false),
1319                 // the b before the plus should not be renamed (requires marks)
1320                 ("macro_rules! f (($x:ident) => ({let b=9; ($x + b)})) fn a() -> int { f!(b)}",
1321                  vec!(vec!(1)), false),
1322                 // the marks going in and out of letty should cancel, allowing that $x to
1323                 // capture the one following the semicolon.
1324                 // this was an awesome test case, and caught a *lot* of bugs.
1325                 ("macro_rules! letty(($x:ident) => (let $x = 15;))
1326                   macro_rules! user(($x:ident) => ({letty!($x); $x}))
1327                   fn main() -> int {user!(z)}",
1328                  vec!(vec!(0)), false)
1329                 );
1330         for (idx,s) in tests.iter().enumerate() {
1331             run_renaming_test(s,idx);
1332         }
1333     }
1334
1335     // no longer a fixme #8062: this test exposes a *potential* bug; our system does
1336     // not behave exactly like MTWT, but a conversation with Matthew Flatt
1337     // suggests that this can only occur in the presence of local-expand, which
1338     // we have no plans to support. ... unless it's needed for item hygiene....
1339     #[ignore]
1340     #[test] fn issue_8062(){
1341         run_renaming_test(
1342             &("fn main() {let hrcoo = 19; macro_rules! getx(()=>(hrcoo)); getx!();}",
1343               vec!(vec!(0)), true), 0)
1344     }
1345
1346     // FIXME #6994:
1347     // the z flows into and out of two macros (g & f) along one path, and one
1348     // (just g) along the other, so the result of the whole thing should
1349     // be "let z_123 = 3; z_123"
1350     #[ignore]
1351     #[test] fn issue_6994(){
1352         run_renaming_test(
1353             &("macro_rules! g (($x:ident) =>
1354               ({macro_rules! f(($y:ident)=>({let $y=3;$x}));f!($x)}))
1355               fn a(){g!(z)}",
1356               vec!(vec!(0)),false),
1357             0)
1358     }
1359
1360     // match variable hygiene. Should expand into
1361     // fn z() {match 8 {x_1 => {match 9 {x_2 | x_2 if x_2 == x_1 => x_2 + x_1}}}}
1362     #[test] fn issue_9384(){
1363         run_renaming_test(
1364             &("macro_rules! bad_macro (($ex:expr) => ({match 9 {x | x if x == $ex => x + $ex}}))
1365               fn z() {match 8 {x => bad_macro!(x)}}",
1366               // NB: the third "binding" is the repeat of the second one.
1367               vec!(vec!(1,3),vec!(0,2),vec!(0,2)),
1368               true),
1369             0)
1370     }
1371
1372     // interpolated nodes weren't getting labeled.
1373     // should expand into
1374     // fn main(){let g1_1 = 13; g1_1}}
1375     #[test] fn pat_expand_issue_15221(){
1376         run_renaming_test(
1377             &("macro_rules! inner ( ($e:pat ) => ($e))
1378               macro_rules! outer ( ($e:pat ) => (inner!($e)))
1379               fn main() { let outer!(g) = 13; g;}",
1380               vec!(vec!(0)),
1381               true),
1382             0)
1383     }
1384
1385     // create a really evil test case where a $x appears inside a binding of $x
1386     // but *shouldn't* bind because it was inserted by a different macro....
1387     // can't write this test case until we have macro-generating macros.
1388
1389     // method arg hygiene
1390     // method expands to fn get_x(&self_0, x_1:int) {self_0 + self_2 + x_3 + x_1}
1391     #[test] fn method_arg_hygiene(){
1392         run_renaming_test(
1393             &("macro_rules! inject_x (()=>(x))
1394               macro_rules! inject_self (()=>(self))
1395               struct A;
1396               impl A{fn get_x(&self, x: int) {self + inject_self!() + inject_x!() + x;} }",
1397               vec!(vec!(0),vec!(3)),
1398               true),
1399             0)
1400     }
1401
1402     // ooh, got another bite?
1403     // expands to struct A; impl A {fn thingy(&self_1) {self_1;}}
1404     #[test] fn method_arg_hygiene_2(){
1405         run_renaming_test(
1406             &("struct A;
1407               macro_rules! add_method (($T:ty) =>
1408               (impl $T {  fn thingy(&self) {self;} }))
1409               add_method!(A)",
1410               vec!(vec!(0)),
1411               true),
1412             0)
1413     }
1414
1415     // item fn hygiene
1416     // expands to fn q(x_1:int){fn g(x_2:int){x_2 + x_1};}
1417     #[test] fn issue_9383(){
1418         run_renaming_test(
1419             &("macro_rules! bad_macro (($ex:expr) => (fn g(x:int){ x + $ex }))
1420               fn q(x:int) { bad_macro!(x); }",
1421               vec!(vec!(1),vec!(0)),true),
1422             0)
1423     }
1424
1425     // closure arg hygiene (ExprFnBlock)
1426     // expands to fn f(){(|x_1 : int| {(x_2 + x_1)})(3);}
1427     #[test] fn closure_arg_hygiene(){
1428         run_renaming_test(
1429             &("macro_rules! inject_x (()=>(x))
1430             fn f(){(|x : int| {(inject_x!() + x)})(3);}",
1431               vec!(vec!(1)),
1432               true),
1433             0)
1434     }
1435
1436     // closure arg hygiene (ExprProc)
1437     // expands to fn f(){(proc(x_1 : int) {(x_2 + x_1)})(3);}
1438     #[test] fn closure_arg_hygiene_2(){
1439         run_renaming_test(
1440             &("macro_rules! inject_x (()=>(x))
1441               fn f(){ (proc(x : int){(inject_x!() + x)})(3); }",
1442               vec!(vec!(1)),
1443               true),
1444             0)
1445     }
1446
1447     // macro_rules in method position. Sadly, unimplemented.
1448     #[test] fn macro_in_method_posn(){
1449         expand_crate_str(
1450             "macro_rules! my_method (() => (fn thirteen(&self) -> int {13}))
1451             struct A;
1452             impl A{ my_method!()}
1453             fn f(){A.thirteen;}".to_string());
1454     }
1455
1456     // another nested macro
1457     // expands to impl Entries {fn size_hint(&self_1) {self_1;}
1458     #[test] fn item_macro_workaround(){
1459         run_renaming_test(
1460             &("macro_rules! item { ($i:item) => {$i}}
1461               struct Entries;
1462               macro_rules! iterator_impl {
1463               () => { item!( impl Entries { fn size_hint(&self) { self;}})}}
1464               iterator_impl! { }",
1465               vec!(vec!(0)), true),
1466             0)
1467     }
1468
1469     // run one of the renaming tests
1470     fn run_renaming_test(t: &RenamingTest, test_idx: uint) {
1471         let invalid_name = token::special_idents::invalid.name;
1472         let (teststr, bound_connections, bound_ident_check) = match *t {
1473             (ref str,ref conns, bic) => (str.to_string(), conns.clone(), bic)
1474         };
1475         let cr = expand_crate_str(teststr.to_string());
1476         let bindings = crate_bindings(&cr);
1477         let varrefs = crate_varrefs(&cr);
1478
1479         // must be one check clause for each binding:
1480         assert_eq!(bindings.len(),bound_connections.len());
1481         for (binding_idx,shouldmatch) in bound_connections.iter().enumerate() {
1482             let binding_name = mtwt::resolve(*bindings.get(binding_idx));
1483             let binding_marks = mtwt::marksof(bindings.get(binding_idx).ctxt, invalid_name);
1484             // shouldmatch can't name varrefs that don't exist:
1485             assert!((shouldmatch.len() == 0) ||
1486                     (varrefs.len() > *shouldmatch.iter().max().unwrap()));
1487             for (idx,varref) in varrefs.iter().enumerate() {
1488                 let print_hygiene_debug_info = || {
1489                     // good lord, you can't make a path with 0 segments, can you?
1490                     let final_varref_ident = match varref.segments.last() {
1491                         Some(pathsegment) => pathsegment.identifier,
1492                         None => fail!("varref with 0 path segments?")
1493                     };
1494                     let varref_name = mtwt::resolve(final_varref_ident);
1495                     let varref_idents : Vec<ast::Ident>
1496                         = varref.segments.iter().map(|s| s.identifier)
1497                         .collect();
1498                     println!("varref #{}: {}, resolves to {}",idx, varref_idents, varref_name);
1499                     let string = token::get_ident(final_varref_ident);
1500                     println!("varref's first segment's string: \"{}\"", string.get());
1501                     println!("binding #{}: {}, resolves to {}",
1502                              binding_idx, *bindings.get(binding_idx), binding_name);
1503                     mtwt::with_sctable(|x| mtwt::display_sctable(x));
1504                 };
1505                 if shouldmatch.contains(&idx) {
1506                     // it should be a path of length 1, and it should
1507                     // be free-identifier=? or bound-identifier=? to the given binding
1508                     assert_eq!(varref.segments.len(),1);
1509                     let varref_name = mtwt::resolve(varref.segments.get(0).identifier);
1510                     let varref_marks = mtwt::marksof(varref.segments
1511                                                            .get(0)
1512                                                            .identifier
1513                                                            .ctxt,
1514                                                      invalid_name);
1515                     if !(varref_name==binding_name) {
1516                         println!("uh oh, should match but doesn't:");
1517                         print_hygiene_debug_info();
1518                     }
1519                     assert_eq!(varref_name,binding_name);
1520                     if bound_ident_check {
1521                         // we're checking bound-identifier=?, and the marks
1522                         // should be the same, too:
1523                         assert_eq!(varref_marks,binding_marks.clone());
1524                     }
1525                 } else {
1526                     let varref_name = mtwt::resolve(varref.segments.get(0).identifier);
1527                     let fail = (varref.segments.len() == 1)
1528                         && (varref_name == binding_name);
1529                     // temp debugging:
1530                     if fail {
1531                         println!("failure on test {}",test_idx);
1532                         println!("text of test case: \"{}\"", teststr);
1533                         println!("");
1534                         println!("uh oh, matches but shouldn't:");
1535                         print_hygiene_debug_info();
1536                     }
1537                     assert!(!fail);
1538                 }
1539             }
1540         }
1541     }
1542
1543     #[test] fn fmt_in_macro_used_inside_module_macro() {
1544         let crate_str = "macro_rules! fmt_wrap(($b:expr)=>($b.to_string()))
1545 macro_rules! foo_module (() => (mod generated { fn a() { let xx = 147; fmt_wrap!(xx);}}))
1546 foo_module!()
1547 ".to_string();
1548         let cr = expand_crate_str(crate_str);
1549         // find the xx binding
1550         let bindings = crate_bindings(&cr);
1551         let cxbinds: Vec<&ast::Ident> =
1552             bindings.iter().filter(|b| {
1553                 let ident = token::get_ident(**b);
1554                 let string = ident.get();
1555                 "xx" == string
1556             }).collect();
1557         let cxbinds: &[&ast::Ident] = cxbinds.as_slice();
1558         let cxbind = match cxbinds {
1559             [b] => b,
1560             _ => fail!("expected just one binding for ext_cx")
1561         };
1562         let resolved_binding = mtwt::resolve(*cxbind);
1563         let varrefs = crate_varrefs(&cr);
1564
1565         // the xx binding should bind all of the xx varrefs:
1566         for (idx,v) in varrefs.iter().filter(|p| {
1567             p.segments.len() == 1
1568             && "xx" == token::get_ident(p.segments.get(0).identifier).get()
1569         }).enumerate() {
1570             if mtwt::resolve(v.segments.get(0).identifier) != resolved_binding {
1571                 println!("uh oh, xx binding didn't match xx varref:");
1572                 println!("this is xx varref \\# {:?}",idx);
1573                 println!("binding: {:?}",cxbind);
1574                 println!("resolves to: {:?}",resolved_binding);
1575                 println!("varref: {:?}",v.segments.get(0).identifier);
1576                 println!("resolves to: {:?}",
1577                          mtwt::resolve(v.segments.get(0).identifier));
1578                 mtwt::with_sctable(|x| mtwt::display_sctable(x));
1579             }
1580             assert_eq!(mtwt::resolve(v.segments.get(0).identifier),
1581                        resolved_binding);
1582         };
1583     }
1584
1585     #[test]
1586     fn pat_idents(){
1587         let pat = string_to_pat(
1588             "(a,Foo{x:c @ (b,9),y:Bar(4,d)})".to_string());
1589         let idents = pattern_bindings(&*pat);
1590         assert_eq!(idents, strs_to_idents(vec!("a","c","b","d")));
1591     }
1592
1593     // test the list of identifier patterns gathered by the visitor. Note that
1594     // 'None' is listed as an identifier pattern because we don't yet know that
1595     // it's the name of a 0-ary variant, and that 'i' appears twice in succession.
1596     #[test]
1597     fn crate_bindings_test(){
1598         let the_crate = string_to_crate("fn main (a : int) -> int {|b| {
1599         match 34 {None => 3, Some(i) | i => j, Foo{k:z,l:y} => \"banana\"}} }".to_string());
1600         let idents = crate_bindings(&the_crate);
1601         assert_eq!(idents, strs_to_idents(vec!("a","b","None","i","i","z","y")));
1602     }
1603
1604     // test the IdentRenamer directly
1605     #[test]
1606     fn ident_renamer_test () {
1607         let the_crate = string_to_crate("fn f(x : int){let x = x; x}".to_string());
1608         let f_ident = token::str_to_ident("f");
1609         let x_ident = token::str_to_ident("x");
1610         let int_ident = token::str_to_ident("int");
1611         let renames = vec!((x_ident,Name(16)));
1612         let mut renamer = IdentRenamer{renames: &renames};
1613         let renamed_crate = renamer.fold_crate(the_crate);
1614         let idents = crate_idents(&renamed_crate);
1615         let resolved : Vec<ast::Name> = idents.iter().map(|id| mtwt::resolve(*id)).collect();
1616         assert_eq!(resolved,vec!(f_ident.name,Name(16),int_ident.name,Name(16),Name(16),Name(16)));
1617     }
1618
1619     // test the PatIdentRenamer; only PatIdents get renamed
1620     #[test]
1621     fn pat_ident_renamer_test () {
1622         let the_crate = string_to_crate("fn f(x : int){let x = x; x}".to_string());
1623         let f_ident = token::str_to_ident("f");
1624         let x_ident = token::str_to_ident("x");
1625         let int_ident = token::str_to_ident("int");
1626         let renames = vec!((x_ident,Name(16)));
1627         let mut renamer = PatIdentRenamer{renames: &renames};
1628         let renamed_crate = renamer.fold_crate(the_crate);
1629         let idents = crate_idents(&renamed_crate);
1630         let resolved : Vec<ast::Name> = idents.iter().map(|id| mtwt::resolve(*id)).collect();
1631         let x_name = x_ident.name;
1632         assert_eq!(resolved,vec!(f_ident.name,Name(16),int_ident.name,Name(16),x_name,x_name));
1633     }
1634
1635
1636 }