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