/
format.rs
850 lines (800 loc) · 34.6 KB
/
format.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
// Copyright 2012 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;
use ast::P;
use codemap::{Span, respan};
use ext::base::*;
use ext::base;
use ext::build::AstBuilder;
use opt_vec;
use parse::token::InternedString;
use parse::token;
use rsparse = parse;
use std::fmt::parse;
use std::hashmap::{HashMap, HashSet};
use std::vec;
#[deriving(Eq)]
enum ArgumentType {
Known(~str),
Unsigned,
String,
}
enum Position {
Exact(uint),
Named(~str),
}
struct Context<'a> {
ecx: &'a mut ExtCtxt<'a>,
fmtsp: Span,
// Parsed argument expressions and the types that we've found so far for
// them.
args: ~[@ast::Expr],
arg_types: ~[Option<ArgumentType>],
// Parsed named expressions and the types that we've found for them so far
names: HashMap<~str, @ast::Expr>,
name_types: HashMap<~str, ArgumentType>,
// Collection of the compiled `rt::Piece` structures
pieces: ~[@ast::Expr],
name_positions: HashMap<~str, uint>,
method_statics: ~[@ast::Item],
// Updated as arguments are consumed or methods are entered
nest_level: uint,
next_arg: uint,
}
/// Parses the arguments from the given list of tokens, returning None
/// if there's a parse error so we can continue parsing other format!
/// expressions.
///
/// If parsing succeeds, the second return value is:
///
/// Some((fmtstr, unnamed arguments, named arguments))
fn parse_args(ecx: &mut ExtCtxt, sp: Span,
tts: &[ast::TokenTree]) -> (@ast::Expr, Option<(@ast::Expr, ~[@ast::Expr],
HashMap<~str, @ast::Expr>)>) {
let mut args = ~[];
let mut names = HashMap::<~str, @ast::Expr>::new();
let mut p = rsparse::new_parser_from_tts(ecx.parse_sess(),
ecx.cfg(),
tts.to_owned());
// Parse the leading function expression (maybe a block, maybe a path)
let extra = p.parse_expr();
if !p.eat(&token::COMMA) {
ecx.span_err(sp, "expected token: `,`");
return (extra, None);
}
if p.token == token::EOF {
ecx.span_err(sp, "requires at least a format string argument");
return (extra, None);
}
let fmtstr = p.parse_expr();
let mut named = false;
while p.token != token::EOF {
if !p.eat(&token::COMMA) {
ecx.span_err(sp, "expected token: `,`");
return (extra, None);
}
if p.token == token::EOF { break } // accept trailing commas
if named || (token::is_ident(&p.token) &&
p.look_ahead(1, |t| *t == token::EQ)) {
named = true;
let ident = match p.token {
token::IDENT(i, _) => {
p.bump();
i
}
_ if named => {
ecx.span_err(p.span,
"expected ident, positional arguments \
cannot follow named arguments");
return (extra, None);
}
_ => {
ecx.span_err(p.span,
format!("expected ident for named argument, but found `{}`",
p.this_token_to_str()));
return (extra, None);
}
};
let interned_name = token::get_ident(ident);
let name = interned_name.get();
p.expect(&token::EQ);
let e = p.parse_expr();
match names.find_equiv(&name) {
None => {}
Some(prev) => {
ecx.span_err(e.span, format!("duplicate argument named `{}`", name));
ecx.parse_sess.span_diagnostic.span_note(prev.span, "previously here");
continue
}
}
names.insert(name.to_str(), e);
} else {
args.push(p.parse_expr());
}
}
return (extra, Some((fmtstr, args, names)));
}
impl<'a> Context<'a> {
/// Verifies one piece of a parse string. All errors are not emitted as
/// fatal so we can continue giving errors about this and possibly other
/// format strings.
fn verify_piece(&mut self, p: &parse::Piece) {
match *p {
parse::String(..) => {}
parse::CurrentArgument => {
if self.nest_level == 0 {
self.ecx.span_err(self.fmtsp,
"`#` reference used with nothing to \
reference back to");
}
}
parse::Argument(ref arg) => {
// width/precision first, if they have implicit positional
// parameters it makes more sense to consume them first.
self.verify_count(arg.format.width);
self.verify_count(arg.format.precision);
// argument second, if it's an implicit positional parameter
// it's written second, so it should come after width/precision.
let pos = match arg.position {
parse::ArgumentNext => {
let i = self.next_arg;
if self.check_positional_ok() {
self.next_arg += 1;
}
Exact(i)
}
parse::ArgumentIs(i) => Exact(i),
parse::ArgumentNamed(s) => Named(s.to_str()),
};
// and finally the method being applied
match arg.method {
None => {
let ty = Known(arg.format.ty.to_str());
self.verify_arg_type(pos, ty);
}
Some(ref method) => { self.verify_method(pos, *method); }
}
}
}
}
fn verify_pieces(&mut self, pieces: &[parse::Piece]) {
for piece in pieces.iter() {
self.verify_piece(piece);
}
}
fn verify_count(&mut self, c: parse::Count) {
match c {
parse::CountImplied | parse::CountIs(..) => {}
parse::CountIsParam(i) => {
self.verify_arg_type(Exact(i), Unsigned);
}
parse::CountIsName(s) => {
self.verify_arg_type(Named(s.to_str()), Unsigned);
}
parse::CountIsNextParam => {
if self.check_positional_ok() {
self.verify_arg_type(Exact(self.next_arg), Unsigned);
self.next_arg += 1;
}
}
}
}
fn check_positional_ok(&mut self) -> bool {
if self.nest_level != 0 {
self.ecx.span_err(self.fmtsp, "cannot use implicit positional \
arguments nested inside methods");
false
} else {
true
}
}
fn verify_method(&mut self, pos: Position, m: &parse::Method) {
self.nest_level += 1;
match *m {
parse::Plural(_, ref arms, ref default) => {
let mut seen_cases = HashSet::new();
self.verify_arg_type(pos, Unsigned);
for arm in arms.iter() {
if !seen_cases.insert(arm.selector) {
match arm.selector {
parse::Keyword(name) => {
self.ecx.span_err(self.fmtsp,
format!("duplicate selector \
`{:?}`", name));
}
parse::Literal(idx) => {
self.ecx.span_err(self.fmtsp,
format!("duplicate selector \
`={}`", idx));
}
}
}
self.verify_pieces(arm.result);
}
self.verify_pieces(*default);
}
parse::Select(ref arms, ref default) => {
self.verify_arg_type(pos, String);
let mut seen_cases = HashSet::new();
for arm in arms.iter() {
if !seen_cases.insert(arm.selector) {
self.ecx.span_err(self.fmtsp,
format!("duplicate selector `{}`",
arm.selector));
} else if arm.selector == "" {
self.ecx.span_err(self.fmtsp,
"empty selector in `select`");
}
self.verify_pieces(arm.result);
}
self.verify_pieces(*default);
}
}
self.nest_level -= 1;
}
fn verify_arg_type(&mut self, arg: Position, ty: ArgumentType) {
match arg {
Exact(arg) => {
if arg < 0 || self.args.len() <= arg {
let msg = format!("invalid reference to argument `{}` (there \
are {} arguments)", arg, self.args.len());
self.ecx.span_err(self.fmtsp, msg);
return;
}
{
let arg_type = match self.arg_types[arg] {
None => None,
Some(ref x) => Some(x)
};
self.verify_same(self.args[arg].span, &ty, arg_type);
}
if self.arg_types[arg].is_none() {
self.arg_types[arg] = Some(ty);
}
}
Named(name) => {
let span = match self.names.find(&name) {
Some(e) => e.span,
None => {
let msg = format!("there is no argument named `{}`", name);
self.ecx.span_err(self.fmtsp, msg);
return;
}
};
self.verify_same(span, &ty, self.name_types.find(&name));
if !self.name_types.contains_key(&name) {
self.name_types.insert(name.clone(), ty);
}
// Assign this named argument a slot in the arguments array if
// it hasn't already been assigned a slot.
if !self.name_positions.contains_key(&name) {
let slot = self.name_positions.len();
self.name_positions.insert(name, slot);
}
}
}
}
/// When we're keeping track of the types that are declared for certain
/// arguments, we assume that `None` means we haven't seen this argument
/// yet, `Some(None)` means that we've seen the argument, but no format was
/// specified, and `Some(Some(x))` means that the argument was declared to
/// have type `x`.
///
/// Obviously `Some(Some(x)) != Some(Some(y))`, but we consider it true
/// that: `Some(None) == Some(Some(x))`
fn verify_same(&self,
sp: Span,
ty: &ArgumentType,
before: Option<&ArgumentType>) {
let cur = match before {
None => return,
Some(t) => t,
};
if *ty == *cur {
return
}
match (cur, ty) {
(&Known(ref cur), &Known(ref ty)) => {
self.ecx.span_err(sp,
format!("argument redeclared with type `{}` when \
it was previously `{}`",
*ty,
*cur));
}
(&Known(ref cur), _) => {
self.ecx.span_err(sp,
format!("argument used to format with `{}` was \
attempted to not be used for formatting",
*cur));
}
(_, &Known(ref ty)) => {
self.ecx.span_err(sp,
format!("argument previously used as a format \
argument attempted to be used as `{}`",
*ty));
}
(_, _) => {
self.ecx.span_err(sp, "argument declared with multiple formats");
}
}
}
/// These attributes are applied to all statics that this syntax extension
/// will generate.
fn static_attrs(&self) -> ~[ast::Attribute] {
// Flag statics as `address_insignificant` so LLVM can merge duplicate
// globals as much as possible (which we're generating a whole lot of).
let unnamed = self.ecx
.meta_word(self.fmtsp,
InternedString::new(
"address_insignificant"));
let unnamed = self.ecx.attribute(self.fmtsp, unnamed);
// Do not warn format string as dead code
let dead_code = self.ecx.meta_word(self.fmtsp,
InternedString::new("dead_code"));
let allow_dead_code = self.ecx.meta_list(self.fmtsp,
InternedString::new("allow"),
~[dead_code]);
let allow_dead_code = self.ecx.attribute(self.fmtsp, allow_dead_code);
return ~[unnamed, allow_dead_code];
}
fn parsepath(&self, s: &str) -> ~[ast::Ident] {
~[self.ecx.ident_of("std"), self.ecx.ident_of("fmt"),
self.ecx.ident_of("parse"), self.ecx.ident_of(s)]
}
fn rtpath(&self, s: &str) -> ~[ast::Ident] {
~[self.ecx.ident_of("std"), self.ecx.ident_of("fmt"),
self.ecx.ident_of("rt"), self.ecx.ident_of(s)]
}
fn ctpath(&self, s: &str) -> ~[ast::Ident] {
~[self.ecx.ident_of("std"), self.ecx.ident_of("fmt"),
self.ecx.ident_of("parse"), self.ecx.ident_of(s)]
}
fn none(&self) -> @ast::Expr {
let none = self.ecx.path_global(self.fmtsp, ~[
self.ecx.ident_of("std"),
self.ecx.ident_of("option"),
self.ecx.ident_of("None")]);
self.ecx.expr_path(none)
}
fn some(&self, e: @ast::Expr) -> @ast::Expr {
let p = self.ecx.path_global(self.fmtsp, ~[
self.ecx.ident_of("std"),
self.ecx.ident_of("option"),
self.ecx.ident_of("Some")]);
let p = self.ecx.expr_path(p);
self.ecx.expr_call(self.fmtsp, p, ~[e])
}
fn trans_count(&self, c: parse::Count) -> @ast::Expr {
let sp = self.fmtsp;
match c {
parse::CountIs(i) => {
self.ecx.expr_call_global(sp, self.rtpath("CountIs"),
~[self.ecx.expr_uint(sp, i)])
}
parse::CountIsParam(i) => {
self.ecx.expr_call_global(sp, self.rtpath("CountIsParam"),
~[self.ecx.expr_uint(sp, i)])
}
parse::CountImplied => {
let path = self.ecx.path_global(sp, self.rtpath("CountImplied"));
self.ecx.expr_path(path)
}
parse::CountIsNextParam => {
let path = self.ecx.path_global(sp, self.rtpath("CountIsNextParam"));
self.ecx.expr_path(path)
}
parse::CountIsName(n) => {
let i = match self.name_positions.find_equiv(&n) {
Some(&i) => i,
None => 0, // error already emitted elsewhere
};
let i = i + self.args.len();
self.ecx.expr_call_global(sp, self.rtpath("CountIsParam"),
~[self.ecx.expr_uint(sp, i)])
}
}
}
fn trans_method(&mut self, method: &parse::Method) -> @ast::Expr {
let sp = self.fmtsp;
let method = match *method {
parse::Select(ref arms, ref default) => {
let arms = arms.iter().map(|arm| {
let p = self.ecx.path_global(sp, self.rtpath("SelectArm"));
let result = arm.result.iter().map(|p| {
self.trans_piece(p)
}).collect();
let s = token::intern_and_get_ident(arm.selector);
let selector = self.ecx.expr_str(sp, s);
self.ecx.expr_struct(sp, p, ~[
self.ecx.field_imm(sp,
self.ecx.ident_of("selector"),
selector),
self.ecx.field_imm(sp, self.ecx.ident_of("result"),
self.ecx.expr_vec_slice(sp, result)),
])
}).collect();
let default = default.iter().map(|p| {
self.trans_piece(p)
}).collect();
self.ecx.expr_call_global(sp, self.rtpath("Select"), ~[
self.ecx.expr_vec_slice(sp, arms),
self.ecx.expr_vec_slice(sp, default),
])
}
parse::Plural(offset, ref arms, ref default) => {
let offset = match offset {
Some(i) => { self.some(self.ecx.expr_uint(sp, i)) }
None => { self.none() }
};
let arms = arms.iter().map(|arm| {
let p = self.ecx.path_global(sp, self.rtpath("PluralArm"));
let result = arm.result.iter().map(|p| {
self.trans_piece(p)
}).collect();
let (lr, selarg) = match arm.selector {
parse::Keyword(t) => {
let p = self.ctpath(format!("{:?}", t));
let p = self.ecx.path_global(sp, p);
(self.rtpath("Keyword"), self.ecx.expr_path(p))
}
parse::Literal(i) => {
(self.rtpath("Literal"), self.ecx.expr_uint(sp, i))
}
};
let selector = self.ecx.expr_call_global(sp,
lr, ~[selarg]);
self.ecx.expr_struct(sp, p, ~[
self.ecx.field_imm(sp,
self.ecx.ident_of("selector"),
selector),
self.ecx.field_imm(sp, self.ecx.ident_of("result"),
self.ecx.expr_vec_slice(sp, result)),
])
}).collect();
let default = default.iter().map(|p| {
self.trans_piece(p)
}).collect();
self.ecx.expr_call_global(sp, self.rtpath("Plural"), ~[
offset,
self.ecx.expr_vec_slice(sp, arms),
self.ecx.expr_vec_slice(sp, default),
])
}
};
let life = self.ecx.lifetime(sp, self.ecx.ident_of("static"));
let ty = self.ecx.ty_path(self.ecx.path_all(
sp,
true,
self.rtpath("Method"),
opt_vec::with(life),
~[]
), None);
let st = ast::ItemStatic(ty, ast::MutImmutable, method);
let static_name = self.ecx.ident_of(format!("__STATIC_METHOD_{}",
self.method_statics.len()));
let item = self.ecx.item(sp, static_name, self.static_attrs(), st);
self.method_statics.push(item);
self.ecx.expr_ident(sp, static_name)
}
/// Translate a `parse::Piece` to a static `rt::Piece`
fn trans_piece(&mut self, piece: &parse::Piece) -> @ast::Expr {
let sp = self.fmtsp;
match *piece {
parse::String(s) => {
let s = token::intern_and_get_ident(s);
self.ecx.expr_call_global(sp,
self.rtpath("String"),
~[
self.ecx.expr_str(sp, s)
])
}
parse::CurrentArgument => {
let nil = self.ecx.expr_lit(sp, ast::LitNil);
self.ecx.expr_call_global(sp, self.rtpath("CurrentArgument"), ~[nil])
}
parse::Argument(ref arg) => {
// Translate the position
let pos = match arg.position {
// These two have a direct mapping
parse::ArgumentNext => {
let path = self.ecx.path_global(sp,
self.rtpath("ArgumentNext"));
self.ecx.expr_path(path)
}
parse::ArgumentIs(i) => {
self.ecx.expr_call_global(sp, self.rtpath("ArgumentIs"),
~[self.ecx.expr_uint(sp, i)])
}
// Named arguments are converted to positional arguments at
// the end of the list of arguments
parse::ArgumentNamed(n) => {
let i = match self.name_positions.find_equiv(&n) {
Some(&i) => i,
None => 0, // error already emitted elsewhere
};
let i = i + self.args.len();
self.ecx.expr_call_global(sp, self.rtpath("ArgumentIs"),
~[self.ecx.expr_uint(sp, i)])
}
};
// Translate the format
let fill = match arg.format.fill { Some(c) => c, None => ' ' };
let fill = self.ecx.expr_lit(sp, ast::LitChar(fill as u32));
let align = match arg.format.align {
parse::AlignLeft => {
self.ecx.path_global(sp, self.parsepath("AlignLeft"))
}
parse::AlignRight => {
self.ecx.path_global(sp, self.parsepath("AlignRight"))
}
parse::AlignUnknown => {
self.ecx.path_global(sp, self.parsepath("AlignUnknown"))
}
};
let align = self.ecx.expr_path(align);
let flags = self.ecx.expr_uint(sp, arg.format.flags);
let prec = self.trans_count(arg.format.precision);
let width = self.trans_count(arg.format.width);
let path = self.ecx.path_global(sp, self.rtpath("FormatSpec"));
let fmt = self.ecx.expr_struct(sp, path, ~[
self.ecx.field_imm(sp, self.ecx.ident_of("fill"), fill),
self.ecx.field_imm(sp, self.ecx.ident_of("align"), align),
self.ecx.field_imm(sp, self.ecx.ident_of("flags"), flags),
self.ecx.field_imm(sp, self.ecx.ident_of("precision"), prec),
self.ecx.field_imm(sp, self.ecx.ident_of("width"), width),
]);
// Translate the method (if any)
let method = match arg.method {
None => { self.none() }
Some(ref m) => {
let m = self.trans_method(*m);
self.some(self.ecx.expr_addr_of(sp, m))
}
};
let path = self.ecx.path_global(sp, self.rtpath("Argument"));
let s = self.ecx.expr_struct(sp, path, ~[
self.ecx.field_imm(sp, self.ecx.ident_of("position"), pos),
self.ecx.field_imm(sp, self.ecx.ident_of("format"), fmt),
self.ecx.field_imm(sp, self.ecx.ident_of("method"), method),
]);
self.ecx.expr_call_global(sp, self.rtpath("Argument"), ~[s])
}
}
}
/// Actually builds the expression which the iformat! block will be expanded
/// to
fn to_expr(&self, extra: @ast::Expr) -> @ast::Expr {
let mut lets = ~[];
let mut locals = ~[];
let mut names = vec::from_fn(self.name_positions.len(), |_| None);
// First, declare all of our methods that are statics
for &method in self.method_statics.iter() {
let decl = respan(self.fmtsp, ast::DeclItem(method));
lets.push(@respan(self.fmtsp,
ast::StmtDecl(@decl, ast::DUMMY_NODE_ID)));
}
// Next, build up the static array which will become our precompiled
// format "string"
let fmt = self.ecx.expr_vec(self.fmtsp, self.pieces.clone());
let piece_ty = self.ecx.ty_path(self.ecx.path_all(
self.fmtsp,
true, ~[
self.ecx.ident_of("std"),
self.ecx.ident_of("fmt"),
self.ecx.ident_of("rt"),
self.ecx.ident_of("Piece"),
],
opt_vec::with(
self.ecx.lifetime(self.fmtsp, self.ecx.ident_of("static"))),
~[]
), None);
let ty = ast::TyFixedLengthVec(
piece_ty,
self.ecx.expr_uint(self.fmtsp, self.pieces.len())
);
let ty = self.ecx.ty(self.fmtsp, ty);
let st = ast::ItemStatic(ty, ast::MutImmutable, fmt);
let static_name = self.ecx.ident_of("__STATIC_FMTSTR");
let item = self.ecx.item(self.fmtsp, static_name,
self.static_attrs(), st);
let decl = respan(self.fmtsp, ast::DeclItem(item));
lets.push(@respan(self.fmtsp, ast::StmtDecl(@decl, ast::DUMMY_NODE_ID)));
// Right now there is a bug such that for the expression:
// foo(bar(&1))
// the lifetime of `1` doesn't outlast the call to `bar`, so it's not
// vald for the call to `foo`. To work around this all arguments to the
// format! string are shoved into locals. Furthermore, we shove the address
// of each variable because we don't want to move out of the arguments
// passed to this function.
for (i, &e) in self.args.iter().enumerate() {
if self.arg_types[i].is_none() { continue } // error already generated
let name = self.ecx.ident_of(format!("__arg{}", i));
let e = self.ecx.expr_addr_of(e.span, e);
lets.push(self.ecx.stmt_let(e.span, false, name, e));
locals.push(self.format_arg(e.span, Exact(i),
self.ecx.expr_ident(e.span, name)));
}
for (name, &e) in self.names.iter() {
if !self.name_types.contains_key(name) {
continue
}
let lname = self.ecx.ident_of(format!("__arg{}", *name));
let e = self.ecx.expr_addr_of(e.span, e);
lets.push(self.ecx.stmt_let(e.span, false, lname, e));
names[*self.name_positions.get(name)] =
Some(self.format_arg(e.span,
Named((*name).clone()),
self.ecx.expr_ident(e.span, lname)));
}
// Now create a vector containing all the arguments
let slicename = self.ecx.ident_of("__args_vec");
{
let args = names.move_iter().map(|a| a.unwrap());
let mut args = locals.move_iter().chain(args);
let args = self.ecx.expr_vec_slice(self.fmtsp, args.collect());
lets.push(self.ecx.stmt_let(self.fmtsp, false, slicename, args));
}
// Now create the fmt::Arguments struct with all our locals we created.
let fmt = self.ecx.expr_ident(self.fmtsp, static_name);
let args_slice = self.ecx.expr_ident(self.fmtsp, slicename);
let result = self.ecx.expr_call_global(self.fmtsp, ~[
self.ecx.ident_of("std"),
self.ecx.ident_of("fmt"),
self.ecx.ident_of("Arguments"),
self.ecx.ident_of("new"),
], ~[fmt, args_slice]);
// We did all the work of making sure that the arguments
// structure is safe, so we can safely have an unsafe block.
let result = self.ecx.expr_block(P(ast::Block {
view_items: ~[],
stmts: ~[],
expr: Some(result),
id: ast::DUMMY_NODE_ID,
rules: ast::UnsafeBlock(ast::CompilerGenerated),
span: self.fmtsp,
}));
let resname = self.ecx.ident_of("__args");
lets.push(self.ecx.stmt_let(self.fmtsp, false, resname, result));
let res = self.ecx.expr_ident(self.fmtsp, resname);
let result = self.ecx.expr_call(extra.span, extra, ~[
self.ecx.expr_addr_of(extra.span, res)]);
self.ecx.expr_block(self.ecx.block(self.fmtsp, lets,
Some(result)))
}
fn format_arg(&self, sp: Span, argno: Position, arg: @ast::Expr)
-> @ast::Expr {
let ty = match argno {
Exact(ref i) => self.arg_types[*i].get_ref(),
Named(ref s) => self.name_types.get(s)
};
let fmt_fn = match *ty {
Known(ref tyname) => {
match tyname.as_slice() {
"" => "secret_show",
"?" => "secret_poly",
"b" => "secret_bool",
"c" => "secret_char",
"d" | "i" => "secret_signed",
"e" => "secret_lower_exp",
"E" => "secret_upper_exp",
"f" => "secret_float",
"o" => "secret_octal",
"p" => "secret_pointer",
"s" => "secret_string",
"t" => "secret_binary",
"u" => "secret_unsigned",
"x" => "secret_lower_hex",
"X" => "secret_upper_hex",
_ => {
self.ecx.span_err(sp, format!("unknown format trait `{}`",
*tyname));
"dummy"
}
}
}
String => {
return self.ecx.expr_call_global(sp, ~[
self.ecx.ident_of("std"),
self.ecx.ident_of("fmt"),
self.ecx.ident_of("argumentstr"),
], ~[arg])
}
Unsigned => {
return self.ecx.expr_call_global(sp, ~[
self.ecx.ident_of("std"),
self.ecx.ident_of("fmt"),
self.ecx.ident_of("argumentuint"),
], ~[arg])
}
};
let format_fn = self.ecx.path_global(sp, ~[
self.ecx.ident_of("std"),
self.ecx.ident_of("fmt"),
self.ecx.ident_of(fmt_fn),
]);
self.ecx.expr_call_global(sp, ~[
self.ecx.ident_of("std"),
self.ecx.ident_of("fmt"),
self.ecx.ident_of("argument"),
], ~[self.ecx.expr_path(format_fn), arg])
}
}
pub fn expand_args(ecx: &mut ExtCtxt, sp: Span,
tts: &[ast::TokenTree]) -> base::MacResult {
match parse_args(ecx, sp, tts) {
(extra, Some((efmt, args, names))) => {
MRExpr(expand_preparsed_format_args(ecx, sp, extra, efmt, args, names))
}
(_, None) => MRExpr(ecx.expr_uint(sp, 2))
}
}
/// Take the various parts of `format_args!(extra, efmt, args...,
/// name=names...)` and construct the appropriate formatting
/// expression.
pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, sp: Span,
extra: @ast::Expr,
efmt: @ast::Expr, args: ~[@ast::Expr],
names: HashMap<~str, @ast::Expr>) -> @ast::Expr {
let arg_types = vec::from_fn(args.len(), |_| None);
let mut cx = Context {
ecx: ecx,
args: args,
arg_types: arg_types,
names: names,
name_positions: HashMap::new(),
name_types: HashMap::new(),
nest_level: 0,
next_arg: 0,
pieces: ~[],
method_statics: ~[],
fmtsp: sp,
};
cx.fmtsp = efmt.span;
// Be sure to recursively expand macros just in case the format string uses
// a macro to build the format expression.
let expr = cx.ecx.expand_expr(efmt);
let fmt = match expr_to_str(cx.ecx,
expr,
"format argument must be a string literal.") {
Some((fmt, _)) => fmt,
None => return MacResult::raw_dummy_expr(sp)
};
let mut parser = parse::Parser::new(fmt.get());
loop {
match parser.next() {
Some(piece) => {
if parser.errors.len() > 0 { break }
cx.verify_piece(&piece);
let piece = cx.trans_piece(&piece);
cx.pieces.push(piece);
}
None => break
}
}
match parser.errors.shift() {
Some(error) => {
cx.ecx.span_err(efmt.span, "invalid format string: " + error);
return MacResult::raw_dummy_expr(sp);
}
None => {}
}
// Make sure that all arguments were used and all arguments have types.
for (i, ty) in cx.arg_types.iter().enumerate() {
if ty.is_none() {
cx.ecx.span_err(cx.args[i].span, "argument never used");
}
}
for (name, e) in cx.names.iter() {
if !cx.name_types.contains_key(name) {
cx.ecx.span_err(e.span, "named argument never used");
}
}
cx.to_expr(extra)
}