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, Mac_, Name};
13 use ast::{ItemMac, MacStmtWithSemicolon, Mrk, Stmt, StmtDecl, StmtMac};
14 use ast::{StmtExpr, StmtSemi};
18 use ext::build::AstBuilder;
20 use attr::AttrMetaMethods;
22 use codemap::{Span, Spanned, ExpnInfo, NameAndSpan, MacroBang, MacroAttribute};
24 use feature_gate::{self, Features, GatedCfg};
28 use parse::token::{fresh_mark, fresh_name, intern};
30 use util::small_vector::SmallVector;
35 use std::collections::HashSet;
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 {
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,
50 return DummyResult::raw_expr(span);
54 // Keep going, outside-in.
55 let fully_expanded = fld.fold_expr(expanded_expr);
56 let span = fld.new_span(span);
59 fully_expanded.map(|e| ast::Expr {
60 id: ast::DUMMY_NODE_ID,
66 ast::ExprInPlace(placer, value_expr) => {
67 // Ensure feature-gate is enabled
68 feature_gate::check_for_placement_in(
70 &fld.cx.parse_sess.span_diagnostic,
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))
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))
84 ast::ExprWhileLet(pat, expr, body, opt_ident) => {
85 let pat = fld.fold_pat(pat);
86 let expr = fld.fold_expr(expr);
88 // Hygienic renaming of the body.
89 let ((body, opt_ident), mut rewritten_pats) =
90 rename_in_scope(vec![pat],
93 |rename_fld, fld, (body, opt_ident)| {
94 expand_loop_block(rename_fld.fold_block(body), opt_ident, fld)
96 assert!(rewritten_pats.len() == 1);
98 fld.cx.expr(span, ast::ExprWhileLet(rewritten_pats.remove(0), expr, body, opt_ident))
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))
106 ast::ExprForLoop(pat, head, body, opt_ident) => {
107 let pat = fld.fold_pat(pat);
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],
114 |rename_fld, fld, (body, opt_ident)| {
115 expand_loop_block(rename_fld.fold_block(body), opt_ident, fld)
117 assert!(rewritten_pats.len() == 1);
119 let head = fld.fold_expr(head);
120 fld.cx.expr(span, ast::ExprForLoop(rewritten_pats.remove(0), head, body, opt_ident))
123 ast::ExprIfLet(pat, sub_expr, body, else_opt) => {
124 let pat = fld.fold_pat(pat);
126 // Hygienic renaming of the body.
127 let (body, mut rewritten_pats) =
128 rename_in_scope(vec![pat],
131 |rename_fld, fld, body| {
132 fld.fold_block(rename_fld.fold_block(body))
134 assert!(rewritten_pats.len() == 1);
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))
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,
147 P(ast::Expr{id:id, node: new_node, span: fld.new_span(span)})
151 P(noop_fold_expr(ast::Expr {
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,
168 fld: &mut MacroExpander)
170 F: for<'a> FnOnce(Box<MacResult+'a>) -> Option<T>,
171 G: FnOnce(T, Mrk) -> T,
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
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 \
184 // let compilation continue
187 let extname = pth.segments[0].identifier.name;
188 match fld.cx.syntax_env.find(extname) {
192 &format!("macro undefined: '{}!'",
194 fld.cx.suggest_macro_name(&extname.as_str(), pth.span);
196 // let compilation continue
199 Some(rc) => match *rc {
200 NormalTT(ref expandfun, exp_span, allow_internal_unstable) => {
201 fld.cx.bt_push(ExpnInfo {
203 callee: NameAndSpan {
204 format: MacroBang(extname),
206 allow_internal_unstable: allow_internal_unstable,
209 let fm = fresh_mark();
210 let marked_before = mark_tts(&tts[..], fm);
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
216 let mac_span = fld.cx.original_span();
219 let expanded = expandfun.expand(fld.cx,
222 parse_thunk(expanded)
224 let parsed = match opt_parsed {
229 &format!("non-expression macro in expression position: {}",
235 Some(mark_thunk(parsed,fm))
240 &format!("'{}' is not a tt-style macro",
248 /// Rename loop label and expand its loop body
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>) {
258 let new_label = fresh_name(label);
259 let rename = (label, new_label);
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);
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();
277 (expanded_block, Some(renamed_ident))
279 None => (fld.fold_block(loop_block), opt_ident)
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;
290 $extsboxexpr.pop_frame();
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);
300 expand_annotatable(it, fld)
301 .into_iter().map(|i| i.expect_item()).collect()
304 /// Expand item_underscore
305 fn expand_item_underscore(item: ast::Item_, fld: &mut MacroExpander) -> ast::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)
314 _ => noop_fold_item_underscore(item, fld)
318 // does this attribute list contain "macro_use" ?
319 fn contains_macro_use(fld: &mut MacroExpander, attrs: &[ast::Attribute]) -> bool {
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");
325 if let ast::AttrStyle::Inner = attr.node.style {
326 fld.cx.fileline_help(attr.span, "consider an outer attribute, \
327 #[macro_use] mod ...");
332 match attr.node.value.node {
333 ast::MetaWord(..) => (),
334 _ => fld.cx.span_err(attr.span, "arguments to macro_use are not allowed here"),
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")
352 let fm = fresh_mark();
354 let expanded = match fld.cx.syntax_env.find(extname) {
356 fld.cx.span_err(path_span,
357 &format!("macro undefined: '{}!'",
359 // let compilation continue
360 return SmallVector::zero();
363 Some(rc) => match *rc {
364 NormalTT(ref expander, tt_span, allow_internal_unstable) => {
365 if ident.name != parse::token::special_idents::invalid.name {
368 &format!("macro {}! expects no ident argument, given '{}'",
371 return SmallVector::zero();
373 fld.cx.bt_push(ExpnInfo {
375 callee: NameAndSpan {
376 format: MacroBang(extname),
378 allow_internal_unstable: allow_internal_unstable,
381 // mark before expansion:
382 let marked_before = mark_tts(&tts[..], fm);
383 expander.expand(fld.cx, span, &marked_before[..])
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",
390 return SmallVector::zero();
392 fld.cx.bt_push(ExpnInfo {
394 callee: NameAndSpan {
395 format: MacroBang(extname),
397 allow_internal_unstable: allow_internal_unstable,
400 // mark before expansion:
401 let marked_tts = mark_tts(&tts[..], fm);
402 expander.expand(fld.cx, span, ident, marked_tts)
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();
410 fld.cx.bt_push(ExpnInfo {
412 callee: NameAndSpan {
413 format: MacroBang(extname),
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,
421 // DON'T mark before expansion.
423 let allow_internal_unstable = attr::contains_name(&attrs,
424 "allow_internal_unstable");
426 // ensure any #[allow_internal_unstable]s are
427 // detected (including nested macro definitions
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",
434 feature_gate::GateIssue::Language,
435 feature_gate::EXPLAIN_ALLOW_INTERNAL_UNSTABLE)
438 let export = attr::contains_name(&attrs, "macro_export");
439 let def = ast::MacroDef {
442 id: ast::DUMMY_NODE_ID,
447 allow_internal_unstable: allow_internal_unstable,
450 fld.cx.insert_macro(def);
452 // macro_rules! has a side effect but expands to nothing.
454 return SmallVector::zero();
457 fld.cx.span_err(span,
458 &format!("{}! is not legal in item position",
460 return SmallVector::zero();
465 expanded.make_items()
468 let items = match items {
471 .map(|i| mark_item(i, fm))
472 .flat_map(|i| fld.fold_item(i).into_iter())
476 fld.cx.span_err(path_span,
477 &format!("non-item macro in item position: {}",
479 return SmallVector::zero();
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)
495 let maybe_new_items =
496 expand_mac_invoc(mac.and_then(|m| m), stmt.span,
498 |stmts, mark| stmts.move_map(|m| mark_stmt(m, mark)),
501 let mut fully_expanded = match maybe_new_items {
503 // Keep going, outside-in.
504 let new_items = stmts.into_iter().flat_map(|s| {
505 fld.fold_stmt(s).into_iter()
510 None => SmallVector::zero()
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}| {
520 StmtExpr(e, stmt_id) => StmtSemi(e, stmt_id),
521 _ => node /* might already have a semi */
526 fully_expanded.push(new_stmt);
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>> {
539 StmtDecl(decl, node_id) => decl.and_then(|Spanned {node: decl, span}| match decl {
540 DeclLocal(local) => {
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)
563 // add them to the existing pending renames:
564 fld.cx.syntax_env.info().pending_renames
565 .extend(new_pending_renames);
570 // also, don't forget to expand the init:
571 init: init.map(|e| fld.fold_expr(e)),
575 SmallVector::one(P(Spanned {
576 node: StmtDecl(P(Spanned {
577 node: DeclLocal(rewritten_local),
585 noop_fold_stmt(Spanned {
586 node: StmtDecl(P(Spanned {
596 noop_fold_stmt(Spanned {
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");
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,
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)
624 attrs: fold::fold_attrs(arm.attrs, fld),
625 pats: rewritten_pats,
626 guard: rewritten_guard,
627 body: rewritten_body,
631 fn rename_in_scope<X, F>(pats: Vec<P<ast::Pat>>,
632 fld: &mut MacroExpander,
635 -> (X, Vec<P<ast::Pat>>)
636 where F: Fn(&mut IdentRenamer, &mut MacroExpander, X) -> X
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));
646 let mut rename_fld = IdentRenamer{ renames:&new_renames };
647 (f(&mut rename_fld, fld, x), rewritten_pats)
650 /// A visitor that extracts the PatIdent (binding) paths
651 /// from a given thingy and puts them in a mutable
654 struct PatIdentFinder {
655 ident_accumulator: Vec<ast::Ident>
658 impl<'v> Visitor<'v> for PatIdentFinder {
659 fn visit_pat(&mut self, pattern: &ast::Pat) {
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)
668 // use the default traversal for non-PatIdents
669 _ => visit::walk_pat(self, pattern)
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
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);
687 pat_idents.ident_accumulator
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))
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
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")
707 // expand macros in the statement
708 fld.fold_stmt(renamed_stmt).into_iter()
710 let new_expr = expr.map(|x| {
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)
728 fn expand_pat(p: P<ast::Pat>, fld: &mut MacroExpander) -> P<ast::Pat> {
731 _ => return noop_fold_pat(p, fld)
733 p.map(|ast::Pat {node, span, ..}| {
734 let (pth, tts) = match node {
735 PatMac(mac) => (mac.node.path, mac.node.tts),
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);
742 let extname = pth.segments[0].identifier.name;
743 let marked_after = match fld.cx.syntax_env.find(extname) {
745 fld.cx.span_err(pth.span,
746 &format!("macro undefined: '{}!'",
748 // let compilation continue
749 return DummyResult::raw_pat(span);
752 Some(rc) => match *rc {
753 NormalTT(ref expander, tt_span, allow_internal_unstable) => {
754 fld.cx.bt_push(ExpnInfo {
756 callee: NameAndSpan {
757 format: MacroBang(extname),
759 allow_internal_unstable: allow_internal_unstable,
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,
768 &marked_before[..]).make_pat();
769 let expanded = match pat {
775 "non-pattern macro in pattern position: {}",
779 return DummyResult::raw_pat(span);
784 mark_pat(expanded,fm)
787 fld.cx.span_err(span,
788 &format!("{}! is not legal in pattern position",
790 return DummyResult::raw_pat(span);
796 fld.fold_pat(marked_after).node.clone();
800 id: ast::DUMMY_NODE_ID,
801 node: fully_expanded,
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,
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))
818 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
819 fold::noop_fold_mac(mac, self)
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,
831 impl<'a> Folder for PatIdentRenamer<'a> {
832 fn fold_pat(&mut self, pat: P<ast::Pat>) -> P<ast::Pat> {
834 ast::PatIdent(..) => {},
835 _ => return noop_fold_pat(pat, self)
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));
843 ast::PatIdent(binding_mode,
844 Spanned{span: self.new_span(sp), node: new_ident},
845 sub.map(|p| self.fold_pat(p)));
849 span: self.new_span(span)
855 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
856 fold::noop_fold_mac(mac, self)
860 fn expand_annotatable(a: Annotatable,
861 fld: &mut MacroExpander)
862 -> SmallVector<Annotatable> {
863 let a = expand_item_multi_modifier(a, fld);
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);
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()
874 ast::ItemMod(_) | ast::ItemForeignMod(_) => {
876 it.ident.name != parse::token::special_idents::invalid.name;
879 fld.cx.mod_push(it.ident);
881 let macro_use = contains_macro_use(fld, &new_attrs[..]);
882 let result = with_exts_frame!(fld.cx.syntax_env,
884 noop_fold_item(it, fld));
888 result.into_iter().map(|i| Annotatable::Item(i)).collect()
891 let it = P(ast::Item {
895 noop_fold_item(it, fld).into_iter().map(|i| Annotatable::Item(i)).collect()
899 Annotatable::TraitItem(it) => match it.node {
900 ast::MethodTraitItem(_, Some(_)) => SmallVector::one(it.map(|ti| ast::TraitItem {
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))
911 span: fld.new_span(ti.span)
913 _ => fold::noop_fold_trait_item(it, fld)
914 }.into_iter().map(Annotatable::TraitItem).collect(),
916 Annotatable::ImplItem(ii) => {
917 expand_impl_item(ii, fld).into_iter().map(Annotatable::ImplItem).collect()
921 new_items.push_all(decorator_items);
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],
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,
945 partition!(multi_modifiers, MultiModifier);
948 fn expand_decorators(a: Annotatable,
949 fld: &mut MacroExpander,
950 decorator_items: &mut SmallVector<Annotatable>,
951 new_attrs: &mut Vec<ast::Attribute>)
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);
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,
967 allow_internal_unstable: true,
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();
978 &mut |ann| items.push(ann));
979 decorator_items.extend(items.into_iter()
980 .flat_map(|ann| expand_annotatable(ann, fld).into_iter()));
984 _ => new_attrs.push((*attr).clone()),
986 _ => new_attrs.push((*attr).clone()),
991 fn expand_item_multi_modifier(mut it: Annotatable,
992 fld: &mut MacroExpander)
994 let (modifiers, other_attrs) = multi_modifiers(it.attrs(), fld);
996 // Update the attrs, leave everything else alone. Is this mutation really a good idea?
997 it = it.fold_attrs(other_attrs);
999 if modifiers.is_empty() {
1003 for attr in &modifiers {
1004 let mname = intern(&attr.name());
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,
1017 allow_internal_unstable: true,
1020 it = mac.expand(fld.cx, attr.span, &*attr.node.value, it);
1029 // Expansion may have added new ItemModifiers.
1030 expand_item_multi_modifier(it, fld)
1033 fn expand_impl_item(ii: P<ast::ImplItem>, fld: &mut MacroExpander)
1034 -> SmallVector<P<ast::ImplItem>> {
1036 ast::ImplItemKind::Method(..) => SmallVector::one(ii.map(|ii| ast::ImplItem {
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)
1048 span: fld.new_span(ii.span)
1050 ast::ImplItemKind::Macro(_) => {
1051 let (span, mac) = ii.and_then(|ii| match ii.node {
1052 ast::ImplItemKind::Macro(mac) => (ii.span, mac),
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)),
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()
1070 None => SmallVector::zero()
1073 _ => fold::noop_fold_impl_item(ii, fld)
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);
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)
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);
1102 generics: fld.fold_generics(sig.generics),
1104 explicit_self: fld.fold_explicit_self(sig.explicit_self),
1105 unsafety: sig.unsafety,
1106 constness: sig.constness,
1107 decl: rewritten_fn_decl
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,
1121 return DummyResult::raw_ty(t.span);
1125 // Keep going, outside-in.
1126 let fully_expanded = fld.fold_ty(expanded_ty);
1129 fully_expanded.map(|t| ast::Ty {
1130 id: ast::DUMMY_NODE_ID,
1135 feature_gate::emit_feature_err(
1136 &fld.cx.parse_sess.span_diagnostic,
1139 feature_gate::GateIssue::Language,
1140 "type macros are experimental");
1142 DummyResult::raw_ty(t.span)
1148 fold::noop_fold_ty(t, fld)
1151 /// A tree-folder that performs macro expansion
1152 pub struct MacroExpander<'a, 'b:'a> {
1153 pub cx: &'a mut ExtCtxt<'b>,
1156 impl<'a, 'b> MacroExpander<'a, 'b> {
1157 pub fn new(cx: &'a mut ExtCtxt<'b>) -> MacroExpander<'a, 'b> {
1158 MacroExpander { cx: cx }
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)
1167 fn fold_pat(&mut self, pat: P<ast::Pat>) -> P<ast::Pat> {
1168 expand_pat(pat, self)
1171 fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
1172 expand_item(item, self)
1175 fn fold_item_underscore(&mut self, item: ast::Item_) -> ast::Item_ {
1176 expand_item_underscore(item, self)
1179 fn fold_stmt(&mut self, stmt: P<ast::Stmt>) -> SmallVector<P<ast::Stmt>> {
1180 expand_stmt(stmt, self)
1183 fn fold_block(&mut self, block: P<Block>) -> P<Block> {
1184 expand_block(block, self)
1187 fn fold_arm(&mut self, arm: ast::Arm) -> ast::Arm {
1188 expand_arm(arm, self)
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()
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()
1201 fn fold_ty(&mut self, ty: P<ast::Ty>) -> P<ast::Ty> {
1202 expand_type(ty, self)
1205 fn new_span(&mut self, span: Span) -> Span {
1206 new_span(self.cx, span)
1210 fn new_span(cx: &ExtCtxt, sp: Span) -> Span {
1211 /* this discards information in the case of macro-defining macros */
1215 expn_id: cx.backtrace(),
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,
1226 macro_rules! feature_tests {
1227 ($( fn $getter:ident = $field:ident, )*) => {
1229 pub fn $getter(&self) -> bool {
1230 match self.features {
1231 Some(&Features { $field: true, .. }) => true,
1239 impl<'feat> ExpansionConfig<'feat> {
1240 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1242 crate_name: crate_name,
1244 recursion_limit: 64,
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,
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");
1275 cx.crate_root = Some("std");
1278 let mut expander = MacroExpander::new(&mut cx);
1280 for def in imported_macros {
1281 expander.cx.insert_macro(def);
1284 for (name, extension) in user_exts {
1285 expander.cx.syntax_env.insert(name, extension);
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();
1293 return (ret, cx.syntax_env.names);
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
1304 // A Marker adds the given mark to the syntax context
1305 struct Marker { mark: Mrk }
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))
1311 fn fold_mac(&mut self, Spanned {node, span}: ast::Mac) -> ast::Mac {
1314 path: self.fold_path(node.path),
1315 tts: self.fold_tts(&node.tts),
1316 ctxt: mtwt::apply_mark(self.mark, node.ctxt),
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})
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)
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)
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")
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")
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")
1356 fn mark_ty(ty: P<ast::Ty>, m: Mrk) -> P<ast::Ty> {
1357 Marker { mark: m }.fold_ty(ty)
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);
1365 /// A visitor that ensures that no macro invocations remain in an AST.
1366 struct MacroExterminator<'a>{
1367 sess: &'a parse::ParseSess
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");
1381 use super::{pattern_bindings, expand_crate};
1382 use super::{PatIdentFinder, IdentRenamer, PatIdentRenamer, ExpansionConfig};
1390 use util::parser_testing::{string_to_parser};
1391 use util::parser_testing::{string_to_pat, string_to_crate, strs_to_idents};
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)
1399 struct PathExprFinderContext {
1400 path_accumulator: Vec<ast::Path> ,
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());
1408 visit::walk_expr(self, expr);
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
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>
1425 impl<'v> Visitor<'v> for IdentFinder {
1426 fn visit_ident(&mut self, _: codemap::Span, id: ast::Ident){
1427 self.ident_accumulator.push(id);
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
1438 // these following tests are quite fragile, in that they don't test what
1439 // *kind* of failure occurs.
1441 fn test_ecfg() -> ExpansionConfig<'static> {
1442 ExpansionConfig::default("test".to_string())
1445 // make sure that macros can't escape fns
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(),
1456 expand_crate(&sess,test_ecfg(),vec!(),vec!(), &mut vec![], crate_ast);
1459 // make sure that macros can't escape modules
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(),
1469 expand_crate(&sess,test_ecfg(),vec!(),vec!(), &mut vec![], crate_ast);
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(),
1481 expand_crate(&sess, test_ecfg(), vec!(), vec!(), &mut vec![], crate_ast);
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
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
1498 #[test] fn macro_tokens_should_match(){
1500 "macro_rules! m((a)=>(13)) ;fn main(){m!(a);}".to_string());
1503 // should be able to use a bound identifier as a literal in a macro definition:
1504 #[test] fn self_macro_parsing(){
1506 "macro_rules! foo ((zz) => (287;));
1507 fn f(zz: i32) {foo!(zz);}".to_string()
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.
1522 // Put differently; this is a sparse representation of a boolean matrix
1523 // indicating which bindings capture which identifiers.
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.
1528 // The comparisons are done post-mtwt-resolve, so we're comparing renamed
1529 // names; differences in marks don't matter any more.
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);
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)
1562 for (idx,s) in tests.iter().enumerate() {
1563 run_renaming_test(s,idx);
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....
1575 &("fn main() {let hrcoo = 19; macro_rules! getx(()=>(hrcoo)); getx!();}",
1576 vec!(vec!(0)), true), 0)
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"
1587 &("macro_rules! g (($x:ident) =>
1588 ({macro_rules! f(($y:ident)=>({let $y=3;$x}));f!($x)}));
1590 vec!(vec!(0)),false),
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}}}}
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)),
1607 // interpolated nodes weren't getting labeled.
1608 // should expand into
1609 // fn main(){let g1_1 = 13; g1_1}}
1611 fn pat_expand_issue_15221(){
1613 &("macro_rules! inner ( ($e:pat ) => ($e));
1614 macro_rules! outer ( ($e:pat ) => (inner!($e)));
1615 fn main() { let outer!(g) = 13; g;}",
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.
1625 // method arg hygiene
1626 // method expands to fn get_x(&self_0, x_1: i32) {self_0 + self_2 + x_3 + x_1}
1628 fn method_arg_hygiene(){
1630 &("macro_rules! inject_x (()=>(x));
1631 macro_rules! inject_self (()=>(self));
1633 impl A{fn get_x(&self, x: i32) {self + inject_self!() + inject_x!() + x;} }",
1634 vec!(vec!(0),vec!(3)),
1639 // ooh, got another bite?
1640 // expands to struct A; impl A {fn thingy(&self_1) {self_1;}}
1642 fn method_arg_hygiene_2(){
1645 macro_rules! add_method (($T:ty) =>
1646 (impl $T { fn thingy(&self) {self;} }));
1654 // expands to fn q(x_1: i32){fn g(x_2: i32){x_2 + x_1};}
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),
1664 // closure arg hygiene (ExprClosure)
1665 // expands to fn f(){(|x_1 : i32| {(x_2 + x_1)})(3);}
1667 fn closure_arg_hygiene(){
1669 &("macro_rules! inject_x (()=>(x));
1670 fn f(){(|x : i32| {(inject_x!() + x)})(3);}",
1676 // macro_rules in method position. Sadly, unimplemented.
1678 fn macro_in_method_posn(){
1680 "macro_rules! my_method (() => (fn thirteen(&self) -> i32 {13}));
1682 impl A{ my_method!(); }
1683 fn f(){A.thirteen;}".to_string());
1686 // another nested macro
1687 // expands to impl Entries {fn size_hint(&self_1) {self_1;}
1689 fn item_macro_workaround(){
1691 &("macro_rules! item { ($i:item) => {$i}}
1693 macro_rules! iterator_impl {
1694 () => { item!( impl Entries { fn size_hint(&self) { self;}});}}
1695 iterator_impl! { }",
1696 vec!(vec!(0)), true),
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)
1706 let cr = expand_crate_str(teststr.to_string());
1707 let bindings = crate_bindings(&cr);
1708 let varrefs = crate_varrefs(&cr);
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?")
1725 let varref_name = mtwt::resolve(final_varref_ident);
1726 let varref_idents : Vec<ast::Ident>
1727 = varref.segments.iter().map(|s| s.identifier)
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));
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]
1744 if !(varref_name==binding_name) {
1745 println!("uh oh, should match but doesn't:");
1746 print_hygiene_debug_info();
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());
1755 let varref_name = mtwt::resolve(varref.segments[0].identifier);
1756 let fail = (varref.segments.len() == 1)
1757 && (varref_name == binding_name);
1760 println!("failure on test {}",test_idx);
1761 println!("text of test case: \"{}\"", teststr);
1763 println!("uh oh, matches but shouldn't:");
1764 print_hygiene_debug_info();
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);}}));
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)) {
1786 _ => panic!("expected just one binding for ext_cx")
1788 let resolved_binding = mtwt::resolve(*cxbind);
1789 let varrefs = crate_varrefs(&cr);
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"
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));
1806 assert_eq!(mtwt::resolve(v.segments[0].identifier),
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")));
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.
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")));
1830 // test the IdentRenamer directly
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)]);
1845 // test the PatIdentRenamer; only PatIdents get renamed
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]);