]> git.lizzy.rs Git - rust.git/blob - src/libsyntax/ext/deriving/show.rs
Tweak ItemDecorator API
[rust.git] / src / libsyntax / ext / deriving / show.rs
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.
4 //
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.
10
11 use ast;
12 use ast::{MetaItem, Item, Expr};
13 use codemap::Span;
14 use ext::format;
15 use ext::base::ExtCtxt;
16 use ext::build::AstBuilder;
17 use ext::deriving::generic::*;
18
19 use parse::token;
20
21 use std::hashmap::HashMap;
22
23 pub fn expand_deriving_show(cx: &mut ExtCtxt,
24                             span: Span,
25                             mitem: @MetaItem,
26                             item: @Item,
27                             push: |@Item|) {
28     // &mut ::std::fmt::Formatter
29     let fmtr = Ptr(~Literal(Path::new(~["std", "fmt", "Formatter"])),
30                    Borrowed(None, ast::MutMutable));
31
32     let trait_def = TraitDef {
33         span: span,
34         path: Path::new(~["std", "fmt", "Show"]),
35         additional_bounds: ~[],
36         generics: LifetimeBounds::empty(),
37         methods: ~[
38             MethodDef {
39                 name: "fmt",
40                 generics: LifetimeBounds::empty(),
41                 explicit_self: borrowed_explicit_self(),
42                 args: ~[fmtr],
43                 ret_ty: Literal(Path::new(~["std", "fmt", "Result"])),
44                 inline: false,
45                 const_nonmatching: false,
46                 combine_substructure: show_substructure
47             }
48         ]
49     };
50     trait_def.expand(cx, mitem, item, push)
51 }
52
53 // we construct a format string and then defer to std::fmt, since that
54 // knows what's up with formatting at so on.
55 fn show_substructure(cx: &mut ExtCtxt, span: Span,
56                      substr: &Substructure) -> @Expr {
57     // build `<name>`, `<name>({}, {}, ...)` or `<name> { <field>: {},
58     // <field>: {}, ... }` based on the "shape".
59     //
60     // Easy start: they all start with the name.
61     let name = match *substr.fields {
62         Struct(_) => substr.type_ident,
63         EnumMatching(_, v, _) => v.node.name,
64
65         EnumNonMatching(..) | StaticStruct(..) | StaticEnum(..) => {
66             cx.span_bug(span, "nonsensical .fields in `#[deriving(Show)]`")
67         }
68     };
69
70     let mut format_string = token::get_ident(name.name).get().to_owned();
71     // the internal fields we're actually formatting
72     let mut exprs = ~[];
73
74     // Getting harder... making the format string:
75     match *substr.fields {
76         // unit struct/nullary variant: no work necessary!
77         Struct([]) | EnumMatching(_, _, []) => {}
78
79         Struct(ref fields) | EnumMatching(_, _, ref fields) => {
80             if fields[0].name.is_none() {
81                 // tuple struct/"normal" variant
82
83                 format_string.push_str("(");
84
85                 for (i, field) in fields.iter().enumerate() {
86                     if i != 0 { format_string.push_str(", "); }
87
88                     format_string.push_str("{}");
89
90                     exprs.push(field.self_);
91                 }
92
93                 format_string.push_str(")");
94             } else {
95                 // normal struct/struct variant
96
97                 format_string.push_str(" \\{");
98
99                 for (i, field) in fields.iter().enumerate() {
100                     if i != 0 { format_string.push_str(","); }
101
102                     let name = token::get_ident(field.name.unwrap().name);
103                     format_string.push_str(" ");
104                     format_string.push_str(name.get());
105                     format_string.push_str(": {}");
106
107                     exprs.push(field.self_);
108                 }
109
110                 format_string.push_str(" \\}");
111             }
112         }
113         _ => unreachable!()
114     }
115
116     // AST construction!
117     // we're basically calling
118     //
119     // format_arg!(|__args| ::std::fmt::write(fmt.buf, __args), "<format_string>", exprs...)
120     //
121     // but doing it directly via ext::format.
122     let formatter = substr.nonself_args[0];
123     let buf = cx.expr_field_access(span, formatter, cx.ident_of("buf"));
124
125     let std_write = ~[cx.ident_of("std"), cx.ident_of("fmt"), cx.ident_of("write")];
126     let args = cx.ident_of("__args");
127     let write_call = cx.expr_call_global(span, std_write, ~[buf, cx.expr_ident(span, args)]);
128     let format_closure = cx.lambda_expr(span, ~[args], write_call);
129
130     let s = token::intern_and_get_ident(format_string);
131     let format_string = cx.expr_str(span, s);
132
133     // phew, not our responsibility any more!
134     format::expand_preparsed_format_args(cx, span,
135                                          format_closure,
136                                          format_string, exprs, HashMap::new())
137 }