]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/format.rs
Add `ecx.stmt_semi()` and fix issues with the pretty-printer
[rust.git] / src / libsyntax_ext / format.rs
1 // Copyright 2012 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 self::ArgumentType::*;
12 use self::Position::*;
13
14 use fmt_macros as parse;
15
16 use syntax::ast;
17 use syntax::codemap::{Span, respan, DUMMY_SP};
18 use syntax::ext::base::*;
19 use syntax::ext::base;
20 use syntax::ext::build::AstBuilder;
21 use syntax::fold::Folder;
22 use syntax::parse::token::{self, keywords};
23 use syntax::ptr::P;
24
25 use std::collections::HashMap;
26
27 #[derive(PartialEq)]
28 enum ArgumentType {
29     Known(String),
30     Unsigned
31 }
32
33 enum Position {
34     Exact(usize),
35     Named(String),
36 }
37
38 struct Context<'a, 'b:'a> {
39     ecx: &'a mut ExtCtxt<'b>,
40     /// The macro's call site. References to unstable formatting internals must
41     /// use this span to pass the stability checker.
42     macsp: Span,
43     /// The span of the format string literal.
44     fmtsp: Span,
45
46     /// Parsed argument expressions and the types that we've found so far for
47     /// them.
48     args: Vec<P<ast::Expr>>,
49     arg_types: Vec<Option<ArgumentType>>,
50     /// Parsed named expressions and the types that we've found for them so far.
51     /// Note that we keep a side-array of the ordering of the named arguments
52     /// found to be sure that we can translate them in the same order that they
53     /// were declared in.
54     names: HashMap<String, P<ast::Expr>>,
55     name_types: HashMap<String, ArgumentType>,
56     name_ordering: Vec<String>,
57
58     /// The latest consecutive literal strings, or empty if there weren't any.
59     literal: String,
60
61     /// Collection of the compiled `rt::Argument` structures
62     pieces: Vec<P<ast::Expr>>,
63     /// Collection of string literals
64     str_pieces: Vec<P<ast::Expr>>,
65     /// Stays `true` if all formatting parameters are default (as in "{}{}").
66     all_pieces_simple: bool,
67
68     name_positions: HashMap<String, usize>,
69
70     /// Updated as arguments are consumed
71     next_arg: usize,
72 }
73
74 /// Parses the arguments from the given list of tokens, returning None
75 /// if there's a parse error so we can continue parsing other format!
76 /// expressions.
77 ///
78 /// If parsing succeeds, the return value is:
79 /// ```ignore
80 /// Some((fmtstr, unnamed arguments, ordering of named arguments,
81 ///       named arguments))
82 /// ```
83 fn parse_args(ecx: &mut ExtCtxt, sp: Span, tts: &[ast::TokenTree])
84               -> Option<(P<ast::Expr>, Vec<P<ast::Expr>>, Vec<String>,
85                          HashMap<String, P<ast::Expr>>)> {
86     let mut args = Vec::new();
87     let mut names = HashMap::<String, P<ast::Expr>>::new();
88     let mut order = Vec::new();
89
90     let mut p = ecx.new_parser_from_tts(tts);
91
92     if p.token == token::Eof {
93         ecx.span_err(sp, "requires at least a format string argument");
94         return None;
95     }
96     let fmtstr = panictry!(p.parse_expr());
97     let mut named = false;
98     while p.token != token::Eof {
99         if !p.eat(&token::Comma) {
100             ecx.span_err(sp, "expected token: `,`");
101             return None;
102         }
103         if p.token == token::Eof { break } // accept trailing commas
104         if named || (p.token.is_ident() && p.look_ahead(1, |t| *t == token::Eq)) {
105             named = true;
106             let ident = match p.token {
107                 token::Ident(i) => {
108                     p.bump();
109                     i
110                 }
111                 _ if named => {
112                     ecx.span_err(p.span,
113                                  "expected ident, positional arguments \
114                                  cannot follow named arguments");
115                     return None;
116                 }
117                 _ => {
118                     ecx.span_err(p.span,
119                                  &format!("expected ident for named argument, found `{}`",
120                                          p.this_token_to_string()));
121                     return None;
122                 }
123             };
124             let name: &str = &ident.name.as_str();
125
126             panictry!(p.expect(&token::Eq));
127             let e = panictry!(p.parse_expr());
128             match names.get(name) {
129                 None => {}
130                 Some(prev) => {
131                     ecx.struct_span_err(e.span,
132                                         &format!("duplicate argument named `{}`",
133                                                  name))
134                        .span_note(prev.span, "previously here")
135                        .emit();
136                     continue
137                 }
138             }
139             order.push(name.to_string());
140             names.insert(name.to_string(), e);
141         } else {
142             args.push(panictry!(p.parse_expr()));
143         }
144     }
145     Some((fmtstr, args, order, names))
146 }
147
148 impl<'a, 'b> Context<'a, 'b> {
149     /// Verifies one piece of a parse string. All errors are not emitted as
150     /// fatal so we can continue giving errors about this and possibly other
151     /// format strings.
152     fn verify_piece(&mut self, p: &parse::Piece) {
153         match *p {
154             parse::String(..) => {}
155             parse::NextArgument(ref arg) => {
156                 // width/precision first, if they have implicit positional
157                 // parameters it makes more sense to consume them first.
158                 self.verify_count(arg.format.width);
159                 self.verify_count(arg.format.precision);
160
161                 // argument second, if it's an implicit positional parameter
162                 // it's written second, so it should come after width/precision.
163                 let pos = match arg.position {
164                     parse::ArgumentNext => {
165                         let i = self.next_arg;
166                         self.next_arg += 1;
167                         Exact(i)
168                     }
169                     parse::ArgumentIs(i) => Exact(i),
170                     parse::ArgumentNamed(s) => Named(s.to_string()),
171                 };
172
173                 let ty = Known(arg.format.ty.to_string());
174                 self.verify_arg_type(pos, ty);
175             }
176         }
177     }
178
179     fn verify_count(&mut self, c: parse::Count) {
180         match c {
181             parse::CountImplied | parse::CountIs(..) => {}
182             parse::CountIsParam(i) => {
183                 self.verify_arg_type(Exact(i), Unsigned);
184             }
185             parse::CountIsName(s) => {
186                 self.verify_arg_type(Named(s.to_string()), Unsigned);
187             }
188             parse::CountIsNextParam => {
189                 let next_arg = self.next_arg;
190                 self.verify_arg_type(Exact(next_arg), Unsigned);
191                 self.next_arg += 1;
192             }
193         }
194     }
195
196     fn describe_num_args(&self) -> String {
197         match self.args.len() {
198             0 => "no arguments given".to_string(),
199             1 => "there is 1 argument".to_string(),
200             x => format!("there are {} arguments", x),
201         }
202     }
203
204     fn verify_arg_type(&mut self, arg: Position, ty: ArgumentType) {
205         match arg {
206             Exact(arg) => {
207                 if self.args.len() <= arg {
208                     let msg = format!("invalid reference to argument `{}` ({})",
209                                       arg, self.describe_num_args());
210
211                     self.ecx.span_err(self.fmtsp, &msg[..]);
212                     return;
213                 }
214                 {
215                     let arg_type = match self.arg_types[arg] {
216                         None => None,
217                         Some(ref x) => Some(x)
218                     };
219                     self.verify_same(self.args[arg].span, &ty, arg_type);
220                 }
221                 if self.arg_types[arg].is_none() {
222                     self.arg_types[arg] = Some(ty);
223                 }
224             }
225
226             Named(name) => {
227                 let span = match self.names.get(&name) {
228                     Some(e) => e.span,
229                     None => {
230                         let msg = format!("there is no argument named `{}`", name);
231                         self.ecx.span_err(self.fmtsp, &msg[..]);
232                         return;
233                     }
234                 };
235                 self.verify_same(span, &ty, self.name_types.get(&name));
236                 if !self.name_types.contains_key(&name) {
237                     self.name_types.insert(name.clone(), ty);
238                 }
239                 // Assign this named argument a slot in the arguments array if
240                 // it hasn't already been assigned a slot.
241                 if !self.name_positions.contains_key(&name) {
242                     let slot = self.name_positions.len();
243                     self.name_positions.insert(name, slot);
244                 }
245             }
246         }
247     }
248
249     /// When we're keeping track of the types that are declared for certain
250     /// arguments, we assume that `None` means we haven't seen this argument
251     /// yet, `Some(None)` means that we've seen the argument, but no format was
252     /// specified, and `Some(Some(x))` means that the argument was declared to
253     /// have type `x`.
254     ///
255     /// Obviously `Some(Some(x)) != Some(Some(y))`, but we consider it true
256     /// that: `Some(None) == Some(Some(x))`
257     fn verify_same(&self,
258                    sp: Span,
259                    ty: &ArgumentType,
260                    before: Option<&ArgumentType>) {
261         let cur = match before {
262             None => return,
263             Some(t) => t,
264         };
265         if *ty == *cur {
266             return
267         }
268         match (cur, ty) {
269             (&Known(ref cur), &Known(ref ty)) => {
270                 self.ecx.span_err(sp,
271                                   &format!("argument redeclared with type `{}` when \
272                                            it was previously `{}`",
273                                           *ty,
274                                           *cur));
275             }
276             (&Known(ref cur), _) => {
277                 self.ecx.span_err(sp,
278                                   &format!("argument used to format with `{}` was \
279                                            attempted to not be used for formatting",
280                                            *cur));
281             }
282             (_, &Known(ref ty)) => {
283                 self.ecx.span_err(sp,
284                                   &format!("argument previously used as a format \
285                                            argument attempted to be used as `{}`",
286                                            *ty));
287             }
288             (_, _) => {
289                 self.ecx.span_err(sp, "argument declared with multiple formats");
290             }
291         }
292     }
293
294     fn rtpath(ecx: &ExtCtxt, s: &str) -> Vec<ast::Ident> {
295         ecx.std_path(&["fmt", "rt", "v1", s])
296     }
297
298     fn trans_count(&self, c: parse::Count) -> P<ast::Expr> {
299         let sp = self.macsp;
300         let count = |c, arg| {
301             let mut path = Context::rtpath(self.ecx, "Count");
302             path.push(self.ecx.ident_of(c));
303             match arg {
304                 Some(arg) => self.ecx.expr_call_global(sp, path, vec![arg]),
305                 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
306             }
307         };
308         match c {
309             parse::CountIs(i) => count("Is", Some(self.ecx.expr_usize(sp, i))),
310             parse::CountIsParam(i) => {
311                 count("Param", Some(self.ecx.expr_usize(sp, i)))
312             }
313             parse::CountImplied => count("Implied", None),
314             parse::CountIsNextParam => count("NextParam", None),
315             parse::CountIsName(n) => {
316                 let i = match self.name_positions.get(n) {
317                     Some(&i) => i,
318                     None => 0, // error already emitted elsewhere
319                 };
320                 let i = i + self.args.len();
321                 count("Param", Some(self.ecx.expr_usize(sp, i)))
322             }
323         }
324     }
325
326     /// Translate the accumulated string literals to a literal expression
327     fn trans_literal_string(&mut self) -> P<ast::Expr> {
328         let sp = self.fmtsp;
329         let s = token::intern_and_get_ident(&self.literal);
330         self.literal.clear();
331         self.ecx.expr_str(sp, s)
332     }
333
334     /// Translate a `parse::Piece` to a static `rt::Argument` or append
335     /// to the `literal` string.
336     fn trans_piece(&mut self, piece: &parse::Piece) -> Option<P<ast::Expr>> {
337         let sp = self.macsp;
338         match *piece {
339             parse::String(s) => {
340                 self.literal.push_str(s);
341                 None
342             }
343             parse::NextArgument(ref arg) => {
344                 // Translate the position
345                 let pos = {
346                     let pos = |c, arg| {
347                         let mut path = Context::rtpath(self.ecx, "Position");
348                         path.push(self.ecx.ident_of(c));
349                         match arg {
350                             Some(i) => {
351                                 let arg = self.ecx.expr_usize(sp, i);
352                                 self.ecx.expr_call_global(sp, path, vec![arg])
353                             }
354                             None => {
355                                 self.ecx.expr_path(self.ecx.path_global(sp, path))
356                             }
357                         }
358                     };
359                     match arg.position {
360                         // These two have a direct mapping
361                         parse::ArgumentNext => pos("Next", None),
362                         parse::ArgumentIs(i) => pos("At", Some(i)),
363
364                         // Named arguments are converted to positional arguments
365                         // at the end of the list of arguments
366                         parse::ArgumentNamed(n) => {
367                             let i = match self.name_positions.get(n) {
368                                 Some(&i) => i,
369                                 None => 0, // error already emitted elsewhere
370                             };
371                             let i = i + self.args.len();
372                             pos("At", Some(i))
373                         }
374                     }
375                 };
376
377                 let simple_arg = parse::Argument {
378                     position: parse::ArgumentNext,
379                     format: parse::FormatSpec {
380                         fill: arg.format.fill,
381                         align: parse::AlignUnknown,
382                         flags: 0,
383                         precision: parse::CountImplied,
384                         width: parse::CountImplied,
385                         ty: arg.format.ty
386                     }
387                 };
388
389                 let fill = match arg.format.fill { Some(c) => c, None => ' ' };
390
391                 if *arg != simple_arg || fill != ' ' {
392                     self.all_pieces_simple = false;
393                 }
394
395                 // Translate the format
396                 let fill = self.ecx.expr_lit(sp, ast::LitKind::Char(fill));
397                 let align = |name| {
398                     let mut p = Context::rtpath(self.ecx, "Alignment");
399                     p.push(self.ecx.ident_of(name));
400                     self.ecx.path_global(sp, p)
401                 };
402                 let align = match arg.format.align {
403                     parse::AlignLeft => align("Left"),
404                     parse::AlignRight => align("Right"),
405                     parse::AlignCenter => align("Center"),
406                     parse::AlignUnknown => align("Unknown"),
407                 };
408                 let align = self.ecx.expr_path(align);
409                 let flags = self.ecx.expr_u32(sp, arg.format.flags);
410                 let prec = self.trans_count(arg.format.precision);
411                 let width = self.trans_count(arg.format.width);
412                 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, "FormatSpec"));
413                 let fmt = self.ecx.expr_struct(sp, path, vec!(
414                     self.ecx.field_imm(sp, self.ecx.ident_of("fill"), fill),
415                     self.ecx.field_imm(sp, self.ecx.ident_of("align"), align),
416                     self.ecx.field_imm(sp, self.ecx.ident_of("flags"), flags),
417                     self.ecx.field_imm(sp, self.ecx.ident_of("precision"), prec),
418                     self.ecx.field_imm(sp, self.ecx.ident_of("width"), width)));
419
420                 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, "Argument"));
421                 Some(self.ecx.expr_struct(sp, path, vec!(
422                     self.ecx.field_imm(sp, self.ecx.ident_of("position"), pos),
423                     self.ecx.field_imm(sp, self.ecx.ident_of("format"), fmt))))
424             }
425         }
426     }
427
428     fn static_array(ecx: &mut ExtCtxt,
429                     name: &str,
430                     piece_ty: P<ast::Ty>,
431                     pieces: Vec<P<ast::Expr>>)
432                     -> P<ast::Expr> {
433         let sp = piece_ty.span;
434         let ty = ecx.ty_rptr(sp,
435             ecx.ty(sp, ast::TyKind::Vec(piece_ty)),
436             Some(ecx.lifetime(sp, keywords::StaticLifetime.name())),
437             ast::Mutability::Immutable);
438         let slice = ecx.expr_vec_slice(sp, pieces);
439         // static instead of const to speed up codegen by not requiring this to be inlined
440         let st = ast::ItemKind::Static(ty, ast::Mutability::Immutable, slice);
441
442         let name = ecx.ident_of(name);
443         let item = ecx.item(sp, name, vec![], st);
444         let decl = respan(sp, ast::DeclKind::Item(item));
445
446         // Wrap the declaration in a block so that it forms a single expression.
447         ecx.expr_block(ecx.block(sp, vec![
448             respan(sp, ast::StmtKind::Decl(P(decl), ast::DUMMY_NODE_ID)),
449             ecx.stmt_expr(ecx.expr_ident(sp, name)),
450         ]))
451     }
452
453     /// Actually builds the expression which the iformat! block will be expanded
454     /// to
455     fn into_expr(mut self) -> P<ast::Expr> {
456         let mut locals = Vec::new();
457         let mut names = vec![None; self.name_positions.len()];
458         let mut pats = Vec::new();
459         let mut heads = Vec::new();
460
461         // First, build up the static array which will become our precompiled
462         // format "string"
463         let static_lifetime = self.ecx.lifetime(self.fmtsp, keywords::StaticLifetime.name());
464         let piece_ty = self.ecx.ty_rptr(
465                 self.fmtsp,
466                 self.ecx.ty_ident(self.fmtsp, self.ecx.ident_of("str")),
467                 Some(static_lifetime),
468                 ast::Mutability::Immutable);
469         let pieces = Context::static_array(self.ecx,
470                                            "__STATIC_FMTSTR",
471                                            piece_ty,
472                                            self.str_pieces);
473
474
475         // Right now there is a bug such that for the expression:
476         //      foo(bar(&1))
477         // the lifetime of `1` doesn't outlast the call to `bar`, so it's not
478         // valid for the call to `foo`. To work around this all arguments to the
479         // format! string are shoved into locals. Furthermore, we shove the address
480         // of each variable because we don't want to move out of the arguments
481         // passed to this function.
482         for (i, e) in self.args.into_iter().enumerate() {
483             let arg_ty = match self.arg_types[i].as_ref() {
484                 Some(ty) => ty,
485                 None => continue // error already generated
486             };
487
488             let name = self.ecx.ident_of(&format!("__arg{}", i));
489             pats.push(self.ecx.pat_ident(DUMMY_SP, name));
490             locals.push(Context::format_arg(self.ecx, self.macsp, e.span, arg_ty,
491                                             self.ecx.expr_ident(e.span, name)));
492             heads.push(self.ecx.expr_addr_of(e.span, e));
493         }
494         for name in &self.name_ordering {
495             let e = match self.names.remove(name) {
496                 Some(e) => e,
497                 None => continue
498             };
499             let arg_ty = match self.name_types.get(name) {
500                 Some(ty) => ty,
501                 None => continue
502             };
503
504             let lname = self.ecx.ident_of(&format!("__arg{}",
505                                                   *name));
506             pats.push(self.ecx.pat_ident(DUMMY_SP, lname));
507             names[*self.name_positions.get(name).unwrap()] =
508                 Some(Context::format_arg(self.ecx, self.macsp, e.span, arg_ty,
509                                          self.ecx.expr_ident(e.span, lname)));
510             heads.push(self.ecx.expr_addr_of(e.span, e));
511         }
512
513         // Now create a vector containing all the arguments
514         let args = locals.into_iter().chain(names.into_iter().map(|a| a.unwrap()));
515
516         let args_array = self.ecx.expr_vec(self.fmtsp, args.collect());
517
518         // Constructs an AST equivalent to:
519         //
520         //      match (&arg0, &arg1) {
521         //          (tmp0, tmp1) => args_array
522         //      }
523         //
524         // It was:
525         //
526         //      let tmp0 = &arg0;
527         //      let tmp1 = &arg1;
528         //      args_array
529         //
530         // Because of #11585 the new temporary lifetime rule, the enclosing
531         // statements for these temporaries become the let's themselves.
532         // If one or more of them are RefCell's, RefCell borrow() will also
533         // end there; they don't last long enough for args_array to use them.
534         // The match expression solves the scope problem.
535         //
536         // Note, it may also very well be transformed to:
537         //
538         //      match arg0 {
539         //          ref tmp0 => {
540         //              match arg1 => {
541         //                  ref tmp1 => args_array } } }
542         //
543         // But the nested match expression is proved to perform not as well
544         // as series of let's; the first approach does.
545         let pat = self.ecx.pat_tuple(self.fmtsp, pats);
546         let arm = self.ecx.arm(self.fmtsp, vec!(pat), args_array);
547         let head = self.ecx.expr(self.fmtsp, ast::ExprKind::Tup(heads));
548         let result = self.ecx.expr_match(self.fmtsp, head, vec!(arm));
549
550         let args_slice = self.ecx.expr_addr_of(self.fmtsp, result);
551
552         // Now create the fmt::Arguments struct with all our locals we created.
553         let (fn_name, fn_args) = if self.all_pieces_simple {
554             ("new_v1", vec![pieces, args_slice])
555         } else {
556             // Build up the static array which will store our precompiled
557             // nonstandard placeholders, if there are any.
558             let piece_ty = self.ecx.ty_path(self.ecx.path_global(
559                     self.macsp,
560                     Context::rtpath(self.ecx, "Argument")));
561             let fmt = Context::static_array(self.ecx,
562                                             "__STATIC_FMTARGS",
563                                             piece_ty,
564                                             self.pieces);
565
566             ("new_v1_formatted", vec![pieces, args_slice, fmt])
567         };
568
569         let path = self.ecx.std_path(&["fmt", "Arguments", fn_name]);
570         self.ecx.expr_call_global(self.macsp, path, fn_args)
571     }
572
573     fn format_arg(ecx: &ExtCtxt, macsp: Span, sp: Span,
574                   ty: &ArgumentType, arg: P<ast::Expr>)
575                   -> P<ast::Expr> {
576         let trait_ = match *ty {
577             Known(ref tyname) => {
578                 match &tyname[..] {
579                     ""  => "Display",
580                     "?" => "Debug",
581                     "e" => "LowerExp",
582                     "E" => "UpperExp",
583                     "o" => "Octal",
584                     "p" => "Pointer",
585                     "b" => "Binary",
586                     "x" => "LowerHex",
587                     "X" => "UpperHex",
588                     _ => {
589                         ecx.span_err(sp,
590                                      &format!("unknown format trait `{}`",
591                                              *tyname));
592                         "Dummy"
593                     }
594                 }
595             }
596             Unsigned => {
597                 let path = ecx.std_path(&["fmt", "ArgumentV1", "from_usize"]);
598                 return ecx.expr_call_global(macsp, path, vec![arg])
599             }
600         };
601
602         let path = ecx.std_path(&["fmt", trait_, "fmt"]);
603         let format_fn = ecx.path_global(sp, path);
604         let path = ecx.std_path(&["fmt", "ArgumentV1", "new"]);
605         ecx.expr_call_global(macsp, path, vec![arg, ecx.expr_path(format_fn)])
606     }
607 }
608
609 pub fn expand_format_args<'cx>(ecx: &'cx mut ExtCtxt, sp: Span,
610                                tts: &[ast::TokenTree])
611                                -> Box<base::MacResult+'cx> {
612
613     match parse_args(ecx, sp, tts) {
614         Some((efmt, args, order, names)) => {
615             MacEager::expr(expand_preparsed_format_args(ecx, sp, efmt,
616                                                       args, order, names))
617         }
618         None => DummyResult::expr(sp)
619     }
620 }
621
622 /// Take the various parts of `format_args!(efmt, args..., name=names...)`
623 /// and construct the appropriate formatting expression.
624 pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, sp: Span,
625                                     efmt: P<ast::Expr>,
626                                     args: Vec<P<ast::Expr>>,
627                                     name_ordering: Vec<String>,
628                                     names: HashMap<String, P<ast::Expr>>)
629                                     -> P<ast::Expr> {
630     let arg_types: Vec<_> = (0..args.len()).map(|_| None).collect();
631     let macsp = ecx.call_site();
632     // Expand the format literal so that efmt.span will have a backtrace. This
633     // is essential for locating a bug when the format literal is generated in
634     // a macro. (e.g. println!("{}"), which uses concat!($fmt, "\n")).
635     let efmt = ecx.expander().fold_expr(efmt);
636     let mut cx = Context {
637         ecx: ecx,
638         args: args,
639         arg_types: arg_types,
640         names: names,
641         name_positions: HashMap::new(),
642         name_types: HashMap::new(),
643         name_ordering: name_ordering,
644         next_arg: 0,
645         literal: String::new(),
646         pieces: Vec::new(),
647         str_pieces: Vec::new(),
648         all_pieces_simple: true,
649         macsp: macsp,
650         fmtsp: efmt.span,
651     };
652     let fmt = match expr_to_string(cx.ecx,
653                                    efmt,
654                                    "format argument must be a string literal.") {
655         Some((fmt, _)) => fmt,
656         None => return DummyResult::raw_expr(sp)
657     };
658
659     let mut parser = parse::Parser::new(&fmt);
660
661     loop {
662         match parser.next() {
663             Some(piece) => {
664                 if !parser.errors.is_empty() { break }
665                 cx.verify_piece(&piece);
666                 match cx.trans_piece(&piece) {
667                     Some(piece) => {
668                         let s = cx.trans_literal_string();
669                         cx.str_pieces.push(s);
670                         cx.pieces.push(piece);
671                     }
672                     None => {}
673                 }
674             }
675             None => break
676         }
677     }
678     if !parser.errors.is_empty() {
679         cx.ecx.span_err(cx.fmtsp, &format!("invalid format string: {}",
680                                           parser.errors.remove(0)));
681         return DummyResult::raw_expr(sp);
682     }
683     if !cx.literal.is_empty() {
684         let s = cx.trans_literal_string();
685         cx.str_pieces.push(s);
686     }
687
688     // Make sure that all arguments were used and all arguments have types.
689     for (i, ty) in cx.arg_types.iter().enumerate() {
690         if ty.is_none() {
691             cx.ecx.span_err(cx.args[i].span, "argument never used");
692         }
693     }
694     for (name, e) in &cx.names {
695         if !cx.name_types.contains_key(name) {
696             cx.ecx.span_err(e.span, "named argument never used");
697         }
698     }
699
700     cx.into_expr()
701 }