rustc_passes/
layout_test.rs1use rustc_abi::{HasDataLayout, TargetDataLayout};
2use rustc_hir::attrs::RustcDumpLayoutKind;
3use rustc_hir::def::DefKind;
4use rustc_hir::def_id::LocalDefId;
5use rustc_hir::find_attr;
6use rustc_middle::span_bug;
7use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutError, LayoutOfHelpers};
8use rustc_middle::ty::{self, Ty, TyCtxt, Unnormalized};
9use rustc_span::Span;
10use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
11use rustc_trait_selection::infer::TyCtxtInferExt;
12use rustc_trait_selection::traits::{self, TraitErrors};
13
14pub fn test_layout(tcx: TyCtxt<'_>) {
15 if !tcx.features().rustc_attrs() {
16 return;
18 }
19 for id in tcx.hir_crate_items(()).definitions() {
20 if let Some(kinds) = {
{
'done:
{
for i in ::rustc_attr_ir::HasAttrs::get_attrs(id, &tcx) {
#[allow(unused_imports)]
use ::rustc_attr_ir::AttributeKind::*;
let i: &::rustc_attr_ir::Attribute = i;
match i {
::rustc_attr_ir::Attribute::Parsed(RustcDumpLayout(kinds))
=> {
break 'done Some(kinds);
}
::rustc_attr_ir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}find_attr!(tcx, id, RustcDumpLayout(kinds) => kinds) {
21 if let DefKind::TyAlias | DefKind::Enum | DefKind::Struct | DefKind::Union =
23 tcx.def_kind(id)
24 {
25 dump_layout_of(tcx, id, kinds);
26 }
27 }
28 }
29}
30
31pub fn ensure_wf<'tcx>(
32 tcx: TyCtxt<'tcx>,
33 typing_env: ty::TypingEnv<'tcx>,
34 ty: Ty<'tcx>,
35 def_id: LocalDefId,
36 span: Span,
37) -> bool {
38 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
39 let ocx = traits::ObligationCtxt::new_with_diagnostics(&infcx);
40 let pred = ty::ClauseKind::WellFormed(ty.into());
41 let obligation = traits::Obligation::new(
42 tcx,
43 traits::ObligationCause::new(
44 span,
45 def_id,
46 traits::ObligationCauseCode::WellFormed(Some(traits::WellFormedLoc::Ty(def_id))),
47 ),
48 param_env,
49 pred,
50 );
51 ocx.register_obligation(obligation);
52 let errors = ocx.evaluate_obligations_error_on_ambiguity();
53 if let TraitErrors::HasErrors(errors) = errors {
54 infcx.err_ctxt().report_fulfillment_errors(errors);
55 false
56 } else {
57 true
59 }
60}
61
62fn dump_layout_of(tcx: TyCtxt<'_>, item_def_id: LocalDefId, kinds: &[RustcDumpLayoutKind]) {
63 let typing_env = ty::TypingEnv::codegen(tcx, item_def_id);
64 let ty = tcx.type_of(item_def_id).instantiate_identity().skip_norm_wip();
65 let span = tcx.def_span(item_def_id.to_def_id());
66 if !ensure_wf(tcx, typing_env, ty, item_def_id, span) {
67 return;
68 }
69 match tcx.layout_of(typing_env.as_query_input(ty)) {
70 Ok(ty_layout) => {
71 for kind in kinds {
72 let message = match kind {
73 RustcDumpLayoutKind::Align => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("align: {0:?}", *ty_layout.align))
})format!("align: {:?}", *ty_layout.align),
74 RustcDumpLayoutKind::BackendRepr => {
75 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("backend_repr: {0:?}",
ty_layout.backend_repr))
})format!("backend_repr: {:?}", ty_layout.backend_repr)
76 }
77 RustcDumpLayoutKind::Debug => {
78 let normalized_ty =
79 tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty));
80 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("layout_of({1}) = {0:#?}",
*ty_layout, normalized_ty))
})format!("layout_of({normalized_ty}) = {:#?}", *ty_layout)
82 }
83 RustcDumpLayoutKind::HomogenousAggregate => {
84 let data =
85 ty_layout.homogeneous_aggregate(&UnwrapLayoutCx { tcx, typing_env });
86 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("homogeneous_aggregate: {0:?}",
data))
})format!("homogeneous_aggregate: {data:?}")
87 }
88 RustcDumpLayoutKind::LargestNiche => {
89 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("largest_niche: {0:?}",
ty_layout.largest_niche))
})format!("largest_niche: {:?}", ty_layout.largest_niche)
90 }
91 RustcDumpLayoutKind::Size => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("size: {0:?}", ty_layout.size))
})format!("size: {:?}", ty_layout.size),
92 };
93 tcx.dcx().span_err(span, message);
94 }
95 }
96
97 Err(layout_error) => {
98 tcx.dcx().span_err(span, layout_error.to_string());
99 }
100 }
101}
102
103struct UnwrapLayoutCx<'tcx> {
104 tcx: TyCtxt<'tcx>,
105 typing_env: ty::TypingEnv<'tcx>,
106}
107
108impl<'tcx> LayoutOfHelpers<'tcx> for UnwrapLayoutCx<'tcx> {
109 fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
110 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("`#[rustc_dump_layout(..)]` test resulted in `layout_of({0}) = Err({1})`",
ty, err));span_bug!(
111 span,
112 "`#[rustc_dump_layout(..)]` test resulted in `layout_of({ty}) = Err({err})`",
113 );
114 }
115}
116
117impl<'tcx> HasTyCtxt<'tcx> for UnwrapLayoutCx<'tcx> {
118 fn tcx(&self) -> TyCtxt<'tcx> {
119 self.tcx
120 }
121}
122
123impl<'tcx> HasTypingEnv<'tcx> for UnwrapLayoutCx<'tcx> {
124 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
125 self.typing_env
126 }
127}
128
129impl<'tcx> HasDataLayout for UnwrapLayoutCx<'tcx> {
130 fn data_layout(&self) -> &TargetDataLayout {
131 self.tcx.data_layout()
132 }
133}