]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_builtin_macros/src/deriving/debug.rs
Test drop_tracking_mir before querying generator.
[rust.git] / compiler / rustc_builtin_macros / src / deriving / debug.rs
1 use crate::deriving::generic::ty::*;
2 use crate::deriving::generic::*;
3 use crate::deriving::path_std;
4
5 use ast::EnumDef;
6 use rustc_ast::{self as ast, MetaItem};
7 use rustc_expand::base::{Annotatable, ExtCtxt};
8 use rustc_span::symbol::{sym, Ident, Symbol};
9 use rustc_span::Span;
10
11 pub fn expand_deriving_debug(
12     cx: &mut ExtCtxt<'_>,
13     span: Span,
14     mitem: &MetaItem,
15     item: &Annotatable,
16     push: &mut dyn FnMut(Annotatable),
17     is_const: bool,
18 ) {
19     // &mut ::std::fmt::Formatter
20     let fmtr = Ref(Box::new(Path(path_std!(fmt::Formatter))), ast::Mutability::Mut);
21
22     let trait_def = TraitDef {
23         span,
24         path: path_std!(fmt::Debug),
25         skip_path_as_bound: false,
26         additional_bounds: Vec::new(),
27         supports_unions: false,
28         methods: vec![MethodDef {
29             name: sym::fmt,
30             generics: Bounds::empty(),
31             explicit_self: true,
32             nonself_args: vec![(fmtr, sym::f)],
33             ret_ty: Path(path_std!(fmt::Result)),
34             attributes: ast::AttrVec::new(),
35             fieldless_variants_strategy:
36                 FieldlessVariantsStrategy::SpecializeIfAllVariantsFieldless,
37             combine_substructure: combine_substructure(Box::new(|a, b, c| {
38                 show_substructure(a, b, c)
39             })),
40         }],
41         associated_types: Vec::new(),
42         is_const,
43     };
44     trait_def.expand(cx, mitem, item, push)
45 }
46
47 fn show_substructure(cx: &mut ExtCtxt<'_>, span: Span, substr: &Substructure<'_>) -> BlockOrExpr {
48     // We want to make sure we have the ctxt set so that we can use unstable methods
49     let span = cx.with_def_site_ctxt(span);
50
51     let (ident, vdata, fields) = match substr.fields {
52         Struct(vdata, fields) => (substr.type_ident, *vdata, fields),
53         EnumMatching(_, _, v, fields) => (v.ident, &v.data, fields),
54         AllFieldlessEnum(enum_def) => return show_fieldless_enum(cx, span, enum_def, substr),
55         EnumTag(..) | StaticStruct(..) | StaticEnum(..) => {
56             cx.span_bug(span, "nonsensical .fields in `#[derive(Debug)]`")
57         }
58     };
59
60     let name = cx.expr_str(span, ident.name);
61     let fmt = substr.nonselflike_args[0].clone();
62
63     // Struct and tuples are similar enough that we use the same code for both,
64     // with some extra pieces for structs due to the field names.
65     let (is_struct, args_per_field) = match vdata {
66         ast::VariantData::Unit(..) => {
67             // Special fast path for unit variants.
68             assert!(fields.is_empty());
69             (false, 0)
70         }
71         ast::VariantData::Tuple(..) => (false, 1),
72         ast::VariantData::Struct(..) => (true, 2),
73     };
74
75     // The number of fields that can be handled without an array.
76     const CUTOFF: usize = 5;
77
78     if fields.is_empty() {
79         // Special case for no fields.
80         let fn_path_write_str = cx.std_path(&[sym::fmt, sym::Formatter, sym::write_str]);
81         let expr = cx.expr_call_global(span, fn_path_write_str, vec![fmt, name]);
82         BlockOrExpr::new_expr(expr)
83     } else if fields.len() <= CUTOFF {
84         // Few enough fields that we can use a specific-length method.
85         let debug = if is_struct {
86             format!("debug_struct_field{}_finish", fields.len())
87         } else {
88             format!("debug_tuple_field{}_finish", fields.len())
89         };
90         let fn_path_debug = cx.std_path(&[sym::fmt, sym::Formatter, Symbol::intern(&debug)]);
91
92         let mut args = Vec::with_capacity(2 + fields.len() * args_per_field);
93         args.extend([fmt, name]);
94         for i in 0..fields.len() {
95             let field = &fields[i];
96             if is_struct {
97                 let name = cx.expr_str(field.span, field.name.unwrap().name);
98                 args.push(name);
99             }
100             // Use an extra indirection to make sure this works for unsized types.
101             let field = cx.expr_addr_of(field.span, field.self_expr.clone());
102             args.push(field);
103         }
104         let expr = cx.expr_call_global(span, fn_path_debug, args);
105         BlockOrExpr::new_expr(expr)
106     } else {
107         // Enough fields that we must use the any-length method.
108         let mut name_exprs = Vec::with_capacity(fields.len());
109         let mut value_exprs = Vec::with_capacity(fields.len());
110
111         for field in fields {
112             if is_struct {
113                 name_exprs.push(cx.expr_str(field.span, field.name.unwrap().name));
114             }
115
116             // Use an extra indirection to make sure this works for unsized types.
117             let field = cx.expr_addr_of(field.span, field.self_expr.clone());
118             value_exprs.push(field);
119         }
120
121         // `let names: &'static _ = &["field1", "field2"];`
122         let names_let = if is_struct {
123             let lt_static = Some(cx.lifetime_static(span));
124             let ty_static_ref = cx.ty_ref(span, cx.ty_infer(span), lt_static, ast::Mutability::Not);
125             Some(cx.stmt_let_ty(
126                 span,
127                 false,
128                 Ident::new(sym::names, span),
129                 Some(ty_static_ref),
130                 cx.expr_array_ref(span, name_exprs),
131             ))
132         } else {
133             None
134         };
135
136         // `let values: &[&dyn Debug] = &[&&self.field1, &&self.field2];`
137         let path_debug = cx.path_global(span, cx.std_path(&[sym::fmt, sym::Debug]));
138         let ty_dyn_debug = cx.ty(
139             span,
140             ast::TyKind::TraitObject(vec![cx.trait_bound(path_debug)], ast::TraitObjectSyntax::Dyn),
141         );
142         let ty_slice = cx.ty(
143             span,
144             ast::TyKind::Slice(cx.ty_ref(span, ty_dyn_debug, None, ast::Mutability::Not)),
145         );
146         let values_let = cx.stmt_let_ty(
147             span,
148             false,
149             Ident::new(sym::values, span),
150             Some(cx.ty_ref(span, ty_slice, None, ast::Mutability::Not)),
151             cx.expr_array_ref(span, value_exprs),
152         );
153
154         // `fmt::Formatter::debug_struct_fields_finish(fmt, name, names, values)` or
155         // `fmt::Formatter::debug_tuple_fields_finish(fmt, name, values)`
156         let sym_debug = if is_struct {
157             sym::debug_struct_fields_finish
158         } else {
159             sym::debug_tuple_fields_finish
160         };
161         let fn_path_debug_internal = cx.std_path(&[sym::fmt, sym::Formatter, sym_debug]);
162
163         let mut args = Vec::with_capacity(4);
164         args.push(fmt);
165         args.push(name);
166         if is_struct {
167             args.push(cx.expr_ident(span, Ident::new(sym::names, span)));
168         }
169         args.push(cx.expr_ident(span, Ident::new(sym::values, span)));
170         let expr = cx.expr_call_global(span, fn_path_debug_internal, args);
171
172         let mut stmts = Vec::with_capacity(3);
173         if is_struct {
174             stmts.push(names_let.unwrap());
175         }
176         stmts.push(values_let);
177         BlockOrExpr::new_mixed(stmts, Some(expr))
178     }
179 }
180
181 /// Special case for enums with no fields. Builds:
182 /// ```text
183 /// impl ::core::fmt::Debug for A {
184 ///     fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
185 ///          ::core::fmt::Formatter::write_str(f,
186 ///             match self {
187 ///                 A::A => "A",
188 ///                 A::B() => "B",
189 ///                 A::C {} => "C",
190 ///             })
191 ///     }
192 /// }
193 /// ```
194 fn show_fieldless_enum(
195     cx: &mut ExtCtxt<'_>,
196     span: Span,
197     def: &EnumDef,
198     substr: &Substructure<'_>,
199 ) -> BlockOrExpr {
200     let fmt = substr.nonselflike_args[0].clone();
201     let arms = def
202         .variants
203         .iter()
204         .map(|v| {
205             let variant_path = cx.path(span, vec![substr.type_ident, v.ident]);
206             let pat = match &v.data {
207                 ast::VariantData::Tuple(fields, _) => {
208                     debug_assert!(fields.is_empty());
209                     cx.pat_tuple_struct(span, variant_path, vec![])
210                 }
211                 ast::VariantData::Struct(fields, _) => {
212                     debug_assert!(fields.is_empty());
213                     cx.pat_struct(span, variant_path, vec![])
214                 }
215                 ast::VariantData::Unit(_) => cx.pat_path(span, variant_path),
216             };
217             cx.arm(span, pat, cx.expr_str(span, v.ident.name))
218         })
219         .collect::<Vec<_>>();
220     let name = cx.expr_match(span, cx.expr_self(span), arms);
221     let fn_path_write_str = cx.std_path(&[sym::fmt, sym::Formatter, sym::write_str]);
222     BlockOrExpr::new_expr(cx.expr_call_global(span, fn_path_write_str, vec![fmt, name]))
223 }