Skip to content

Commit 30d7559

Browse files
committed
Expand the deriving(ToStr) implementation
1 parent dc4560d commit 30d7559

File tree

3 files changed

+102
-45
lines changed

3 files changed

+102
-45
lines changed

doc/rust.md

+3-1
Original file line numberDiff line numberDiff line change
@@ -1562,7 +1562,9 @@ Supported traits for `deriving` are:
15621562
* `IterBytes`, to iterate over the bytes in a data type.
15631563
* `Rand`, to create a random instance of a data type.
15641564
* `ToStr`, to convert to a string. For a type with this instance,
1565-
`obj.to_str()` has the same output as `fmt!("%?", obj)`.
1565+
`obj.to_str()` has similar output as `fmt!("%?", obj)`, but it differs in that
1566+
each constituent field of the type must also implement `ToStr` and will have
1567+
`field.to_str()` invoked to build up the result.
15661568

15671569
# Statements and expressions
15681570

src/libsyntax/ext/deriving/to_str.rs

+64-11
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
use core::prelude::*;
1212

13+
use ast;
1314
use ast::{meta_item, item, expr};
1415
use codemap::span;
1516
use ext::base::ExtCtxt;
@@ -40,16 +41,68 @@ pub fn expand_deriving_to_str(cx: @ExtCtxt,
4041
trait_def.expand(cx, span, mitem, in_items)
4142
}
4243

43-
fn to_str_substructure(cx: @ExtCtxt, span: span, substr: &Substructure) -> @expr {
44-
match substr.self_args {
45-
[self_obj] => {
46-
let self_addr = cx.expr_addr_of(span, self_obj);
47-
cx.expr_call_global(span,
48-
~[cx.ident_of("std"),
49-
cx.ident_of("sys"),
50-
cx.ident_of("log_str")],
51-
~[self_addr])
44+
// It used to be the case that this deriving implementation invoked
45+
// std::sys::log_str, but this isn't sufficient because it doesn't invoke the
46+
// to_str() method on each field. Hence we mirror the logic of the log_str()
47+
// method, but with tweaks to call to_str() on sub-fields.
48+
fn to_str_substructure(cx: @ExtCtxt, span: span,
49+
substr: &Substructure) -> @expr {
50+
let to_str = cx.ident_of("to_str");
51+
52+
let doit = |start: &str, end: @str, name: ast::ident,
53+
fields: &[(Option<ast::ident>, @expr, ~[@expr])]| {
54+
if fields.len() == 0 {
55+
cx.expr_str_uniq(span, cx.str_of(name))
56+
} else {
57+
let buf = cx.ident_of("buf");
58+
let start = cx.str_of(name) + start;
59+
let init = cx.expr_str_uniq(span, start.to_managed());
60+
let mut stmts = ~[cx.stmt_let(span, true, buf, init)];
61+
let push_str = cx.ident_of("push_str");
62+
63+
let push = |s: @expr| {
64+
let ebuf = cx.expr_ident(span, buf);
65+
let call = cx.expr_method_call(span, ebuf, push_str, ~[s]);
66+
stmts.push(cx.stmt_expr(call));
67+
};
68+
69+
for fields.iter().enumerate().advance |(i, &(name, e, _))| {
70+
if i > 0 {
71+
push(cx.expr_str(span, @", "));
72+
}
73+
match name {
74+
None => {}
75+
Some(id) => {
76+
let name = cx.str_of(id) + ": ";
77+
push(cx.expr_str(span, name.to_managed()));
78+
}
79+
}
80+
push(cx.expr_method_call(span, e, to_str, ~[]));
81+
}
82+
push(cx.expr_str(span, end));
83+
84+
cx.expr_blk(cx.blk(span, stmts, Some(cx.expr_ident(span, buf))))
85+
}
86+
};
87+
88+
return match *substr.fields {
89+
Struct(ref fields) => {
90+
if fields.len() == 0 || fields[0].n0_ref().is_none() {
91+
doit("(", @")", substr.type_ident, *fields)
92+
} else {
93+
doit("{", @"}", substr.type_ident, *fields)
94+
}
5295
}
53-
_ => cx.span_bug(span, "Invalid number of arguments in `deriving(ToStr)`")
54-
}
96+
97+
EnumMatching(_, variant, ref fields) => {
98+
match variant.node.kind {
99+
ast::tuple_variant_kind(*) =>
100+
doit("(", @")", variant.node.name, *fields),
101+
ast::struct_variant_kind(*) =>
102+
doit("{", @"}", variant.node.name, *fields),
103+
}
104+
}
105+
106+
_ => cx.bug("expected Struct or EnumMatching in deriving(ToStr)")
107+
};
55108
}

src/test/run-pass/deriving-to-str.rs

+35-33
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
// xfail-fast #6330
2-
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
1+
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
32
// file at the top-level directory of this distribution and at
43
// http://rust-lang.org/COPYRIGHT.
54
//
@@ -9,39 +8,42 @@
98
// option. This file may not be copied, modified, or distributed
109
// except according to those terms.
1110

12-
use std::rand;
11+
#[deriving(ToStr)]
12+
enum A {}
13+
#[deriving(ToStr)]
14+
enum B { B1, B2, B3 }
15+
#[deriving(ToStr)]
16+
enum C { C1(int), C2(B), C3(~str) }
17+
#[deriving(ToStr)]
18+
enum D { D1{ a: int } }
19+
#[deriving(ToStr)]
20+
struct E;
21+
#[deriving(ToStr)]
22+
struct F(int);
23+
#[deriving(ToStr)]
24+
struct G(int, int);
25+
#[deriving(ToStr)]
26+
struct H { a: int }
27+
#[deriving(ToStr)]
28+
struct I { a: int, b: int }
29+
#[deriving(ToStr)]
30+
struct J(Custom);
1331

14-
#[deriving(Rand,ToStr)]
15-
struct A;
16-
17-
#[deriving(Rand,ToStr)]
18-
struct B(int, int);
19-
20-
#[deriving(Rand,ToStr)]
21-
struct C {
22-
x: f64,
23-
y: (u8, u8)
24-
}
25-
26-
#[deriving(Rand,ToStr)]
27-
enum D {
28-
D0,
29-
D1(uint),
30-
D2 { x: (), y: () }
32+
struct Custom;
33+
impl ToStr for Custom {
34+
fn to_str(&self) -> ~str { ~"yay" }
3135
}
3236

3337
fn main() {
34-
macro_rules! t(
35-
($ty:ty) => {{
36-
let x =rand::random::<$ty>();
37-
assert_eq!(x.to_str(), fmt!("%?", x));
38-
}}
39-
);
40-
41-
for 20.times {
42-
t!(A);
43-
t!(B);
44-
t!(C);
45-
t!(D);
46-
}
38+
assert_eq!(B1.to_str(), ~"B1");
39+
assert_eq!(B2.to_str(), ~"B2");
40+
assert_eq!(C1(3).to_str(), ~"C1(3)");
41+
assert_eq!(C2(B2).to_str(), ~"C2(B2)");
42+
assert_eq!(D1{ a: 2 }.to_str(), ~"D1{a: 2}");
43+
assert_eq!(E.to_str(), ~"E");
44+
assert_eq!(F(3).to_str(), ~"F(3)");
45+
assert_eq!(G(3, 4).to_str(), ~"G(3, 4)");
46+
assert_eq!(G(3, 4).to_str(), ~"G(3, 4)");
47+
assert_eq!(I{ a: 2, b: 4 }.to_str(), ~"I{a: 2, b: 4}");
48+
assert_eq!(J(Custom).to_str(), ~"J(yay)");
4749
}

0 commit comments

Comments
 (0)