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