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, 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, CompilerExpansion};
24 use feature_gate::{self, Features};
28 use parse::token::{fresh_mark, fresh_name, intern};
31 use util::small_vector::SmallVector;
36 pub fn expand_expr(e: P<ast::Expr>, fld: &mut MacroExpander) -> P<ast::Expr> {
37 fn push_compiler_expansion(fld: &mut MacroExpander, span: Span, expansion_desc: &str) {
38 fld.cx.bt_push(ExpnInfo {
41 name: expansion_desc.to_string(),
42 format: CompilerExpansion,
43 allow_internal_unstable: true,
49 e.and_then(|ast::Expr {id, node, span}| match node {
50 // expr_mac should really be expr_ext or something; it's the
51 // entry-point for all syntax extensions.
52 ast::ExprMac(mac) => {
53 let expanded_expr = match expand_mac_invoc(mac, span,
58 return DummyResult::raw_expr(span);
62 // Keep going, outside-in.
63 let fully_expanded = fld.fold_expr(expanded_expr);
64 let span = fld.new_span(span);
67 fully_expanded.map(|e| ast::Expr {
68 id: ast::DUMMY_NODE_ID,
74 ast::ExprWhile(cond, body, opt_ident) => {
75 let cond = fld.fold_expr(cond);
76 let (body, opt_ident) = expand_loop_block(body, opt_ident, fld);
77 fld.cx.expr(span, ast::ExprWhile(cond, body, opt_ident))
80 // Desugar ExprWhileLet
81 // From: `[opt_ident]: while let <pat> = <expr> <body>`
82 ast::ExprWhileLet(pat, expr, body, opt_ident) => {
85 // [opt_ident]: loop {
92 push_compiler_expansion(fld, span, "while let expansion");
96 let body_expr = fld.cx.expr_block(body);
97 fld.cx.arm(pat.span, vec![pat], body_expr)
102 let pat_under = fld.cx.pat_wild(span);
103 let break_expr = fld.cx.expr_break(span);
104 fld.cx.arm(span, vec![pat_under], break_expr)
107 // `match <expr> { ... }`
108 let arms = vec![pat_arm, break_arm];
109 let match_expr = fld.cx.expr(span,
110 ast::ExprMatch(expr, arms, ast::MatchSource::WhileLetDesugar));
112 // `[opt_ident]: loop { ... }`
113 let loop_block = fld.cx.block_expr(match_expr);
114 let (loop_block, opt_ident) = expand_loop_block(loop_block, opt_ident, fld);
115 let result = fld.cx.expr(span, ast::ExprLoop(loop_block, opt_ident));
121 // From: `if let <pat> = <expr> <body> [<elseopt>]`
122 ast::ExprIfLet(pat, expr, body, mut elseopt) => {
127 // [_ if <elseopt_if_cond> => <elseopt_if_body>,]
128 // _ => [<elseopt> | ()]
131 push_compiler_expansion(fld, span, "if let expansion");
135 let body_expr = fld.cx.expr_block(body);
136 fld.cx.arm(pat.span, vec![pat], body_expr)
139 // `[_ if <elseopt_if_cond> => <elseopt_if_body>,]`
141 let mut arms = vec![];
143 let elseopt_continue = elseopt
144 .and_then(|els| els.and_then(|els| match els.node {
146 ast::ExprIf(cond, then, elseopt) => {
147 let pat_under = fld.cx.pat_wild(span);
150 pats: vec![pat_under],
152 body: fld.cx.expr_block(then)
154 elseopt.map(|elseopt| (elseopt, true))
156 _ => Some((P(els), false))
158 match elseopt_continue {
162 Some((e, false)) => {
175 let contains_else_clause = elseopt.is_some();
177 // `_ => [<elseopt> | ()]`
179 let pat_under = fld.cx.pat_wild(span);
180 let else_expr = elseopt.unwrap_or_else(|| fld.cx.expr_tuple(span, vec![]));
181 fld.cx.arm(span, vec![pat_under], else_expr)
184 let mut arms = Vec::with_capacity(else_if_arms.len() + 2);
186 arms.extend(else_if_arms);
189 let match_expr = fld.cx.expr(span,
190 ast::ExprMatch(expr, arms,
191 ast::MatchSource::IfLetDesugar {
192 contains_else_clause: contains_else_clause,
194 let result = fld.fold_expr(match_expr);
199 // Desugar support for ExprIfLet in the ExprIf else position
200 ast::ExprIf(cond, blk, elseopt) => {
201 let elseopt = elseopt.map(|els| els.and_then(|els| match els.node {
202 ast::ExprIfLet(..) => {
203 push_compiler_expansion(fld, span, "if let expansion");
204 // wrap the if-let expr in a block
206 let blk = P(ast::Block {
209 id: ast::DUMMY_NODE_ID,
210 rules: ast::DefaultBlock,
213 let result = fld.cx.expr_block(blk);
219 let if_expr = fld.cx.expr(span, ast::ExprIf(cond, blk, elseopt));
220 if_expr.map(|e| noop_fold_expr(e, fld))
223 ast::ExprLoop(loop_block, opt_ident) => {
224 let (loop_block, opt_ident) = expand_loop_block(loop_block, opt_ident, fld);
225 fld.cx.expr(span, ast::ExprLoop(loop_block, opt_ident))
228 // Desugar ExprForLoop
229 // From: `[opt_ident]: for <pat> in <head> <body>`
230 ast::ExprForLoop(pat, head, body, opt_ident) => {
234 // let result = match ::std::iter::IntoIterator::into_iter(<head>) {
236 // [opt_ident]: loop {
237 // match ::std::iter::Iterator::next(&mut iter) {
238 // ::std::option::Option::Some(<pat>) => <body>,
239 // ::std::option::Option::None => break
247 push_compiler_expansion(fld, span, "for loop expansion");
249 let span = fld.new_span(span);
252 let head = fld.fold_expr(head);
254 // create an hygienic ident
256 let ident = fld.cx.ident_of("iter");
257 let new_ident = fresh_name(&ident);
258 let rename = (ident, new_ident);
259 let mut rename_list = vec![rename];
260 let mut rename_fld = IdentRenamer{ renames: &mut rename_list };
262 rename_fld.fold_ident(ident)
265 let pat_span = fld.new_span(pat.span);
266 // `::std::option::Option::Some(<pat>) => <body>`
268 let body_expr = fld.cx.expr_block(body);
269 let pat = noop_fold_pat(pat, fld);
270 let some_pat = fld.cx.pat_some(pat_span, pat);
272 fld.cx.arm(pat_span, vec![some_pat], body_expr)
275 // `::std::option::Option::None => break`
277 let break_expr = fld.cx.expr_break(span);
279 fld.cx.arm(span, vec![fld.cx.pat_none(span)], break_expr)
282 // `match ::std::iter::Iterator::next(&mut iter) { ... }`
286 fld.cx.ident_of_std("core"),
287 fld.cx.ident_of("iter"),
288 fld.cx.ident_of("Iterator"),
289 fld.cx.ident_of("next"),
292 fld.cx.path_global(span, strs)
294 let ref_mut_iter = fld.cx.expr_mut_addr_of(span, fld.cx.expr_ident(span, iter));
296 fld.cx.expr_call(span, fld.cx.expr_path(next_path), vec![ref_mut_iter]);
297 let arms = vec![pat_arm, break_arm];
299 fld.cx.expr(pat_span,
300 ast::ExprMatch(next_expr, arms, ast::MatchSource::ForLoopDesugar))
303 // `[opt_ident]: loop { ... }`
304 let loop_block = fld.cx.block_expr(match_expr);
305 let (loop_block, opt_ident) = expand_loop_block(loop_block, opt_ident, fld);
306 let loop_expr = fld.cx.expr(span, ast::ExprLoop(loop_block, opt_ident));
308 // `mut iter => { ... }`
311 fld.cx.pat_ident_binding_mode(span, iter, ast::BindByValue(ast::MutMutable));
312 fld.cx.arm(span, vec![iter_pat], loop_expr)
315 // `match ::std::iter::IntoIterator::into_iter(<head>) { ... }`
316 let into_iter_expr = {
317 let into_iter_path = {
319 fld.cx.ident_of_std("core"),
320 fld.cx.ident_of("iter"),
321 fld.cx.ident_of("IntoIterator"),
322 fld.cx.ident_of("into_iter"),
325 fld.cx.path_global(span, strs)
328 fld.cx.expr_call(span, fld.cx.expr_path(into_iter_path), vec![head])
331 let match_expr = fld.cx.expr_match(span, into_iter_expr, vec![iter_arm]);
333 // `{ let result = ...; result }`
334 let result_ident = token::gensym_ident("result");
335 let result = fld.cx.expr_block(
338 vec![fld.cx.stmt_let(span, false, result_ident, match_expr)],
339 Some(fld.cx.expr_ident(span, result_ident))));
344 ast::ExprClosure(capture_clause, fn_decl, block) => {
345 push_compiler_expansion(fld, span, "closure expansion");
346 let (rewritten_fn_decl, rewritten_block)
347 = expand_and_rename_fn_decl_and_block(fn_decl, block, fld);
348 let new_node = ast::ExprClosure(capture_clause,
351 let result = P(ast::Expr{id:id, node: new_node, span: fld.new_span(span)});
357 P(noop_fold_expr(ast::Expr {
366 /// Expand a (not-ident-style) macro invocation. Returns the result
367 /// of expansion and the mark which must be applied to the result.
368 /// Our current interface doesn't allow us to apply the mark to the
369 /// result until after calling make_expr, make_items, etc.
370 fn expand_mac_invoc<T, F, G>(mac: ast::Mac,
374 fld: &mut MacroExpander)
376 F: for<'a> FnOnce(Box<MacResult+'a>) -> Option<T>,
377 G: FnOnce(T, Mrk) -> T,
380 // it would almost certainly be cleaner to pass the whole
381 // macro invocation in, rather than pulling it apart and
382 // marking the tts and the ctxt separately. This also goes
383 // for the other three macro invocation chunks of code
385 // Token-tree macros:
386 MacInvocTT(pth, tts, _) => {
387 if pth.segments.len() > 1 {
388 fld.cx.span_err(pth.span,
389 "expected macro name without module \
391 // let compilation continue
394 let extname = pth.segments[0].identifier;
395 let extnamestr = token::get_ident(extname);
396 match fld.cx.syntax_env.find(&extname.name) {
400 &format!("macro undefined: '{}!'",
403 // let compilation continue
406 Some(rc) => match *rc {
407 NormalTT(ref expandfun, exp_span, allow_internal_unstable) => {
408 fld.cx.bt_push(ExpnInfo {
410 callee: NameAndSpan {
411 name: extnamestr.to_string(),
414 allow_internal_unstable: allow_internal_unstable,
417 let fm = fresh_mark();
418 let marked_before = mark_tts(&tts[..], fm);
420 // The span that we pass to the expanders we want to
421 // be the root of the call stack. That's the most
422 // relevant span and it's the actual invocation of
424 let mac_span = fld.cx.original_span();
427 let expanded = expandfun.expand(fld.cx,
430 parse_thunk(expanded)
432 let parsed = match opt_parsed {
437 &format!("non-expression macro in expression position: {}",
443 Some(mark_thunk(parsed,fm))
448 &format!("'{}' is not a tt-style macro",
458 /// Rename loop label and expand its loop body
460 /// The renaming procedure for loop is different in the sense that the loop
461 /// body is in a block enclosed by loop head so the renaming of loop label
462 /// must be propagated to the enclosed context.
463 fn expand_loop_block(loop_block: P<Block>,
464 opt_ident: Option<Ident>,
465 fld: &mut MacroExpander) -> (P<Block>, Option<Ident>) {
468 let new_label = fresh_name(&label);
469 let rename = (label, new_label);
471 // The rename *must not* be added to the pending list of current
472 // syntax context otherwise an unrelated `break` or `continue` in
473 // the same context will pick that up in the deferred renaming pass
474 // and be renamed incorrectly.
475 let mut rename_list = vec!(rename);
476 let mut rename_fld = IdentRenamer{renames: &mut rename_list};
477 let renamed_ident = rename_fld.fold_ident(label);
479 // The rename *must* be added to the enclosed syntax context for
480 // `break` or `continue` to pick up because by definition they are
481 // in a block enclosed by loop head.
482 fld.cx.syntax_env.push_frame();
483 fld.cx.syntax_env.info().pending_renames.push(rename);
484 let expanded_block = expand_block_elts(loop_block, fld);
485 fld.cx.syntax_env.pop_frame();
487 (expanded_block, Some(renamed_ident))
489 None => (fld.fold_block(loop_block), opt_ident)
493 // eval $e with a new exts frame.
494 // must be a macro so that $e isn't evaluated too early.
495 macro_rules! with_exts_frame {
496 ($extsboxexpr:expr,$macros_escape:expr,$e:expr) =>
497 ({$extsboxexpr.push_frame();
498 $extsboxexpr.info().macros_escape = $macros_escape;
500 $extsboxexpr.pop_frame();
505 // When we enter a module, record it, for the sake of `module!`
506 pub fn expand_item(it: P<ast::Item>, fld: &mut MacroExpander)
507 -> SmallVector<P<ast::Item>> {
508 let it = expand_item_modifiers(it, fld);
510 expand_annotatable(Annotatable::Item(it), fld)
511 .into_iter().map(|i| i.expect_item()).collect()
514 /// Expand item_underscore
515 fn expand_item_underscore(item: ast::Item_, fld: &mut MacroExpander) -> ast::Item_ {
517 ast::ItemFn(decl, unsafety, constness, abi, generics, body) => {
518 let (rewritten_fn_decl, rewritten_body)
519 = expand_and_rename_fn_decl_and_block(decl, body, fld);
520 let expanded_generics = fold::noop_fold_generics(generics,fld);
521 ast::ItemFn(rewritten_fn_decl, unsafety, constness, abi,
522 expanded_generics, rewritten_body)
524 _ => noop_fold_item_underscore(item, fld)
528 // does this attribute list contain "macro_use" ?
529 fn contains_macro_use(fld: &mut MacroExpander, attrs: &[ast::Attribute]) -> bool {
531 let mut is_use = attr.check_name("macro_use");
532 if attr.check_name("macro_escape") {
533 fld.cx.span_warn(attr.span, "macro_escape is a deprecated synonym for macro_use");
535 if let ast::AttrInner = attr.node.style {
536 fld.cx.fileline_help(attr.span, "consider an outer attribute, \
537 #[macro_use] mod ...");
542 match attr.node.value.node {
543 ast::MetaWord(..) => (),
544 _ => fld.cx.span_err(attr.span, "arguments to macro_use are not allowed here"),
552 // Support for item-position macro invocations, exactly the same
553 // logic as for expression-position macro invocations.
554 pub fn expand_item_mac(it: P<ast::Item>,
555 fld: &mut MacroExpander) -> SmallVector<P<ast::Item>> {
556 let (extname, path_span, tts) = match it.node {
557 ItemMac(codemap::Spanned {
558 node: MacInvocTT(ref pth, ref tts, _),
561 (pth.segments[0].identifier, pth.span, (*tts).clone())
563 _ => fld.cx.span_bug(it.span, "invalid item macro invocation")
566 let extnamestr = token::get_ident(extname);
567 let fm = fresh_mark();
569 let expanded = match fld.cx.syntax_env.find(&extname.name) {
571 fld.cx.span_err(path_span,
572 &format!("macro undefined: '{}!'",
574 // let compilation continue
575 return SmallVector::zero();
578 Some(rc) => match *rc {
579 NormalTT(ref expander, span, allow_internal_unstable) => {
580 if it.ident.name != parse::token::special_idents::invalid.name {
583 &format!("macro {}! expects no ident argument, given '{}'",
585 token::get_ident(it.ident)));
586 return SmallVector::zero();
588 fld.cx.bt_push(ExpnInfo {
590 callee: NameAndSpan {
591 name: extnamestr.to_string(),
594 allow_internal_unstable: allow_internal_unstable,
597 // mark before expansion:
598 let marked_before = mark_tts(&tts[..], fm);
599 expander.expand(fld.cx, it.span, &marked_before[..])
601 IdentTT(ref expander, span, allow_internal_unstable) => {
602 if it.ident.name == parse::token::special_idents::invalid.name {
603 fld.cx.span_err(path_span,
604 &format!("macro {}! expects an ident argument",
606 return SmallVector::zero();
608 fld.cx.bt_push(ExpnInfo {
610 callee: NameAndSpan {
611 name: extnamestr.to_string(),
614 allow_internal_unstable: allow_internal_unstable,
617 // mark before expansion:
618 let marked_tts = mark_tts(&tts[..], fm);
619 expander.expand(fld.cx, it.span, it.ident, marked_tts)
622 if it.ident.name == parse::token::special_idents::invalid.name {
623 fld.cx.span_err(path_span,
624 &format!("macro_rules! expects an ident argument")
626 return SmallVector::zero();
629 fld.cx.bt_push(ExpnInfo {
631 callee: NameAndSpan {
632 name: extnamestr.to_string(),
635 // `macro_rules!` doesn't directly allow
636 // unstable (this is orthogonal to whether
637 // the macro it creates allows it)
638 allow_internal_unstable: false,
641 // DON'T mark before expansion.
643 let allow_internal_unstable = attr::contains_name(&it.attrs,
644 "allow_internal_unstable");
646 // ensure any #[allow_internal_unstable]s are
647 // detected (including nested macro definitions
649 if allow_internal_unstable && !fld.cx.ecfg.enable_allow_internal_unstable() {
650 feature_gate::emit_feature_err(
651 &fld.cx.parse_sess.span_diagnostic,
652 "allow_internal_unstable",
654 feature_gate::EXPLAIN_ALLOW_INTERNAL_UNSTABLE)
657 let def = ast::MacroDef {
659 attrs: it.attrs.clone(),
660 id: ast::DUMMY_NODE_ID,
663 export: attr::contains_name(&it.attrs, "macro_export"),
665 allow_internal_unstable: allow_internal_unstable,
668 fld.cx.insert_macro(def);
670 // macro_rules! has a side effect but expands to nothing.
672 return SmallVector::zero();
675 fld.cx.span_err(it.span,
676 &format!("{}! is not legal in item position",
678 return SmallVector::zero();
683 expanded.make_items()
686 let items = match items {
689 .map(|i| mark_item(i, fm))
690 .flat_map(|i| fld.fold_item(i).into_iter())
694 fld.cx.span_err(path_span,
695 &format!("non-item macro in item position: {}",
697 return SmallVector::zero();
706 fn expand_stmt(stmt: P<Stmt>, fld: &mut MacroExpander) -> SmallVector<P<Stmt>> {
707 let stmt = stmt.and_then(|stmt| stmt);
708 let (mac, style) = match stmt.node {
709 StmtMac(mac, style) => (mac, style),
710 _ => return expand_non_macro_stmt(stmt, fld)
713 let maybe_new_items =
714 expand_mac_invoc(mac.and_then(|m| m), stmt.span,
716 |stmts, mark| stmts.move_map(|m| mark_stmt(m, mark)),
719 let mut fully_expanded = match maybe_new_items {
721 // Keep going, outside-in.
722 let new_items = stmts.into_iter().flat_map(|s| {
723 fld.fold_stmt(s).into_iter()
728 None => SmallVector::zero()
731 // If this is a macro invocation with a semicolon, then apply that
732 // semicolon to the final statement produced by expansion.
733 if style == MacStmtWithSemicolon {
734 if let Some(stmt) = fully_expanded.pop() {
735 let new_stmt = stmt.map(|Spanned {node, span}| {
738 StmtExpr(e, stmt_id) => StmtSemi(e, stmt_id),
739 _ => node /* might already have a semi */
744 fully_expanded.push(new_stmt);
751 // expand a non-macro stmt. this is essentially the fallthrough for
752 // expand_stmt, above.
753 fn expand_non_macro_stmt(Spanned {node, span: stmt_span}: Stmt, fld: &mut MacroExpander)
754 -> SmallVector<P<Stmt>> {
757 StmtDecl(decl, node_id) => decl.and_then(|Spanned {node: decl, span}| match decl {
758 DeclLocal(local) => {
760 let rewritten_local = local.map(|Local {id, pat, ty, init, source, span}| {
761 // expand the ty since TyFixedLengthVec contains an Expr
762 // and thus may have a macro use
763 let expanded_ty = ty.map(|t| fld.fold_ty(t));
764 // expand the pat (it might contain macro uses):
765 let expanded_pat = fld.fold_pat(pat);
766 // find the PatIdents in the pattern:
767 // oh dear heaven... this is going to include the enum
768 // names, as well... but that should be okay, as long as
769 // the new names are gensyms for the old ones.
770 // generate fresh names, push them to a new pending list
771 let idents = pattern_bindings(&*expanded_pat);
772 let mut new_pending_renames =
773 idents.iter().map(|ident| (*ident, fresh_name(ident))).collect();
774 // rewrite the pattern using the new names (the old
775 // ones have already been applied):
776 let rewritten_pat = {
777 // nested binding to allow borrow to expire:
778 let mut rename_fld = IdentRenamer{renames: &mut new_pending_renames};
779 rename_fld.fold_pat(expanded_pat)
781 // add them to the existing pending renames:
782 fld.cx.syntax_env.info().pending_renames
783 .extend(new_pending_renames);
788 // also, don't forget to expand the init:
789 init: init.map(|e| fld.fold_expr(e)),
794 SmallVector::one(P(Spanned {
795 node: StmtDecl(P(Spanned {
796 node: DeclLocal(rewritten_local),
804 noop_fold_stmt(Spanned {
805 node: StmtDecl(P(Spanned {
815 noop_fold_stmt(Spanned {
823 // expand the arm of a 'match', renaming for macro hygiene
824 fn expand_arm(arm: ast::Arm, fld: &mut MacroExpander) -> ast::Arm {
825 // expand pats... they might contain macro uses:
826 let expanded_pats = arm.pats.move_map(|pat| fld.fold_pat(pat));
827 if expanded_pats.is_empty() {
828 panic!("encountered match arm with 0 patterns");
830 // all of the pats must have the same set of bindings, so use the
831 // first one to extract them and generate new names:
832 let idents = pattern_bindings(&*expanded_pats[0]);
833 let new_renames = idents.into_iter().map(|id| (id, fresh_name(&id))).collect();
834 // apply the renaming, but only to the PatIdents:
835 let mut rename_pats_fld = PatIdentRenamer{renames:&new_renames};
836 let rewritten_pats = expanded_pats.move_map(|pat| rename_pats_fld.fold_pat(pat));
837 // apply renaming and then expansion to the guard and the body:
838 let mut rename_fld = IdentRenamer{renames:&new_renames};
839 let rewritten_guard =
840 arm.guard.map(|g| fld.fold_expr(rename_fld.fold_expr(g)));
841 let rewritten_body = fld.fold_expr(rename_fld.fold_expr(arm.body));
843 attrs: fold::fold_attrs(arm.attrs, fld),
844 pats: rewritten_pats,
845 guard: rewritten_guard,
846 body: rewritten_body,
850 /// A visitor that extracts the PatIdent (binding) paths
851 /// from a given thingy and puts them in a mutable
854 struct PatIdentFinder {
855 ident_accumulator: Vec<ast::Ident>
858 impl<'v> Visitor<'v> for PatIdentFinder {
859 fn visit_pat(&mut self, pattern: &ast::Pat) {
861 ast::Pat { id: _, node: ast::PatIdent(_, ref path1, ref inner), span: _ } => {
862 self.ident_accumulator.push(path1.node);
863 // visit optional subpattern of PatIdent:
864 if let Some(ref subpat) = *inner {
865 self.visit_pat(&**subpat)
868 // use the default traversal for non-PatIdents
869 _ => visit::walk_pat(self, pattern)
874 /// find the PatIdent paths in a pattern
875 fn pattern_bindings(pat: &ast::Pat) -> Vec<ast::Ident> {
876 let mut name_finder = PatIdentFinder{ident_accumulator:Vec::new()};
877 name_finder.visit_pat(pat);
878 name_finder.ident_accumulator
881 /// find the PatIdent paths in a
882 fn fn_decl_arg_bindings(fn_decl: &ast::FnDecl) -> Vec<ast::Ident> {
883 let mut pat_idents = PatIdentFinder{ident_accumulator:Vec::new()};
884 for arg in &fn_decl.inputs {
885 pat_idents.visit_pat(&*arg.pat);
887 pat_idents.ident_accumulator
890 // expand a block. pushes a new exts_frame, then calls expand_block_elts
891 pub fn expand_block(blk: P<Block>, fld: &mut MacroExpander) -> P<Block> {
892 // see note below about treatment of exts table
893 with_exts_frame!(fld.cx.syntax_env,false,
894 expand_block_elts(blk, fld))
897 // expand the elements of a block.
898 pub fn expand_block_elts(b: P<Block>, fld: &mut MacroExpander) -> P<Block> {
899 b.map(|Block {id, stmts, expr, rules, span}| {
900 let new_stmts = stmts.into_iter().flat_map(|x| {
901 // perform all pending renames
903 let pending_renames = &mut fld.cx.syntax_env.info().pending_renames;
904 let mut rename_fld = IdentRenamer{renames:pending_renames};
905 rename_fld.fold_stmt(x).expect_one("rename_fold didn't return one value")
907 // expand macros in the statement
908 fld.fold_stmt(renamed_stmt).into_iter()
910 let new_expr = expr.map(|x| {
912 let pending_renames = &mut fld.cx.syntax_env.info().pending_renames;
913 let mut rename_fld = IdentRenamer{renames:pending_renames};
914 rename_fld.fold_expr(x)
928 fn expand_pat(p: P<ast::Pat>, fld: &mut MacroExpander) -> P<ast::Pat> {
931 _ => return noop_fold_pat(p, fld)
933 p.map(|ast::Pat {node, span, ..}| {
934 let (pth, tts) = match node {
935 PatMac(mac) => match mac.node {
936 MacInvocTT(pth, tts, _) => {
942 if pth.segments.len() > 1 {
943 fld.cx.span_err(pth.span, "expected macro name without module separators");
944 return DummyResult::raw_pat(span);
946 let extname = pth.segments[0].identifier;
947 let extnamestr = token::get_ident(extname);
948 let marked_after = match fld.cx.syntax_env.find(&extname.name) {
950 fld.cx.span_err(pth.span,
951 &format!("macro undefined: '{}!'",
953 // let compilation continue
954 return DummyResult::raw_pat(span);
957 Some(rc) => match *rc {
958 NormalTT(ref expander, tt_span, allow_internal_unstable) => {
959 fld.cx.bt_push(ExpnInfo {
961 callee: NameAndSpan {
962 name: extnamestr.to_string(),
965 allow_internal_unstable: allow_internal_unstable,
969 let fm = fresh_mark();
970 let marked_before = mark_tts(&tts[..], fm);
971 let mac_span = fld.cx.original_span();
972 let pat = expander.expand(fld.cx,
974 &marked_before[..]).make_pat();
975 let expanded = match pat {
981 "non-pattern macro in pattern position: {}",
985 return DummyResult::raw_pat(span);
990 mark_pat(expanded,fm)
993 fld.cx.span_err(span,
994 &format!("{}! is not legal in pattern position",
996 return DummyResult::raw_pat(span);
1001 let fully_expanded =
1002 fld.fold_pat(marked_after).node.clone();
1006 id: ast::DUMMY_NODE_ID,
1007 node: fully_expanded,
1013 /// A tree-folder that applies every rename in its (mutable) list
1014 /// to every identifier, including both bindings and varrefs
1015 /// (and lots of things that will turn out to be neither)
1016 pub struct IdentRenamer<'a> {
1017 renames: &'a mtwt::RenameList,
1020 impl<'a> Folder for IdentRenamer<'a> {
1021 fn fold_ident(&mut self, id: Ident) -> Ident {
1024 ctxt: mtwt::apply_renames(self.renames, id.ctxt),
1027 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
1028 fold::noop_fold_mac(mac, self)
1032 /// A tree-folder that applies every rename in its list to
1033 /// the idents that are in PatIdent patterns. This is more narrowly
1034 /// focused than IdentRenamer, and is needed for FnDecl,
1035 /// where we want to rename the args but not the fn name or the generics etc.
1036 pub struct PatIdentRenamer<'a> {
1037 renames: &'a mtwt::RenameList,
1040 impl<'a> Folder for PatIdentRenamer<'a> {
1041 fn fold_pat(&mut self, pat: P<ast::Pat>) -> P<ast::Pat> {
1043 ast::PatIdent(..) => {},
1044 _ => return noop_fold_pat(pat, self)
1047 pat.map(|ast::Pat {id, node, span}| match node {
1048 ast::PatIdent(binding_mode, Spanned{span: sp, node: ident}, sub) => {
1049 let new_ident = Ident{name: ident.name,
1050 ctxt: mtwt::apply_renames(self.renames, ident.ctxt)};
1052 ast::PatIdent(binding_mode,
1053 Spanned{span: self.new_span(sp), node: new_ident},
1054 sub.map(|p| self.fold_pat(p)));
1058 span: self.new_span(span)
1064 fn fold_mac(&mut self, mac: ast::Mac) -> ast::Mac {
1065 fold::noop_fold_mac(mac, self)
1069 fn expand_annotatable(a: Annotatable,
1070 fld: &mut MacroExpander)
1071 -> SmallVector<Annotatable> {
1072 let a = expand_item_multi_modifier(a, fld);
1074 let mut decorator_items = SmallVector::zero();
1075 let mut new_attrs = Vec::new();
1076 expand_decorators(a.clone(), fld, &mut decorator_items, &mut new_attrs);
1078 let mut new_items: SmallVector<Annotatable> = match a {
1079 Annotatable::Item(it) => match it.node {
1080 ast::ItemMac(..) => {
1081 expand_item_mac(it, fld).into_iter().map(|i| Annotatable::Item(i)).collect()
1083 ast::ItemMod(_) | ast::ItemForeignMod(_) => {
1085 it.ident.name != parse::token::special_idents::invalid.name;
1088 fld.cx.mod_push(it.ident);
1090 let macro_use = contains_macro_use(fld, &new_attrs[..]);
1091 let result = with_exts_frame!(fld.cx.syntax_env,
1093 noop_fold_item(it, fld));
1097 result.into_iter().map(|i| Annotatable::Item(i)).collect()
1100 let it = P(ast::Item {
1104 noop_fold_item(it, fld).into_iter().map(|i| Annotatable::Item(i)).collect()
1108 Annotatable::TraitItem(it) => match it.node {
1109 ast::MethodTraitItem(_, Some(_)) => SmallVector::one(it.map(|ti| ast::TraitItem {
1113 node: match ti.node {
1114 ast::MethodTraitItem(sig, Some(body)) => {
1115 let (sig, body) = expand_and_rename_method(sig, body, fld);
1116 ast::MethodTraitItem(sig, Some(body))
1120 span: fld.new_span(ti.span)
1122 _ => fold::noop_fold_trait_item(it, fld)
1123 }.into_iter().map(Annotatable::TraitItem).collect(),
1125 Annotatable::ImplItem(ii) => {
1126 expand_impl_item(ii, fld).into_iter().map(Annotatable::ImplItem).collect()
1130 new_items.push_all(decorator_items);
1134 // Partition a set of attributes into one kind of attribute, and other kinds.
1135 macro_rules! partition {
1136 ($fn_name: ident, $variant: ident) => {
1137 #[allow(deprecated)] // The `allow` is needed because the `Modifier` variant might be used.
1138 fn $fn_name(attrs: &[ast::Attribute],
1139 fld: &MacroExpander)
1140 -> (Vec<ast::Attribute>, Vec<ast::Attribute>) {
1141 attrs.iter().cloned().partition(|attr| {
1142 match fld.cx.syntax_env.find(&intern(&attr.name())) {
1143 Some(rc) => match *rc {
1144 $variant(..) => true,
1154 partition!(modifiers, Modifier);
1155 partition!(multi_modifiers, MultiModifier);
1158 #[allow(deprecated)] // The `allow` is needed because the `Decorator` variant is used.
1159 fn expand_decorators(a: Annotatable,
1160 fld: &mut MacroExpander,
1161 decorator_items: &mut SmallVector<Annotatable>,
1162 new_attrs: &mut Vec<ast::Attribute>)
1164 for attr in a.attrs() {
1165 let mname = attr.name();
1166 match fld.cx.syntax_env.find(&intern(&mname)) {
1167 Some(rc) => match *rc {
1168 Decorator(ref dec) => {
1169 attr::mark_used(&attr);
1171 fld.cx.bt_push(ExpnInfo {
1172 call_site: attr.span,
1173 callee: NameAndSpan {
1174 name: mname.to_string(),
1175 format: MacroAttribute,
1176 span: Some(attr.span),
1177 // attributes can do whatever they like,
1179 allow_internal_unstable: true,
1183 // we'd ideally decorator_items.push_all(expand_item(item, fld)),
1184 // but that double-mut-borrows fld
1185 let mut items: SmallVector<Annotatable> = SmallVector::zero();
1189 &a.clone().expect_item(),
1190 &mut |item| items.push(Annotatable::Item(item)));
1191 decorator_items.extend(items.into_iter()
1192 .flat_map(|ann| expand_annotatable(ann, fld).into_iter()));
1196 MultiDecorator(ref dec) => {
1197 attr::mark_used(&attr);
1199 fld.cx.bt_push(ExpnInfo {
1200 call_site: attr.span,
1201 callee: NameAndSpan {
1202 name: mname.to_string(),
1203 format: MacroAttribute,
1204 span: Some(attr.span),
1205 // attributes can do whatever they like,
1207 allow_internal_unstable: true,
1211 // we'd ideally decorator_items.push_all(expand_annotatable(ann, fld)),
1212 // but that double-mut-borrows fld
1213 let mut items: SmallVector<Annotatable> = SmallVector::zero();
1218 &mut |ann| items.push(ann));
1219 decorator_items.extend(items.into_iter()
1220 .flat_map(|ann| expand_annotatable(ann, fld).into_iter()));
1224 _ => new_attrs.push((*attr).clone()),
1226 _ => new_attrs.push((*attr).clone()),
1231 fn expand_item_multi_modifier(mut it: Annotatable,
1232 fld: &mut MacroExpander)
1234 let (modifiers, other_attrs) = multi_modifiers(it.attrs(), fld);
1236 // Update the attrs, leave everything else alone. Is this mutation really a good idea?
1237 it = it.fold_attrs(other_attrs);
1239 if modifiers.is_empty() {
1243 for attr in &modifiers {
1244 let mname = attr.name();
1246 match fld.cx.syntax_env.find(&intern(&mname)) {
1247 Some(rc) => match *rc {
1248 MultiModifier(ref mac) => {
1249 attr::mark_used(attr);
1250 fld.cx.bt_push(ExpnInfo {
1251 call_site: attr.span,
1252 callee: NameAndSpan {
1253 name: mname.to_string(),
1254 format: MacroAttribute,
1255 span: Some(attr.span),
1256 // attributes can do whatever they like,
1258 allow_internal_unstable: true,
1261 it = mac.expand(fld.cx, attr.span, &*attr.node.value, it);
1270 // Expansion may have added new ItemModifiers.
1271 expand_item_multi_modifier(it, fld)
1274 #[allow(deprecated)] // This is needed because the `ItemModifier` trait is used
1275 fn expand_item_modifiers(mut it: P<ast::Item>,
1276 fld: &mut MacroExpander)
1278 // partition the attributes into ItemModifiers and others
1279 let (modifiers, other_attrs) = modifiers(&it.attrs, fld);
1281 // update the attrs, leave everything else alone. Is this mutation really a good idea?
1287 if modifiers.is_empty() {
1288 let it = expand_item_multi_modifier(Annotatable::Item(it), fld);
1289 return it.expect_item();
1292 for attr in &modifiers {
1293 let mname = attr.name();
1295 match fld.cx.syntax_env.find(&intern(&mname)) {
1296 Some(rc) => match *rc {
1297 Modifier(ref mac) => {
1298 attr::mark_used(attr);
1299 fld.cx.bt_push(ExpnInfo {
1300 call_site: attr.span,
1301 callee: NameAndSpan {
1302 name: mname.to_string(),
1303 format: MacroAttribute,
1304 span: Some(attr.span),
1305 // attributes can do whatever they like,
1307 allow_internal_unstable: true,
1310 it = mac.expand(fld.cx, attr.span, &*attr.node.value, it);
1319 // Expansion may have added new ItemModifiers.
1320 // It is possible, that an item modifier could expand to a multi-modifier or
1321 // vice versa. In this case we will expand all modifiers before multi-modifiers,
1322 // which might give an odd ordering. However, I think it is unlikely that the
1323 // two kinds will be mixed, and old-style multi-modifiers are deprecated.
1324 expand_item_modifiers(it, fld)
1327 fn expand_impl_item(ii: P<ast::ImplItem>, fld: &mut MacroExpander)
1328 -> SmallVector<P<ast::ImplItem>> {
1330 ast::MethodImplItem(..) => SmallVector::one(ii.map(|ii| ast::ImplItem {
1335 node: match ii.node {
1336 ast::MethodImplItem(sig, body) => {
1337 let (sig, body) = expand_and_rename_method(sig, body, fld);
1338 ast::MethodImplItem(sig, body)
1342 span: fld.new_span(ii.span)
1344 ast::MacImplItem(_) => {
1345 let (span, mac) = ii.and_then(|ii| match ii.node {
1346 ast::MacImplItem(mac) => (ii.span, mac),
1349 let maybe_new_items =
1350 expand_mac_invoc(mac, span,
1351 |r| r.make_impl_items(),
1352 |meths, mark| meths.move_map(|m| mark_impl_item(m, mark)),
1355 match maybe_new_items {
1356 Some(impl_items) => {
1357 // expand again if necessary
1358 let new_items = impl_items.into_iter().flat_map(|ii| {
1359 expand_impl_item(ii, fld).into_iter()
1364 None => SmallVector::zero()
1367 _ => fold::noop_fold_impl_item(ii, fld)
1371 /// Given a fn_decl and a block and a MacroExpander, expand the fn_decl, then use the
1372 /// PatIdents in its arguments to perform renaming in the FnDecl and
1373 /// the block, returning both the new FnDecl and the new Block.
1374 fn expand_and_rename_fn_decl_and_block(fn_decl: P<ast::FnDecl>, block: P<ast::Block>,
1375 fld: &mut MacroExpander)
1376 -> (P<ast::FnDecl>, P<ast::Block>) {
1377 let expanded_decl = fld.fold_fn_decl(fn_decl);
1378 let idents = fn_decl_arg_bindings(&*expanded_decl);
1380 idents.iter().map(|id : &ast::Ident| (*id,fresh_name(id))).collect();
1381 // first, a renamer for the PatIdents, for the fn_decl:
1382 let mut rename_pat_fld = PatIdentRenamer{renames: &renames};
1383 let rewritten_fn_decl = rename_pat_fld.fold_fn_decl(expanded_decl);
1384 // now, a renamer for *all* idents, for the body:
1385 let mut rename_fld = IdentRenamer{renames: &renames};
1386 let rewritten_body = fld.fold_block(rename_fld.fold_block(block));
1387 (rewritten_fn_decl,rewritten_body)
1390 fn expand_and_rename_method(sig: ast::MethodSig, body: P<ast::Block>,
1391 fld: &mut MacroExpander)
1392 -> (ast::MethodSig, P<ast::Block>) {
1393 let (rewritten_fn_decl, rewritten_body)
1394 = expand_and_rename_fn_decl_and_block(sig.decl, body, fld);
1396 generics: fld.fold_generics(sig.generics),
1398 explicit_self: fld.fold_explicit_self(sig.explicit_self),
1399 unsafety: sig.unsafety,
1400 constness: sig.constness,
1401 decl: rewritten_fn_decl
1405 /// A tree-folder that performs macro expansion
1406 pub struct MacroExpander<'a, 'b:'a> {
1407 pub cx: &'a mut ExtCtxt<'b>,
1410 impl<'a, 'b> MacroExpander<'a, 'b> {
1411 pub fn new(cx: &'a mut ExtCtxt<'b>) -> MacroExpander<'a, 'b> {
1412 MacroExpander { cx: cx }
1416 impl<'a, 'b> Folder for MacroExpander<'a, 'b> {
1417 fn fold_expr(&mut self, expr: P<ast::Expr>) -> P<ast::Expr> {
1418 expand_expr(expr, self)
1421 fn fold_pat(&mut self, pat: P<ast::Pat>) -> P<ast::Pat> {
1422 expand_pat(pat, self)
1425 fn fold_item(&mut self, item: P<ast::Item>) -> SmallVector<P<ast::Item>> {
1426 expand_item(item, self)
1429 fn fold_item_underscore(&mut self, item: ast::Item_) -> ast::Item_ {
1430 expand_item_underscore(item, self)
1433 fn fold_stmt(&mut self, stmt: P<ast::Stmt>) -> SmallVector<P<ast::Stmt>> {
1434 expand_stmt(stmt, self)
1437 fn fold_block(&mut self, block: P<Block>) -> P<Block> {
1438 expand_block(block, self)
1441 fn fold_arm(&mut self, arm: ast::Arm) -> ast::Arm {
1442 expand_arm(arm, self)
1445 fn fold_trait_item(&mut self, i: P<ast::TraitItem>) -> SmallVector<P<ast::TraitItem>> {
1446 expand_annotatable(Annotatable::TraitItem(i), self)
1447 .into_iter().map(|i| i.expect_trait_item()).collect()
1450 fn fold_impl_item(&mut self, i: P<ast::ImplItem>) -> SmallVector<P<ast::ImplItem>> {
1451 expand_annotatable(Annotatable::ImplItem(i), self)
1452 .into_iter().map(|i| i.expect_impl_item()).collect()
1455 fn new_span(&mut self, span: Span) -> Span {
1456 new_span(self.cx, span)
1460 fn new_span(cx: &ExtCtxt, sp: Span) -> Span {
1461 /* this discards information in the case of macro-defining macros */
1465 expn_id: cx.backtrace(),
1469 pub struct ExpansionConfig<'feat> {
1470 pub crate_name: String,
1471 pub features: Option<&'feat Features>,
1472 pub recursion_limit: usize,
1473 pub trace_mac: bool,
1476 macro_rules! feature_tests {
1477 ($( fn $getter:ident = $field:ident, )*) => {
1479 pub fn $getter(&self) -> bool {
1480 match self.features {
1481 Some(&Features { $field: true, .. }) => true,
1489 impl<'feat> ExpansionConfig<'feat> {
1490 pub fn default(crate_name: String) -> ExpansionConfig<'static> {
1492 crate_name: crate_name,
1494 recursion_limit: 64,
1500 fn enable_quotes = allow_quote,
1501 fn enable_asm = allow_asm,
1502 fn enable_log_syntax = allow_log_syntax,
1503 fn enable_concat_idents = allow_concat_idents,
1504 fn enable_trace_macros = allow_trace_macros,
1505 fn enable_allow_internal_unstable = allow_internal_unstable,
1506 fn enable_custom_derive = allow_custom_derive,
1510 pub fn expand_crate<'feat>(parse_sess: &parse::ParseSess,
1511 cfg: ExpansionConfig<'feat>,
1512 // these are the macros being imported to this crate:
1513 imported_macros: Vec<ast::MacroDef>,
1514 user_exts: Vec<NamedSyntaxExtension>,
1515 c: Crate) -> Crate {
1516 let mut cx = ExtCtxt::new(parse_sess, c.config.clone(), cfg);
1517 cx.use_std = std_inject::use_std(&c);
1519 let mut expander = MacroExpander::new(&mut cx);
1521 for def in imported_macros {
1522 expander.cx.insert_macro(def);
1525 for (name, extension) in user_exts {
1526 expander.cx.syntax_env.insert(name, extension);
1529 let mut ret = expander.fold_crate(c);
1530 ret.exported_macros = expander.cx.exported_macros.clone();
1531 parse_sess.span_diagnostic.handler().abort_if_errors();
1535 // HYGIENIC CONTEXT EXTENSION:
1536 // all of these functions are for walking over
1537 // ASTs and making some change to the context of every
1538 // element that has one. a CtxtFn is a trait-ified
1539 // version of a closure in (SyntaxContext -> SyntaxContext).
1540 // the ones defined here include:
1541 // Marker - add a mark to a context
1543 // A Marker adds the given mark to the syntax context
1544 struct Marker { mark: Mrk }
1546 impl Folder for Marker {
1547 fn fold_ident(&mut self, id: Ident) -> Ident {
1550 ctxt: mtwt::apply_mark(self.mark, id.ctxt)
1553 fn fold_mac(&mut self, Spanned {node, span}: ast::Mac) -> ast::Mac {
1556 MacInvocTT(path, tts, ctxt) => {
1557 MacInvocTT(self.fold_path(path),
1558 self.fold_tts(&tts[..]),
1559 mtwt::apply_mark(self.mark, ctxt))
1567 // apply a given mark to the given token trees. Used prior to expansion of a macro.
1568 fn mark_tts(tts: &[TokenTree], m: Mrk) -> Vec<TokenTree> {
1569 noop_fold_tts(tts, &mut Marker{mark:m})
1572 // apply a given mark to the given expr. Used following the expansion of a macro.
1573 fn mark_expr(expr: P<ast::Expr>, m: Mrk) -> P<ast::Expr> {
1574 Marker{mark:m}.fold_expr(expr)
1577 // apply a given mark to the given pattern. Used following the expansion of a macro.
1578 fn mark_pat(pat: P<ast::Pat>, m: Mrk) -> P<ast::Pat> {
1579 Marker{mark:m}.fold_pat(pat)
1582 // apply a given mark to the given stmt. Used following the expansion of a macro.
1583 fn mark_stmt(stmt: P<ast::Stmt>, m: Mrk) -> P<ast::Stmt> {
1584 Marker{mark:m}.fold_stmt(stmt)
1585 .expect_one("marking a stmt didn't return exactly one stmt")
1588 // apply a given mark to the given item. Used following the expansion of a macro.
1589 fn mark_item(expr: P<ast::Item>, m: Mrk) -> P<ast::Item> {
1590 Marker{mark:m}.fold_item(expr)
1591 .expect_one("marking an item didn't return exactly one item")
1594 // apply a given mark to the given item. Used following the expansion of a macro.
1595 fn mark_impl_item(ii: P<ast::ImplItem>, m: Mrk) -> P<ast::ImplItem> {
1596 Marker{mark:m}.fold_impl_item(ii)
1597 .expect_one("marking an impl item didn't return exactly one impl item")
1600 /// Check that there are no macro invocations left in the AST:
1601 pub fn check_for_macros(sess: &parse::ParseSess, krate: &ast::Crate) {
1602 visit::walk_crate(&mut MacroExterminator{sess:sess}, krate);
1605 /// A visitor that ensures that no macro invocations remain in an AST.
1606 struct MacroExterminator<'a>{
1607 sess: &'a parse::ParseSess
1610 impl<'a, 'v> Visitor<'v> for MacroExterminator<'a> {
1611 fn visit_mac(&mut self, mac: &ast::Mac) {
1612 self.sess.span_diagnostic.span_bug(mac.span,
1613 "macro exterminator: expected AST \
1614 with no macro invocations");
1621 use super::{pattern_bindings, expand_crate};
1622 use super::{PatIdentFinder, IdentRenamer, PatIdentRenamer, ExpansionConfig};
1630 use util::parser_testing::{string_to_parser};
1631 use util::parser_testing::{string_to_pat, string_to_crate, strs_to_idents};
1635 // a visitor that extracts the paths
1636 // from a given thingy and puts them in a mutable
1637 // array (passed in to the traversal)
1639 struct PathExprFinderContext {
1640 path_accumulator: Vec<ast::Path> ,
1643 impl<'v> Visitor<'v> for PathExprFinderContext {
1644 fn visit_expr(&mut self, expr: &ast::Expr) {
1645 if let ast::ExprPath(None, ref p) = expr.node {
1646 self.path_accumulator.push(p.clone());
1648 visit::walk_expr(self, expr);
1652 // find the variable references in a crate
1653 fn crate_varrefs(the_crate : &ast::Crate) -> Vec<ast::Path> {
1654 let mut path_finder = PathExprFinderContext{path_accumulator:Vec::new()};
1655 visit::walk_crate(&mut path_finder, the_crate);
1656 path_finder.path_accumulator
1659 /// A Visitor that extracts the identifiers from a thingy.
1660 // as a side note, I'm starting to want to abstract over these....
1661 struct IdentFinder {
1662 ident_accumulator: Vec<ast::Ident>
1665 impl<'v> Visitor<'v> for IdentFinder {
1666 fn visit_ident(&mut self, _: codemap::Span, id: ast::Ident){
1667 self.ident_accumulator.push(id);
1671 /// Find the idents in a crate
1672 fn crate_idents(the_crate: &ast::Crate) -> Vec<ast::Ident> {
1673 let mut ident_finder = IdentFinder{ident_accumulator: Vec::new()};
1674 visit::walk_crate(&mut ident_finder, the_crate);
1675 ident_finder.ident_accumulator
1678 // these following tests are quite fragile, in that they don't test what
1679 // *kind* of failure occurs.
1681 fn test_ecfg() -> ExpansionConfig<'static> {
1682 ExpansionConfig::default("test".to_string())
1685 // make sure that macros can't escape fns
1687 #[test] fn macros_cant_escape_fns_test () {
1688 let src = "fn bogus() {macro_rules! z (() => (3+4));}\
1689 fn inty() -> i32 { z!() }".to_string();
1690 let sess = parse::ParseSess::new();
1691 let crate_ast = parse::parse_crate_from_source_str(
1692 "<test>".to_string(),
1696 expand_crate(&sess,test_ecfg(),vec!(),vec!(),crate_ast);
1699 // make sure that macros can't escape modules
1701 #[test] fn macros_cant_escape_mods_test () {
1702 let src = "mod foo {macro_rules! z (() => (3+4));}\
1703 fn inty() -> i32 { z!() }".to_string();
1704 let sess = parse::ParseSess::new();
1705 let crate_ast = parse::parse_crate_from_source_str(
1706 "<test>".to_string(),
1709 expand_crate(&sess,test_ecfg(),vec!(),vec!(),crate_ast);
1712 // macro_use modules should allow macros to escape
1713 #[test] fn macros_can_escape_flattened_mods_test () {
1714 let src = "#[macro_use] mod foo {macro_rules! z (() => (3+4));}\
1715 fn inty() -> i32 { z!() }".to_string();
1716 let sess = parse::ParseSess::new();
1717 let crate_ast = parse::parse_crate_from_source_str(
1718 "<test>".to_string(),
1721 expand_crate(&sess, test_ecfg(), vec!(), vec!(), crate_ast);
1724 fn expand_crate_str(crate_str: String) -> ast::Crate {
1725 let ps = parse::ParseSess::new();
1726 let crate_ast = panictry!(string_to_parser(&ps, crate_str).parse_crate_mod());
1727 // the cfg argument actually does matter, here...
1728 expand_crate(&ps,test_ecfg(),vec!(),vec!(),crate_ast)
1731 // find the pat_ident paths in a crate
1732 fn crate_bindings(the_crate : &ast::Crate) -> Vec<ast::Ident> {
1733 let mut name_finder = PatIdentFinder{ident_accumulator:Vec::new()};
1734 visit::walk_crate(&mut name_finder, the_crate);
1735 name_finder.ident_accumulator
1738 #[test] fn macro_tokens_should_match(){
1740 "macro_rules! m((a)=>(13)) ;fn main(){m!(a);}".to_string());
1743 // should be able to use a bound identifier as a literal in a macro definition:
1744 #[test] fn self_macro_parsing(){
1746 "macro_rules! foo ((zz) => (287;));
1747 fn f(zz: i32) {foo!(zz);}".to_string()
1751 // renaming tests expand a crate and then check that the bindings match
1752 // the right varrefs. The specification of the test case includes the
1753 // text of the crate, and also an array of arrays. Each element in the
1754 // outer array corresponds to a binding in the traversal of the AST
1755 // induced by visit. Each of these arrays contains a list of indexes,
1756 // interpreted as the varrefs in the varref traversal that this binding
1757 // should match. So, for instance, in a program with two bindings and
1758 // three varrefs, the array [[1, 2], [0]] would indicate that the first
1759 // binding should match the second two varrefs, and the second binding
1760 // should match the first varref.
1762 // Put differently; this is a sparse representation of a boolean matrix
1763 // indicating which bindings capture which identifiers.
1765 // Note also that this matrix is dependent on the implicit ordering of
1766 // the bindings and the varrefs discovered by the name-finder and the path-finder.
1768 // The comparisons are done post-mtwt-resolve, so we're comparing renamed
1769 // names; differences in marks don't matter any more.
1771 // oog... I also want tests that check "bound-identifier-=?". That is,
1772 // not just "do these have the same name", but "do they have the same
1773 // name *and* the same marks"? Understanding this is really pretty painful.
1774 // in principle, you might want to control this boolean on a per-varref basis,
1775 // but that would make things even harder to understand, and might not be
1776 // necessary for thorough testing.
1777 type RenamingTest = (&'static str, Vec<Vec<usize>>, bool);
1780 fn automatic_renaming () {
1781 let tests: Vec<RenamingTest> =
1782 vec!(// b & c should get new names throughout, in the expr too:
1783 ("fn a() -> i32 { let b = 13; let c = b; b+c }",
1784 vec!(vec!(0,1),vec!(2)), false),
1785 // both x's should be renamed (how is this causing a bug?)
1786 ("fn main () {let x: i32 = 13;x;}",
1787 vec!(vec!(0)), false),
1788 // the use of b after the + should be renamed, the other one not:
1789 ("macro_rules! f (($x:ident) => (b + $x)); fn a() -> i32 { let b = 13; f!(b)}",
1790 vec!(vec!(1)), false),
1791 // the b before the plus should not be renamed (requires marks)
1792 ("macro_rules! f (($x:ident) => ({let b=9; ($x + b)})); fn a() -> i32 { f!(b)}",
1793 vec!(vec!(1)), false),
1794 // the marks going in and out of letty should cancel, allowing that $x to
1795 // capture the one following the semicolon.
1796 // this was an awesome test case, and caught a *lot* of bugs.
1797 ("macro_rules! letty(($x:ident) => (let $x = 15;));
1798 macro_rules! user(($x:ident) => ({letty!($x); $x}));
1799 fn main() -> i32 {user!(z)}",
1800 vec!(vec!(0)), false)
1802 for (idx,s) in tests.iter().enumerate() {
1803 run_renaming_test(s,idx);
1807 // no longer a fixme #8062: this test exposes a *potential* bug; our system does
1808 // not behave exactly like MTWT, but a conversation with Matthew Flatt
1809 // suggests that this can only occur in the presence of local-expand, which
1810 // we have no plans to support. ... unless it's needed for item hygiene....
1815 &("fn main() {let hrcoo = 19; macro_rules! getx(()=>(hrcoo)); getx!();}",
1816 vec!(vec!(0)), true), 0)
1820 // the z flows into and out of two macros (g & f) along one path, and one
1821 // (just g) along the other, so the result of the whole thing should
1822 // be "let z_123 = 3; z_123"
1827 &("macro_rules! g (($x:ident) =>
1828 ({macro_rules! f(($y:ident)=>({let $y=3;$x}));f!($x)}));
1830 vec!(vec!(0)),false),
1834 // match variable hygiene. Should expand into
1835 // fn z() {match 8 {x_1 => {match 9 {x_2 | x_2 if x_2 == x_1 => x_2 + x_1}}}}
1839 &("macro_rules! bad_macro (($ex:expr) => ({match 9 {x | x if x == $ex => x + $ex}}));
1840 fn z() {match 8 {x => bad_macro!(x)}}",
1841 // NB: the third "binding" is the repeat of the second one.
1842 vec!(vec!(1,3),vec!(0,2),vec!(0,2)),
1847 // interpolated nodes weren't getting labeled.
1848 // should expand into
1849 // fn main(){let g1_1 = 13; g1_1}}
1851 fn pat_expand_issue_15221(){
1853 &("macro_rules! inner ( ($e:pat ) => ($e));
1854 macro_rules! outer ( ($e:pat ) => (inner!($e)));
1855 fn main() { let outer!(g) = 13; g;}",
1861 // create a really evil test case where a $x appears inside a binding of $x
1862 // but *shouldn't* bind because it was inserted by a different macro....
1863 // can't write this test case until we have macro-generating macros.
1865 // method arg hygiene
1866 // method expands to fn get_x(&self_0, x_1: i32) {self_0 + self_2 + x_3 + x_1}
1868 fn method_arg_hygiene(){
1870 &("macro_rules! inject_x (()=>(x));
1871 macro_rules! inject_self (()=>(self));
1873 impl A{fn get_x(&self, x: i32) {self + inject_self!() + inject_x!() + x;} }",
1874 vec!(vec!(0),vec!(3)),
1879 // ooh, got another bite?
1880 // expands to struct A; impl A {fn thingy(&self_1) {self_1;}}
1882 fn method_arg_hygiene_2(){
1885 macro_rules! add_method (($T:ty) =>
1886 (impl $T { fn thingy(&self) {self;} }));
1894 // expands to fn q(x_1: i32){fn g(x_2: i32){x_2 + x_1};}
1898 &("macro_rules! bad_macro (($ex:expr) => (fn g(x: i32){ x + $ex }));
1899 fn q(x: i32) { bad_macro!(x); }",
1900 vec!(vec!(1),vec!(0)),true),
1904 // closure arg hygiene (ExprClosure)
1905 // expands to fn f(){(|x_1 : i32| {(x_2 + x_1)})(3);}
1907 fn closure_arg_hygiene(){
1909 &("macro_rules! inject_x (()=>(x));
1910 fn f(){(|x : i32| {(inject_x!() + x)})(3);}",
1916 // macro_rules in method position. Sadly, unimplemented.
1918 fn macro_in_method_posn(){
1920 "macro_rules! my_method (() => (fn thirteen(&self) -> i32 {13}));
1922 impl A{ my_method!(); }
1923 fn f(){A.thirteen;}".to_string());
1926 // another nested macro
1927 // expands to impl Entries {fn size_hint(&self_1) {self_1;}
1929 fn item_macro_workaround(){
1931 &("macro_rules! item { ($i:item) => {$i}}
1933 macro_rules! iterator_impl {
1934 () => { item!( impl Entries { fn size_hint(&self) { self;}});}}
1935 iterator_impl! { }",
1936 vec!(vec!(0)), true),
1940 // run one of the renaming tests
1941 fn run_renaming_test(t: &RenamingTest, test_idx: usize) {
1942 let invalid_name = token::special_idents::invalid.name;
1943 let (teststr, bound_connections, bound_ident_check) = match *t {
1944 (ref str,ref conns, bic) => (str.to_string(), conns.clone(), bic)
1946 let cr = expand_crate_str(teststr.to_string());
1947 let bindings = crate_bindings(&cr);
1948 let varrefs = crate_varrefs(&cr);
1950 // must be one check clause for each binding:
1951 assert_eq!(bindings.len(),bound_connections.len());
1952 for (binding_idx,shouldmatch) in bound_connections.iter().enumerate() {
1953 let binding_name = mtwt::resolve(bindings[binding_idx]);
1954 let binding_marks = mtwt::marksof(bindings[binding_idx].ctxt, invalid_name);
1955 // shouldmatch can't name varrefs that don't exist:
1956 assert!((shouldmatch.is_empty()) ||
1957 (varrefs.len() > *shouldmatch.iter().max().unwrap()));
1958 for (idx,varref) in varrefs.iter().enumerate() {
1959 let print_hygiene_debug_info = || {
1960 // good lord, you can't make a path with 0 segments, can you?
1961 let final_varref_ident = match varref.segments.last() {
1962 Some(pathsegment) => pathsegment.identifier,
1963 None => panic!("varref with 0 path segments?")
1965 let varref_name = mtwt::resolve(final_varref_ident);
1966 let varref_idents : Vec<ast::Ident>
1967 = varref.segments.iter().map(|s| s.identifier)
1969 println!("varref #{}: {:?}, resolves to {}",idx, varref_idents, varref_name);
1970 let string = token::get_ident(final_varref_ident);
1971 println!("varref's first segment's string: \"{}\"", &string[..]);
1972 println!("binding #{}: {}, resolves to {}",
1973 binding_idx, bindings[binding_idx], binding_name);
1974 mtwt::with_sctable(|x| mtwt::display_sctable(x));
1976 if shouldmatch.contains(&idx) {
1977 // it should be a path of length 1, and it should
1978 // be free-identifier=? or bound-identifier=? to the given binding
1979 assert_eq!(varref.segments.len(),1);
1980 let varref_name = mtwt::resolve(varref.segments[0].identifier);
1981 let varref_marks = mtwt::marksof(varref.segments[0]
1985 if !(varref_name==binding_name) {
1986 println!("uh oh, should match but doesn't:");
1987 print_hygiene_debug_info();
1989 assert_eq!(varref_name,binding_name);
1990 if bound_ident_check {
1991 // we're checking bound-identifier=?, and the marks
1992 // should be the same, too:
1993 assert_eq!(varref_marks,binding_marks.clone());
1996 let varref_name = mtwt::resolve(varref.segments[0].identifier);
1997 let fail = (varref.segments.len() == 1)
1998 && (varref_name == binding_name);
2001 println!("failure on test {}",test_idx);
2002 println!("text of test case: \"{}\"", teststr);
2004 println!("uh oh, matches but shouldn't:");
2005 print_hygiene_debug_info();
2014 fn fmt_in_macro_used_inside_module_macro() {
2015 let crate_str = "macro_rules! fmt_wrap(($b:expr)=>($b.to_string()));
2016 macro_rules! foo_module (() => (mod generated { fn a() { let xx = 147; fmt_wrap!(xx);}}));
2019 let cr = expand_crate_str(crate_str);
2020 // find the xx binding
2021 let bindings = crate_bindings(&cr);
2022 let cxbinds: Vec<&ast::Ident> =
2023 bindings.iter().filter(|b| {
2024 let ident = token::get_ident(**b);
2025 let string = &ident[..];
2028 let cxbinds: &[&ast::Ident] = &cxbinds[..];
2029 let cxbind = match (cxbinds.len(), cxbinds.get(0)) {
2031 _ => panic!("expected just one binding for ext_cx")
2033 let resolved_binding = mtwt::resolve(*cxbind);
2034 let varrefs = crate_varrefs(&cr);
2036 // the xx binding should bind all of the xx varrefs:
2037 for (idx,v) in varrefs.iter().filter(|p| {
2038 p.segments.len() == 1
2039 && "xx" == &*token::get_ident(p.segments[0].identifier)
2041 if mtwt::resolve(v.segments[0].identifier) != resolved_binding {
2042 println!("uh oh, xx binding didn't match xx varref:");
2043 println!("this is xx varref \\# {}", idx);
2044 println!("binding: {}", cxbind);
2045 println!("resolves to: {}", resolved_binding);
2046 println!("varref: {}", v.segments[0].identifier);
2047 println!("resolves to: {}",
2048 mtwt::resolve(v.segments[0].identifier));
2049 mtwt::with_sctable(|x| mtwt::display_sctable(x));
2051 assert_eq!(mtwt::resolve(v.segments[0].identifier),
2058 let pat = string_to_pat(
2059 "(a,Foo{x:c @ (b,9),y:Bar(4,d)})".to_string());
2060 let idents = pattern_bindings(&*pat);
2061 assert_eq!(idents, strs_to_idents(vec!("a","c","b","d")));
2064 // test the list of identifier patterns gathered by the visitor. Note that
2065 // 'None' is listed as an identifier pattern because we don't yet know that
2066 // it's the name of a 0-ary variant, and that 'i' appears twice in succession.
2068 fn crate_bindings_test(){
2069 let the_crate = string_to_crate("fn main (a: i32) -> i32 {|b| {
2070 match 34 {None => 3, Some(i) | i => j, Foo{k:z,l:y} => \"banana\"}} }".to_string());
2071 let idents = crate_bindings(&the_crate);
2072 assert_eq!(idents, strs_to_idents(vec!("a","b","None","i","i","z","y")));
2075 // test the IdentRenamer directly
2077 fn ident_renamer_test () {
2078 let the_crate = string_to_crate("fn f(x: i32){let x = x; x}".to_string());
2079 let f_ident = token::str_to_ident("f");
2080 let x_ident = token::str_to_ident("x");
2081 let int_ident = token::str_to_ident("i32");
2082 let renames = vec!((x_ident,Name(16)));
2083 let mut renamer = IdentRenamer{renames: &renames};
2084 let renamed_crate = renamer.fold_crate(the_crate);
2085 let idents = crate_idents(&renamed_crate);
2086 let resolved : Vec<ast::Name> = idents.iter().map(|id| mtwt::resolve(*id)).collect();
2087 assert_eq!(resolved, [f_ident.name,Name(16),int_ident.name,Name(16),Name(16),Name(16)]);
2090 // test the PatIdentRenamer; only PatIdents get renamed
2092 fn pat_ident_renamer_test () {
2093 let the_crate = string_to_crate("fn f(x: i32){let x = x; x}".to_string());
2094 let f_ident = token::str_to_ident("f");
2095 let x_ident = token::str_to_ident("x");
2096 let int_ident = token::str_to_ident("i32");
2097 let renames = vec!((x_ident,Name(16)));
2098 let mut renamer = PatIdentRenamer{renames: &renames};
2099 let renamed_crate = renamer.fold_crate(the_crate);
2100 let idents = crate_idents(&renamed_crate);
2101 let resolved : Vec<ast::Name> = idents.iter().map(|id| mtwt::resolve(*id)).collect();
2102 let x_name = x_ident.name;
2103 assert_eq!(resolved, [f_ident.name,Name(16),int_ident.name,Name(16),x_name,x_name]);