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