]> git.lizzy.rs Git - rust.git/blob - src/libsyntax_ext/deriving/debug.rs
Auto merge of #52046 - cramertj:fix-generator-mir, r=eddyb
[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::path_std;
12 use deriving::generic::*;
13 use deriving::generic::ty::*;
14
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;
19 use syntax::ptr::P;
20 use syntax_pos::{DUMMY_SP, Span};
21
22 pub fn expand_deriving_debug(cx: &mut ExtCtxt,
23                              span: Span,
24                              mitem: &MetaItem,
25                              item: &Annotatable,
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));
30
31     let trait_def = TraitDef {
32         span,
33         attributes: Vec::new(),
34         path: path_std!(cx, fmt::Debug),
35         additional_bounds: Vec::new(),
36         generics: LifetimeBounds::empty(),
37         is_unsafe: false,
38         supports_unions: false,
39         methods: vec![MethodDef {
40                           name: "fmt",
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(),
46                           is_unsafe: false,
47                           unify_fieldless_variants: false,
48                           combine_substructure: combine_substructure(Box::new(|a, b, c| {
49                               show_substructure(a, b, c)
50                           })),
51                       }],
52         associated_types: Vec::new(),
53     };
54     trait_def.expand(cx, mitem, item, push)
55 }
56
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(..) |
66         StaticStruct(..) |
67         StaticEnum(..) => cx.span_bug(span, "nonsensical .fields in `#[derive(Debug)]`"),
68     };
69
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());
75
76     let fmt = substr.nonself_args[0].clone();
77
78     let mut stmts = match *substr.fields {
79         Struct(_, ref fields) |
80         EnumMatching(.., ref fields) => {
81             let mut stmts = vec![];
82             if !is_struct {
83                 // tuple struct/"normal" variant
84                 let expr =
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));
87
88                 for field in fields {
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);
92
93                     let expr = cx.expr_method_call(span,
94                                                    builder_expr.clone(),
95                                                    Ident::from_str("field"),
96                                                    vec![field]);
97
98                     // Use `let _ = expr;` to avoid triggering the
99                     // unused_results lint.
100                     stmts.push(stmt_let_undescore(cx, span, expr));
101                 }
102             } else {
103                 // normal struct/struct variant
104                 let expr =
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));
107
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));
112
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"),
119                                                    vec![name, field]);
120                     stmts.push(stmt_let_undescore(cx, span, expr));
121                 }
122             }
123             stmts
124         }
125         _ => unreachable!(),
126     };
127
128     let expr = cx.expr_method_call(span, builder_expr, Ident::from_str("finish"), vec![]);
129
130     stmts.push(cx.stmt_expr(expr));
131     let block = cx.block(span, stmts);
132     cx.expr_block(block)
133 }
134
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),
138         ty: None,
139         init: Some(expr),
140         id: ast::DUMMY_NODE_ID,
141         span: sp,
142         attrs: ast::ThinVec::new(),
143     });
144     ast::Stmt {
145         id: ast::DUMMY_NODE_ID,
146         node: ast::StmtKind::Local(local),
147         span: sp,
148     }
149 }