rustc_passes/
layout_test.rs1use rustc_abi::{HasDataLayout, TargetDataLayout};
2use rustc_hir::attrs::RustcLayoutType;
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};
9use rustc_span::Span;
10use rustc_span::source_map::Spanned;
11use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
12use rustc_trait_selection::infer::TyCtxtInferExt;
13use rustc_trait_selection::traits;
14
15use crate::errors::{LayoutAbi, LayoutAlign, LayoutHomogeneousAggregate, LayoutOf, LayoutSize};
16
17pub fn test_layout(tcx: TyCtxt<'_>) {
18 if !tcx.features().rustc_attrs() {
19 return;
21 }
22 for id in tcx.hir_crate_items(()).definitions() {
23 if let Some(attrs) = {
#[allow(deprecated)]
{
{
'done:
{
for i in tcx.get_all_attrs(id) {
#[allow(unused_imports)]
use rustc_hir::attrs::AttributeKind::*;
let i: &rustc_hir::Attribute = i;
match i {
rustc_hir::Attribute::Parsed(RustcLayout(attrs)) => {
break 'done Some(attrs);
}
rustc_hir::Attribute::Unparsed(..) =>
{}
#[deny(unreachable_patterns)]
_ => {}
}
}
None
}
}
}
}find_attr!(tcx, id, RustcLayout(attrs) => attrs) {
24 if #[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(id) {
DefKind::TyAlias | DefKind::Enum | DefKind::Struct | DefKind::Union =>
true,
_ => false,
}matches!(
26 tcx.def_kind(id),
27 DefKind::TyAlias | DefKind::Enum | DefKind::Struct | DefKind::Union
28 ) {
29 dump_layout_of(tcx, id, attrs);
30 }
31 }
32 }
33}
34
35pub fn ensure_wf<'tcx>(
36 tcx: TyCtxt<'tcx>,
37 typing_env: ty::TypingEnv<'tcx>,
38 ty: Ty<'tcx>,
39 def_id: LocalDefId,
40 span: Span,
41) -> bool {
42 let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
43 let ocx = traits::ObligationCtxt::new_with_diagnostics(&infcx);
44 let pred = ty::ClauseKind::WellFormed(ty.into());
45 let obligation = traits::Obligation::new(
46 tcx,
47 traits::ObligationCause::new(
48 span,
49 def_id,
50 traits::ObligationCauseCode::WellFormed(Some(traits::WellFormedLoc::Ty(def_id))),
51 ),
52 param_env,
53 pred,
54 );
55 ocx.register_obligation(obligation);
56 let errors = ocx.evaluate_obligations_error_on_ambiguity();
57 if !errors.is_empty() {
58 infcx.err_ctxt().report_fulfillment_errors(errors);
59 false
60 } else {
61 true
63 }
64}
65
66fn dump_layout_of(tcx: TyCtxt<'_>, item_def_id: LocalDefId, attrs: &[RustcLayoutType]) {
67 let typing_env = ty::TypingEnv::post_analysis(tcx, item_def_id);
68 let ty = tcx.type_of(item_def_id).instantiate_identity();
69 let span = tcx.def_span(item_def_id.to_def_id());
70 if !ensure_wf(tcx, typing_env, ty, item_def_id, span) {
71 return;
72 }
73 match tcx.layout_of(typing_env.as_query_input(ty)) {
74 Ok(ty_layout) => {
75 for attr in attrs {
76 match attr {
77 RustcLayoutType::Abi => {
79 tcx.dcx().emit_err(LayoutAbi {
80 span,
81 abi: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty_layout.backend_repr))
})format!("{:?}", ty_layout.backend_repr),
82 });
83 }
84
85 RustcLayoutType::Align => {
86 tcx.dcx().emit_err(LayoutAlign {
87 span,
88 align: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty_layout.align))
})format!("{:?}", ty_layout.align),
89 });
90 }
91
92 RustcLayoutType::Size => {
93 tcx.dcx()
94 .emit_err(LayoutSize { span, size: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}", ty_layout.size))
})format!("{:?}", ty_layout.size) });
95 }
96
97 RustcLayoutType::HomogenousAggregate => {
98 tcx.dcx().emit_err(LayoutHomogeneousAggregate {
99 span,
100 homogeneous_aggregate: ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:?}",
ty_layout.homogeneous_aggregate(&UnwrapLayoutCx {
tcx,
typing_env,
})))
})format!(
101 "{:?}",
102 ty_layout
103 .homogeneous_aggregate(&UnwrapLayoutCx { tcx, typing_env })
104 ),
105 });
106 }
107
108 RustcLayoutType::Debug => {
109 let normalized_ty = tcx.normalize_erasing_regions(typing_env, ty);
110 let ty_layout = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0:#?}", *ty_layout))
})format!("{:#?}", *ty_layout);
112 tcx.dcx().emit_err(LayoutOf { span, normalized_ty, ty_layout });
113 }
114 }
115 }
116 }
117
118 Err(layout_error) => {
119 tcx.dcx().emit_err(Spanned { node: layout_error.into_diagnostic(), span });
120 }
121 }
122}
123
124struct UnwrapLayoutCx<'tcx> {
125 tcx: TyCtxt<'tcx>,
126 typing_env: ty::TypingEnv<'tcx>,
127}
128
129impl<'tcx> LayoutOfHelpers<'tcx> for UnwrapLayoutCx<'tcx> {
130 fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
131 ::rustc_middle::util::bug::span_bug_fmt(span,
format_args!("`#[rustc_layout(..)]` test resulted in `layout_of({0}) = Err({1})`",
ty, err));span_bug!(span, "`#[rustc_layout(..)]` test resulted in `layout_of({ty}) = Err({err})`",);
132 }
133}
134
135impl<'tcx> HasTyCtxt<'tcx> for UnwrapLayoutCx<'tcx> {
136 fn tcx(&self) -> TyCtxt<'tcx> {
137 self.tcx
138 }
139}
140
141impl<'tcx> HasTypingEnv<'tcx> for UnwrapLayoutCx<'tcx> {
142 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
143 self.typing_env
144 }
145}
146
147impl<'tcx> HasDataLayout for UnwrapLayoutCx<'tcx> {
148 fn data_layout(&self) -> &TargetDataLayout {
149 self.tcx.data_layout()
150 }
151}