1use std::cell::RefCell;
2
3use rustc_attr_ir::lang_items::LangItem;
4use rustc_hir as hir;
5use rustc_hir::def::DefKind;
6use rustc_hir_analysis::check::check_function_signature;
7use rustc_infer::infer::RegionVariableOrigin;
8use rustc_infer::traits::WellFormedLoc;
9use rustc_lint_defs::builtin::UNSAFE_PANIC_HANDLERS;
10use rustc_middle::ty::{self, Binder, Ty, TyCtxt};
11use rustc_span::def_id::LocalDefId;
12use rustc_span::sym;
13use rustc_trait_selection::traits::{ObligationCause, ObligationCauseCode};
14use tracing::{debug, instrument};
15
16use crate::coercion::CoerceMany;
17use crate::diagnostics::UnsafePanicHandlers;
18use crate::gather_locals::GatherLocalsVisitor;
19use crate::{CoroutineTypes, Diverges, FnCtxt};
20
21{}
#[allow(clippy :: suspicious_else_formatting)]
{
let __tracing_attr_span;
let __tracing_attr_guard;
if ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
&&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() ||
{ false } {
__tracing_attr_span =
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("check_fn",
"rustc_hir_typeck::check", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/28221559263a3976766cf305940e80e30cf9ba8a/compiler/rustc_hir_typeck/src/check.rs"),
::tracing_core::__macro_support::Option::Some(27u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::check"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("fn_sig")
}> =
::tracing::__macro_support::FieldName::new("fn_sig");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("coroutine_types")
}> =
::tracing::__macro_support::FieldName::new("coroutine_types");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("decl")
}> =
::tracing::__macro_support::FieldName::new("decl");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("fn_def_id")
}> =
::tracing::__macro_support::FieldName::new("fn_def_id");
NAME.as_str()
},
{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("params_can_be_unsized")
}> =
::tracing::__macro_support::FieldName::new("params_can_be_unsized");
NAME.as_str()
}], ::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::SPAN)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let mut interest = ::tracing::subscriber::Interest::never();
if ::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{ interest = __CALLSITE.interest(); !interest.is_never() }
&&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest) {
let meta = __CALLSITE.metadata();
::tracing::Span::new(meta,
&{
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
meta.fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_sig)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&coroutine_types)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&decl)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(&::tracing::field::debug(&fn_def_id)
as &dyn ::tracing::field::Value)),
(::tracing::__macro_support::Option::Some(¶ms_can_be_unsized
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[warn(clippy :: suspicious_else_formatting)]
{
#[allow(unknown_lints, unreachable_code, clippy ::
diverging_sub_expression, clippy :: empty_loop, clippy ::
let_unit_value, clippy :: let_with_type_underscore, clippy ::
needless_return, clippy :: unreachable)]
if false {
let __tracing_attr_fake_return: Option<CoroutineTypes<'tcx>> =
loop {};
return __tracing_attr_fake_return;
}
{
let fn_id = fcx.tcx.local_def_id_to_hir_id(fn_def_id);
let tcx = fcx.tcx;
let declared_ret_ty = fn_sig.output();
let ret_ty =
fcx.register_infer_ok_obligations(fcx.infcx.replace_opaque_types_with_inference_vars(declared_ret_ty,
fn_def_id, decl.output.span(), fcx.param_env));
fcx.coroutine_types = coroutine_types;
fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(ret_ty)));
let span = body.value.span;
for param in body.params {
GatherLocalsVisitor::gather_from_param(fcx, param);
}
let maybe_va_list =
fn_sig.c_variadic().then(||
{
let span = body.params.last().unwrap().span;
let va_list_did =
tcx.require_lang_item(LangItem::VaList, span);
let region =
fcx.next_region_var(RegionVariableOrigin::Misc(span));
tcx.type_of(va_list_did).instantiate(tcx,
&[region.into()]).skip_norm_wip()
});
let inputs_hir =
tcx.hir_fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs);
let inputs_fn = fn_sig.inputs().iter().copied();
for (idx, (param_ty, param)) in
inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() {
if fcx.tcx.is_typeck_child(fn_def_id.to_def_id()) {
fcx.register_wf_obligation(param_ty.into(), param.span,
ObligationCauseCode::WellFormed(Some(WellFormedLoc::Param {
function: fn_def_id,
param_idx: idx,
})));
}
let ty: Option<&hir::Ty<'_>> =
inputs_hir.and_then(|h| h.get(idx));
let ty_span = ty.map(|ty| ty.span);
fcx.check_pat_top(param.pat, param_ty, ty_span, None, None);
if param.pat.is_never_pattern() {
fcx.function_diverges_because_of_empty_arguments.set(Diverges::Always {
span: param.pat.span,
custom_note: Some("any code following a never pattern is unreachable"),
});
}
if !params_can_be_unsized ||
fn_sig.abi() == rustc_abi::ExternAbi::RustTail {
fcx.require_type_is_sized(param_ty, param.ty_span,
ObligationCauseCode::SizedArgumentType(if ty_span ==
Some(param.span) && tcx.is_closure_like(fn_def_id.into()) {
None
} else { ty.map(|ty| ty.hir_id) }));
}
fcx.write_ty(param.hir_id, param_ty);
}
fcx.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id,
fn_sig);
if fcx.tcx.is_typeck_child(fn_def_id.to_def_id()) {
let return_or_body_span =
match decl.output {
hir::FnRetTy::DefaultReturn(_) => body.value.span,
hir::FnRetTy::Return(ty) => ty.span,
};
fcx.require_type_is_sized(declared_ret_ty,
return_or_body_span, ObligationCauseCode::SizedReturnType);
}
fcx.is_whole_body.set(true);
fcx.check_return_or_body_tail(body.value, false);
let coercion = fcx.ret_coercion.take().unwrap().into_inner();
let mut actual_return_ty = coercion.complete(fcx);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/28221559263a3976766cf305940e80e30cf9ba8a/compiler/rustc_hir_typeck/src/check.rs:139",
"rustc_hir_typeck::check", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/28221559263a3976766cf305940e80e30cf9ba8a/compiler/rustc_hir_typeck/src/check.rs"),
::tracing_core::__macro_support::Option::Some(139u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::check"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("actual_return_ty = {0:?}",
actual_return_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
if let ty::Dynamic(..) = declared_ret_ty.kind() {
actual_return_ty = fcx.next_ty_var(span);
{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/28221559263a3976766cf305940e80e30cf9ba8a/compiler/rustc_hir_typeck/src/check.rs:145",
"rustc_hir_typeck::check", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/28221559263a3976766cf305940e80e30cf9ba8a/compiler/rustc_hir_typeck/src/check.rs"),
::tracing_core::__macro_support::Option::Some(145u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck::check"),
::tracing_core::field::FieldSet::new(&["message"],
::tracing_core::callsite::Identifier(&__CALLSITE)),
::tracing::metadata::Kind::EVENT)
};
::tracing::callsite::DefaultCallsite::new(&META)
};
let enabled =
::tracing::Level::DEBUG <=
::tracing::level_filters::STATIC_MAX_LEVEL &&
::tracing::Level::DEBUG <=
::tracing::level_filters::LevelFilter::current() &&
{
let interest = __CALLSITE.interest();
!interest.is_never() &&
::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
interest)
};
if enabled {
(|value_set: ::tracing::field::ValueSet|
{
let meta = __CALLSITE.metadata();
::tracing::Event::dispatch(meta, &value_set);
;
})({
#[allow(unused_imports)]
use ::tracing::field::{debug, display, Value};
__CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("actual_return_ty replaced with {0:?}",
actual_return_ty) as &dyn ::tracing::field::Value))])
});
} else { ; }
};
}
fcx.demand_suptype(span, ret_ty, actual_return_ty);
if tcx.is_lang_item(fn_def_id.to_def_id(), LangItem::PanicImpl) {
check_panic_info_fn(tcx, fn_def_id, fn_sig);
}
if tcx.is_lang_item(fn_def_id.to_def_id(), LangItem::Start) {
check_lang_start_fn(tcx, fn_sig, fn_def_id);
}
fcx.coroutine_types
}
}
}#[instrument(skip(fcx, body), level = "debug")]
28pub(super) fn check_fn<'a, 'tcx>(
29 fcx: &mut FnCtxt<'a, 'tcx>,
30 fn_sig: ty::FnSig<'tcx>,
31 coroutine_types: Option<CoroutineTypes<'tcx>>,
32 decl: &'tcx hir::FnDecl<'tcx>,
33 fn_def_id: LocalDefId,
34 body: &'tcx hir::Body<'tcx>,
35 params_can_be_unsized: bool,
36) -> Option<CoroutineTypes<'tcx>> {
37 let fn_id = fcx.tcx.local_def_id_to_hir_id(fn_def_id);
38 let tcx = fcx.tcx;
39 let declared_ret_ty = fn_sig.output();
40 let ret_ty =
41 fcx.register_infer_ok_obligations(fcx.infcx.replace_opaque_types_with_inference_vars(
42 declared_ret_ty,
43 fn_def_id,
44 decl.output.span(),
45 fcx.param_env,
46 ));
47
48 fcx.coroutine_types = coroutine_types;
49 fcx.ret_coercion = Some(RefCell::new(CoerceMany::new(ret_ty)));
50
51 let span = body.value.span;
52
53 for param in body.params {
54 GatherLocalsVisitor::gather_from_param(fcx, param);
55 }
56
57 let maybe_va_list = fn_sig.c_variadic().then(|| {
60 let span = body.params.last().unwrap().span;
61 let va_list_did = tcx.require_lang_item(LangItem::VaList, span);
62 let region = fcx.next_region_var(RegionVariableOrigin::Misc(span));
63
64 tcx.type_of(va_list_did).instantiate(tcx, &[region.into()]).skip_norm_wip()
65 });
66
67 let inputs_hir = tcx.hir_fn_decl_by_hir_id(fn_id).map(|decl| &decl.inputs);
69 let inputs_fn = fn_sig.inputs().iter().copied();
70 for (idx, (param_ty, param)) in inputs_fn.chain(maybe_va_list).zip(body.params).enumerate() {
71 if fcx.tcx.is_typeck_child(fn_def_id.to_def_id()) {
73 fcx.register_wf_obligation(
74 param_ty.into(),
75 param.span,
76 ObligationCauseCode::WellFormed(Some(WellFormedLoc::Param {
77 function: fn_def_id,
78 param_idx: idx,
79 })),
80 );
81 }
82
83 let ty: Option<&hir::Ty<'_>> = inputs_hir.and_then(|h| h.get(idx));
85 let ty_span = ty.map(|ty| ty.span);
86 fcx.check_pat_top(param.pat, param_ty, ty_span, None, None);
87 if param.pat.is_never_pattern() {
88 fcx.function_diverges_because_of_empty_arguments.set(Diverges::Always {
89 span: param.pat.span,
90 custom_note: Some("any code following a never pattern is unreachable"),
91 });
92 }
93
94 if !params_can_be_unsized || fn_sig.abi() == rustc_abi::ExternAbi::RustTail {
96 fcx.require_type_is_sized(
97 param_ty,
98 param.ty_span,
99 ObligationCauseCode::SizedArgumentType(
102 if ty_span == Some(param.span) && tcx.is_closure_like(fn_def_id.into()) {
103 None
104 } else {
105 ty.map(|ty| ty.hir_id)
106 },
107 ),
108 );
109 }
110
111 fcx.write_ty(param.hir_id, param_ty);
112 }
113
114 fcx.typeck_results.borrow_mut().liberated_fn_sigs_mut().insert(fn_id, fn_sig);
115
116 if fcx.tcx.is_typeck_child(fn_def_id.to_def_id()) {
118 let return_or_body_span = match decl.output {
119 hir::FnRetTy::DefaultReturn(_) => body.value.span,
120 hir::FnRetTy::Return(ty) => ty.span,
121 };
122
123 fcx.require_type_is_sized(
124 declared_ret_ty,
125 return_or_body_span,
126 ObligationCauseCode::SizedReturnType,
127 );
128 }
129
130 fcx.is_whole_body.set(true);
131 fcx.check_return_or_body_tail(body.value, false);
132
133 let coercion = fcx.ret_coercion.take().unwrap().into_inner();
138 let mut actual_return_ty = coercion.complete(fcx);
139 debug!("actual_return_ty = {:?}", actual_return_ty);
140 if let ty::Dynamic(..) = declared_ret_ty.kind() {
141 actual_return_ty = fcx.next_ty_var(span);
145 debug!("actual_return_ty replaced with {:?}", actual_return_ty);
146 }
147
148 fcx.demand_suptype(span, ret_ty, actual_return_ty);
153
154 if tcx.is_lang_item(fn_def_id.to_def_id(), LangItem::PanicImpl) {
156 check_panic_info_fn(tcx, fn_def_id, fn_sig);
157 }
158
159 if tcx.is_lang_item(fn_def_id.to_def_id(), LangItem::Start) {
160 check_lang_start_fn(tcx, fn_sig, fn_def_id);
161 }
162
163 fcx.coroutine_types
164}
165
166fn check_panic_info_fn(tcx: TyCtxt<'_>, fn_id: LocalDefId, fn_sig: ty::FnSig<'_>) {
167 let span = tcx.def_span(fn_id);
168
169 let DefKind::Fn = tcx.def_kind(fn_id) else {
170 tcx.dcx().span_err(span, "should be a function");
171 return;
172 };
173
174 let generic_counts = tcx.generics_of(fn_id).own_counts();
175 if generic_counts.types != 0 {
176 tcx.dcx().span_err(span, "should have no type parameters");
177 }
178 if generic_counts.consts != 0 {
179 tcx.dcx().span_err(span, "should have no const parameters");
180 }
181
182 if fn_sig.safety().is_unsafe() {
183 let hir_id = tcx.local_def_id_to_hir_id(fn_id);
184 let span = tcx.def_span(fn_id);
185 if let Some(hir_fn_sig) = tcx.hir_fn_sig_by_hir_id(hir_id)
189 && hir_fn_sig.header.safety == hir::HeaderSafety::SafeTargetFeatures
190 {
191 tcx.dcx().span_delayed_bug(span, "`unsafe_panic_handlers` lint suppressed because there should already be an error for `#[target_feature]`");
192 } else {
193 tcx.emit_node_span_lint(UNSAFE_PANIC_HANDLERS, hir_id, span, UnsafePanicHandlers);
194 }
195 }
196
197 let panic_info_did = tcx.require_lang_item(LangItem::PanicInfo, span);
198
199 let panic_info_ty = tcx
201 .type_of(panic_info_did)
202 .instantiate(
203 tcx,
204 &[ty::GenericArg::from(ty::Region::new_bound(
205 tcx,
206 ty::INNERMOST,
207 ty::BoundRegion { var: ty::BoundVar::from_u32(1), kind: ty::BoundRegionKind::Anon },
208 ))],
209 )
210 .skip_norm_wip();
211 let panic_info_ref_ty = Ty::new_imm_ref(
212 tcx,
213 ty::Region::new_bound(
214 tcx,
215 ty::INNERMOST,
216 ty::BoundRegion { var: ty::BoundVar::ZERO, kind: ty::BoundRegionKind::Anon },
217 ),
218 panic_info_ty,
219 );
220
221 let bounds = tcx.mk_bound_variable_kinds(&[
222 ty::BoundVariableKind::Region(ty::BoundRegionKind::Anon),
223 ty::BoundVariableKind::Region(ty::BoundRegionKind::Anon),
224 ]);
225 let expected_sig = ty::Binder::bind_with_vars(
226 tcx.mk_fn_sig_rust_abi([panic_info_ref_ty], tcx.types.never, fn_sig.safety()),
227 bounds,
228 );
229
230 let _ = check_function_signature(
231 tcx,
232 ObligationCause::new(span, fn_id, ObligationCauseCode::LangFunctionType(sym::panic_impl)),
233 fn_id.into(),
234 expected_sig,
235 );
236}
237
238fn check_lang_start_fn<'tcx>(tcx: TyCtxt<'tcx>, fn_sig: ty::FnSig<'tcx>, def_id: LocalDefId) {
239 let generics = tcx.generics_of(def_id);
245 let fn_generic = generics.param_at(0, tcx);
246 let generic_ty = Ty::new_param(tcx, fn_generic.index, fn_generic.name);
247 let main_fn_ty =
248 Ty::new_fn_ptr(tcx, Binder::dummy(tcx.mk_fn_sig_safe_rust_abi([], generic_ty)));
249
250 let expected_sig = ty::Binder::dummy(tcx.mk_fn_sig_rust_abi(
251 [
252 main_fn_ty,
253 tcx.types.isize,
254 Ty::new_imm_ptr(tcx, Ty::new_imm_ptr(tcx, tcx.types.u8)),
255 tcx.types.u8,
256 ],
257 tcx.types.isize,
258 fn_sig.safety(),
259 ));
260
261 let _ = check_function_signature(
262 tcx,
263 ObligationCause::new(
264 tcx.def_span(def_id),
265 def_id,
266 ObligationCauseCode::LangFunctionType(sym::start),
267 ),
268 def_id.into(),
269 expected_sig,
270 );
271}