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