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