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