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::*;
14 use fmt_macros as parse;
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};
23 use syntax_pos::{Span, DUMMY_SP};
24 use syntax::tokenstream;
26 use std::collections::HashMap;
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.
44 /// The span of the format string literal.
47 /// Parsed argument expressions and the types that we've found so far for
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
55 names: HashMap<String, P<ast::Expr>>,
56 name_types: HashMap<String, ArgumentType>,
57 name_ordering: Vec<String>,
59 /// The latest consecutive literal strings, or empty if there weren't any.
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,
69 name_positions: HashMap<String, usize>,
71 /// Updated as arguments are consumed
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: &[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();
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());
98 let mut named = false;
99 while p.token != token::Eof {
100 if !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 {
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());
129 match names.get(name) {
132 ecx.struct_span_err(e.span,
133 &format!("duplicate argument named `{}`",
135 .span_note(prev.span, "previously here")
140 order.push(name.to_string());
141 names.insert(name.to_string(), e);
143 args.push(panictry!(p.parse_expr()));
146 Some((fmtstr, args, order, names))
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
153 fn verify_piece(&mut self, p: &parse::Piece) {
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);
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;
170 parse::ArgumentIs(i) => Exact(i),
171 parse::ArgumentNamed(s) => Named(s.to_string()),
174 let ty = Known(arg.format.ty.to_string());
175 self.verify_arg_type(pos, ty);
180 fn verify_count(&mut self, c: parse::Count) {
182 parse::CountImplied | parse::CountIs(..) => {}
183 parse::CountIsParam(i) => {
184 self.verify_arg_type(Exact(i), Unsigned);
186 parse::CountIsName(s) => {
187 self.verify_arg_type(Named(s.to_string()), Unsigned);
189 parse::CountIsNextParam => {
190 let next_arg = self.next_arg;
191 self.verify_arg_type(Exact(next_arg), Unsigned);
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),
205 fn verify_arg_type(&mut self, arg: Position, ty: ArgumentType) {
208 if self.args.len() <= arg {
209 let msg = format!("invalid reference to argument `{}` ({})",
210 arg, self.describe_num_args());
212 self.ecx.span_err(self.fmtsp, &msg[..]);
216 let arg_type = match self.arg_types[arg] {
218 Some(ref x) => Some(x)
220 self.verify_same(self.args[arg].span, &ty, arg_type);
222 if self.arg_types[arg].is_none() {
223 self.arg_types[arg] = Some(ty);
228 let span = match self.names.get(&name) {
231 let msg = format!("there is no argument named `{}`", name);
232 self.ecx.span_err(self.fmtsp, &msg[..]);
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);
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);
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
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,
261 before: Option<&ArgumentType>) {
262 let cur = match before {
270 (&Known(ref cur), &Known(ref ty)) => {
271 self.ecx.span_err(sp,
272 &format!("argument redeclared with type `{}` when \
273 it was previously `{}`",
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",
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 `{}`",
290 self.ecx.span_err(sp, "argument declared with multiple formats");
295 fn rtpath(ecx: &ExtCtxt, s: &str) -> Vec<ast::Ident> {
296 ecx.std_path(&["fmt", "rt", "v1", s])
299 fn trans_count(&self, c: parse::Count) -> P<ast::Expr> {
301 let count = |c, arg| {
302 let mut path = Context::rtpath(self.ecx, "Count");
303 path.push(self.ecx.ident_of(c));
305 Some(arg) => self.ecx.expr_call_global(sp, path, vec![arg]),
306 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
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)))
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) {
319 None => 0, // error already emitted elsewhere
321 let i = i + self.args.len();
322 count("Param", Some(self.ecx.expr_usize(sp, i)))
327 /// Translate the accumulated string literals to a literal expression
328 fn trans_literal_string(&mut self) -> P<ast::Expr> {
330 let s = token::intern_and_get_ident(&self.literal);
331 self.literal.clear();
332 self.ecx.expr_str(sp, s)
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>> {
340 parse::String(s) => {
341 self.literal.push_str(s);
344 parse::NextArgument(ref arg) => {
345 // Translate the position
348 let mut path = Context::rtpath(self.ecx, "Position");
349 path.push(self.ecx.ident_of(c));
352 let arg = self.ecx.expr_usize(sp, i);
353 self.ecx.expr_call_global(sp, path, vec![arg])
356 self.ecx.expr_path(self.ecx.path_global(sp, path))
361 // These two have a direct mapping
362 parse::ArgumentNext => pos("Next", None),
363 parse::ArgumentIs(i) => pos("At", Some(i)),
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) {
370 None => 0, // error already emitted elsewhere
372 let i = i + self.args.len();
378 let simple_arg = parse::Argument {
379 position: parse::ArgumentNext,
380 format: parse::FormatSpec {
381 fill: arg.format.fill,
382 align: parse::AlignUnknown,
384 precision: parse::CountImplied,
385 width: parse::CountImplied,
390 let fill = match arg.format.fill { Some(c) => c, None => ' ' };
392 if *arg != simple_arg || fill != ' ' {
393 self.all_pieces_simple = false;
396 // Translate the format
397 let fill = self.ecx.expr_lit(sp, ast::LitKind::Char(fill));
399 let mut p = Context::rtpath(self.ecx, "Alignment");
400 p.push(self.ecx.ident_of(name));
401 self.ecx.path_global(sp, p)
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"),
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)));
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))))
429 fn static_array(ecx: &mut ExtCtxt,
431 piece_ty: P<ast::Ty>,
432 pieces: Vec<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);
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),
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))]))
455 /// Actually builds the expression which the iformat! block will be expanded
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();
463 // First, build up the static array which will become our precompiled
465 let static_lifetime = self.ecx.lifetime(self.fmtsp, keywords::StaticLifetime.name());
466 let piece_ty = self.ecx.ty_rptr(
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,
477 // Right now there is a bug such that for the expression:
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() {
487 None => continue // error already generated
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));
496 for name in &self.name_ordering {
497 let e = match self.names.remove(name) {
501 let arg_ty = match self.name_types.get(name) {
506 let lname = self.ecx.ident_of(&format!("__arg{}",
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));
515 // Now create a vector containing all the arguments
516 let args = locals.into_iter().chain(names.into_iter().map(|a| a.unwrap()));
518 let args_array = self.ecx.expr_vec(self.fmtsp, args.collect());
520 // Constructs an AST equivalent to:
522 // match (&arg0, &arg1) {
523 // (tmp0, tmp1) => args_array
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.
538 // Note, it may also very well be transformed to:
543 // ref tmp1 => args_array } } }
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));
552 let args_slice = self.ecx.expr_addr_of(self.fmtsp, result);
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])
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(
562 Context::rtpath(self.ecx, "Argument")));
563 let fmt = Context::static_array(self.ecx,
568 ("new_v1_formatted", vec![pieces, args_slice, fmt])
571 let path = self.ecx.std_path(&["fmt", "Arguments", fn_name]);
572 self.ecx.expr_call_global(self.macsp, path, fn_args)
575 fn format_arg(ecx: &ExtCtxt, macsp: Span, sp: Span,
576 ty: &ArgumentType, arg: P<ast::Expr>)
578 let trait_ = match *ty {
579 Known(ref tyname) => {
592 &format!("unknown format trait `{}`",
599 let path = ecx.std_path(&["fmt", "ArgumentV1", "from_usize"]);
600 return ecx.expr_call_global(macsp, path, vec![arg])
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)])
611 pub fn expand_format_args<'cx>(ecx: &'cx mut ExtCtxt, sp: Span,
612 tts: &[tokenstream::TokenTree])
613 -> Box<base::MacResult+'cx> {
615 match parse_args(ecx, sp, tts) {
616 Some((efmt, args, order, names)) => {
617 MacEager::expr(expand_preparsed_format_args(ecx, sp, efmt,
620 None => DummyResult::expr(sp)
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,
628 args: Vec<P<ast::Expr>>,
629 name_ordering: Vec<String>,
630 names: HashMap<String, 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 {
641 arg_types: arg_types,
643 name_positions: HashMap::new(),
644 name_types: HashMap::new(),
645 name_ordering: name_ordering,
647 literal: String::new(),
649 str_pieces: Vec::new(),
650 all_pieces_simple: true,
654 let fmt = match expr_to_string(cx.ecx,
656 "format argument must be a string literal.") {
657 Some((fmt, _)) => fmt,
658 None => return DummyResult::raw_expr(sp)
661 let mut parser = parse::Parser::new(&fmt);
664 match parser.next() {
666 if !parser.errors.is_empty() { break }
667 cx.verify_piece(&piece);
668 match cx.trans_piece(&piece) {
670 let s = cx.trans_literal_string();
671 cx.str_pieces.push(s);
672 cx.pieces.push(piece);
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);
685 if !cx.literal.is_empty() {
686 let s = cx.trans_literal_string();
687 cx.str_pieces.push(s);
690 // Make sure that all arguments were used and all arguments have types.
691 for (i, ty) in cx.arg_types.iter().enumerate() {
693 cx.ecx.span_err(cx.args[i].span, "argument never used");
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");