1 // Copyright 2014 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.
12 use ast::{MetaItem, Item, Expr};
15 use ext::base::ExtCtxt;
16 use ext::build::AstBuilder;
17 use ext::deriving::generic::*;
20 use collections::HashMap;
21 use std::strbuf::StrBuf;
23 pub fn expand_deriving_show(cx: &mut ExtCtxt,
28 // &mut ::std::fmt::Formatter
29 let fmtr = Ptr(~Literal(Path::new(vec!("std", "fmt", "Formatter"))),
30 Borrowed(None, ast::MutMutable));
32 let trait_def = TraitDef {
34 attributes: Vec::new(),
35 path: Path::new(vec!("std", "fmt", "Show")),
36 additional_bounds: Vec::new(),
37 generics: LifetimeBounds::empty(),
41 generics: LifetimeBounds::empty(),
42 explicit_self: borrowed_explicit_self(),
44 ret_ty: Literal(Path::new(vec!("std", "fmt", "Result"))),
45 attributes: Vec::new(),
46 const_nonmatching: false,
47 combine_substructure: combine_substructure(|a, b, c| {
48 show_substructure(a, b, c)
53 trait_def.expand(cx, mitem, item, push)
56 // we construct a format string and then defer to std::fmt, since that
57 // knows what's up with formatting at so on.
58 fn show_substructure(cx: &mut ExtCtxt, span: Span,
59 substr: &Substructure) -> @Expr {
60 // build `<name>`, `<name>({}, {}, ...)` or `<name> { <field>: {},
61 // <field>: {}, ... }` based on the "shape".
63 // Easy start: they all start with the name.
64 let name = match *substr.fields {
65 Struct(_) => substr.type_ident,
66 EnumMatching(_, v, _) => v.node.name,
68 EnumNonMatching(..) | StaticStruct(..) | StaticEnum(..) => {
69 cx.span_bug(span, "nonsensical .fields in `#[deriving(Show)]`")
73 let mut format_string = StrBuf::from_str(token::get_ident(name).get());
74 // the internal fields we're actually formatting
75 let mut exprs = Vec::new();
77 // Getting harder... making the format string:
78 match *substr.fields {
79 // unit struct/nullary variant: no work necessary!
80 Struct(ref fields) if fields.len() == 0 => {}
81 EnumMatching(_, _, ref fields) if fields.len() == 0 => {}
83 Struct(ref fields) | EnumMatching(_, _, ref fields) => {
84 if fields.get(0).name.is_none() {
85 // tuple struct/"normal" variant
87 format_string.push_str("(");
89 for (i, field) in fields.iter().enumerate() {
90 if i != 0 { format_string.push_str(", "); }
92 format_string.push_str("{}");
94 exprs.push(field.self_);
97 format_string.push_str(")");
99 // normal struct/struct variant
101 format_string.push_str(" \\{");
103 for (i, field) in fields.iter().enumerate() {
104 if i != 0 { format_string.push_str(","); }
106 let name = token::get_ident(field.name.unwrap());
107 format_string.push_str(" ");
108 format_string.push_str(name.get());
109 format_string.push_str(": {}");
111 exprs.push(field.self_);
114 format_string.push_str(" \\}");
121 // we're basically calling
123 // format_arg!(|__args| ::std::fmt::write(fmt.buf, __args), "<format_string>", exprs...)
125 // but doing it directly via ext::format.
126 let formatter = substr.nonself_args[0];
127 let buf = cx.expr_field_access(span, formatter, cx.ident_of("buf"));
129 let std_write = vec!(cx.ident_of("std"), cx.ident_of("fmt"), cx.ident_of("write"));
130 let args = cx.ident_of("__args");
131 let write_call = cx.expr_call_global(span, std_write, vec!(buf, cx.expr_ident(span, args)));
132 let format_closure = cx.lambda_expr(span, vec!(args), write_call);
134 let s = token::intern_and_get_ident(format_string.as_slice());
135 let format_string = cx.expr_str(span, s);
137 // phew, not our responsibility any more!
138 format::expand_preparsed_format_args(cx, span,
140 format_string, exprs, Vec::new(),