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