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;
20 use parse::token::special_idents;
24 use std::collections::HashMap;
25 use std::iter::repeat;
38 struct Context<'a, 'b:'a> {
39 ecx: &'a mut ExtCtxt<'b>,
42 /// Parsed argument expressions and the types that we've found so far for
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
50 names: HashMap<String, P<ast::Expr>>,
51 name_types: HashMap<String, ArgumentType>,
52 name_ordering: Vec<String>,
54 /// The latest consecutive literal strings, or empty if there weren't any.
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,
64 name_positions: HashMap<String, usize>,
66 /// Updated as arguments are consumed or methods are entered
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!
75 /// If parsing succeeds, the return value is:
77 /// Some((fmtstr, unnamed arguments, ordering of 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();
86 let mut p = ecx.new_parser_from_tts(tts);
88 if p.token == token::Eof {
89 ecx.span_err(sp, "requires at least a format string argument");
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: `,`");
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)) {
102 let ident = match p.token {
103 token::Ident(i, _) => {
109 "expected ident, positional arguments \
110 cannot follow named arguments");
115 &format!("expected ident for named argument, found `{}`",
116 p.this_token_to_string())[]);
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) {
128 &format!("duplicate argument named `{}`",
130 ecx.parse_sess.span_diagnostic.span_note(prev.span, "previously here");
134 order.push(name.to_string());
135 names.insert(name.to_string(), e);
137 args.push(p.parse_expr());
140 Some((fmtstr, args, order, names))
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
147 fn verify_piece(&mut self, p: &parse::Piece) {
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);
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() {
166 parse::ArgumentIs(i) => Exact(i),
167 parse::ArgumentNamed(s) => Named(s.to_string()),
170 let ty = Known(arg.format.ty.to_string());
171 self.verify_arg_type(pos, ty);
176 fn verify_count(&mut self, c: parse::Count) {
178 parse::CountImplied | parse::CountIs(..) => {}
179 parse::CountIsParam(i) => {
180 self.verify_arg_type(Exact(i), Unsigned);
182 parse::CountIsName(s) => {
183 self.verify_arg_type(Named(s.to_string()), Unsigned);
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);
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");
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),
213 fn verify_arg_type(&mut self, arg: Position, ty: ArgumentType) {
216 if self.args.len() <= arg {
217 let msg = format!("invalid reference to argument `{}` ({})",
218 arg, self.describe_num_args());
220 self.ecx.span_err(self.fmtsp, &msg[]);
224 let arg_type = match self.arg_types[arg] {
226 Some(ref x) => Some(x)
228 self.verify_same(self.args[arg].span, &ty, arg_type);
230 if self.arg_types[arg].is_none() {
231 self.arg_types[arg] = Some(ty);
236 let span = match self.names.get(&name) {
239 let msg = format!("there is no argument named `{}`", name);
240 self.ecx.span_err(self.fmtsp, &msg[]);
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);
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);
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
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,
269 before: Option<&ArgumentType>) {
270 let cur = match before {
278 (&Known(ref cur), &Known(ref ty)) => {
279 self.ecx.span_err(sp,
280 &format!("argument redeclared with type `{}` when \
281 it was previously `{}`",
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",
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 `{}`",
298 self.ecx.span_err(sp, "argument declared with multiple formats");
303 fn rtpath(ecx: &ExtCtxt, s: &str) -> Vec<ast::Ident> {
304 vec![ecx.ident_of("std"), ecx.ident_of("fmt"), ecx.ident_of("rt"),
305 ecx.ident_of("v1"), ecx.ident_of(s)]
308 fn trans_count(&self, c: parse::Count) -> P<ast::Expr> {
310 let count = |c, arg| {
311 let mut path = Context::rtpath(self.ecx, "Count");
312 path.push(self.ecx.ident_of(c));
314 Some(arg) => self.ecx.expr_call_global(sp, path, vec![arg]),
315 None => self.ecx.expr_path(self.ecx.path_global(sp, path)),
319 parse::CountIs(i) => count("Is", Some(self.ecx.expr_usize(sp, i))),
320 parse::CountIsParam(i) => {
321 count("Param", Some(self.ecx.expr_usize(sp, i)))
323 parse::CountImplied => count("Implied", None),
324 parse::CountIsNextParam => count("NextParam", None),
325 parse::CountIsName(n) => {
326 let i = match self.name_positions.get(n) {
328 None => 0, // error already emitted elsewhere
330 let i = i + self.args.len();
331 count("Param", Some(self.ecx.expr_usize(sp, i)))
336 /// Translate the accumulated string literals to a literal expression
337 fn trans_literal_string(&mut self) -> P<ast::Expr> {
339 let s = token::intern_and_get_ident(&self.literal[]);
340 self.literal.clear();
341 self.ecx.expr_str(sp, s)
344 /// Translate a `parse::Piece` to a static `rt::Argument` or append
345 /// to the `literal` string.
346 fn trans_piece(&mut self, piece: &parse::Piece) -> Option<P<ast::Expr>> {
349 parse::String(s) => {
350 self.literal.push_str(s);
353 parse::NextArgument(ref arg) => {
354 // Translate the position
357 let mut path = Context::rtpath(self.ecx, "Position");
358 path.push(self.ecx.ident_of(c));
361 let arg = self.ecx.expr_usize(sp, i);
362 self.ecx.expr_call_global(sp, path, vec![arg])
365 self.ecx.expr_path(self.ecx.path_global(sp, path))
370 // These two have a direct mapping
371 parse::ArgumentNext => pos("Next", None),
372 parse::ArgumentIs(i) => pos("At", Some(i)),
374 // Named arguments are converted to positional arguments
375 // at the end of the list of arguments
376 parse::ArgumentNamed(n) => {
377 let i = match self.name_positions.get(n) {
379 None => 0, // error already emitted elsewhere
381 let i = i + self.args.len();
387 let simple_arg = parse::Argument {
388 position: parse::ArgumentNext,
389 format: parse::FormatSpec {
390 fill: arg.format.fill,
391 align: parse::AlignUnknown,
393 precision: parse::CountImplied,
394 width: parse::CountImplied,
399 let fill = match arg.format.fill { Some(c) => c, None => ' ' };
401 if *arg != simple_arg || fill != ' ' {
402 self.all_pieces_simple = false;
405 // Translate the format
406 let fill = self.ecx.expr_lit(sp, ast::LitChar(fill));
408 let mut p = Context::rtpath(self.ecx, "Alignment");
409 p.push(self.ecx.ident_of(name));
410 self.ecx.path_global(sp, p)
412 let align = match arg.format.align {
413 parse::AlignLeft => align("Left"),
414 parse::AlignRight => align("Right"),
415 parse::AlignCenter => align("Center"),
416 parse::AlignUnknown => align("Unknown"),
418 let align = self.ecx.expr_path(align);
419 let flags = self.ecx.expr_usize(sp, arg.format.flags);
420 let prec = self.trans_count(arg.format.precision);
421 let width = self.trans_count(arg.format.width);
422 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, "FormatSpec"));
423 let fmt = self.ecx.expr_struct(sp, path, vec!(
424 self.ecx.field_imm(sp, self.ecx.ident_of("fill"), fill),
425 self.ecx.field_imm(sp, self.ecx.ident_of("align"), align),
426 self.ecx.field_imm(sp, self.ecx.ident_of("flags"), flags),
427 self.ecx.field_imm(sp, self.ecx.ident_of("precision"), prec),
428 self.ecx.field_imm(sp, self.ecx.ident_of("width"), width)));
430 let path = self.ecx.path_global(sp, Context::rtpath(self.ecx, "Argument"));
431 Some(self.ecx.expr_struct(sp, path, vec!(
432 self.ecx.field_imm(sp, self.ecx.ident_of("position"), pos),
433 self.ecx.field_imm(sp, self.ecx.ident_of("format"), fmt))))
438 fn static_array(ecx: &mut ExtCtxt,
440 piece_ty: P<ast::Ty>,
441 pieces: Vec<P<ast::Expr>>)
443 let fmtsp = piece_ty.span;
444 let ty = ecx.ty_rptr(fmtsp,
445 ecx.ty(fmtsp, ast::TyVec(piece_ty)),
446 Some(ecx.lifetime(fmtsp, special_idents::static_lifetime.name)),
448 let slice = ecx.expr_vec_slice(fmtsp, pieces);
449 let st = ast::ItemStatic(ty, ast::MutImmutable, slice);
451 let name = ecx.ident_of(name);
452 let item = ecx.item(fmtsp, name, vec![], st);
453 let decl = respan(fmtsp, ast::DeclItem(item));
455 // Wrap the declaration in a block so that it forms a single expression.
456 ecx.expr_block(ecx.block(fmtsp,
457 vec![P(respan(fmtsp, ast::StmtDecl(P(decl), ast::DUMMY_NODE_ID)))],
458 Some(ecx.expr_ident(fmtsp, name))))
461 /// Actually builds the expression which the iformat! block will be expanded
463 fn into_expr(mut self) -> P<ast::Expr> {
464 let mut locals = Vec::new();
465 let mut names: Vec<_> = repeat(None).take(self.name_positions.len()).collect();
466 let mut pats = Vec::new();
467 let mut heads = Vec::new();
469 // First, build up the static array which will become our precompiled
471 let static_lifetime = self.ecx.lifetime(self.fmtsp, special_idents::static_lifetime.name);
472 let piece_ty = self.ecx.ty_rptr(
474 self.ecx.ty_ident(self.fmtsp, self.ecx.ident_of("str")),
475 Some(static_lifetime),
477 let pieces = Context::static_array(self.ecx,
483 // Right now there is a bug such that for the expression:
485 // the lifetime of `1` doesn't outlast the call to `bar`, so it's not
486 // valid for the call to `foo`. To work around this all arguments to the
487 // format! string are shoved into locals. Furthermore, we shove the address
488 // of each variable because we don't want to move out of the arguments
489 // passed to this function.
490 for (i, e) in self.args.into_iter().enumerate() {
491 let arg_ty = match self.arg_types[i].as_ref() {
493 None => continue // error already generated
496 let name = self.ecx.ident_of(&format!("__arg{}", i)[]);
497 pats.push(self.ecx.pat_ident(e.span, name));
498 locals.push(Context::format_arg(self.ecx, e.span, arg_ty,
499 self.ecx.expr_ident(e.span, name)));
500 heads.push(self.ecx.expr_addr_of(e.span, e));
502 for name in &self.name_ordering {
503 let e = match self.names.remove(name) {
507 let arg_ty = match self.name_types.get(name) {
512 let lname = self.ecx.ident_of(&format!("__arg{}",
514 pats.push(self.ecx.pat_ident(e.span, lname));
515 names[self.name_positions[*name]] =
516 Some(Context::format_arg(self.ecx, e.span, arg_ty,
517 self.ecx.expr_ident(e.span, lname)));
518 heads.push(self.ecx.expr_addr_of(e.span, e));
521 // Now create a vector containing all the arguments
522 let args = locals.into_iter().chain(names.into_iter().map(|a| a.unwrap()));
524 let args_array = self.ecx.expr_vec(self.fmtsp, args.collect());
526 // Constructs an AST equivalent to:
528 // match (&arg0, &arg1) {
529 // (tmp0, tmp1) => args_array
538 // Because of #11585 the new temporary lifetime rule, the enclosing
539 // statements for these temporaries become the let's themselves.
540 // If one or more of them are RefCell's, RefCell borrow() will also
541 // end there; they don't last long enough for args_array to use them.
542 // The match expression solves the scope problem.
544 // Note, it may also very well be transformed to:
549 // ref tmp1 => args_array } } }
551 // But the nested match expression is proved to perform not as well
552 // as series of let's; the first approach does.
553 let pat = self.ecx.pat_tuple(self.fmtsp, pats);
554 let arm = self.ecx.arm(self.fmtsp, vec!(pat), args_array);
555 let head = self.ecx.expr(self.fmtsp, ast::ExprTup(heads));
556 let result = self.ecx.expr_match(self.fmtsp, head, vec!(arm));
558 let args_slice = self.ecx.expr_addr_of(self.fmtsp, result);
560 // Now create the fmt::Arguments struct with all our locals we created.
561 let (fn_name, fn_args) = if self.all_pieces_simple {
562 ("new_v1", vec![pieces, args_slice])
564 // Build up the static array which will store our precompiled
565 // nonstandard placeholders, if there are any.
566 let piece_ty = self.ecx.ty_path(self.ecx.path_global(
568 Context::rtpath(self.ecx, "Argument")));
569 let fmt = Context::static_array(self.ecx,
574 ("new_v1_formatted", vec![pieces, args_slice, fmt])
577 self.ecx.expr_call_global(self.fmtsp, vec!(
578 self.ecx.ident_of("std"),
579 self.ecx.ident_of("fmt"),
580 self.ecx.ident_of("Arguments"),
581 self.ecx.ident_of(fn_name)), fn_args)
584 fn format_arg(ecx: &ExtCtxt, sp: Span,
585 ty: &ArgumentType, arg: P<ast::Expr>)
587 let trait_ = match *ty {
588 Known(ref tyname) => {
601 &format!("unknown format trait `{}`",
608 return ecx.expr_call_global(sp, vec![
611 ecx.ident_of("ArgumentV1"),
612 ecx.ident_of("from_uint")], vec![arg])
616 let format_fn = ecx.path_global(sp, vec![
619 ecx.ident_of(trait_),
620 ecx.ident_of("fmt")]);
621 ecx.expr_call_global(sp, vec![
624 ecx.ident_of("ArgumentV1"),
625 ecx.ident_of("new")], vec![arg, ecx.expr_path(format_fn)])
629 pub fn expand_format_args<'cx>(ecx: &'cx mut ExtCtxt, sp: Span,
630 tts: &[ast::TokenTree])
631 -> Box<base::MacResult+'cx> {
633 match parse_args(ecx, sp, tts) {
634 Some((efmt, args, order, names)) => {
635 MacExpr::new(expand_preparsed_format_args(ecx, sp, efmt,
638 None => DummyResult::expr(sp)
642 /// Take the various parts of `format_args!(efmt, args..., name=names...)`
643 /// and construct the appropriate formatting expression.
644 pub fn expand_preparsed_format_args(ecx: &mut ExtCtxt, sp: Span,
646 args: Vec<P<ast::Expr>>,
647 name_ordering: Vec<String>,
648 names: HashMap<String, P<ast::Expr>>)
650 let arg_types: Vec<_> = (0..args.len()).map(|_| None).collect();
651 let mut cx = Context {
654 arg_types: arg_types,
656 name_positions: HashMap::new(),
657 name_types: HashMap::new(),
658 name_ordering: name_ordering,
661 literal: String::new(),
663 str_pieces: Vec::new(),
664 all_pieces_simple: true,
667 cx.fmtsp = efmt.span;
668 let fmt = match expr_to_string(cx.ecx,
670 "format argument must be a string literal.") {
671 Some((fmt, _)) => fmt,
672 None => return DummyResult::raw_expr(sp)
675 let mut parser = parse::Parser::new(fmt.get());
677 match parser.next() {
679 if parser.errors.len() > 0 { break }
680 cx.verify_piece(&piece);
681 match cx.trans_piece(&piece) {
683 let s = cx.trans_literal_string();
684 cx.str_pieces.push(s);
685 cx.pieces.push(piece);
693 if !parser.errors.is_empty() {
694 cx.ecx.span_err(cx.fmtsp, &format!("invalid format string: {}",
695 parser.errors.remove(0))[]);
696 return DummyResult::raw_expr(sp);
698 if !cx.literal.is_empty() {
699 let s = cx.trans_literal_string();
700 cx.str_pieces.push(s);
703 // Make sure that all arguments were used and all arguments have types.
704 for (i, ty) in cx.arg_types.iter().enumerate() {
706 cx.ecx.span_err(cx.args[i].span, "argument never used");
709 for (name, e) in &cx.names {
710 if !cx.name_types.contains_key(name) {
711 cx.ecx.span_err(e.span, "named argument never used");