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