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.
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.
11 use ast::{Block, Crate, DeclLocal, ExprMac, PatMac};
12 use ast::{Local, Ident, MacInvocTT};
13 use ast::{ItemMac, Mrk, Stmt, StmtDecl, StmtMac, StmtExpr, StmtSemi};
17 use ext::build::AstBuilder;
19 use attr::AttrMetaMethods;
21 use codemap::{Span, Spanned, ExpnInfo, NameAndSpan, MacroBang, MacroAttribute};
26 use parse::token::{fresh_mark, fresh_name, intern};
29 use util::small_vector::SmallVector;
38 pub fn expand_expr(e: P<ast::Expr>, fld: &mut MacroExpander) -> P<ast::Expr> {
39 e.and_then(|ast::Expr {id, node, span}| match node {
40 // expr_mac should really be expr_ext or something; it's the
41 // entry-point for all syntax extensions.
43 let expanded_expr = match expand_mac_invoc(mac, span,
48 return DummyResult::raw_expr(span);
52 // Keep going, outside-in.
54 let fully_expanded = fld.fold_expr(expanded_expr);
57 fully_expanded.map(|e| ast::Expr {
58 id: ast::DUMMY_NODE_ID,
64 ast::ExprWhile(cond, body, opt_ident) => {
65 let cond = fld.fold_expr(cond);
66 let (body, opt_ident) = expand_loop_block(body, opt_ident, fld);
67 fld.cx.expr(span, ast::ExprWhile(cond, body, opt_ident))
70 ast::ExprLoop(loop_block, opt_ident) => {
71 let (loop_block, opt_ident) = expand_loop_block(loop_block, opt_ident, fld);
72 fld.cx.expr(span, ast::ExprLoop(loop_block, opt_ident))
75 ast::ExprForLoop(pat, head, body, opt_ident) => {
76 let pat = fld.fold_pat(pat);
77 let head = fld.fold_expr(head);
78 let (body, opt_ident) = expand_loop_block(body, opt_ident, fld);
79 fld.cx.expr(span, ast::ExprForLoop(pat, head, body, opt_ident))
82 ast::ExprFnBlock(capture_clause, fn_decl, block) => {
83 let (rewritten_fn_decl, rewritten_block)
84 = expand_and_rename_fn_decl_and_block(fn_decl, block, fld);
85 let new_node = ast::ExprFnBlock(capture_clause,
88 P(ast::Expr{id:id, node: new_node, span: fld.new_span(span)})
91 ast::ExprProc(fn_decl, block) => {
92 let (rewritten_fn_decl, rewritten_block)
93 = expand_and_rename_fn_decl_and_block(fn_decl, block, fld);
94 let new_node = ast::ExprProc(rewritten_fn_decl, rewritten_block);
95 P(ast::Expr{id:id, node: new_node, span: fld.new_span(span)})
99 P(noop_fold_expr(ast::Expr {
108 /// Expand a (not-ident-style) macro invocation. Returns the result
109 /// of expansion and the mark which must be applied to the result.
110 /// Our current interface doesn't allow us to apply the mark to the
111 /// result until after calling make_expr, make_items, etc.
112 fn expand_mac_invoc<T>(mac: ast::Mac, span: codemap::Span,
113 parse_thunk: |Box<MacResult>|->Option<T>,
114 mark_thunk: |T,Mrk|->T,
115 fld: &mut MacroExpander)
119 // it would almost certainly be cleaner to pass the whole
120 // macro invocation in, rather than pulling it apart and
121 // marking the tts and the ctxt separately. This also goes
122 // for the other three macro invocation chunks of code
124 // Token-tree macros:
125 MacInvocTT(pth, tts, _) => {
126 if pth.segments.len() > 1u {
127 fld.cx.span_err(pth.span,
128 "expected macro name without module \
130 // let compilation continue
133 let extname = pth.segments.get(0).identifier;
134 let extnamestr = token::get_ident(extname);
135 match fld.cx.syntax_env.find(&extname.name) {
139 format!("macro undefined: '{}!'",
140 extnamestr.get()).as_slice());
142 // let compilation continue
145 Some(rc) => match *rc {
146 NormalTT(ref expandfun, exp_span) => {
147 fld.cx.bt_push(ExpnInfo {
149 callee: NameAndSpan {
150 name: extnamestr.get().to_string(),
155 let fm = fresh_mark();
156 let marked_before = mark_tts(tts.as_slice(), fm);
158 // The span that we pass to the expanders we want to
159 // be the root of the call stack. That's the most
160 // relevant span and it's the actual invocation of
162 let mac_span = fld.cx.original_span();
165 let expanded = expandfun.expand(fld.cx,
167 marked_before.as_slice());
168 parse_thunk(expanded)
170 let parsed = match opt_parsed {
175 format!("non-expression macro in expression position: {}",
176 extnamestr.get().as_slice()
181 Some(mark_thunk(parsed,fm))
186 format!("'{}' is not a tt-style macro",
187 extnamestr.get()).as_slice());
196 /// Rename loop label and expand its loop body
198 /// The renaming procedure for loop is different in the sense that the loop
199 /// body is in a block enclosed by loop head so the renaming of loop label
200 /// must be propagated to the enclosed context.
201 fn expand_loop_block(loop_block: P<Block>,
202 opt_ident: Option<Ident>,
203 fld: &mut MacroExpander) -> (P<Block>, Option<Ident>) {
206 let new_label = fresh_name(&label);
207 let rename = (label, new_label);
209 // The rename *must not* be added to the pending list of current
210 // syntax context otherwise an unrelated `break` or `continue` in
211 // the same context will pick that up in the deferred renaming pass
212 // and be renamed incorrectly.
213 let mut rename_list = vec!(rename);
214 let mut rename_fld = IdentRenamer{renames: &mut rename_list};
215 let renamed_ident = rename_fld.fold_ident(label);
217 // The rename *must* be added to the enclosed syntax context for
218 // `break` or `continue` to pick up because by definition they are
219 // in a block enclosed by loop head.
220 fld.cx.syntax_env.push_frame();
221 fld.cx.syntax_env.info().pending_renames.push(rename);
222 let expanded_block = expand_block_elts(loop_block, fld);
223 fld.cx.syntax_env.pop_frame();
225 (expanded_block, Some(renamed_ident))
227 None => (fld.fold_block(loop_block), opt_ident)
231 // eval $e with a new exts frame.
232 // must be a macro so that $e isn't evaluated too early.
233 macro_rules! with_exts_frame (
234 ($extsboxexpr:expr,$macros_escape:expr,$e:expr) =>
235 ({$extsboxexpr.push_frame();
236 $extsboxexpr.info().macros_escape = $macros_escape;
238 $extsboxexpr.pop_frame();
243 // When we enter a module, record it, for the sake of `module!`
244 pub fn expand_item(it: P<ast::Item>, fld: &mut MacroExpander)
245 -> SmallVector<P<ast::Item>> {
246 let it = expand_item_modifiers(it, fld);
248 let mut decorator_items = SmallVector::zero();
249 let mut new_attrs = Vec::new();
250 for attr in it.attrs.iter() {
251 let mname = attr.name();
253 match fld.cx.syntax_env.find(&intern(mname.get())) {
254 Some(rc) => match *rc {
255 Decorator(ref dec) => {
256 attr::mark_used(attr);
258 fld.cx.bt_push(ExpnInfo {
259 call_site: attr.span,
260 callee: NameAndSpan {
261 name: mname.get().to_string(),
262 format: MacroAttribute,
267 // we'd ideally decorator_items.push_all(expand_item(item, fld)),
268 // but that double-mut-borrows fld
269 let mut items: SmallVector<P<ast::Item>> = SmallVector::zero();
270 dec.expand(fld.cx, attr.span, &*attr.node.value, &*it,
271 |item| items.push(item));
272 decorator_items.extend(items.into_iter()
273 .flat_map(|item| expand_item(item, fld).into_iter()));
277 _ => new_attrs.push((*attr).clone()),
279 _ => new_attrs.push((*attr).clone()),
283 let mut new_items = match it.node {
284 ast::ItemMac(..) => expand_item_mac(it, fld),
285 ast::ItemMod(_) | ast::ItemForeignMod(_) => {
286 fld.cx.mod_push(it.ident);
287 let macro_escape = contains_macro_escape(new_attrs.as_slice());
288 let result = with_exts_frame!(fld.cx.syntax_env,
290 noop_fold_item(it, fld));
295 let it = P(ast::Item {
299 noop_fold_item(it, fld)
303 new_items.push_all(decorator_items);
307 fn expand_item_modifiers(mut it: P<ast::Item>, fld: &mut MacroExpander)
309 // partition the attributes into ItemModifiers and others
310 let (modifiers, other_attrs) = it.attrs.partitioned(|attr| {
311 match fld.cx.syntax_env.find(&intern(attr.name().get())) {
312 Some(rc) => match *rc { Modifier(_) => true, _ => false },
316 // update the attrs, leave everything else alone. Is this mutation really a good idea?
322 if modifiers.is_empty() {
326 for attr in modifiers.iter() {
327 let mname = attr.name();
329 match fld.cx.syntax_env.find(&intern(mname.get())) {
330 Some(rc) => match *rc {
331 Modifier(ref mac) => {
332 attr::mark_used(attr);
333 fld.cx.bt_push(ExpnInfo {
334 call_site: attr.span,
335 callee: NameAndSpan {
336 name: mname.get().to_string(),
337 format: MacroAttribute,
341 it = mac.expand(fld.cx, attr.span, &*attr.node.value, it);
350 // expansion may have added new ItemModifiers
351 expand_item_modifiers(it, fld)
354 /// Expand item_underscore
355 fn expand_item_underscore(item: ast::Item_, fld: &mut MacroExpander) -> ast::Item_ {
357 ast::ItemFn(decl, fn_style, abi, generics, body) => {
358 let (rewritten_fn_decl, rewritten_body)
359 = expand_and_rename_fn_decl_and_block(decl, body, fld);
360 let expanded_generics = fold::noop_fold_generics(generics,fld);
361 ast::ItemFn(rewritten_fn_decl, fn_style, abi, expanded_generics, rewritten_body)
363 _ => noop_fold_item_underscore(item, fld)
367 // does this attribute list contain "macro_escape" ?
368 fn contains_macro_escape(attrs: &[ast::Attribute]) -> bool {
369 attr::contains_name(attrs, "macro_escape")
372 // Support for item-position macro invocations, exactly the same
373 // logic as for expression-position macro invocations.
374 pub fn expand_item_mac(it: P<ast::Item>, fld: &mut MacroExpander)
375 -> SmallVector<P<ast::Item>> {
376 let (extname, path_span, tts) = match it.node {
377 ItemMac(codemap::Spanned {
378 node: MacInvocTT(ref pth, ref tts, _),
381 (pth.segments.get(0).identifier, pth.span, (*tts).clone())
383 _ => fld.cx.span_bug(it.span, "invalid item macro invocation")
386 let extnamestr = token::get_ident(extname);
387 let fm = fresh_mark();
389 let mut expanded = match fld.cx.syntax_env.find(&extname.name) {
391 fld.cx.span_err(path_span,
392 format!("macro undefined: '{}!'",
393 extnamestr).as_slice());
394 // let compilation continue
395 return SmallVector::zero();
398 Some(rc) => match *rc {
399 NormalTT(ref expander, span) => {
400 if it.ident.name != parse::token::special_idents::invalid.name {
403 format!("macro {}! expects no ident argument, \
406 token::get_ident(it.ident)).as_slice());
407 return SmallVector::zero();
409 fld.cx.bt_push(ExpnInfo {
411 callee: NameAndSpan {
412 name: extnamestr.get().to_string(),
417 // mark before expansion:
418 let marked_before = mark_tts(tts.as_slice(), fm);
419 expander.expand(fld.cx, it.span, marked_before.as_slice())
421 IdentTT(ref expander, span) => {
422 if it.ident.name == parse::token::special_idents::invalid.name {
423 fld.cx.span_err(path_span,
424 format!("macro {}! expects an ident argument",
425 extnamestr.get()).as_slice());
426 return SmallVector::zero();
428 fld.cx.bt_push(ExpnInfo {
430 callee: NameAndSpan {
431 name: extnamestr.get().to_string(),
436 // mark before expansion:
437 let marked_tts = mark_tts(tts.as_slice(), fm);
438 expander.expand(fld.cx, it.span, it.ident, marked_tts)
440 LetSyntaxTT(ref expander, span) => {
441 if it.ident.name == parse::token::special_idents::invalid.name {
442 fld.cx.span_err(path_span,
443 format!("macro {}! expects an ident argument",
444 extnamestr.get()).as_slice());
445 return SmallVector::zero();
447 fld.cx.bt_push(ExpnInfo {
449 callee: NameAndSpan {
450 name: extnamestr.get().to_string(),
455 // DON'T mark before expansion:
456 expander.expand(fld.cx, it.span, it.ident, tts)
459 fld.cx.span_err(it.span,
460 format!("{}! is not legal in item position",
461 extnamestr.get()).as_slice());
462 return SmallVector::zero();
467 match expanded.make_def() {
468 Some(def) => Left(def),
469 None => Right(expanded.make_items())
473 let items = match def_or_items {
474 Left(MacroDef { name, ext }) => {
475 // hidden invariant: this should only be possible as the
476 // result of expanding a LetSyntaxTT, and thus doesn't
477 // need to be marked. Not that it could be marked anyway.
478 // create issue to recommend refactoring here?
479 fld.cx.syntax_env.insert(intern(name.as_slice()), ext);
480 if attr::contains_name(it.attrs.as_slice(), "macro_export") {
481 fld.cx.exported_macros.push(it);
485 Right(Some(items)) => {
487 .map(|i| mark_item(i, fm))
488 .flat_map(|i| fld.fold_item(i).into_iter())
492 fld.cx.span_err(path_span,
493 format!("non-item macro in item position: {}",
494 extnamestr.get()).as_slice());
495 return SmallVector::zero();
505 // I don't understand why this returns a vector... it looks like we're
506 // half done adding machinery to allow macros to expand into multiple statements.
507 fn expand_stmt(s: Stmt, fld: &mut MacroExpander) -> SmallVector<P<Stmt>> {
508 let (mac, semi) = match s.node {
509 StmtMac(mac, semi) => (mac, semi),
510 _ => return expand_non_macro_stmt(s, fld)
512 let expanded_stmt = match expand_mac_invoc(mac, s.span,
517 return SmallVector::zero();
521 // Keep going, outside-in.
522 let fully_expanded = fld.fold_stmt(expanded_stmt);
526 fully_expanded.into_iter().map(|s| s.map(|Spanned {node, span}| {
529 StmtExpr(e, stmt_id) => StmtSemi(e, stmt_id),
530 _ => node /* might already have a semi */
540 // expand a non-macro stmt. this is essentially the fallthrough for
541 // expand_stmt, above.
542 fn expand_non_macro_stmt(Spanned {node, span: stmt_span}: Stmt, fld: &mut MacroExpander)
543 -> SmallVector<P<Stmt>> {
546 StmtDecl(decl, node_id) => decl.and_then(|Spanned {node: decl, span}| match decl {
547 DeclLocal(local) => {
549 let rewritten_local = local.map(|Local {id, pat, ty, init, source, span}| {
550 // expand the ty since TyFixedLengthVec contains an Expr
551 // and thus may have a macro use
552 let expanded_ty = fld.fold_ty(ty);
553 // expand the pat (it might contain macro uses):
554 let expanded_pat = fld.fold_pat(pat);
555 // find the PatIdents in the pattern:
556 // oh dear heaven... this is going to include the enum
557 // names, as well... but that should be okay, as long as
558 // the new names are gensyms for the old ones.
559 // generate fresh names, push them to a new pending list
560 let idents = pattern_bindings(&*expanded_pat);
561 let mut new_pending_renames =
562 idents.iter().map(|ident| (*ident, fresh_name(ident))).collect();
563 // rewrite the pattern using the new names (the old
564 // ones have already been applied):
565 let rewritten_pat = {
566 // nested binding to allow borrow to expire:
567 let mut rename_fld = IdentRenamer{renames: &mut new_pending_renames};
568 rename_fld.fold_pat(expanded_pat)
570 // add them to the existing pending renames:
571 fld.cx.syntax_env.info().pending_renames.push_all_move(new_pending_renames);
576 // also, don't forget to expand the init:
577 init: init.map(|e| fld.fold_expr(e)),
582 SmallVector::one(P(Spanned {
583 node: StmtDecl(P(Spanned {
584 node: DeclLocal(rewritten_local),
592 noop_fold_stmt(Spanned {
593 node: StmtDecl(P(Spanned {
603 noop_fold_stmt(Spanned {
611 // expand the arm of a 'match', renaming for macro hygiene
612 fn expand_arm(arm: ast::Arm, fld: &mut MacroExpander) -> ast::Arm {
613 // expand pats... they might contain macro uses:
614 let expanded_pats = arm.pats.move_map(|pat| fld.fold_pat(pat));
615 if expanded_pats.len() == 0 {
616 fail!("encountered match arm with 0 patterns");
618 // all of the pats must have the same set of bindings, so use the
619 // first one to extract them and generate new names:
620 let idents = pattern_bindings(&**expanded_pats.get(0));
621 let new_renames = idents.into_iter().map(|id| (id, fresh_name(&id))).collect();
622 // apply the renaming, but only to the PatIdents:
623 let mut rename_pats_fld = PatIdentRenamer{renames:&new_renames};
624 let rewritten_pats = expanded_pats.move_map(|pat| rename_pats_fld.fold_pat(pat));
625 // apply renaming and then expansion to the guard and the body:
626 let mut rename_fld = IdentRenamer{renames:&new_renames};
627 let rewritten_guard =
628 arm.guard.map(|g| fld.fold_expr(rename_fld.fold_expr(g)));
629 let rewritten_body = fld.fold_expr(rename_fld.fold_expr(arm.body));
631 attrs: arm.attrs.move_map(|x| fld.fold_attribute(x)),
632 pats: rewritten_pats,
633 guard: rewritten_guard,
634 body: rewritten_body,
638 /// A visitor that extracts the PatIdent (binding) paths
639 /// from a given thingy and puts them in a mutable
642 struct PatIdentFinder {
643 ident_accumulator: Vec<ast::Ident>
646 impl<'v> Visitor<'v> for PatIdentFinder {
647 fn visit_pat(&mut self, pattern: &ast::Pat) {
649 ast::Pat { id: _, node: ast::PatIdent(_, ref path1, ref inner), span: _ } => {
650 self.ident_accumulator.push(path1.node);
651 // visit optional subpattern of PatIdent:
652 for subpat in inner.iter() {
653 self.visit_pat(&**subpat)
656 // use the default traversal for non-PatIdents
657 _ => visit::walk_pat(self, pattern)
662 /// find the PatIdent paths in a pattern
663 fn pattern_bindings(pat: &ast::Pat) -> Vec<ast::Ident> {
664 let mut name_finder = PatIdentFinder{ident_accumulator:Vec::new()};
665 name_finder.visit_pat(pat);
666 name_finder.ident_accumulator
669 /// find the PatIdent paths in a
670 fn fn_decl_arg_bindings(fn_decl: &ast::FnDecl) -> Vec<ast::Ident> {
671 let mut pat_idents = PatIdentFinder{ident_accumulator:Vec::new()};
672 for arg in fn_decl.inputs.iter() {
673 pat_idents.visit_pat(&*arg.pat);
675 pat_idents.ident_accumulator
678 // expand a block. pushes a new exts_frame, then calls expand_block_elts
679 pub fn expand_block(blk: P<Block>, fld: &mut MacroExpander) -> P<Block> {
680 // see note below about treatment of exts table
681 with_exts_frame!(fld.cx.syntax_env,false,
682 expand_block_elts(blk, fld))
685 // expand the elements of a block.
686 pub fn expand_block_elts(b: P<Block>, fld: &mut MacroExpander) -> P<Block> {
687 b.map(|Block {id, view_items, stmts, expr, rules, span}| {
688 let new_view_items = view_items.into_iter().map(|x| fld.fold_view_item(x)).collect();
689 let new_stmts = stmts.into_iter().flat_map(|x| {
690 // perform all pending renames
692 let pending_renames = &mut fld.cx.syntax_env.info().pending_renames;
693 let mut rename_fld = IdentRenamer{renames:pending_renames};
694 rename_fld.fold_stmt(x).expect_one("rename_fold didn't return one value")
696 // expand macros in the statement
697 fld.fold_stmt(renamed_stmt).into_iter()
699 let new_expr = expr.map(|x| {
701 let pending_renames = &mut fld.cx.syntax_env.info().pending_renames;
702 let mut rename_fld = IdentRenamer{renames:pending_renames};
703 rename_fld.fold_expr(x)
709 view_items: new_view_items,
718 fn expand_pat(p: P<ast::Pat>, fld: &mut MacroExpander) -> P<ast::Pat> {
721 _ => return noop_fold_pat(p, fld)
723 p.map(|ast::Pat {node, span, ..}| {
724 let (pth, tts) = match node {
725 PatMac(mac) => match mac.node {
726 MacInvocTT(pth, tts, _) => {
732 if pth.segments.len() > 1u {
733 fld.cx.span_err(pth.span, "expected macro name without module separators");
734 return DummyResult::raw_pat(span);
736 let extname = pth.segments.get(0).identifier;
737 let extnamestr = token::get_ident(extname);
738 let marked_after = match fld.cx.syntax_env.find(&extname.name) {
740 fld.cx.span_err(pth.span,
741 format!("macro undefined: '{}!'",
742 extnamestr).as_slice());
743 // let compilation continue
744 return DummyResult::raw_pat(span);
747 Some(rc) => match *rc {
748 NormalTT(ref expander, tt_span) => {
749 fld.cx.bt_push(ExpnInfo {
751 callee: NameAndSpan {
752 name: extnamestr.get().to_string(),
758 let fm = fresh_mark();
759 let marked_before = mark_tts(tts.as_slice(), fm);
760 let mac_span = fld.cx.original_span();
761 let expanded = match expander.expand(fld.cx,
763 marked_before.as_slice()).make_pat() {
769 "non-pattern macro in pattern position: {}",
773 return DummyResult::raw_pat(span);
778 mark_pat(expanded,fm)
781 fld.cx.span_err(span,
782 format!("{}! is not legal in pattern position",
783 extnamestr.get()).as_slice());
784 return DummyResult::raw_pat(span);
790 fld.fold_pat(marked_after).node.clone();
794 id: ast::DUMMY_NODE_ID,
795 node: fully_expanded,
801 /// A tree-folder that applies every rename in its (mutable) list
802 /// to every identifier, including both bindings and varrefs
803 /// (and lots of things that will turn out to be neither)
804 pub struct IdentRenamer<'a> {
805 renames: &'a mtwt::RenameList,
808 impl<'a> Folder for IdentRenamer<'a> {
809 fn fold_ident(&mut self, id: Ident) -> Ident {
812 ctxt: mtwt::apply_renames(self.renames, id.ctxt),
815 fn fold_mac(&mut self, macro: ast::Mac) -> ast::Mac {
816 fold::noop_fold_mac(macro, self)
820 /// A tree-folder that applies every rename in its list to
821 /// the idents that are in PatIdent patterns. This is more narrowly
822 /// focused than IdentRenamer, and is needed for FnDecl,
823 /// where we want to rename the args but not the fn name or the generics etc.
824 pub struct PatIdentRenamer<'a> {
825 renames: &'a mtwt::RenameList,
828 impl<'a> Folder for PatIdentRenamer<'a> {
829 fn fold_pat(&mut self, pat: P<ast::Pat>) -> P<ast::Pat> {
831 ast::PatIdent(..) => {},
832 _ => return noop_fold_pat(pat, self)
835 pat.map(|ast::Pat {id, node, span}| match node {
836 ast::PatIdent(binding_mode, Spanned{span: sp, node: ident}, sub) => {
837 let new_ident = Ident{name: ident.name,
838 ctxt: mtwt::apply_renames(self.renames, ident.ctxt)};
840 ast::PatIdent(binding_mode,
841 Spanned{span: self.new_span(sp), node: new_ident},
842 sub.map(|p| self.fold_pat(p)));
846 span: self.new_span(span)
852 fn fold_mac(&mut self, macro: ast::Mac) -> ast::Mac {
853 fold::noop_fold_mac(macro, self)
858 fn expand_method(m: P<ast::Method>, fld: &mut MacroExpander) -> SmallVector<P<ast::Method>> {
859 m.and_then(|m| match m.node {
868 let id = fld.new_id(m.id);
869 let (rewritten_fn_decl, rewritten_body)
870 = expand_and_rename_fn_decl_and_block(decl,body,fld);
871 SmallVector::one(P(ast::Method {
872 attrs: m.attrs.move_map(|a| fld.fold_attribute(a)),
874 span: fld.new_span(m.span),
875 node: ast::MethDecl(fld.fold_ident(ident),
876 noop_fold_generics(generics, fld),
878 fld.fold_explicit_self(explicit_self),
885 ast::MethMac(mac) => {
886 let maybe_new_methods =
887 expand_mac_invoc(mac, m.span,
888 |r| r.make_methods(),
889 |meths, mark| meths.move_map(|m| mark_method(m, mark)),
892 let new_methods = match maybe_new_methods {
893 Some(methods) => methods,
894 None => SmallVector::zero()
897 // expand again if necessary
898 let new_methods = new_methods.move_iter()
899 .flat_map(|m| fld.fold_method(m).into_iter()).collect();
906 /// Given a fn_decl and a block and a MacroExpander, expand the fn_decl, then use the
907 /// PatIdents in its arguments to perform renaming in the FnDecl and
908 /// the block, returning both the new FnDecl and the new Block.
909 fn expand_and_rename_fn_decl_and_block(fn_decl: P<ast::FnDecl>, block: P<ast::Block>,
910 fld: &mut MacroExpander)
911 -> (P<ast::FnDecl>, P<ast::Block>) {
912 let expanded_decl = fld.fold_fn_decl(fn_decl);
913 let idents = fn_decl_arg_bindings(&*expanded_decl);
915 idents.iter().map(|id : &ast::Ident| (*id,fresh_name(id))).collect();
916 // first, a renamer for the PatIdents, for the fn_decl:
917 let mut rename_pat_fld = PatIdentRenamer{renames: &renames};
918 let rewritten_fn_decl = rename_pat_fld.fold_fn_decl(expanded_decl);
919 // now, a renamer for *all* idents, for the body:
920 let mut rename_fld = IdentRenamer{renames: &renames};
921 let rewritten_body = fld.fold_block(rename_fld.fold_block(block));
922 (rewritten_fn_decl,rewritten_body)
925 /// A tree-folder that performs macro expansion
926 pub struct MacroExpander<'a, 'b:'a> {
927 pub cx: &'a mut ExtCtxt<'b>,
930 impl<'a, 'b> Folder for MacroExpander<'a, 'b> {
931 fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
932 expand_expr(expr, self)
935 fn fold_pat(&mut self, pat: P<ast::Pat>) -> P<ast::Pat> {
936 expand_pat(pat, self)
939 fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
940 expand_item(item, self)
943 fn fold_item_underscore(&mut self, item: ast::Item_) -> ast::Item_ {
944 expand_item_underscore(item, self)
947 fn fold_stmt(&mut self, stmt: P<ast::Stmt>) -> SmallVector<P<ast::Stmt>> {
948 stmt.and_then(|stmt| expand_stmt(stmt, self))
951 fn fold_block(&mut self, block: P<Block>) -> P<Block> {
952 expand_block(block, self)
955 fn fold_arm(&mut self, arm: ast::Arm) -> ast::Arm {
956 expand_arm(arm, self)
959 fn fold_method(&mut self, method: P<ast::Method>) -> SmallVector<P<ast::Method>> {
960 expand_method(method, self)
963 fn new_span(&mut self, span: Span) -> Span {
964 new_span(self.cx, span)
968 fn new_span(cx: &ExtCtxt, sp: Span) -> Span {
969 /* this discards information in the case of macro-defining macros */
973 expn_id: cx.backtrace(),
977 pub struct ExpansionConfig {
978 pub crate_name: String,
979 pub deriving_hash_type_parameter: bool,
980 pub enable_quotes: bool,
983 impl ExpansionConfig {
984 pub fn default(crate_name: String) -> ExpansionConfig {
986 crate_name: crate_name,
987 deriving_hash_type_parameter: false,
988 enable_quotes: false,
993 pub struct ExportedMacros {
994 pub crate_name: Ident,
995 pub macros: Vec<String>,
998 pub fn expand_crate(parse_sess: &parse::ParseSess,
999 cfg: ExpansionConfig,
1000 // these are the macros being imported to this crate:
1001 imported_macros: Vec<ExportedMacros>,
1002 user_exts: Vec<NamedSyntaxExtension>,
1003 c: Crate) -> Crate {
1004 let mut cx = ExtCtxt::new(parse_sess, c.config.clone(), cfg);
1005 let mut expander = MacroExpander {
1009 for ExportedMacros { crate_name, macros } in imported_macros.into_iter() {
1010 let name = format!("<{} macros>", token::get_ident(crate_name))
1013 for source in macros.into_iter() {
1014 let item = parse::parse_item_from_source_str(name.clone(),
1017 expander.cx.parse_sess())
1018 .expect("expected a serialized item");
1019 expand_item_mac(item, &mut expander);
1023 for (name, extension) in user_exts.into_iter() {
1024 expander.cx.syntax_env.insert(name, extension);
1027 let mut ret = expander.fold_crate(c);
1028 ret.exported_macros = expander.cx.exported_macros.clone();
1029 parse_sess.span_diagnostic.handler().abort_if_errors();
1033 // HYGIENIC CONTEXT EXTENSION:
1034 // all of these functions are for walking over
1035 // ASTs and making some change to the context of every
1036 // element that has one. a CtxtFn is a trait-ified
1037 // version of a closure in (SyntaxContext -> SyntaxContext).
1038 // the ones defined here include:
1039 // Marker - add a mark to a context
1041 // A Marker adds the given mark to the syntax context
1042 struct Marker { mark: Mrk }
1044 impl Folder for Marker {
1045 fn fold_ident(&mut self, id: Ident) -> Ident {
1048 ctxt: mtwt::apply_mark(self.mark, id.ctxt)
1051 fn fold_mac(&mut self, Spanned {node, span}: ast::Mac) -> ast::Mac {
1054 MacInvocTT(path, tts, ctxt) => {
1055 MacInvocTT(self.fold_path(path),
1056 self.fold_tts(tts.as_slice()),
1057 mtwt::apply_mark(self.mark, ctxt))
1065 // apply a given mark to the given token trees. Used prior to expansion of a macro.
1066 fn mark_tts(tts: &[TokenTree], m: Mrk) -> Vec<TokenTree> {
1067 noop_fold_tts(tts, &mut Marker{mark:m})
1070 // apply a given mark to the given expr. Used following the expansion of a macro.
1071 fn mark_expr(expr: P<ast::Expr>, m: Mrk) -> P<ast::Expr> {
1072 Marker{mark:m}.fold_expr(expr)
1075 // apply a given mark to the given pattern. Used following the expansion of a macro.
1076 fn mark_pat(pat: P<ast::Pat>, m: Mrk) -> P<ast::Pat> {
1077 Marker{mark:m}.fold_pat(pat)
1080 // apply a given mark to the given stmt. Used following the expansion of a macro.
1081 fn mark_stmt(expr: P<ast::Stmt>, m: Mrk) -> P<ast::Stmt> {
1082 Marker{mark:m}.fold_stmt(expr)
1083 .expect_one("marking a stmt didn't return exactly one stmt")
1086 // apply a given mark to the given item. Used following the expansion of a macro.
1087 fn mark_item(expr: P<ast::Item>, m: Mrk) -> P<ast::Item> {
1088 Marker{mark:m}.fold_item(expr)
1089 .expect_one("marking an item didn't return exactly one item")
1092 // apply a given mark to the given item. Used following the expansion of a macro.
1093 fn mark_method(expr: P<ast::Method>, m: Mrk) -> P<ast::Method> {
1094 Marker{mark:m}.fold_method(expr)
1095 .expect_one("marking an item didn't return exactly one method")
1098 /// Check that there are no macro invocations left in the AST:
1099 pub fn check_for_macros(sess: &parse::ParseSess, krate: &ast::Crate) {
1100 visit::walk_crate(&mut MacroExterminator{sess:sess}, krate);
1103 /// A visitor that ensures that no macro invocations remain in an AST.
1104 struct MacroExterminator<'a>{
1105 sess: &'a parse::ParseSess
1108 impl<'a, 'v> Visitor<'v> for MacroExterminator<'a> {
1109 fn visit_mac(&mut self, macro: &ast::Mac) {
1110 self.sess.span_diagnostic.span_bug(macro.span,
1111 "macro exterminator: expected AST \
1112 with no macro invocations");
1119 use super::{pattern_bindings, expand_crate, contains_macro_escape};
1120 use super::{PatIdentFinder, IdentRenamer, PatIdentRenamer, ExpansionConfig};
1122 use ast::{Attribute_, AttrOuter, MetaWord, Name};
1125 use codemap::Spanned;
1131 use util::parser_testing::{string_to_parser};
1132 use util::parser_testing::{string_to_pat, string_to_crate, strs_to_idents};
1136 // a visitor that extracts the paths
1137 // from a given thingy and puts them in a mutable
1138 // array (passed in to the traversal)
1140 struct PathExprFinderContext {
1141 path_accumulator: Vec<ast::Path> ,
1144 impl<'v> Visitor<'v> for PathExprFinderContext {
1145 fn visit_expr(&mut self, expr: &ast::Expr) {
1147 ast::ExprPath(ref p) => {
1148 self.path_accumulator.push(p.clone());
1149 // not calling visit_path, but it should be fine.
1151 _ => visit::walk_expr(self, expr)
1156 // find the variable references in a crate
1157 fn crate_varrefs(the_crate : &ast::Crate) -> Vec<ast::Path> {
1158 let mut path_finder = PathExprFinderContext{path_accumulator:Vec::new()};
1159 visit::walk_crate(&mut path_finder, the_crate);
1160 path_finder.path_accumulator
1163 /// A Visitor that extracts the identifiers from a thingy.
1164 // as a side note, I'm starting to want to abstract over these....
1165 struct IdentFinder {
1166 ident_accumulator: Vec<ast::Ident>
1169 impl<'v> Visitor<'v> for IdentFinder {
1170 fn visit_ident(&mut self, _: codemap::Span, id: ast::Ident){
1171 self.ident_accumulator.push(id);
1175 /// Find the idents in a crate
1176 fn crate_idents(the_crate: &ast::Crate) -> Vec<ast::Ident> {
1177 let mut ident_finder = IdentFinder{ident_accumulator: Vec::new()};
1178 visit::walk_crate(&mut ident_finder, the_crate);
1179 ident_finder.ident_accumulator
1182 // these following tests are quite fragile, in that they don't test what
1183 // *kind* of failure occurs.
1185 fn test_ecfg() -> ExpansionConfig {
1186 ExpansionConfig::default("test".to_string())
1189 // make sure that macros can't escape fns
1191 #[test] fn macros_cant_escape_fns_test () {
1192 let src = "fn bogus() {macro_rules! z (() => (3+4))}\
1193 fn inty() -> int { z!() }".to_string();
1194 let sess = parse::new_parse_sess();
1195 let crate_ast = parse::parse_crate_from_source_str(
1196 "<test>".to_string(),
1200 expand_crate(&sess,test_ecfg(),vec!(),vec!(),crate_ast);
1203 // make sure that macros can't escape modules
1205 #[test] fn macros_cant_escape_mods_test () {
1206 let src = "mod foo {macro_rules! z (() => (3+4))}\
1207 fn inty() -> int { z!() }".to_string();
1208 let sess = parse::new_parse_sess();
1209 let crate_ast = parse::parse_crate_from_source_str(
1210 "<test>".to_string(),
1213 expand_crate(&sess,test_ecfg(),vec!(),vec!(),crate_ast);
1216 // macro_escape modules should allow macros to escape
1217 #[test] fn macros_can_escape_flattened_mods_test () {
1218 let src = "#[macro_escape] mod foo {macro_rules! z (() => (3+4))}\
1219 fn inty() -> int { z!() }".to_string();
1220 let sess = parse::new_parse_sess();
1221 let crate_ast = parse::parse_crate_from_source_str(
1222 "<test>".to_string(),
1225 expand_crate(&sess, test_ecfg(), vec!(), vec!(), crate_ast);
1228 #[test] fn test_contains_flatten (){
1229 let attr1 = make_dummy_attr ("foo");
1230 let attr2 = make_dummy_attr ("bar");
1231 let escape_attr = make_dummy_attr ("macro_escape");
1232 let attrs1 = vec!(attr1.clone(), escape_attr, attr2.clone());
1233 assert_eq!(contains_macro_escape(attrs1.as_slice()),true);
1234 let attrs2 = vec!(attr1,attr2);
1235 assert_eq!(contains_macro_escape(attrs2.as_slice()),false);
1238 // make a MetaWord outer attribute with the given name
1239 fn make_dummy_attr(s: &str) -> ast::Attribute {
1241 span:codemap::DUMMY_SP,
1243 id: attr::mk_attr_id(),
1246 node: MetaWord(token::intern_and_get_ident(s)),
1247 span: codemap::DUMMY_SP,
1249 is_sugared_doc: false,
1254 fn expand_crate_str(crate_str: String) -> ast::Crate {
1255 let ps = parse::new_parse_sess();
1256 let crate_ast = string_to_parser(&ps, crate_str).parse_crate_mod();
1257 // the cfg argument actually does matter, here...
1258 expand_crate(&ps,test_ecfg(),vec!(),vec!(),crate_ast)
1261 // find the pat_ident paths in a crate
1262 fn crate_bindings(the_crate : &ast::Crate) -> Vec<ast::Ident> {
1263 let mut name_finder = PatIdentFinder{ident_accumulator:Vec::new()};
1264 visit::walk_crate(&mut name_finder, the_crate);
1265 name_finder.ident_accumulator
1268 #[test] fn macro_tokens_should_match(){
1270 "macro_rules! m((a)=>(13)) fn main(){m!(a);}".to_string());
1273 // should be able to use a bound identifier as a literal in a macro definition:
1274 #[test] fn self_macro_parsing(){
1276 "macro_rules! foo ((zz) => (287u;))
1277 fn f(zz : int) {foo!(zz);}".to_string()
1281 // renaming tests expand a crate and then check that the bindings match
1282 // the right varrefs. The specification of the test case includes the
1283 // text of the crate, and also an array of arrays. Each element in the
1284 // outer array corresponds to a binding in the traversal of the AST
1285 // induced by visit. Each of these arrays contains a list of indexes,
1286 // interpreted as the varrefs in the varref traversal that this binding
1287 // should match. So, for instance, in a program with two bindings and
1288 // three varrefs, the array ~[~[1,2],~[0]] would indicate that the first
1289 // binding should match the second two varrefs, and the second binding
1290 // should match the first varref.
1292 // Put differently; this is a sparse representation of a boolean matrix
1293 // indicating which bindings capture which identifiers.
1295 // Note also that this matrix is dependent on the implicit ordering of
1296 // the bindings and the varrefs discovered by the name-finder and the path-finder.
1298 // The comparisons are done post-mtwt-resolve, so we're comparing renamed
1299 // names; differences in marks don't matter any more.
1301 // oog... I also want tests that check "bound-identifier-=?". That is,
1302 // not just "do these have the same name", but "do they have the same
1303 // name *and* the same marks"? Understanding this is really pretty painful.
1304 // in principle, you might want to control this boolean on a per-varref basis,
1305 // but that would make things even harder to understand, and might not be
1306 // necessary for thorough testing.
1307 type RenamingTest = (&'static str, Vec<Vec<uint>>, bool);
1310 fn automatic_renaming () {
1311 let tests: Vec<RenamingTest> =
1312 vec!(// b & c should get new names throughout, in the expr too:
1313 ("fn a() -> int { let b = 13; let c = b; b+c }",
1314 vec!(vec!(0,1),vec!(2)), false),
1315 // both x's should be renamed (how is this causing a bug?)
1316 ("fn main () {let x: int = 13;x;}",
1317 vec!(vec!(0)), false),
1318 // the use of b after the + should be renamed, the other one not:
1319 ("macro_rules! f (($x:ident) => (b + $x)) fn a() -> int { let b = 13; f!(b)}",
1320 vec!(vec!(1)), false),
1321 // the b before the plus should not be renamed (requires marks)
1322 ("macro_rules! f (($x:ident) => ({let b=9; ($x + b)})) fn a() -> int { f!(b)}",
1323 vec!(vec!(1)), false),
1324 // the marks going in and out of letty should cancel, allowing that $x to
1325 // capture the one following the semicolon.
1326 // this was an awesome test case, and caught a *lot* of bugs.
1327 ("macro_rules! letty(($x:ident) => (let $x = 15;))
1328 macro_rules! user(($x:ident) => ({letty!($x); $x}))
1329 fn main() -> int {user!(z)}",
1330 vec!(vec!(0)), false)
1332 for (idx,s) in tests.iter().enumerate() {
1333 run_renaming_test(s,idx);
1337 // no longer a fixme #8062: this test exposes a *potential* bug; our system does
1338 // not behave exactly like MTWT, but a conversation with Matthew Flatt
1339 // suggests that this can only occur in the presence of local-expand, which
1340 // we have no plans to support. ... unless it's needed for item hygiene....
1342 #[test] fn issue_8062(){
1344 &("fn main() {let hrcoo = 19; macro_rules! getx(()=>(hrcoo)); getx!();}",
1345 vec!(vec!(0)), true), 0)
1349 // the z flows into and out of two macros (g & f) along one path, and one
1350 // (just g) along the other, so the result of the whole thing should
1351 // be "let z_123 = 3; z_123"
1353 #[test] fn issue_6994(){
1355 &("macro_rules! g (($x:ident) =>
1356 ({macro_rules! f(($y:ident)=>({let $y=3;$x}));f!($x)}))
1358 vec!(vec!(0)),false),
1362 // match variable hygiene. Should expand into
1363 // fn z() {match 8 {x_1 => {match 9 {x_2 | x_2 if x_2 == x_1 => x_2 + x_1}}}}
1364 #[test] fn issue_9384(){
1366 &("macro_rules! bad_macro (($ex:expr) => ({match 9 {x | x if x == $ex => x + $ex}}))
1367 fn z() {match 8 {x => bad_macro!(x)}}",
1368 // NB: the third "binding" is the repeat of the second one.
1369 vec!(vec!(1,3),vec!(0,2),vec!(0,2)),
1374 // interpolated nodes weren't getting labeled.
1375 // should expand into
1376 // fn main(){let g1_1 = 13; g1_1}}
1377 #[test] fn pat_expand_issue_15221(){
1379 &("macro_rules! inner ( ($e:pat ) => ($e))
1380 macro_rules! outer ( ($e:pat ) => (inner!($e)))
1381 fn main() { let outer!(g) = 13; g;}",
1387 // create a really evil test case where a $x appears inside a binding of $x
1388 // but *shouldn't* bind because it was inserted by a different macro....
1389 // can't write this test case until we have macro-generating macros.
1391 // method arg hygiene
1392 // method expands to fn get_x(&self_0, x_1:int) {self_0 + self_2 + x_3 + x_1}
1393 #[test] fn method_arg_hygiene(){
1395 &("macro_rules! inject_x (()=>(x))
1396 macro_rules! inject_self (()=>(self))
1398 impl A{fn get_x(&self, x: int) {self + inject_self!() + inject_x!() + x;} }",
1399 vec!(vec!(0),vec!(3)),
1404 // ooh, got another bite?
1405 // expands to struct A; impl A {fn thingy(&self_1) {self_1;}}
1406 #[test] fn method_arg_hygiene_2(){
1409 macro_rules! add_method (($T:ty) =>
1410 (impl $T { fn thingy(&self) {self;} }))
1418 // expands to fn q(x_1:int){fn g(x_2:int){x_2 + x_1};}
1419 #[test] fn issue_9383(){
1421 &("macro_rules! bad_macro (($ex:expr) => (fn g(x:int){ x + $ex }))
1422 fn q(x:int) { bad_macro!(x); }",
1423 vec!(vec!(1),vec!(0)),true),
1427 // closure arg hygiene (ExprFnBlock)
1428 // expands to fn f(){(|x_1 : int| {(x_2 + x_1)})(3);}
1429 #[test] fn closure_arg_hygiene(){
1431 &("macro_rules! inject_x (()=>(x))
1432 fn f(){(|x : int| {(inject_x!() + x)})(3);}",
1438 // closure arg hygiene (ExprProc)
1439 // expands to fn f(){(proc(x_1 : int) {(x_2 + x_1)})(3);}
1440 #[test] fn closure_arg_hygiene_2(){
1442 &("macro_rules! inject_x (()=>(x))
1443 fn f(){ (proc(x : int){(inject_x!() + x)})(3); }",
1449 // macro_rules in method position. Sadly, unimplemented.
1450 #[test] fn macro_in_method_posn(){
1452 "macro_rules! my_method (() => (fn thirteen(&self) -> int {13}))
1454 impl A{ my_method!()}
1455 fn f(){A.thirteen;}".to_string());
1458 // another nested macro
1459 // expands to impl Entries {fn size_hint(&self_1) {self_1;}
1460 #[test] fn item_macro_workaround(){
1462 &("macro_rules! item { ($i:item) => {$i}}
1464 macro_rules! iterator_impl {
1465 () => { item!( impl Entries { fn size_hint(&self) { self;}})}}
1466 iterator_impl! { }",
1467 vec!(vec!(0)), true),
1471 // run one of the renaming tests
1472 fn run_renaming_test(t: &RenamingTest, test_idx: uint) {
1473 let invalid_name = token::special_idents::invalid.name;
1474 let (teststr, bound_connections, bound_ident_check) = match *t {
1475 (ref str,ref conns, bic) => (str.to_string(), conns.clone(), bic)
1477 let cr = expand_crate_str(teststr.to_string());
1478 let bindings = crate_bindings(&cr);
1479 let varrefs = crate_varrefs(&cr);
1481 // must be one check clause for each binding:
1482 assert_eq!(bindings.len(),bound_connections.len());
1483 for (binding_idx,shouldmatch) in bound_connections.iter().enumerate() {
1484 let binding_name = mtwt::resolve(*bindings.get(binding_idx));
1485 let binding_marks = mtwt::marksof(bindings.get(binding_idx).ctxt, invalid_name);
1486 // shouldmatch can't name varrefs that don't exist:
1487 assert!((shouldmatch.len() == 0) ||
1488 (varrefs.len() > *shouldmatch.iter().max().unwrap()));
1489 for (idx,varref) in varrefs.iter().enumerate() {
1490 let print_hygiene_debug_info = || {
1491 // good lord, you can't make a path with 0 segments, can you?
1492 let final_varref_ident = match varref.segments.last() {
1493 Some(pathsegment) => pathsegment.identifier,
1494 None => fail!("varref with 0 path segments?")
1496 let varref_name = mtwt::resolve(final_varref_ident);
1497 let varref_idents : Vec<ast::Ident>
1498 = varref.segments.iter().map(|s| s.identifier)
1500 println!("varref #{}: {}, resolves to {}",idx, varref_idents, varref_name);
1501 let string = token::get_ident(final_varref_ident);
1502 println!("varref's first segment's string: \"{}\"", string.get());
1503 println!("binding #{}: {}, resolves to {}",
1504 binding_idx, *bindings.get(binding_idx), binding_name);
1505 mtwt::with_sctable(|x| mtwt::display_sctable(x));
1507 if shouldmatch.contains(&idx) {
1508 // it should be a path of length 1, and it should
1509 // be free-identifier=? or bound-identifier=? to the given binding
1510 assert_eq!(varref.segments.len(),1);
1511 let varref_name = mtwt::resolve(varref.segments.get(0).identifier);
1512 let varref_marks = mtwt::marksof(varref.segments
1517 if !(varref_name==binding_name) {
1518 println!("uh oh, should match but doesn't:");
1519 print_hygiene_debug_info();
1521 assert_eq!(varref_name,binding_name);
1522 if bound_ident_check {
1523 // we're checking bound-identifier=?, and the marks
1524 // should be the same, too:
1525 assert_eq!(varref_marks,binding_marks.clone());
1528 let varref_name = mtwt::resolve(varref.segments.get(0).identifier);
1529 let fail = (varref.segments.len() == 1)
1530 && (varref_name == binding_name);
1533 println!("failure on test {}",test_idx);
1534 println!("text of test case: \"{}\"", teststr);
1536 println!("uh oh, matches but shouldn't:");
1537 print_hygiene_debug_info();
1545 #[test] fn fmt_in_macro_used_inside_module_macro() {
1546 let crate_str = "macro_rules! fmt_wrap(($b:expr)=>($b.to_string()))
1547 macro_rules! foo_module (() => (mod generated { fn a() { let xx = 147; fmt_wrap!(xx);}}))
1550 let cr = expand_crate_str(crate_str);
1551 // find the xx binding
1552 let bindings = crate_bindings(&cr);
1553 let cxbinds: Vec<&ast::Ident> =
1554 bindings.iter().filter(|b| {
1555 let ident = token::get_ident(**b);
1556 let string = ident.get();
1559 let cxbinds: &[&ast::Ident] = cxbinds.as_slice();
1560 let cxbind = match cxbinds {
1562 _ => fail!("expected just one binding for ext_cx")
1564 let resolved_binding = mtwt::resolve(*cxbind);
1565 let varrefs = crate_varrefs(&cr);
1567 // the xx binding should bind all of the xx varrefs:
1568 for (idx,v) in varrefs.iter().filter(|p| {
1569 p.segments.len() == 1
1570 && "xx" == token::get_ident(p.segments.get(0).identifier).get()
1572 if mtwt::resolve(v.segments.get(0).identifier) != resolved_binding {
1573 println!("uh oh, xx binding didn't match xx varref:");
1574 println!("this is xx varref \\# {:?}",idx);
1575 println!("binding: {:?}",cxbind);
1576 println!("resolves to: {:?}",resolved_binding);
1577 println!("varref: {:?}",v.segments.get(0).identifier);
1578 println!("resolves to: {:?}",
1579 mtwt::resolve(v.segments.get(0).identifier));
1580 mtwt::with_sctable(|x| mtwt::display_sctable(x));
1582 assert_eq!(mtwt::resolve(v.segments.get(0).identifier),
1589 let pat = string_to_pat(
1590 "(a,Foo{x:c @ (b,9),y:Bar(4,d)})".to_string());
1591 let idents = pattern_bindings(&*pat);
1592 assert_eq!(idents, strs_to_idents(vec!("a","c","b","d")));
1595 // test the list of identifier patterns gathered by the visitor. Note that
1596 // 'None' is listed as an identifier pattern because we don't yet know that
1597 // it's the name of a 0-ary variant, and that 'i' appears twice in succession.
1599 fn crate_bindings_test(){
1600 let the_crate = string_to_crate("fn main (a : int) -> int {|b| {
1601 match 34 {None => 3, Some(i) | i => j, Foo{k:z,l:y} => \"banana\"}} }".to_string());
1602 let idents = crate_bindings(&the_crate);
1603 assert_eq!(idents, strs_to_idents(vec!("a","b","None","i","i","z","y")));
1606 // test the IdentRenamer directly
1608 fn ident_renamer_test () {
1609 let the_crate = string_to_crate("fn f(x : int){let x = x; x}".to_string());
1610 let f_ident = token::str_to_ident("f");
1611 let x_ident = token::str_to_ident("x");
1612 let int_ident = token::str_to_ident("int");
1613 let renames = vec!((x_ident,Name(16)));
1614 let mut renamer = IdentRenamer{renames: &renames};
1615 let renamed_crate = renamer.fold_crate(the_crate);
1616 let idents = crate_idents(&renamed_crate);
1617 let resolved : Vec<ast::Name> = idents.iter().map(|id| mtwt::resolve(*id)).collect();
1618 assert_eq!(resolved,vec!(f_ident.name,Name(16),int_ident.name,Name(16),Name(16),Name(16)));
1621 // test the PatIdentRenamer; only PatIdents get renamed
1623 fn pat_ident_renamer_test () {
1624 let the_crate = string_to_crate("fn f(x : int){let x = x; x}".to_string());
1625 let f_ident = token::str_to_ident("f");
1626 let x_ident = token::str_to_ident("x");
1627 let int_ident = token::str_to_ident("int");
1628 let renames = vec!((x_ident,Name(16)));
1629 let mut renamer = PatIdentRenamer{renames: &renames};
1630 let renamed_crate = renamer.fold_crate(the_crate);
1631 let idents = crate_idents(&renamed_crate);
1632 let resolved : Vec<ast::Name> = idents.iter().map(|id| mtwt::resolve(*id)).collect();
1633 let x_name = x_ident.name;
1634 assert_eq!(resolved,vec!(f_ident.name,Name(16),int_ident.name,Name(16),x_name,x_name));