]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/deriving/debug.rs
Make fields of `Span` private
[rust.git] / src / libsyntax_ext / deriving / debug.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 deriving::generic::*;
12 use deriving::generic::ty::*;
13
14 use syntax::ast::{self, Ident};
15 use syntax::ast::{Expr, MetaItem};
16 use syntax::ext::base::{Annotatable, ExtCtxt};
17 use syntax::ext::build::AstBuilder;
18 use syntax::ptr::P;
19 use syntax_pos::{DUMMY_SP, Span};
20
21 pub fn expand_deriving_debug(cx: &mut ExtCtxt,
22                              span: Span,
23                              mitem: &MetaItem,
24                              item: &Annotatable,
25                              push: &mut FnMut(Annotatable)) {
26     // &mut ::std::fmt::Formatter
27     let fmtr = Ptr(Box::new(Literal(path_std!(cx, core::fmt::Formatter))),
28                    Borrowed(None, ast::Mutability::Mutable));
29
30     let trait_def = TraitDef {
31         span,
32         attributes: Vec::new(),
33         path: path_std!(cx, core::fmt::Debug),
34         additional_bounds: Vec::new(),
35         generics: LifetimeBounds::empty(),
36         is_unsafe: false,
37         supports_unions: false,
38         methods: vec![MethodDef {
39                           name: "fmt",
40                           generics: LifetimeBounds::empty(),
41                           explicit_self: borrowed_explicit_self(),
42                           args: vec![fmtr],
43                           ret_ty: Literal(path_std!(cx, core::fmt::Result)),
44                           attributes: Vec::new(),
45                           is_unsafe: false,
46                           unify_fieldless_variants: false,
47                           combine_substructure: combine_substructure(Box::new(|a, b, c| {
48                               show_substructure(a, b, c)
49                           })),
50                       }],
51         associated_types: Vec::new(),
52     };
53     trait_def.expand(cx, mitem, item, push)
54 }
55
56 /// We use the debug builders to do the heavy lifting here
57 fn show_substructure(cx: &mut ExtCtxt, span: Span, substr: &Substructure) -> P<Expr> {
58     // build fmt.debug_struct(<name>).field(<fieldname>, &<fieldval>)....build()
59     // or fmt.debug_tuple(<name>).field(&<fieldval>)....build()
60     // based on the "shape".
61     let (ident, is_struct) = match *substr.fields {
62         Struct(vdata, _) => (substr.type_ident, vdata.is_struct()),
63         EnumMatching(_, _, v, _) => (v.node.name, v.node.data.is_struct()),
64         EnumNonMatchingCollapsed(..) |
65         StaticStruct(..) |
66         StaticEnum(..) => cx.span_bug(span, "nonsensical .fields in `#[derive(Debug)]`"),
67     };
68
69     // We want to make sure we have the ctxt set so that we can use unstable methods
70     let span = span.with_ctxt(cx.backtrace());
71     let name = cx.expr_lit(span, ast::LitKind::Str(ident.name, ast::StrStyle::Cooked));
72     let builder = Ident::from_str("builder");
73     let builder_expr = cx.expr_ident(span, builder.clone());
74
75     let fmt = substr.nonself_args[0].clone();
76
77     let mut stmts = match *substr.fields {
78         Struct(_, ref fields) |
79         EnumMatching(.., ref fields) => {
80             let mut stmts = vec![];
81             if !is_struct {
82                 // tuple struct/"normal" variant
83                 let expr =
84                     cx.expr_method_call(span, fmt, Ident::from_str("debug_tuple"), vec![name]);
85                 stmts.push(cx.stmt_let(DUMMY_SP, true, builder, expr));
86
87                 for field in fields {
88                     // Use double indirection to make sure this works for unsized types
89                     let field = cx.expr_addr_of(field.span, field.self_.clone());
90                     let field = cx.expr_addr_of(field.span, field);
91
92                     let expr = cx.expr_method_call(span,
93                                                    builder_expr.clone(),
94                                                    Ident::from_str("field"),
95                                                    vec![field]);
96
97                     // Use `let _ = expr;` to avoid triggering the
98                     // unused_results lint.
99                     stmts.push(stmt_let_undescore(cx, span, expr));
100                 }
101             } else {
102                 // normal struct/struct variant
103                 let expr =
104                     cx.expr_method_call(span, fmt, Ident::from_str("debug_struct"), vec![name]);
105                 stmts.push(cx.stmt_let(DUMMY_SP, true, builder, expr));
106
107                 for field in fields {
108                     let name = cx.expr_lit(field.span,
109                                            ast::LitKind::Str(field.name.unwrap().name,
110                                                              ast::StrStyle::Cooked));
111
112                     // Use double indirection to make sure this works for unsized types
113                     let field = cx.expr_addr_of(field.span, field.self_.clone());
114                     let field = cx.expr_addr_of(field.span, field);
115                     let expr = cx.expr_method_call(span,
116                                                    builder_expr.clone(),
117                                                    Ident::from_str("field"),
118                                                    vec![name, field]);
119                     stmts.push(stmt_let_undescore(cx, span, expr));
120                 }
121             }
122             stmts
123         }
124         _ => unreachable!(),
125     };
126
127     let expr = cx.expr_method_call(span, builder_expr, Ident::from_str("finish"), vec![]);
128
129     stmts.push(cx.stmt_expr(expr));
130     let block = cx.block(span, stmts);
131     cx.expr_block(block)
132 }
133
134 fn stmt_let_undescore(cx: &mut ExtCtxt, sp: Span, expr: P<ast::Expr>) -> ast::Stmt {
135     let local = P(ast::Local {
136         pat: cx.pat_wild(sp),
137         ty: None,
138         init: Some(expr),
139         id: ast::DUMMY_NODE_ID,
140         span: sp,
141         attrs: ast::ThinVec::new(),
142     });
143     ast::Stmt {
144         id: ast::DUMMY_NODE_ID,
145         node: ast::StmtKind::Local(local),
146         span: sp,
147     }
148 }