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.
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.
11 use self::ArgumentType::*;
12 use self::Position::*;
15 use codemap::{Span, respan};
18 use ext::build::AstBuilder;
19 use fmt_macros as parse;
21 use parse::token::special_idents;
25 use std::collections::HashMap;
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.
43 /// The span of the format string literal.
46 /// Parsed argument expressions and the types that we've found so far for
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
54 names: HashMap<String, P<ast::Expr>>,
55 name_types: HashMap<String, ArgumentType>,
56 name_ordering: Vec<String>,
58 /// The latest consecutive literal strings, or empty if there weren't any.
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,
68 name_positions: HashMap<String, usize>,
70 /// Updated as arguments are consumed or methods are entered
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!
79 /// If parsing succeeds, the return value is:
81 /// Some((fmtstr, unnamed arguments, ordering of named arguments,
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();
91 let mut p = ecx.new_parser_from_tts(tts);
93 if p.token == token::Eof {
94 ecx.span_err(sp, "requires at least a format string argument");
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: `,`");
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)) {
107 let ident = match p.token {
108 token::Ident(i, _) => {
114 "expected ident, positional arguments \
115 cannot follow named arguments");
120 &format!("expected ident for named argument, found `{}`",
121 p.this_token_to_string()));
125 let name: &str = &ident.name.as_str();
127 panictry!(p.expect(&token::Eq));
128 let e = panictry!(p.parse_expr_nopanic());
129 match names.get(name) {
133 &format!("duplicate argument named `{}`",
135 ecx.parse_sess.span_diagnostic.span_note(prev.span, "previously here");
139 order.push(name.to_string());
140 names.insert(name.to_string(), e);
142 args.push(panictry!(p.parse_expr_nopanic()));
145 Some((fmtstr, args, order, names))
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
152 fn verify_piece(&mut self, p: &parse::Piece) {
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);
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() {
171 parse::ArgumentIs(i) => Exact(i),
172 parse::ArgumentNamed(s) => Named(s.to_string()),
175 let ty = Known(arg.format.ty.to_string());
176 self.verify_arg_type(pos, ty);
181 fn verify_count(&mut self, c: parse::Count) {
183 parse::CountImplied | parse::CountIs(..) => {}
184 parse::CountIsParam(i) => {
185 self.verify_arg_type(Exact(i), Unsigned);
187 parse::CountIsName(s) => {
188 self.verify_arg_type(Named(s.to_string()), Unsigned);
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);
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");
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),
218 fn verify_arg_type(&mut self, arg: Position, ty: ArgumentType) {
221 if self.args.len() <= arg {
222 let msg = format!("invalid reference to argument `{}` ({})",
223 arg, self.describe_num_args());
225 self.ecx.span_err(self.fmtsp, &msg[..]);
229 let arg_type = match self.arg_types[arg] {
231 Some(ref x) => Some(x)
233 self.verify_same(self.args[arg].span, &ty, arg_type);
235 if self.arg_types[arg].is_none() {
236 self.arg_types[arg] = Some(ty);
241 let span = match self.names.get(&name) {
244 let msg = format!("there is no argument named `{}`", name);
245 self.ecx.span_err(self.fmtsp, &msg[..]);
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);
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);
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
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,
274 before: Option<&ArgumentType>) {
275 let cur = match before {
283 (&Known(ref cur), &Known(ref ty)) => {
284 self.ecx.span_err(sp,
285 &format!("argument redeclared with type `{}` when \
286 it was previously `{}`",
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",
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 `{}`",
303 self.ecx.span_err(sp, "argument declared with multiple formats");
308 fn rtpath(ecx: &ExtCtxt, s: &str) -> Vec<ast::Ident> {
309 ecx.std_path(&["fmt", "rt", "v1", s])
312 fn trans_count(&self, c: parse::Count) -> P<ast::Expr> {
314 let count = |c, arg| {
315 let mut path = Context::rtpath(self.ecx, "Count");
316 path.push(self.ecx.ident_of(c));
318 Some(arg) => self.ecx.expr_call_global(sp, path, vec![arg]),
319 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
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)))
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) {
332 None => 0, // error already emitted elsewhere
334 let i = i + self.args.len();
335 count("Param", Some(self.ecx.expr_usize(sp, i)))
340 /// Translate the accumulated string literals to a literal expression
341 fn trans_literal_string(&mut self) -> P<ast::Expr> {
343 let s = token::intern_and_get_ident(&self.literal);
344 self.literal.clear();
345 self.ecx.expr_str(sp, s)
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>> {
353 parse::String(s) => {
354 self.literal.push_str(s);
357 parse::NextArgument(ref arg) => {
358 // Translate the position
361 let mut path = Context::rtpath(self.ecx, "Position");
362 path.push(self.ecx.ident_of(c));
365 let arg = self.ecx.expr_usize(sp, i);
366 self.ecx.expr_call_global(sp, path, vec![arg])
369 self.ecx.expr_path(self.ecx.path_global(sp, path))
374 // These two have a direct mapping
375 parse::ArgumentNext => pos("Next", None),
376 parse::ArgumentIs(i) => pos("At", Some(i)),
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) {
383 None => 0, // error already emitted elsewhere
385 let i = i + self.args.len();
391 let simple_arg = parse::Argument {
392 position: parse::ArgumentNext,
393 format: parse::FormatSpec {
394 fill: arg.format.fill,
395 align: parse::AlignUnknown,
397 precision: parse::CountImplied,
398 width: parse::CountImplied,
403 let fill = match arg.format.fill { Some(c) => c, None => ' ' };
405 if *arg != simple_arg || fill != ' ' {
406 self.all_pieces_simple = false;
409 // Translate the format
410 let fill = self.ecx.expr_lit(sp, ast::LitChar(fill));
412 let mut p = Context::rtpath(self.ecx, "Alignment");
413 p.push(self.ecx.ident_of(name));
414 self.ecx.path_global(sp, p)
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"),
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)));
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))))
442 fn static_array(ecx: &mut ExtCtxt,
444 piece_ty: P<ast::Ty>,
445 pieces: Vec<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)),
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);
456 let name = ecx.ident_of(name);
457 let item = ecx.item(sp, name, vec![], st);
458 let decl = respan(sp, ast::DeclItem(item));
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))))
466 /// Actually builds the expression which the iformat! block will be expanded
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();
474 // First, build up the static array which will become our precompiled
476 let static_lifetime = self.ecx.lifetime(self.fmtsp, special_idents::static_lifetime.name);
477 let piece_ty = self.ecx.ty_rptr(
479 self.ecx.ty_ident(self.fmtsp, self.ecx.ident_of("str")),
480 Some(static_lifetime),
482 let pieces = Context::static_array(self.ecx,
488 // Right now there is a bug such that for the expression:
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() {
498 None => continue // error already generated
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));
507 for name in &self.name_ordering {
508 let e = match self.names.remove(name) {
512 let arg_ty = match self.name_types.get(name) {
517 let lname = self.ecx.ident_of(&format!("__arg{}",
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));
526 // Now create a vector containing all the arguments
527 let args = locals.into_iter().chain(names.into_iter().map(|a| a.unwrap()));
529 let args_array = self.ecx.expr_vec(self.fmtsp, args.collect());
531 // Constructs an AST equivalent to:
533 // match (&arg0, &arg1) {
534 // (tmp0, tmp1) => args_array
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.
549 // Note, it may also very well be transformed to:
554 // ref tmp1 => args_array } } }
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));
563 let args_slice = self.ecx.expr_addr_of(self.fmtsp, result);
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])
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(
573 Context::rtpath(self.ecx, "Argument")));
574 let fmt = Context::static_array(self.ecx,
579 ("new_v1_formatted", vec![pieces, args_slice, fmt])
582 let path = self.ecx.std_path(&["fmt", "Arguments", fn_name]);
583 self.ecx.expr_call_global(self.macsp, path, fn_args)
586 fn format_arg(ecx: &ExtCtxt, macsp: Span, sp: Span,
587 ty: &ArgumentType, arg: P<ast::Expr>)
589 let trait_ = match *ty {
590 Known(ref tyname) => {
603 &format!("unknown format trait `{}`",
610 let path = ecx.std_path(&["fmt", "ArgumentV1", "from_usize"]);
611 return ecx.expr_call_global(macsp, path, vec![arg])
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)])
622 pub fn expand_format_args<'cx>(ecx: &'cx mut ExtCtxt, sp: Span,
623 tts: &[ast::TokenTree])
624 -> Box<base::MacResult+'cx> {
626 match parse_args(ecx, sp, tts) {
627 Some((efmt, args, order, names)) => {
628 MacEager::expr(expand_preparsed_format_args(ecx, sp, efmt,
631 None => DummyResult::expr(sp)
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,
639 args: Vec<P<ast::Expr>>,
640 name_ordering: Vec<String>,
641 names: HashMap<String, 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 {
652 arg_types: arg_types,
654 name_positions: HashMap::new(),
655 name_types: HashMap::new(),
656 name_ordering: name_ordering,
659 literal: String::new(),
661 str_pieces: Vec::new(),
662 all_pieces_simple: true,
666 let fmt = match expr_to_string(cx.ecx,
668 "format argument must be a string literal.") {
669 Some((fmt, _)) => fmt,
670 None => return DummyResult::raw_expr(sp)
673 let mut parser = parse::Parser::new(&fmt);
676 match parser.next() {
678 if !parser.errors.is_empty() { break }
679 cx.verify_piece(&piece);
680 match cx.trans_piece(&piece) {
682 let s = cx.trans_literal_string();
683 cx.str_pieces.push(s);
684 cx.pieces.push(piece);
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);
697 if !cx.literal.is_empty() {
698 let s = cx.trans_literal_string();
699 cx.str_pieces.push(s);
702 // Make sure that all arguments were used and all arguments have types.
703 for (i, ty) in cx.arg_types.iter().enumerate() {
705 cx.ecx.span_err(cx.args[i].span, "argument never used");
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");