1#![feature(deref_patterns)]
3#![feature(iter_intersperse)]
4#![feature(iter_order_by)]
5#![feature(option_into_flat_iter)]
6#![feature(option_reference_flattening)]
7mod _match;
10mod autoderef;
11mod callee;
12pub mod cast;
14mod check;
15mod closure;
16mod coercion;
17mod demand;
18mod diagnostics;
19mod diverges;
20mod expectation;
21mod expr;
22mod inline_asm;
23pub mod expr_use_visitor;
25mod fallback;
26mod fn_ctxt;
27mod gather_locals;
28mod intrinsicck;
29mod loops;
30mod method;
31mod naked_functions;
32mod op;
33mod opaque_types;
34mod pat;
35mod place_op;
36mod typeck_root_ctxt;
37mod upvar;
38mod writeback;
39
40pub use coercion::can_coerce;
41use fn_ctxt::FnCtxt;
42use rustc_data_structures::unord::UnordSet;
43use rustc_errors::codes::*;
44use rustc_errors::{Applicability, Diag, ErrorGuaranteed, struct_span_code_err};
45use rustc_hir as hir;
46use rustc_hir::def::{DefKind, Res};
47use rustc_hir::{HirId, HirIdMap, Node};
48use rustc_hir_analysis::check::check_abi;
49use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
50use rustc_infer::traits::{ObligationCauseCode, ObligationInspector, TraitEngine, WellFormedLoc};
51use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
52use rustc_middle::query::Providers;
53use rustc_middle::ty::{self, FnSigKind, Ty, TyCtxt, Unnormalized};
54use rustc_session::config;
55use rustc_span::def_id::LocalDefId;
56use rustc_span::{Span, bug, span_bug};
57use tracing::{debug, instrument};
58use typeck_root_ctxt::TypeckRootCtxt;
59
60use crate::check::check_fn;
61use crate::coercion::CoerceMany;
62use crate::diverges::Diverges;
63use crate::expectation::Expectation;
64use crate::fn_ctxt::LoweredTy;
65use crate::gather_locals::GatherLocalsVisitor;
66
67#[macro_export]
68macro_rules! type_error_struct {
69 ($dcx:expr, $span:expr, $typ:expr, $code:expr, $($message:tt)*) => ({
70 let mut err = rustc_errors::struct_span_code_err!($dcx, $span, $code, $($message)*);
71
72 if $typ.references_error() {
73 err.downgrade_to_delayed_bug();
74 }
75
76 err
77 })
78}
79
80fn used_trait_imports(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &UnordSet<LocalDefId> {
81 &tcx.typeck(def_id).used_trait_imports
82}
83
84fn typeck_root<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ty::TypeckResults<'tcx> {
85 typeck_with_inspect(tcx, def_id, None)
86}
87
88pub fn inspect_typeck<'tcx>(
93 tcx: TyCtxt<'tcx>,
94 def_id: LocalDefId,
95 inspect: ObligationInspector<'tcx>,
96) -> &'tcx ty::TypeckResults<'tcx> {
97 let typeck_root_def_id = tcx.typeck_root_def_id_local(def_id);
100 if typeck_root_def_id != def_id {
101 return tcx.typeck(typeck_root_def_id);
102 }
103
104 typeck_with_inspect(tcx, def_id, Some(inspect))
105}
106
107{}
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("typeck_with_inspect",
"rustc_hir_typeck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/28221559263a3976766cf305940e80e30cf9ba8a/compiler/rustc_hir_typeck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(107u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("def_id")
}> =
::tracing::__macro_support::FieldName::new("def_id");
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(&def_id)
as &dyn ::tracing::field::Value))])
})
} else {
let span =
::tracing::__macro_support::__disabled_span(__CALLSITE.metadata());
{};
span
}
};
__tracing_attr_guard = __tracing_attr_span.enter();
}
#[allow(clippy :: redundant_closure_call)]
let x =
(move ||
{
#[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:
&'tcx ty::TypeckResults<'tcx> = loop {};
return __tracing_attr_fake_return;
}
{
if !!tcx.is_typeck_child(def_id.to_def_id()) {
::core::panicking::panic("assertion failed: !tcx.is_typeck_child(def_id.to_def_id())")
};
let id = tcx.local_def_id_to_hir_id(def_id);
let node = tcx.hir_node(id);
let span = tcx.def_span(def_id);
let body_id =
node.body_id().unwrap_or_else(||
{
::rustc_span::macros::bug_impl(Some(span),
format_args!("can\'t type-check body of {0:?}", def_id),
Location::caller());
});
let body = tcx.hir_body(body_id);
let param_env = tcx.param_env(def_id);
let root_ctxt = TypeckRootCtxt::new(tcx, def_id);
if let Some(inspector) = inspector {
root_ctxt.infcx.attach_obligation_inspector(inspector);
}
let mut fcx = FnCtxt::new(&root_ctxt, param_env, def_id);
if let hir::Node::Item(hir::Item {
kind: hir::ItemKind::GlobalAsm { .. }, .. }) = node {
let ty = fcx.check_expr(body.value);
fcx.write_ty(id, ty);
} else if let Some(hir::FnSig { header, decl, span: _ }) =
node.fn_sig() {
let fn_sig =
if decl.output.is_suggestable_infer_ty().is_some() {
fcx.lowerer().lower_fn_ty(id, header.safety(), header.abi,
decl, None, None)
} else {
tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip()
};
check_abi(tcx, id, span, fn_sig.abi());
loops::check(tcx, def_id, body);
let mut fn_sig =
tcx.liberate_late_bound_regions(def_id.to_def_id(), fn_sig);
let arg_span =
|idx|
decl.inputs.get(idx).map_or(decl.output.span(),
|arg: &hir::Ty<'_>| arg.span);
fn_sig.inputs_and_output =
tcx.mk_type_list_from_iter(fn_sig.inputs_and_output.iter().enumerate().map(|(idx,
ty)|
fcx.normalize(arg_span(idx), Unnormalized::new_wip(ty))));
if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::NAKED)
{
naked_functions::typeck_naked_fn(tcx, def_id, body);
}
check_fn(&mut fcx, fn_sig, None, decl, def_id, body,
tcx.features().unsized_fn_params());
} else {
let expected_type =
if let Some(infer_ty) = infer_type_if_missing(&fcx, node) {
infer_ty
} else if let Some(ty) = node.ty() &&
ty.is_suggestable_infer_ty() {
fcx.lowerer().lower_ty(ty)
} else {
tcx.type_of(def_id).instantiate_identity().skip_norm_wip()
};
loops::check(tcx, def_id, body);
let expected_type =
fcx.normalize(body.value.span,
Unnormalized::new_wip(expected_type));
let wf_code =
ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(def_id)));
fcx.register_wf_obligation(expected_type.into(),
body.value.span, wf_code);
if let hir::Node::AnonConst(_) = node {
fcx.require_type_is_sized(expected_type, body.value.span,
ObligationCauseCode::SizedConstOrStatic);
}
fcx.check_expr_coercible_to_type_or_error(body.value,
expected_type, None,
|err, _|
{
extend_err_with_const_context(err, tcx, node,
expected_type);
});
fcx.write_ty(id, expected_type);
};
fcx.check_repeat_exprs();
if fcx.next_trait_solver() {
fcx.try_handle_opaque_type_uses_next();
}
fcx.type_inference_fallback();
fcx.check_casts();
fcx.select_obligations_where_possible(|_| {});
fcx.closure_analyze(body);
if !fcx.deferred_call_resolutions.borrow().is_empty() {
::core::panicking::panic("assertion failed: fcx.deferred_call_resolutions.borrow().is_empty()")
};
for (ty, span, code) in
fcx.deferred_sized_obligations.borrow_mut().drain(..) {
let ty = fcx.normalize(span, Unnormalized::new_wip(ty));
fcx.require_type_is_sized(ty, span, code);
}
fcx.select_obligations_where_possible(|_| {});
{
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/lib.rs:251",
"rustc_hir_typeck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/28221559263a3976766cf305940e80e30cf9ba8a/compiler/rustc_hir_typeck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(251u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("pending_obligations")
}> =
::tracing::__macro_support::FieldName::new("pending_obligations");
NAME.as_str()
}], ::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(&::tracing::field::debug(&fcx.fulfillment_cx.borrow().pending_obligations())
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
if fcx.next_trait_solver() {
fcx.handle_opaque_type_uses_next();
}
fcx.drain_stalled_coroutine_obligations();
if fcx.infcx.tainted_by_errors().is_none() {
fcx.report_ambiguity_errors();
}
fcx.check_asms();
let typeck_results = fcx.resolve_type_vars_in_body(body);
fcx.detect_opaque_types_added_during_writeback();
{
match (&typeck_results.hir_owner, &id.owner) {
(left_val, right_val) => {
if !(*left_val == *right_val) {
let kind = ::core::panicking::AssertKind::Eq;
::core::panicking::assert_failed(kind, &*left_val,
&*right_val, ::core::option::Option::None);
}
}
}
};
typeck_results
}
})();
{
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/lib.rs:107",
"rustc_hir_typeck", ::tracing::Level::DEBUG,
::tracing_core::__macro_support::Option::Some("/rustc-dev/28221559263a3976766cf305940e80e30cf9ba8a/compiler/rustc_hir_typeck/src/lib.rs"),
::tracing_core::__macro_support::Option::Some(107u32),
::tracing_core::__macro_support::Option::Some("rustc_hir_typeck"),
::tracing_core::field::FieldSet::new(&[{
const NAME:
::tracing::__macro_support::FieldName<{
::tracing::__macro_support::FieldName::len("return")
}> =
::tracing::__macro_support::FieldName::new("return");
NAME.as_str()
}], ::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(&::tracing::field::debug(&x)
as &dyn ::tracing::field::Value))])
});
} else { ; }
};
x;#[instrument(level = "debug", skip(tcx, inspector), ret)]
108fn typeck_with_inspect<'tcx>(
109 tcx: TyCtxt<'tcx>,
110 def_id: LocalDefId,
111 inspector: Option<ObligationInspector<'tcx>>,
112) -> &'tcx ty::TypeckResults<'tcx> {
113 assert!(!tcx.is_typeck_child(def_id.to_def_id()));
114
115 let id = tcx.local_def_id_to_hir_id(def_id);
116 let node = tcx.hir_node(id);
117 let span = tcx.def_span(def_id);
118
119 let body_id = node.body_id().unwrap_or_else(|| {
121 span_bug!(span, "can't type-check body of {:?}", def_id);
122 });
123 let body = tcx.hir_body(body_id);
124
125 let param_env = tcx.param_env(def_id);
126
127 let root_ctxt = TypeckRootCtxt::new(tcx, def_id);
128 if let Some(inspector) = inspector {
129 root_ctxt.infcx.attach_obligation_inspector(inspector);
130 }
131 let mut fcx = FnCtxt::new(&root_ctxt, param_env, def_id);
132
133 if let hir::Node::Item(hir::Item { kind: hir::ItemKind::GlobalAsm { .. }, .. }) = node {
134 let ty = fcx.check_expr(body.value);
137 fcx.write_ty(id, ty);
138 } else if let Some(hir::FnSig { header, decl, span: _ }) = node.fn_sig() {
139 let fn_sig = if decl.output.is_suggestable_infer_ty().is_some() {
140 fcx.lowerer().lower_fn_ty(id, header.safety(), header.abi, decl, None, None)
145 } else {
146 tcx.fn_sig(def_id).instantiate_identity().skip_norm_wip()
147 };
148
149 check_abi(tcx, id, span, fn_sig.abi());
150
151 loops::check(tcx, def_id, body);
152
153 let mut fn_sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), fn_sig);
155
156 let arg_span =
162 |idx| decl.inputs.get(idx).map_or(decl.output.span(), |arg: &hir::Ty<'_>| arg.span);
163
164 fn_sig.inputs_and_output = tcx.mk_type_list_from_iter(
165 fn_sig
166 .inputs_and_output
167 .iter()
168 .enumerate()
169 .map(|(idx, ty)| fcx.normalize(arg_span(idx), Unnormalized::new_wip(ty))),
170 );
171
172 if tcx.codegen_fn_attrs(def_id).flags.contains(CodegenFnAttrFlags::NAKED) {
173 naked_functions::typeck_naked_fn(tcx, def_id, body);
174 }
175
176 check_fn(&mut fcx, fn_sig, None, decl, def_id, body, tcx.features().unsized_fn_params());
177 } else {
178 let expected_type = if let Some(infer_ty) = infer_type_if_missing(&fcx, node) {
179 infer_ty
180 } else if let Some(ty) = node.ty()
181 && ty.is_suggestable_infer_ty()
182 {
183 fcx.lowerer().lower_ty(ty)
188 } else {
189 tcx.type_of(def_id).instantiate_identity().skip_norm_wip()
190 };
191
192 loops::check(tcx, def_id, body);
193
194 let expected_type = fcx.normalize(body.value.span, Unnormalized::new_wip(expected_type));
195
196 let wf_code = ObligationCauseCode::WellFormed(Some(WellFormedLoc::Ty(def_id)));
197 fcx.register_wf_obligation(expected_type.into(), body.value.span, wf_code);
198
199 if let hir::Node::AnonConst(_) = node {
200 fcx.require_type_is_sized(
201 expected_type,
202 body.value.span,
203 ObligationCauseCode::SizedConstOrStatic,
204 );
205 }
206
207 fcx.check_expr_coercible_to_type_or_error(body.value, expected_type, None, |err, _| {
208 extend_err_with_const_context(err, tcx, node, expected_type);
209 });
210
211 fcx.write_ty(id, expected_type);
212 };
213
214 fcx.check_repeat_exprs();
225
226 if fcx.next_trait_solver() {
229 fcx.try_handle_opaque_type_uses_next();
230 }
231
232 fcx.type_inference_fallback();
233
234 fcx.check_casts();
237 fcx.select_obligations_where_possible(|_| {});
238
239 fcx.closure_analyze(body);
242 assert!(fcx.deferred_call_resolutions.borrow().is_empty());
243
244 for (ty, span, code) in fcx.deferred_sized_obligations.borrow_mut().drain(..) {
245 let ty = fcx.normalize(span, Unnormalized::new_wip(ty));
246 fcx.require_type_is_sized(ty, span, code);
247 }
248
249 fcx.select_obligations_where_possible(|_| {});
250
251 debug!(pending_obligations = ?fcx.fulfillment_cx.borrow().pending_obligations());
252
253 if fcx.next_trait_solver() {
256 fcx.handle_opaque_type_uses_next();
257 }
258
259 fcx.drain_stalled_coroutine_obligations();
262 if fcx.infcx.tainted_by_errors().is_none() {
263 fcx.report_ambiguity_errors();
264 }
265
266 fcx.check_asms();
267
268 let typeck_results = fcx.resolve_type_vars_in_body(body);
269
270 fcx.detect_opaque_types_added_during_writeback();
271
272 assert_eq!(typeck_results.hir_owner, id.owner);
275
276 typeck_results
277}
278
279fn extend_err_with_const_context(
280 err: &mut Diag<'_>,
281 tcx: TyCtxt<'_>,
282 node: hir::Node<'_>,
283 expected_ty: Ty<'_>,
284) {
285 match node {
286 hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, _), .. })
287 | hir::Node::TraitItem(hir::TraitItem { kind: hir::TraitItemKind::Const(ty, _), .. }) => {
288 err.span_label(ty.span, "expected because of the type of the associated constant");
290 }
291 hir::Node::Item(hir::Item { kind: hir::ItemKind::Const(_, _, ty, _), .. }) => {
292 err.span_label(ty.span, "expected because of the type of the constant");
294 }
295 hir::Node::Item(hir::Item { kind: hir::ItemKind::Static(_, _, ty, _), .. }) => {
296 err.span_label(ty.span, "expected because of the type of the static");
298 }
299 hir::Node::AnonConst(anon)
300 if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
301 && let hir::Node::Ty(parent) = tcx.parent_hir_node(parent.hir_id)
302 && let hir::TyKind::Array(_ty, _len) = parent.kind =>
303 {
304 err.note("array length can only be `usize`");
306 }
307 hir::Node::AnonConst(anon)
308 if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
309 && let hir::Node::Expr(parent) = tcx.parent_hir_node(parent.hir_id)
310 && let hir::ExprKind::Repeat(_ty, _len) = parent.kind =>
311 {
312 err.note("array length can only be `usize`");
314 }
315 hir::Node::AnonConst(anon)
317 if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
318 && let Some(path) = tcx.parent_hir_node(parent.hir_id).path()
319 && let hir::QPath::Resolved(_, path) = path
320 && let Res::Def(_, def_id) = path.res =>
321 {
322 if let Some(i) =
324 path.segments.last().and_then(|segment| segment.args).and_then(|args| {
325 args.args.iter().position(|arg| {
326 #[allow(non_exhaustive_omitted_patterns)] match arg {
hir::GenericArg::Const(arg) if arg.hir_id == parent.hir_id => true,
_ => false,
}matches!(arg, hir::GenericArg::Const(arg) if arg.hir_id == parent.hir_id)
327 })
328 })
329 {
330 let generics = tcx.generics_of(def_id);
331 let param = &generics.param_at(i, tcx);
332 let sp = tcx.def_span(param.def_id);
333 err.span_note(sp, "expected because of the type of the const parameter");
334 }
335 }
336 hir::Node::AnonConst(anon)
337 if let hir::Node::Variant(_variant) = tcx.parent_hir_node(anon.hir_id) =>
338 {
339 err.note(
341 "enum variant discriminant can only be of a primitive type compatible with the \
342 enum's `repr`",
343 );
344 }
345 hir::Node::AnonConst(anon)
346 if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
347 && let hir::Node::GenericParam(param) = tcx.parent_hir_node(parent.hir_id)
348 && let hir::GenericParamKind::Const { ty, .. } = param.kind =>
349 {
350 err.span_label(ty.span, "expected because of the type of the const parameter");
352 }
353 hir::Node::AnonConst(anon)
354 if let hir::Node::ConstArg(parent) = tcx.parent_hir_node(anon.hir_id)
355 && let hir::Node::TyPat(ty_pat) = tcx.parent_hir_node(parent.hir_id)
356 && let hir::Node::Ty(ty) = tcx.parent_hir_node(ty_pat.hir_id)
357 && let hir::TyKind::Pat(ty, _) = ty.kind =>
358 {
359 err.span_label(ty.span, "the pattern must match the type");
361 }
362 hir::Node::AnonConst(anon)
363 if let hir::Node::Field(_) = tcx.parent_hir_node(anon.hir_id)
364 && let ty::Param(_) = expected_ty.kind() =>
365 {
366 err.note(
367 "the type of default fields referencing type parameters can't be assumed inside \
368 the struct defining them",
369 );
370 }
371 _ => {}
372 }
373}
374
375fn infer_type_if_missing<'tcx>(fcx: &FnCtxt<'_, 'tcx>, node: Node<'tcx>) -> Option<Ty<'tcx>> {
376 let tcx = fcx.tcx;
377 let def_id = fcx.body_def_id;
378 let expected_type = if let Some(&hir::Ty { kind: hir::TyKind::Infer(()), span, .. }) = node.ty()
379 {
380 if let Some(item) = tcx.opt_associated_item(def_id.into())
381 && let ty::AssocKind::Const { .. } = item.kind
382 && let ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) = item.container
383 {
384 let impl_def_id = item.container_id(tcx);
385 let impl_trait_ref =
386 tcx.impl_trait_ref(impl_def_id).instantiate_identity().skip_norm_wip();
387 let args = ty::GenericArgs::identity_for_item(tcx, def_id).rebase_onto(
388 tcx,
389 impl_def_id,
390 impl_trait_ref.args,
391 );
392 let alias_kind = ty::AliasTermKind::ProjectionConst { def_id: trait_item_def_id };
393 tcx.check_alias_term_args_compatible(alias_kind, args)
394 .then(|| tcx.type_of(trait_item_def_id).instantiate(tcx, args).skip_norm_wip())
395 } else {
396 Some(fcx.next_ty_var(span))
397 }
398 } else if let Node::AnonConst(_) = node {
399 let id = tcx.local_def_id_to_hir_id(def_id);
400 match tcx.parent_hir_node(id) {
401 Node::Expr(&hir::Expr { kind: hir::ExprKind::InlineAsm(asm), span, .. })
402 | Node::Item(&hir::Item { kind: hir::ItemKind::GlobalAsm { asm, .. }, span, .. }) => {
403 asm.operands.iter().find_map(|(op, _op_sp)| match op {
404 hir::InlineAsmOperand::Const { anon_const } if anon_const.hir_id == id => {
405 Some(fcx.next_ty_var(span))
406 }
407 _ => None,
408 })
409 }
410 _ => None,
411 }
412 } else {
413 None
414 };
415 expected_type
416}
417
418#[derive(#[automatically_derived]
impl<'tcx> ::core::fmt::Debug for CoroutineTypes<'tcx> {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::debug_struct_field2_finish(f,
"CoroutineTypes", "resume_ty", &self.resume_ty, "yield_ty",
&&self.yield_ty)
}
}Debug, #[automatically_derived]
impl<'tcx> ::core::marker::StructuralPartialEq for CoroutineTypes<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::cmp::PartialEq for CoroutineTypes<'tcx> {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.resume_ty == other.resume_ty && self.yield_ty == other.yield_ty
}
}PartialEq, #[automatically_derived]
impl<'tcx> ::core::marker::Copy for CoroutineTypes<'tcx> { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl<'tcx> ::core::clone::TrivialClone for CoroutineTypes<'tcx> { }
#[automatically_derived]
impl<'tcx> ::core::clone::Clone for CoroutineTypes<'tcx> {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
let _: ::core::clone::AssertParamIsClone<Ty<'tcx>>;
*self
}
}Clone)]
422struct CoroutineTypes<'tcx> {
423 resume_ty: Ty<'tcx>,
425
426 yield_ty: Ty<'tcx>,
428}
429
430#[derive(#[automatically_derived]
impl ::core::marker::Copy for Needs { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for Needs { }
#[automatically_derived]
impl ::core::clone::Clone for Needs {
#[inline]
fn clone(&self) -> Self { *self }
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for Needs {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
Needs::MutPlace => "MutPlace",
Needs::None => "None",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for Needs { }
#[automatically_derived]
impl ::core::cmp::PartialEq for Needs {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other)
}
}PartialEq, #[automatically_derived]
impl ::core::cmp::Eq for Needs { }Eq)]
431pub enum Needs {
432 MutPlace,
433 None,
434}
435
436impl Needs {
437 fn maybe_mut_place(m: hir::Mutability) -> Self {
438 match m {
439 hir::Mutability::Mut => Needs::MutPlace,
440 hir::Mutability::Not => Needs::None,
441 }
442 }
443}
444
445#[derive(#[automatically_derived]
impl ::core::fmt::Debug for PlaceOp {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
::core::fmt::Formatter::write_str(f,
match self {
PlaceOp::Deref => "Deref",
PlaceOp::Index => "Index",
})
}
}Debug, #[automatically_derived]
impl ::core::marker::Copy for PlaceOp { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for PlaceOp { }
#[automatically_derived]
impl ::core::clone::Clone for PlaceOp {
#[inline]
fn clone(&self) -> Self { *self }
}Clone)]
446pub enum PlaceOp {
447 Deref,
448 Index,
449}
450
451pub struct BreakableCtxt<'tcx> {
452 may_break: bool,
453
454 coerce: Option<CoerceMany<'tcx>>,
457}
458
459pub struct EnclosingBreakables<'tcx> {
460 stack: Vec<BreakableCtxt<'tcx>>,
461 by_id: HirIdMap<usize>,
462}
463
464impl<'tcx> EnclosingBreakables<'tcx> {
465 fn find_breakable(&mut self, target_id: HirId) -> &mut BreakableCtxt<'tcx> {
466 self.opt_find_breakable(target_id).unwrap_or_else(|| {
467 ::rustc_span::macros::bug_impl(None,
format_args!("could not find enclosing breakable with id {0}", target_id),
Location::caller());bug!("could not find enclosing breakable with id {}", target_id);
468 })
469 }
470
471 fn opt_find_breakable(&mut self, target_id: HirId) -> Option<&mut BreakableCtxt<'tcx>> {
472 match self.by_id.get(&target_id) {
473 Some(ix) => Some(&mut self.stack[*ix]),
474 None => None,
475 }
476 }
477}
478impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
479 fn report_unexpected_variant_res(
480 &self,
481 res: Res,
482 expr: Option<&hir::Expr<'_>>,
483 sub_pats: &[hir::Pat<'_>],
484 qpath: &hir::QPath<'_>,
485 span: Span,
486 err_code: ErrCode,
487 expected: &str,
488 ) -> ErrorGuaranteed {
489 let tcx = self.tcx;
490 let res_descr = match res {
491 Res::Def(DefKind::Variant, _) => "struct variant",
492 _ => res.descr(),
493 };
494 let path_str = rustc_hir_pretty::qpath_to_string(self, qpath);
495 let mut err = tcx
496 .dcx()
497 .struct_span_err(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("expected {0}, found {1} `{2}`",
expected, res_descr, path_str))
})format!("expected {expected}, found {res_descr} `{path_str}`"))
498 .with_code(err_code);
499 match res {
500 Res::Def(DefKind::Fn | DefKind::AssocFn, _) if err_code == E0164 => {
501 let patterns_url = "https://doc.rust-lang.org/book/ch19-00-patterns.html";
502 err.with_span_label(span, "`fn` calls are not allowed in patterns")
503 .with_help(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("for more information, visit {0}",
patterns_url))
})format!("for more information, visit {patterns_url}"))
504 }
505 Res::Def(DefKind::Variant, _) if let Some(expr) = expr => {
506 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("not a {0}", expected))
})format!("not a {expected}"));
507 let variant = tcx.expect_variant_res(res);
508 let sugg = if variant.fields.is_empty() {
509 " {}".to_string()
510 } else {
511 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {{ {0} }}",
variant.fields.iter().map(|f|
::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: /* value */",
f.name))
})).collect::<Vec<_>>().join(", ")))
})format!(
512 " {{ {} }}",
513 variant
514 .fields
515 .iter()
516 .map(|f| format!("{}: /* value */", f.name))
517 .collect::<Vec<_>>()
518 .join(", ")
519 )
520 };
521 let descr = "you might have meant to create a new value of the struct";
522 let mut suggestion = ::alloc::vec::Vec::new()vec![];
523 match tcx.parent_hir_node(expr.hir_id) {
524 hir::Node::Expr(hir::Expr {
525 kind: hir::ExprKind::Call(..),
526 span: call_span,
527 ..
528 }) => {
529 suggestion.push((span.shrink_to_hi().with_hi(call_span.hi()), sugg));
530 }
531 hir::Node::Expr(hir::Expr {
532 kind: hir::ExprKind::Binary(..), hir_id, ..
533 }) => {
534 suggestion.push((expr.span.shrink_to_lo(), "(".to_string()));
535 if let hir::Node::Expr(parent) = tcx.parent_hir_node(*hir_id)
536 && let hir::ExprKind::If(condition, block, None) = parent.kind
537 && condition.hir_id == *hir_id
538 && let hir::ExprKind::Block(block, _) = block.kind
539 && block.stmts.is_empty()
540 && let Some(expr) = block.expr
541 && let hir::ExprKind::Path(..) = expr.kind
542 {
543 suggestion.push((block.span.shrink_to_hi(), ")".to_string()));
548 } else {
549 suggestion.push((span.shrink_to_hi().with_hi(expr.span.hi()), sugg));
550 }
551 }
552 _ => {
553 suggestion.push((span.shrink_to_hi(), sugg));
554 }
555 }
556
557 err.multipart_suggestion(descr, suggestion, Applicability::HasPlaceholders);
558 err
559 }
560 Res::Def(DefKind::Variant, _) if expr.is_none() => {
561 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("not a {0}", expected))
})format!("not a {expected}"));
562
563 let fields = &tcx.expect_variant_res(res).fields.raw;
564 let span = qpath.span().shrink_to_hi().to(span.shrink_to_hi());
565 let (msg, sugg) = if fields.is_empty() {
566 ("use the struct variant pattern syntax", " {}".to_string())
567 } else {
568 let msg = if fields.is_empty() {
569 "use struct variant pattern syntax"
570 } else {
571 "add the names to match a struct variant's fields"
572 };
573 let fields_sugg = fields
574 .iter()
575 .enumerate()
576 .map(|(i, field)| {
577 let field_name = field.ident(tcx).to_string();
578
579 let pat_snippet = sub_pats
580 .get(i)
581 .and_then(|sub_pat| {
582 tcx.sess.source_map().span_to_snippet(sub_pat.span).ok()
583 })
584 .unwrap_or_else(|| "_".to_string());
585
586 if field_name == pat_snippet {
587 field_name
588 } else {
589 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: {1}", field_name,
pat_snippet))
})format!("{field_name}: {pat_snippet}")
590 }
591 })
592 .collect::<Vec<_>>()
593 .join(", ");
594 let sugg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {{ {0} }}", fields_sugg))
})format!(" {{ {} }}", fields_sugg);
595 (msg, sugg)
596 };
597
598 err.span_suggestion_verbose(
599 qpath.span().shrink_to_hi().to(span.shrink_to_hi()),
600 msg,
601 sugg,
602 Applicability::HasPlaceholders,
603 );
604 err
605 }
606 _ => err.with_span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("not a {0}", expected))
})format!("not a {expected}")),
607 }
608 .emit_err()
609 }
610}
611
612#[derive(#[automatically_derived]
impl ::core::marker::Copy for TupleArgumentsFlag { }Copy, #[automatically_derived]
#[doc(hidden)]
unsafe impl ::core::clone::TrivialClone for TupleArgumentsFlag { }
#[automatically_derived]
impl ::core::clone::Clone for TupleArgumentsFlag {
#[inline]
fn clone(&self) -> Self {
let _: ::core::clone::AssertParamIsClone<u8>;
*self
}
}Clone, #[automatically_derived]
impl ::core::fmt::Debug for TupleArgumentsFlag {
#[inline]
fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
match self {
Self::DontTupleArguments =>
::core::fmt::Formatter::write_str(f, "DontTupleArguments"),
Self::TupleAllCallArgs =>
::core::fmt::Formatter::write_str(f, "TupleAllCallArgs"),
Self::TupleSplattedSelfArg =>
::core::fmt::Formatter::write_str(f, "TupleSplattedSelfArg"),
Self::TupleSplattedArg(__self_0) =>
::core::fmt::Formatter::debug_tuple_field1_finish(f,
"TupleSplattedArg", &__self_0),
}
}
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for TupleArgumentsFlag {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {
let _: ::core::cmp::AssertParamIsEq<u8>;
}
}Eq, #[automatically_derived]
impl ::core::marker::StructuralPartialEq for TupleArgumentsFlag { }
#[automatically_derived]
impl ::core::cmp::PartialEq for TupleArgumentsFlag {
#[inline]
fn eq(&self, other: &Self) -> bool {
::core::intrinsics::discriminant_value(self) ==
::core::intrinsics::discriminant_value(other) &&
match (self, other) {
(Self::TupleSplattedArg(__self_0),
Self::TupleSplattedArg(__arg1_0)) => __self_0 == __arg1_0,
_ => true,
}
}
}PartialEq)]
632enum TupleArgumentsFlag {
633 DontTupleArguments,
635 TupleAllCallArgs,
638 TupleSplattedSelfArg,
640 TupleSplattedArg(u8),
642}
643
644impl TupleArgumentsFlag {
645 fn rust_fn_trait_call() -> Self {
647 Self::TupleAllCallArgs
648 }
649
650 fn with_fn_sig_kind<'tcx>(fn_sig_kind: FnSigKind<'tcx>, is_method: bool) -> Self {
652 if let Some(splatted_arg_index) = fn_sig_kind.splatted() {
653 if is_method {
654 if let Some(splatted_arg_index) = splatted_arg_index.checked_sub(1) {
655 return Self::TupleSplattedArg(splatted_arg_index);
656 } else {
657 return Self::TupleSplattedSelfArg;
659 }
660 }
661
662 return Self::TupleSplattedArg(splatted_arg_index);
663 }
664
665 Self::DontTupleArguments
666 }
667
668 fn is_tupled(self) -> bool {
670 match self {
671 Self::DontTupleArguments => false,
672 Self::TupleAllCallArgs | Self::TupleSplattedSelfArg | Self::TupleSplattedArg(_) => true,
673 }
674 }
675
676 fn is_splatted(self) -> bool {
679 match self {
680 Self::TupleSplattedSelfArg | Self::TupleSplattedArg(_) => true,
681 Self::DontTupleArguments | Self::TupleAllCallArgs => false,
682 }
683 }
684
685 fn tupled_arg_index(self) -> (Option<u16>, bool ) {
688 match self {
689 Self::TupleSplattedArg(index) => (Some(u16::from(index)), false),
690 Self::TupleAllCallArgs => (Some(0), false),
691 Self::TupleSplattedSelfArg => (None, true),
692 Self::DontTupleArguments => (None, false),
693 }
694 }
695}
696
697fn fatally_break_rust(tcx: TyCtxt<'_>, span: Span) -> ! {
698 let dcx = tcx.dcx();
699 let mut diag = dcx.struct_span_bug(
700 span,
701 "It looks like you're trying to break rust; would you like some ICE?",
702 );
703 diag.note("the compiler expectedly panicked. this is a feature.");
704 diag.note(
705 "we would appreciate a joke overview: \
706 https://github.com/rust-lang/rust/issues/43162#issuecomment-320764675",
707 );
708 diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("rustc {0} running on {1}",
tcx.sess.cfg_version, config::host_tuple()))
})format!("rustc {} running on {}", tcx.sess.cfg_version, config::host_tuple(),));
709 if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
710 diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("compiler flags: {0}",
flags.join(" ")))
})format!("compiler flags: {}", flags.join(" ")));
711 if excluded_cargo_defaults {
712 diag.note("some of the compiler flags provided by cargo are hidden");
713 }
714 }
715 diag.emit_bug()
716}
717
718pub fn provide(providers: &mut Providers) {
720 *providers = Providers {
721 method_autoderef_steps: method::probe::method_autoderef_steps,
722 typeck_root,
723 used_trait_imports,
724 check_transmutes: intrinsicck::check_transmutes,
725 check_offloads: intrinsicck::check_offloads,
726 ..*providers
727 };
728}