-
-
Notifications
You must be signed in to change notification settings - Fork 14.9k
Expand file tree
/
Copy pathdebug.rs
More file actions
397 lines (363 loc) · 14.3 KB
/
debug.rs
File metadata and controls
397 lines (363 loc) · 14.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
use rustc_ast::{self as ast, EnumDef, ExprKind, MetaItem, Safety, TyKind, token};
use rustc_expand::base::{Annotatable, ExtCtxt};
use rustc_session::config::FmtDebug;
use rustc_span::{Ident, Span, Symbol, sym};
use thin_vec::{ThinVec, thin_vec};
use crate::deriving::generic::ty::*;
use crate::deriving::generic::*;
use crate::deriving::path_std;
pub(crate) fn expand_deriving_debug(
cx: &ExtCtxt<'_>,
span: Span,
mitem: &MetaItem,
item: &Annotatable,
push: &mut dyn FnMut(Annotatable),
is_const: bool,
) {
// &mut ::std::fmt::Formatter
let fmtr = Ref(Box::new(Path(path_std!(fmt::Formatter))), ast::Mutability::Mut);
let trait_def = TraitDef {
span,
path: path_std!(fmt::Debug),
skip_path_as_bound: false,
needs_copy_as_bound_if_packed: true,
additional_bounds: Vec::new(),
supports_unions: false,
methods: vec![MethodDef {
name: sym::fmt,
generics: Bounds::empty(),
explicit_self: true,
nonself_args: vec![(fmtr, sym::character('f'))],
ret_ty: Path(path_std!(fmt::Result)),
attributes: thin_vec![cx.attr_word(sym::inline, span)],
fieldless_variants_strategy:
FieldlessVariantsStrategy::SpecializeIfAllVariantsFieldless,
combine_substructure: combine_substructure(Box::new(|a, b, c| {
show_substructure(a, b, c)
})),
}],
associated_types: Vec::new(),
is_const,
is_staged_api_crate: cx.ecfg.features.staged_api(),
safety: Safety::Default,
document: true,
};
trait_def.expand(cx, mitem, item, push)
}
fn show_substructure(cx: &ExtCtxt<'_>, span: Span, substr: &Substructure<'_>) -> BlockOrExpr {
// We want to make sure we have the ctxt set so that we can use unstable methods
let span = cx.with_def_site_ctxt(span);
let fmt_detail = cx.sess.opts.unstable_opts.fmt_debug;
if fmt_detail == FmtDebug::None {
return BlockOrExpr::new_expr(cx.expr_ok(span, cx.expr_tuple(span, ThinVec::new())));
}
let (ident, vdata, fields) = match substr.fields {
Struct(vdata, fields) => (substr.type_ident, *vdata, fields),
EnumMatching(v, fields) => (v.ident, &v.data, fields),
AllFieldlessEnum(enum_def) => return show_fieldless_enum(cx, span, enum_def, substr),
EnumDiscr(..) | StaticStruct(..) | StaticEnum(..) => {
cx.dcx().span_bug(span, "nonsensical .fields in `#[derive(Debug)]`")
}
};
let name = cx.expr_str(span, ident.name);
let fmt = substr.nonselflike_args[0].clone();
// Fieldless enums have been special-cased earlier
if fmt_detail == FmtDebug::Shallow {
let fn_path_write_str = cx.std_path(&[sym::fmt, sym::Formatter, sym::write_str]);
let expr = cx.expr_call_global(span, fn_path_write_str, thin_vec![fmt, name]);
return BlockOrExpr::new_expr(expr);
}
// Struct and tuples are similar enough that we use the same code for both,
// with some extra pieces for structs due to the field names.
let (is_struct, args_per_field) = match vdata {
ast::VariantData::Unit(..) => {
// Special fast path for unit variants.
assert!(fields.is_empty());
(false, 0)
}
ast::VariantData::Tuple(..) => (false, 1),
ast::VariantData::Struct { .. } => (true, 2),
};
// The number of fields that can be handled without an array.
const CUTOFF: usize = 5;
fn expr_for_field(
cx: &ExtCtxt<'_>,
field: &FieldInfo,
index: usize,
len: usize,
) -> Box<ast::Expr> {
if index < len - 1 {
field.self_expr.clone()
} else {
// Unsized types need an extra indirection, but only the last field
// may be unsized.
cx.expr_addr_of(field.span, field.self_expr.clone())
}
}
if fields.is_empty() {
// Special case for no fields.
let fn_path_write_str = cx.std_path(&[sym::fmt, sym::Formatter, sym::write_str]);
let expr = cx.expr_call_global(span, fn_path_write_str, thin_vec![fmt, name]);
BlockOrExpr::new_expr(expr)
} else if fields.len() <= CUTOFF {
// Few enough fields that we can use a specific-length method.
let debug = if is_struct {
format!("debug_struct_field{}_finish", fields.len())
} else {
format!("debug_tuple_field{}_finish", fields.len())
};
let fn_path_debug = cx.std_path(&[sym::fmt, sym::Formatter, Symbol::intern(&debug)]);
let mut args = ThinVec::with_capacity(2 + fields.len() * args_per_field);
args.extend([fmt, name]);
for i in 0..fields.len() {
let field = &fields[i];
if is_struct {
let name = cx.expr_str(field.span, field.name.unwrap().name);
args.push(name);
}
let field = expr_for_field(cx, field, i, fields.len());
args.push(field);
}
let expr = cx.expr_call_global(span, fn_path_debug, args);
BlockOrExpr::new_expr(expr)
} else {
// Enough fields that we must use the any-length method.
let mut name_exprs = ThinVec::with_capacity(fields.len());
let mut value_exprs = ThinVec::with_capacity(fields.len());
for i in 0..fields.len() {
let field = &fields[i];
if is_struct {
name_exprs.push(cx.expr_str(field.span, field.name.unwrap().name));
}
let field = expr_for_field(cx, field, i, fields.len());
value_exprs.push(field);
}
// `let names: &'static _ = &["field1", "field2"];`
let names_let = is_struct.then(|| {
let lt_static = Some(cx.lifetime_static(span));
let ty_static_ref = cx.ty_ref(span, cx.ty_infer(span), lt_static, ast::Mutability::Not);
cx.stmt_let_ty(
span,
false,
Ident::new(sym::names, span),
Some(ty_static_ref),
cx.expr_array_ref(span, name_exprs),
)
});
// `let values: &[&dyn Debug] = &[&&self.field1, &&self.field2];`
let path_debug = cx.path_global(span, cx.std_path(&[sym::fmt, sym::Debug]));
let ty_dyn_debug = cx.ty(
span,
TyKind::TraitObject(
vec![cx.trait_bound(path_debug, false)],
ast::TraitObjectSyntax::Dyn,
),
);
let ty_slice =
cx.ty(span, TyKind::Slice(cx.ty_ref(span, ty_dyn_debug, None, ast::Mutability::Not)));
let values_let = cx.stmt_let_ty(
span,
false,
Ident::new(sym::values, span),
Some(cx.ty_ref(span, ty_slice, None, ast::Mutability::Not)),
cx.expr_array_ref(span, value_exprs),
);
// `fmt::Formatter::debug_struct_fields_finish(fmt, name, names, values)` or
// `fmt::Formatter::debug_tuple_fields_finish(fmt, name, values)`
let sym_debug = if is_struct {
sym::debug_struct_fields_finish
} else {
sym::debug_tuple_fields_finish
};
let fn_path_debug_internal = cx.std_path(&[sym::fmt, sym::Formatter, sym_debug]);
let mut args = ThinVec::with_capacity(4);
args.push(fmt);
args.push(name);
if is_struct {
args.push(cx.expr_ident(span, Ident::new(sym::names, span)));
}
args.push(cx.expr_ident(span, Ident::new(sym::values, span)));
let expr = cx.expr_call_global(span, fn_path_debug_internal, args);
let mut stmts = ThinVec::with_capacity(2);
if is_struct {
stmts.push(names_let.unwrap());
}
stmts.push(values_let);
BlockOrExpr::new_mixed(stmts, Some(expr))
}
}
/// Special case for enums with no fields. Builds:
/// ```text
/// impl ::core::fmt::Debug for A {
/// fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
/// ::core::fmt::Formatter::write_str(f,
/// match self {
/// A::A => "A",
/// A::B() => "B",
/// A::C {} => "C",
/// })
/// }
/// }
/// ```
fn show_fieldless_enum(
cx: &ExtCtxt<'_>,
span: Span,
def: &EnumDef,
substr: &Substructure<'_>,
) -> BlockOrExpr {
let fmt = substr.nonselflike_args[0].clone();
let fn_path_write_str = cx.std_path(&[sym::fmt, sym::Formatter, sym::write_str]);
if let Some(name) = show_fieldless_enum_concat_str(cx, span, def) {
return BlockOrExpr::new_expr(cx.expr_call_global(
span,
fn_path_write_str,
thin_vec![fmt, name],
));
}
let arms = def
.variants
.iter()
.map(|v| {
let variant_path = cx.path(span, vec![substr.type_ident, v.ident]);
let pat = match &v.data {
ast::VariantData::Tuple(fields, _) => {
debug_assert!(fields.is_empty());
cx.pat_tuple_struct(span, variant_path, ThinVec::new())
}
ast::VariantData::Struct { fields, .. } => {
debug_assert!(fields.is_empty());
cx.pat_struct(span, variant_path, ThinVec::new())
}
ast::VariantData::Unit(_) => cx.pat_path(span, variant_path),
};
cx.arm(span, pat, cx.expr_str(span, v.ident.name))
})
.collect::<ThinVec<_>>();
let name = cx.expr_match(span, cx.expr_self(span), arms);
BlockOrExpr::new_expr(cx.expr_call_global(span, fn_path_write_str, thin_vec![fmt, name]))
}
/// Specialer case for fieldless enums with no discriminants. Builds
/// ```text
/// impl ::core::fmt::Debug for A {
/// fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
/// ::core::fmt::Formatter::write_str(f, {
/// const __NAMES: &str = "ABBBCC";
/// const __OFFSET: [usize; 4] =[0, 1, 4, 6];
/// let __d = ::core::intrinsics::discriminant_value(self) as usize;
/// __NAMES[__OFFSET[d]..__OFFSET[d + 1]]
/// })
/// }
/// }
/// ```
fn show_fieldless_enum_concat_str(
cx: &ExtCtxt<'_>,
span: Span,
def: &EnumDef,
) -> Option<Box<ast::Expr>> {
let variant_count = def.variants.len();
if variant_count >= cx.sess.target.pointer_width as usize {
return None;
}
let variant_names = def
.variants
.iter()
.map(|v| v.disr_expr.is_none().then_some(v.ident.name.as_str()))
.collect::<Option<ThinVec<_>>>()?;
let total_bytes: usize = variant_names.iter().map(|n| n.len()).sum();
let mut concatenated_names = String::with_capacity(total_bytes);
let mut offset_indices = Vec::with_capacity(variant_names.len() + 1);
offset_indices.push(0);
for name in variant_names.iter() {
concatenated_names.push_str(name);
offset_indices.push(concatenated_names.len());
}
// Create the constant concatenated string
let names_ident = Ident::from_str_and_span("__NAMES", span);
let str_ty = cx.ty(
span,
TyKind::Ref(
None,
ast::MutTy {
ty: cx.ty(
span,
TyKind::Path(None, ast::Path::from_ident(Ident::new(sym::str, span))),
),
mutbl: ast::Mutability::Not,
},
),
);
let names_str_expr =
ast::ConstItemRhsKind::new_body(cx.expr_str(span, Symbol::intern(&concatenated_names)));
let names_const_item = cx.item_const(span, names_ident, str_ty, names_str_expr);
// Create the constant offset array
let offset_ident = Ident::from_str_and_span("__OFFSET", span);
let offset_index_exprs =
offset_indices.iter().map(|s| cx.expr_usize(span, *s)).collect::<ThinVec<_>>();
let starts_array_expr =
ast::ConstItemRhsKind::new_body(cx.expr_array(span, offset_index_exprs));
let usize_ty =
cx.ty(span, TyKind::Path(None, ast::Path::from_ident(Ident::new(sym::usize, span))));
let offset_array_len_expr = cx.anon_const(
span,
ExprKind::Lit(token::Lit::new(
token::LitKind::Integer,
Symbol::intern(&(variant_count + 1).to_string()),
None,
)),
);
let offset_const_item = cx.item_const(
span,
offset_ident,
cx.ty(span, TyKind::Array(usize_ty, offset_array_len_expr)),
starts_array_expr,
);
// let __d = ::core::intrinsics::discriminant_value(self) as usize;
let discriminant_ident = Ident::from_str_and_span("__d", span);
let discriminant_intrinsic_path = cx.std_path(&[sym::intrinsics, sym::discriminant_value]);
let discriminant_cast_expr = cx.expr(
span,
ast::ExprKind::Cast(
cx.expr_call_global(span, discriminant_intrinsic_path, thin_vec![cx.expr_self(span)]),
cx.ty_path(ast::Path::from_ident(Ident::new(sym::usize, span))),
),
);
let discriminant_let_stmt =
cx.stmt_let(span, false, discriminant_ident, discriminant_cast_expr);
// __OFFSET[__d]
let discriminant_expr = cx.expr_ident(span, discriminant_ident);
let start_index_expr = cx.expr(
span,
ExprKind::Index(cx.expr_ident(span, offset_ident), discriminant_expr.clone(), span),
);
// __OFFSET[__d + 1]
let one_expr = cx.expr_usize(span, 1);
let discriminant_plus_one_expr =
cx.expr_binary(span, ast::BinOpKind::Add, discriminant_expr, one_expr);
let end_index_expr = cx.expr(
span,
ExprKind::Index(cx.expr_ident(span, offset_ident), discriminant_plus_one_expr, span),
);
// __OFFSET[__d]..__OFFSET[__d + 1]
let slice_range_expr = cx.expr(
span,
ExprKind::Range(
Some(start_index_expr),
Some(end_index_expr),
rustc_ast::RangeLimits::HalfOpen,
),
);
// &__NAMES[__STARTS[__d]..__STARTS[__d + 1]]
let name_slice_expr = cx.expr_addr_of(
span,
cx.expr(span, ExprKind::Index(cx.expr_ident(span, names_ident), slice_range_expr, span)),
);
Some(cx.expr_block(cx.block(
span,
thin_vec![
cx.stmt_item(span, names_const_item),
cx.stmt_item(span, offset_const_item),
discriminant_let_stmt,
cx.stmt_expr(name_slice_expr)
],
)))
}