-
Notifications
You must be signed in to change notification settings - Fork 13.2k
/
Copy pathexpand.rs
1653 lines (1495 loc) · 59.4 KB
/
expand.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
use ast::{Block, Crate, DeclLocal, Expr_, ExprMac, SyntaxContext};
use ast::{Local, Ident, mac_invoc_tt};
use ast::{item_mac, Mrk, Stmt, StmtDecl, StmtMac, StmtExpr, StmtSemi};
use ast::{token_tree};
use ast;
use ast_util::{mtwt_outer_mark, new_rename, new_mark};
use ext::build::AstBuilder;
use attr;
use attr::AttrMetaMethods;
use codemap;
use codemap::{Span, Spanned, ExpnInfo, NameAndSpan};
use ext::base::*;
use fold::*;
use opt_vec;
use parse;
use parse::{parse_item_from_source_str};
use parse::token;
use parse::token::{fresh_mark, fresh_name, ident_to_str, intern};
use visit;
use visit::Visitor;
use std::vec;
pub fn expand_expr(extsbox: @mut SyntaxEnv,
cx: @ExtCtxt,
e: @ast::Expr,
fld: &MacroExpander)
-> @ast::Expr {
match e.node {
// expr_mac should really be expr_ext or something; it's the
// entry-point for all syntax extensions.
ExprMac(ref mac) => {
match (*mac).node {
// it would almost certainly be cleaner to pass the whole
// macro invocation in, rather than pulling it apart and
// marking the tts and the ctxt separately. This also goes
// for the other three macro invocation chunks of code
// in this file.
// Token-tree macros:
mac_invoc_tt(ref pth, ref tts, ctxt) => {
if (pth.segments.len() > 1u) {
cx.span_fatal(
pth.span,
format!("expected macro name without module \
separators"));
}
let extname = &pth.segments[0].identifier;
let extnamestr = ident_to_str(extname);
// leaving explicit deref here to highlight unbox op:
match (*extsbox).find(&extname.name) {
None => {
cx.span_fatal(
pth.span,
format!("macro undefined: '{}'", extnamestr))
}
Some(@SE(NormalTT(expandfun, exp_span))) => {
cx.bt_push(ExpnInfo {
call_site: e.span,
callee: NameAndSpan {
name: extnamestr,
span: exp_span,
},
});
let fm = fresh_mark();
// mark before:
let marked_before = mark_tts(*tts,fm);
let marked_ctxt = new_mark(fm, ctxt);
// The span that we pass to the expanders we want to
// be the root of the call stack. That's the most
// relevant span and it's the actual invocation of
// the macro.
let mac_span = original_span(cx);
let expanded =
match expandfun.expand(cx,
mac_span.call_site,
marked_before,
marked_ctxt) {
MRExpr(e) => e,
MRAny(any_macro) => any_macro.make_expr(),
_ => {
cx.span_fatal(
pth.span,
format!(
"non-expr macro in expr pos: {}",
extnamestr
)
)
}
};
// mark after:
let marked_after = mark_expr(expanded,fm);
// Keep going, outside-in.
//
// XXX(pcwalton): Is it necessary to clone the
// node here?
let fully_expanded =
fld.fold_expr(marked_after).node.clone();
cx.bt_pop();
@ast::Expr {
id: ast::DUMMY_NODE_ID,
node: fully_expanded,
span: e.span,
}
}
_ => {
cx.span_fatal(
pth.span,
format!("'{}' is not a tt-style macro", extnamestr)
)
}
}
}
}
}
// Desugar expr_for_loop
// From: `['<ident>:] for <src_pat> in <src_expr> <src_loop_block>`
// FIXME #6993 : change type of opt_ident to Option<Name>
ast::ExprForLoop(src_pat, src_expr, ref src_loop_block, opt_ident) => {
// Expand any interior macros etc.
// NB: we don't fold pats yet. Curious.
let src_expr = fld.fold_expr(src_expr).clone();
let src_loop_block = fld.fold_block(src_loop_block).clone();
let span = e.span;
fn mk_expr(_: @ExtCtxt, span: Span, node: Expr_)
-> @ast::Expr {
@ast::Expr {
id: ast::DUMMY_NODE_ID,
node: node,
span: span,
}
}
fn mk_block(_: @ExtCtxt,
stmts: &[@ast::Stmt],
expr: Option<@ast::Expr>,
span: Span)
-> ast::Block {
ast::Block {
view_items: ~[],
stmts: stmts.to_owned(),
expr: expr,
id: ast::DUMMY_NODE_ID,
rules: ast::DefaultBlock,
span: span,
}
}
fn mk_simple_path(ident: ast::Ident, span: Span) -> ast::Path {
ast::Path {
span: span,
global: false,
segments: ~[
ast::PathSegment {
identifier: ident,
lifetimes: opt_vec::Empty,
types: opt_vec::Empty,
}
],
}
}
// to:
//
// {
// let _i = &mut <src_expr>;
// ['<ident>:] loop {
// match i.next() {
// None => break,
// Some(<src_pat>) => <src_loop_block>
// }
// }
// }
let local_ident = token::gensym_ident("i");
let next_ident = cx.ident_of("next");
let none_ident = cx.ident_of("None");
let local_path = cx.path_ident(span, local_ident);
let some_path = cx.path_ident(span, cx.ident_of("Some"));
// `let i = &mut <src_expr>`
let iter_decl_stmt = cx.stmt_let(span, false, local_ident,
cx.expr_mut_addr_of(span, src_expr));
// `None => break ['<ident>];`
let none_arm = {
// FIXME #6993: this map goes away:
let break_expr = cx.expr(span, ast::ExprBreak(opt_ident.map(|x| x.name)));
let none_pat = cx.pat_ident(span, none_ident);
cx.arm(span, ~[none_pat], break_expr)
};
// `Some(<src_pat>) => <src_loop_block>`
let some_arm =
cx.arm(span,
~[cx.pat_enum(span, some_path, ~[src_pat])],
cx.expr_block(src_loop_block));
// `match i.next() { ... }`
let match_expr = {
let next_call_expr =
cx.expr_method_call(span, cx.expr_path(local_path), next_ident, ~[]);
cx.expr_match(span, next_call_expr, ~[none_arm, some_arm])
};
// ['ident:] loop { ... }
let loop_expr = cx.expr(span,
ast::ExprLoop(cx.block_expr(match_expr), opt_ident));
// `{ let ... ; loop { ... } }`
let block = cx.block(span,
~[iter_decl_stmt],
Some(loop_expr));
@ast::Expr {
id: ast::DUMMY_NODE_ID,
node: ast::ExprBlock(block),
span: span,
}
}
_ => noop_fold_expr(e, fld)
}
}
// This is a secondary mechanism for invoking syntax extensions on items:
// "decorator" attributes, such as #[auto_encode]. These are invoked by an
// attribute prefixing an item, and are interpreted by feeding the item
// through the named attribute _as a syntax extension_ and splicing in the
// resulting item vec into place in favour of the decorator. Note that
// these do _not_ work for macro extensions, just ItemDecorator ones.
//
// NB: there is some redundancy between this and expand_item, below, and
// they might benefit from some amount of semantic and language-UI merger.
pub fn expand_mod_items(extsbox: @mut SyntaxEnv,
cx: @ExtCtxt,
module_: &ast::_mod,
fld: &MacroExpander)
-> ast::_mod {
// Fold the contents first:
let module_ = noop_fold_mod(module_, fld);
// For each item, look through the attributes. If any of them are
// decorated with "item decorators", then use that function to transform
// the item into a new set of items.
let new_items = do vec::flat_map(module_.items) |item| {
do item.attrs.rev_iter().fold(~[*item]) |items, attr| {
let mname = attr.name();
match (*extsbox).find(&intern(mname)) {
Some(@SE(ItemDecorator(dec_fn))) => {
cx.bt_push(ExpnInfo {
call_site: attr.span,
callee: NameAndSpan {
name: mname,
span: None
}
});
let r = dec_fn(cx, attr.span, attr.node.value, items);
cx.bt_pop();
r
},
_ => items,
}
}
};
ast::_mod {
items: new_items,
..module_
}
}
// eval $e with a new exts frame:
macro_rules! with_exts_frame (
($extsboxexpr:expr,$macros_escape:expr,$e:expr) =>
({let extsbox = $extsboxexpr;
let oldexts = *extsbox;
*extsbox = oldexts.push_frame();
extsbox.insert(intern(special_block_name),
@BlockInfo(BlockInfo{macros_escape:$macros_escape,pending_renames:@mut ~[]}));
let result = $e;
*extsbox = oldexts;
result
})
)
static special_block_name : &'static str = " block";
// When we enter a module, record it, for the sake of `module!`
pub fn expand_item(extsbox: @mut SyntaxEnv,
cx: @ExtCtxt,
it: @ast::item,
fld: &MacroExpander)
-> Option<@ast::item> {
match it.node {
ast::item_mac(*) => expand_item_mac(extsbox, cx, it, fld),
ast::item_mod(_) | ast::item_foreign_mod(_) => {
cx.mod_push(it.ident);
let macro_escape = contains_macro_escape(it.attrs);
let result = with_exts_frame!(extsbox,
macro_escape,
noop_fold_item(it, fld));
cx.mod_pop();
result
},
_ => noop_fold_item(it, fld)
}
}
// does this attribute list contain "macro_escape" ?
pub fn contains_macro_escape(attrs: &[ast::Attribute]) -> bool {
attr::contains_name(attrs, "macro_escape")
}
// Support for item-position macro invocations, exactly the same
// logic as for expression-position macro invocations.
pub fn expand_item_mac(extsbox: @mut SyntaxEnv,
cx: @ExtCtxt,
it: @ast::item,
fld: &MacroExpander)
-> Option<@ast::item> {
let (pth, tts, ctxt) = match it.node {
item_mac(codemap::Spanned {
node: mac_invoc_tt(ref pth, ref tts, ctxt),
_
}) => {
(pth, (*tts).clone(), ctxt)
}
_ => cx.span_bug(it.span, "invalid item macro invocation")
};
let extname = &pth.segments[0].identifier;
let extnamestr = ident_to_str(extname);
let fm = fresh_mark();
let expanded = match (*extsbox).find(&extname.name) {
None => cx.span_fatal(pth.span,
format!("macro undefined: '{}!'", extnamestr)),
Some(@SE(NormalTT(expander, span))) => {
if it.ident.name != parse::token::special_idents::invalid.name {
cx.span_fatal(pth.span,
format!("macro {}! expects no ident argument, \
given '{}'", extnamestr,
ident_to_str(&it.ident)));
}
cx.bt_push(ExpnInfo {
call_site: it.span,
callee: NameAndSpan {
name: extnamestr,
span: span
}
});
// mark before expansion:
let marked_before = mark_tts(tts,fm);
let marked_ctxt = new_mark(fm,ctxt);
expander.expand(cx, it.span, marked_before, marked_ctxt)
}
Some(@SE(IdentTT(expander, span))) => {
if it.ident.name == parse::token::special_idents::invalid.name {
cx.span_fatal(pth.span,
format!("macro {}! expects an ident argument",
extnamestr));
}
cx.bt_push(ExpnInfo {
call_site: it.span,
callee: NameAndSpan {
name: extnamestr,
span: span
}
});
// mark before expansion:
let marked_tts = mark_tts(tts,fm);
let marked_ctxt = new_mark(fm,ctxt);
expander.expand(cx, it.span, it.ident, marked_tts, marked_ctxt)
}
_ => cx.span_fatal(
it.span, format!("{}! is not legal in item position", extnamestr))
};
let maybe_it = match expanded {
MRItem(it) => {
mark_item(it,fm)
.and_then(|i| fld.fold_item(i))
}
MRExpr(_) => {
cx.span_fatal(pth.span, format!("expr macro in item position: {}", extnamestr))
}
MRAny(any_macro) => {
any_macro.make_item()
.and_then(|i| mark_item(i,fm))
.and_then(|i| fld.fold_item(i))
}
MRDef(ref mdef) => {
// yikes... no idea how to apply the mark to this. I'm afraid
// we're going to have to wait-and-see on this one.
insert_macro(*extsbox,intern(mdef.name), @SE((*mdef).ext));
None
}
};
cx.bt_pop();
return maybe_it;
}
// insert a macro into the innermost frame that doesn't have the
// macro_escape tag.
fn insert_macro(exts: SyntaxEnv, name: ast::Name, transformer: @Transformer) {
let is_non_escaping_block =
|t : &@Transformer| -> bool{
match t {
&@BlockInfo(BlockInfo {macros_escape:false,_}) => true,
&@BlockInfo(BlockInfo {_}) => false,
_ => fail!("special identifier {:?} was bound to a non-BlockInfo",
special_block_name)
}
};
exts.insert_into_frame(name,transformer,intern(special_block_name),
is_non_escaping_block)
}
// expand a stmt
pub fn expand_stmt(extsbox: @mut SyntaxEnv,
cx: @ExtCtxt,
s: &Stmt,
fld: &MacroExpander)
-> Option<@Stmt> {
// why the copying here and not in expand_expr?
// looks like classic changed-in-only-one-place
let (pth, tts, semi, ctxt) = match s.node {
StmtMac(ref mac, semi) => {
match mac.node {
mac_invoc_tt(ref pth, ref tts, ctxt) => {
(pth, (*tts).clone(), semi, ctxt)
}
}
}
_ => return expand_non_macro_stmt(*extsbox, s, fld)
};
if (pth.segments.len() > 1u) {
cx.span_fatal(pth.span,
"expected macro name without module separators");
}
let extname = &pth.segments[0].identifier;
let extnamestr = ident_to_str(extname);
let fully_expanded: @ast::Stmt = match (*extsbox).find(&extname.name) {
None => {
cx.span_fatal(pth.span, format!("macro undefined: '{}'", extnamestr))
}
Some(@SE(NormalTT(expandfun, exp_span))) => {
cx.bt_push(ExpnInfo {
call_site: s.span,
callee: NameAndSpan {
name: extnamestr,
span: exp_span,
}
});
let fm = fresh_mark();
// mark before expansion:
let marked_tts = mark_tts(tts,fm);
let marked_ctxt = new_mark(fm,ctxt);
// See the comment in expand_expr for why we want the original span,
// not the current mac.span.
let mac_span = original_span(cx);
let expanded = match expandfun.expand(cx,
mac_span.call_site,
marked_tts,
marked_ctxt) {
MRExpr(e) => {
@codemap::Spanned {
node: StmtExpr(e, ast::DUMMY_NODE_ID),
span: e.span,
}
}
MRAny(any_macro) => any_macro.make_stmt(),
_ => cx.span_fatal(
pth.span,
format!("non-stmt macro in stmt pos: {}", extnamestr))
};
let marked_after = mark_stmt(expanded,fm);
// Keep going, outside-in.
let fully_expanded = match fld.fold_stmt(marked_after) {
Some(stmt) => {
let fully_expanded = &stmt.node;
cx.bt_pop();
@Spanned {
span: stmt.span,
node: (*fully_expanded).clone(),
}
}
None => {
cx.span_fatal(pth.span,
"macro didn't expand to a statement")
}
};
fully_expanded
}
_ => {
cx.span_fatal(pth.span,
format!("'{}' is not a tt-style macro", extnamestr))
}
};
match fully_expanded.node {
StmtExpr(e, stmt_id) if semi => {
Some(@Spanned {
span: fully_expanded.span,
node: StmtSemi(e, stmt_id),
})
}
_ => Some(fully_expanded), /* might already have a semi */
}
}
// expand a non-macro stmt. this is essentially the fallthrough for
// expand_stmt, above.
fn expand_non_macro_stmt(exts: SyntaxEnv, s: &Stmt, fld: &MacroExpander)
-> Option<@Stmt> {
// is it a let?
match s.node {
StmtDecl(@Spanned {
node: DeclLocal(ref local),
span: stmt_span
},
node_id) => {
let block_info = get_block_info(exts);
let pending_renames = block_info.pending_renames;
// take it apart:
let @Local {
ty: _,
pat: pat,
init: init,
id: id,
span: span
} = *local;
// types can't be copied automatically because of the owned ptr in ty_tup...
let ty = local.ty.clone();
// expand the pat (it might contain exprs... #:(o)>
let expanded_pat = fld.fold_pat(pat);
// find the pat_idents in the pattern:
// oh dear heaven... this is going to include the enum names, as well....
// ... but that should be okay, as long as the new names are gensyms
// for the old ones.
let mut name_finder = new_name_finder(~[]);
name_finder.visit_pat(expanded_pat,());
// generate fresh names, push them to a new pending list
let new_pending_renames = @mut ~[];
for ident in name_finder.ident_accumulator.iter() {
let new_name = fresh_name(ident);
new_pending_renames.push((*ident,new_name));
}
let rename_fld = renames_to_fold(new_pending_renames);
// rewrite the pattern using the new names (the old ones
// have already been applied):
let rewritten_pat = rename_fld.fold_pat(expanded_pat);
// add them to the existing pending renames:
for pr in new_pending_renames.iter() {pending_renames.push(*pr)}
// also, don't forget to expand the init:
let new_init_opt = init.map(|e| fld.fold_expr(e));
let rewritten_local =
@Local {
ty: ty,
pat: rewritten_pat,
init: new_init_opt,
id: id,
span: span,
};
Some(@Spanned {
node: StmtDecl(@Spanned {
node: DeclLocal(rewritten_local),
span: stmt_span
},
node_id),
span: span
})
},
_ => noop_fold_stmt(s, fld),
}
}
// a visitor that extracts the pat_ident paths
// from a given thingy and puts them in a mutable
// array (passed in to the traversal)
#[deriving(Clone)]
struct NewNameFinderContext {
ident_accumulator: ~[ast::Ident],
}
impl Visitor<()> for NewNameFinderContext {
fn visit_pat(&mut self, pattern: @ast::Pat, _: ()) {
match *pattern {
// we found a pat_ident!
ast::Pat {
id: _,
node: ast::PatIdent(_, ref path, ref inner),
span: _
} => {
match path {
// a path of length one:
&ast::Path {
global: false,
span: _,
segments: [
ast::PathSegment {
identifier: id,
lifetimes: _,
types: _
}
]
} => self.ident_accumulator.push(id),
// I believe these must be enums...
_ => ()
}
// visit optional subpattern of pat_ident:
for subpat in inner.iter() {
self.visit_pat(*subpat, ())
}
}
// use the default traversal for non-pat_idents
_ => visit::walk_pat(self, pattern, ())
}
}
fn visit_ty(&mut self, typ: &ast::Ty, _: ()) {
visit::walk_ty(self, typ, ())
}
}
// return a visitor that extracts the pat_ident paths
// from a given thingy and puts them in a mutable
// array (passed in to the traversal)
pub fn new_name_finder(idents: ~[ast::Ident]) -> NewNameFinderContext {
NewNameFinderContext {
ident_accumulator: idents,
}
}
// expand a block. pushes a new exts_frame, then calls expand_block_elts
pub fn expand_block(extsbox: @mut SyntaxEnv,
_: @ExtCtxt,
blk: &Block,
fld: &MacroExpander)
-> Block {
// see note below about treatment of exts table
with_exts_frame!(extsbox,false,
expand_block_elts(*extsbox, blk, fld))
}
// expand the elements of a block.
pub fn expand_block_elts(exts: SyntaxEnv, b: &Block, fld: &MacroExpander)
-> Block {
let block_info = get_block_info(exts);
let pending_renames = block_info.pending_renames;
let rename_fld = renames_to_fold(pending_renames);
let new_view_items = b.view_items.map(|x| fld.fold_view_item(x));
let mut new_stmts = ~[];
for x in b.stmts.iter() {
match fld.fold_stmt(mustbesome(rename_fld.fold_stmt(*x))) {
Some(s) => new_stmts.push(s),
None => ()
}
}
let new_expr = b.expr.map(|x| fld.fold_expr(rename_fld.fold_expr(x)));
Block{
view_items: new_view_items,
stmts: new_stmts,
expr: new_expr,
id: fld.new_id(b.id),
rules: b.rules,
span: b.span,
}
}
// rename_fold should never return "None".
// (basically, just .get() with a better message...)
fn mustbesome<T>(val : Option<T>) -> T {
match val {
Some(v) => v,
None => fail!("rename_fold returned None")
}
}
// get the (innermost) BlockInfo from an exts stack
fn get_block_info(exts : SyntaxEnv) -> BlockInfo {
match exts.find_in_topmost_frame(&intern(special_block_name)) {
Some(@BlockInfo(bi)) => bi,
_ => fail!("special identifier {:?} was bound to a non-BlockInfo",
@" block")
}
}
struct IdentRenamer {
renames: @mut ~[(ast::Ident,ast::Name)],
}
impl ast_fold for IdentRenamer {
fn fold_ident(&self, id: ast::Ident) -> ast::Ident {
let new_ctxt = self.renames.iter().fold(id.ctxt, |ctxt, &(from, to)| {
new_rename(from, to, ctxt)
});
ast::Ident {
name: id.name,
ctxt: new_ctxt,
}
}
}
// given a mutable list of renames, return a tree-folder that applies those
// renames.
pub fn renames_to_fold(renames: @mut ~[(ast::Ident,ast::Name)]) -> @ast_fold {
@IdentRenamer {
renames: renames,
} as @ast_fold
}
// perform a bunch of renames
fn apply_pending_renames(folder : @ast_fold, stmt : ast::Stmt) -> @ast::Stmt {
match folder.fold_stmt(&stmt) {
Some(s) => s,
None => fail!("renaming of stmt produced None")
}
}
pub fn new_span(cx: @ExtCtxt, sp: Span) -> Span {
/* this discards information in the case of macro-defining macros */
Span {
lo: sp.lo,
hi: sp.hi,
expn_info: cx.backtrace(),
}
}
// FIXME (#2247): this is a moderately bad kludge to inject some macros into
// the default compilation environment in that it injects strings, rather than
// syntax elements.
pub fn std_macros() -> @str {
@r#"mod __std_macros {
#[macro_escape];
#[doc(hidden)];
macro_rules! ignore (($($x:tt)*) => (()))
macro_rules! log(
($lvl:expr, $($arg:tt)+) => ({
let lvl = $lvl;
if lvl <= __log_level() {
format_args!(|args| {
::std::logging::log(lvl, args)
}, $($arg)+)
}
})
)
macro_rules! error( ($($arg:tt)*) => (log!(1u32, $($arg)*)) )
macro_rules! warn ( ($($arg:tt)*) => (log!(2u32, $($arg)*)) )
macro_rules! info ( ($($arg:tt)*) => (log!(3u32, $($arg)*)) )
macro_rules! debug( ($($arg:tt)*) => (
if cfg!(not(ndebug)) { log!(4u32, $($arg)*) }
))
macro_rules! fail(
() => (
fail!("explicit failure")
);
($msg:expr) => (
::std::rt::task::begin_unwind($msg, file!(), line!())
);
($fmt:expr, $($arg:tt)*) => (
::std::rt::task::begin_unwind(format!($fmt, $($arg)*), file!(), line!())
)
)
macro_rules! assert(
($cond:expr) => {
if !$cond {
fail!("assertion failed: {:s}", stringify!($cond))
}
};
($cond:expr, $msg:expr) => {
if !$cond {
fail!($msg)
}
};
($cond:expr, $( $arg:expr ),+) => {
if !$cond {
fail!( $($arg),+ )
}
}
)
macro_rules! assert_eq (
($given:expr , $expected:expr) => (
{
let given_val = &($given);
let expected_val = &($expected);
// check both directions of equality....
if !((*given_val == *expected_val) &&
(*expected_val == *given_val)) {
fail!("assertion failed: `(left == right) && (right == left)` \
(left: `{:?}`, right: `{:?}`)", *given_val, *expected_val)
}
}
)
)
macro_rules! assert_approx_eq (
($given:expr , $expected:expr) => (
{
use std::cmp::ApproxEq;
let given_val = $given;
let expected_val = $expected;
// check both directions of equality....
if !(
given_val.approx_eq(&expected_val) &&
expected_val.approx_eq(&given_val)
) {
fail!("left: {:?} does not approximately equal right: {:?}",
given_val, expected_val);
}
}
);
($given:expr , $expected:expr , $epsilon:expr) => (
{
use std::cmp::ApproxEq;
let given_val = $given;
let expected_val = $expected;
let epsilon_val = $epsilon;
// check both directions of equality....
if !(
given_val.approx_eq_eps(&expected_val, &epsilon_val) &&
expected_val.approx_eq_eps(&given_val, &epsilon_val)
) {
fail!("left: {:?} does not approximately equal right: \
{:?} with epsilon: {:?}",
given_val, expected_val, epsilon_val);
}
}
)
)
/// A utility macro for indicating unreachable code. It will fail if
/// executed. This is occasionally useful to put after loops that never
/// terminate normally, but instead directly return from a function.
///
/// # Example
///
/// ```rust
/// fn choose_weighted_item(v: &[Item]) -> Item {
/// assert!(!v.is_empty());
/// let mut so_far = 0u;
/// for item in v.iter() {
/// so_far += item.weight;
/// if so_far > 100 {
/// return item;
/// }
/// }
/// // The above loop always returns, so we must hint to the
/// // type checker that it isn't possible to get down here
/// unreachable!();
/// }
/// ```
macro_rules! unreachable (() => (
fail!("internal error: entered unreachable code");
))
macro_rules! condition (
{ pub $c:ident: $input:ty -> $out:ty; } => {
pub mod $c {
#[allow(unused_imports)];
#[allow(non_uppercase_statics)];
#[allow(missing_doc)];
use super::*;
local_data_key!(key: @::std::condition::Handler<$input, $out>)
pub static cond :
::std::condition::Condition<$input,$out> =
::std::condition::Condition {
name: stringify!($c),
key: key
};
}
};
{ $c:ident: $input:ty -> $out:ty; } => {
mod $c {
#[allow(unused_imports)];
#[allow(non_uppercase_statics)];
use super::*;
local_data_key!(key: @::std::condition::Handler<$input, $out>)
pub static cond :
::std::condition::Condition<$input,$out> =
::std::condition::Condition {
name: stringify!($c),
key: key
};
}
}
)
macro_rules! format(($($arg:tt)*) => (
format_args!(::std::fmt::format, $($arg)*)
))
macro_rules! write(($dst:expr, $($arg:tt)*) => (
format_args!(|args| { ::std::fmt::write($dst, args) }, $($arg)*)
))
macro_rules! writeln(($dst:expr, $($arg:tt)*) => (
format_args!(|args| { ::std::fmt::writeln($dst, args) }, $($arg)*)
))
macro_rules! print (
($($arg:tt)*) => (format_args!(::std::io::stdio::print_args, $($arg)*))
)
macro_rules! println (
($($arg:tt)*) => (format_args!(::std::io::stdio::println_args, $($arg)*))
)
macro_rules! local_data_key (
($name:ident: $ty:ty) => (
static $name: ::std::local_data::Key<$ty> = &::std::local_data::Key;
);
(pub $name:ident: $ty:ty) => (
pub static $name: ::std::local_data::Key<$ty> = &::std::local_data::Key;
)
)
}"#
}
struct Injector {
sm: @ast::item,
}
impl ast_fold for Injector {
fn fold_mod(&self, module: &ast::_mod) -> ast::_mod {
// Just inject the standard macros at the start of the first module
// in the crate: that is, at the start of the crate file itself.
let items = vec::append(~[ self.sm ], module.items);
ast::_mod {
items: items,
..(*module).clone() // FIXME #2543: Bad copy.
}
}
}
// add a bunch of macros as though they were placed at the head of the
// program (ick). This should run before cfg stripping.
pub fn inject_std_macros(parse_sess: @mut parse::ParseSess,
cfg: ast::CrateConfig,
c: Crate)
-> Crate {
let sm = match parse_item_from_source_str(@"<std-macros>",
std_macros(),
cfg.clone(),
~[],
parse_sess) {
Some(item) => item,
None => fail!("expected core macros to parse correctly")
};
let injector = @Injector {
sm: sm,
} as @ast_fold;
injector.fold_crate(c)
}