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.
11 use deriving::path_std;
12 use deriving::generic::*;
13 use deriving::generic::ty::*;
15 use syntax::ast::{self, Ident};
16 use syntax::ast::{Expr, MetaItem};
17 use syntax::ext::base::{Annotatable, ExtCtxt};
18 use syntax::ext::build::AstBuilder;
20 use syntax_pos::{DUMMY_SP, Span};
22 pub fn expand_deriving_debug(cx: &mut ExtCtxt,
26 push: &mut dyn FnMut(Annotatable)) {
27 // &mut ::std::fmt::Formatter
28 let fmtr = Ptr(Box::new(Literal(path_std!(cx, fmt::Formatter))),
29 Borrowed(None, ast::Mutability::Mutable));
31 let trait_def = TraitDef {
33 attributes: Vec::new(),
34 path: path_std!(cx, fmt::Debug),
35 additional_bounds: Vec::new(),
36 generics: LifetimeBounds::empty(),
38 supports_unions: false,
39 methods: vec![MethodDef {
41 generics: LifetimeBounds::empty(),
42 explicit_self: borrowed_explicit_self(),
43 args: vec![(fmtr, "f")],
44 ret_ty: Literal(path_std!(cx, fmt::Result)),
45 attributes: Vec::new(),
47 unify_fieldless_variants: false,
48 combine_substructure: combine_substructure(Box::new(|a, b, c| {
49 show_substructure(a, b, c)
52 associated_types: Vec::new(),
54 trait_def.expand(cx, mitem, item, push)
57 /// We use the debug builders to do the heavy lifting here
58 fn show_substructure(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
59 // build fmt.debug_struct(<name>).field(<fieldname>, &<fieldval>)....build()
60 // or fmt.debug_tuple(<name>).field(&<fieldval>)....build()
61 // based on the "shape".
62 let (ident, is_struct) = match *substr.fields {
63 Struct(vdata, _) => (substr.type_ident, vdata.is_struct()),
64 EnumMatching(_, _, v, _) => (v.node.ident, v.node.data.is_struct()),
65 EnumNonMatchingCollapsed(..) |
67 StaticEnum(..) => cx.span_bug(span, "nonsensical .fields in `#[derive(Debug)]`"),
70 // We want to make sure we have the ctxt set so that we can use unstable methods
71 let span = span.with_ctxt(cx.backtrace());
72 let name = cx.expr_lit(span, ast::LitKind::Str(ident.name, ast::StrStyle::Cooked));
73 let builder = Ident::from_str("debug_trait_builder").gensym();
74 let builder_expr = cx.expr_ident(span, builder.clone());
76 let fmt = substr.nonself_args[0].clone();
78 let mut stmts = match *substr.fields {
79 Struct(_, ref fields) |
80 EnumMatching(.., ref fields) => {
81 let mut stmts = vec![];
83 // tuple struct/"normal" variant
85 cx.expr_method_call(span, fmt, Ident::from_str("debug_tuple"), vec![name]);
86 stmts.push(cx.stmt_let(DUMMY_SP, true, builder, expr));
89 // Use double indirection to make sure this works for unsized types
90 let field = cx.expr_addr_of(field.span, field.self_.clone());
91 let field = cx.expr_addr_of(field.span, field);
93 let expr = cx.expr_method_call(span,
95 Ident::from_str("field"),
98 // Use `let _ = expr;` to avoid triggering the
99 // unused_results lint.
100 stmts.push(stmt_let_undescore(cx, span, expr));
103 // normal struct/struct variant
105 cx.expr_method_call(span, fmt, Ident::from_str("debug_struct"), vec![name]);
106 stmts.push(cx.stmt_let(DUMMY_SP, true, builder, expr));
108 for field in fields {
109 let name = cx.expr_lit(field.span,
110 ast::LitKind::Str(field.name.unwrap().name,
111 ast::StrStyle::Cooked));
113 // Use double indirection to make sure this works for unsized types
114 let field = cx.expr_addr_of(field.span, field.self_.clone());
115 let field = cx.expr_addr_of(field.span, field);
116 let expr = cx.expr_method_call(span,
117 builder_expr.clone(),
118 Ident::from_str("field"),
120 stmts.push(stmt_let_undescore(cx, span, expr));
128 let expr = cx.expr_method_call(span, builder_expr, Ident::from_str("finish"), vec![]);
130 stmts.push(cx.stmt_expr(expr));
131 let block = cx.block(span, stmts);
135 fn stmt_let_undescore(cx: &mut ExtCtxt, sp: Span, expr: P<ast::Expr>) -> ast::Stmt {
136 let local = P(ast::Local {
137 pat: cx.pat_wild(sp),
140 id: ast::DUMMY_NODE_ID,
142 attrs: ast::ThinVec::new(),
145 id: ast::DUMMY_NODE_ID,
146 node: ast::StmtKind::Local(local),