1#![feature(box_patterns)]
3#![feature(iter_intersperse)]
4#![feature(iter_order_by)]
5#![feature(never_type)]
6#![feature(trim_prefix_suffix)]
7mod _match;
10mod autoderef;
11mod callee;
12pub mod cast;
14mod check;
15mod closure;
16mod coercion;
17mod demand;
18mod diverges;
19mod errors;
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, ErrorGuaranteed, pluralize, 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, check_custom_abi};
49use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
50use rustc_infer::traits::{ObligationCauseCode, ObligationInspector, WellFormedLoc};
51use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
52use rustc_middle::query::Providers;
53use rustc_middle::ty::{self, Ty, TyCtxt};
54use rustc_middle::{bug, span_bug};
55use rustc_session::config;
56use rustc_span::Span;
57use rustc_span::def_id::LocalDefId;
58use tracing::{debug, instrument};
59use typeck_root_ctxt::TypeckRootCtxt;
60
61use crate::check::check_fn;
62use crate::coercion::CoerceMany;
63use crate::diverges::Diverges;
64use crate::expectation::Expectation;
65use crate::fn_ctxt::LoweredTy;
66use crate::gather_locals::GatherLocalsVisitor;
67
68#[macro_export]
69macro_rules! type_error_struct {
70 ($dcx:expr, $span:expr, $typ:expr, $code:expr, $($message:tt)*) => ({
71 let mut err = rustc_errors::struct_span_code_err!($dcx, $span, $code, $($message)*);
72
73 if $typ.references_error() {
74 err.downgrade_to_delayed_bug();
75 }
76
77 err
78 })
79}
80
81fn used_trait_imports(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &UnordSet<LocalDefId> {
82 &tcx.typeck(def_id).used_trait_imports
83}
84
85fn typeck<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx ty::TypeckResults<'tcx> {
86 typeck_with_inspect(tcx, def_id, None)
87}
88
89pub fn inspect_typeck<'tcx>(
94 tcx: TyCtxt<'tcx>,
95 def_id: LocalDefId,
96 inspect: ObligationInspector<'tcx>,
97) -> &'tcx ty::TypeckResults<'tcx> {
98 typeck_with_inspect(tcx, def_id, Some(inspect))
99}
100
101x;#[instrument(level = "debug", skip(tcx, inspector), ret)]
102fn typeck_with_inspect<'tcx>(
103 tcx: TyCtxt<'tcx>,
104 def_id: LocalDefId,
105 inspector: Option<ObligationInspector<'tcx>>,
106) -> &'tcx ty::TypeckResults<'tcx> {
107 let typeck_root_def_id = tcx.typeck_root_def_id(def_id.to_def_id()).expect_local();
110 if typeck_root_def_id != def_id {
111 return tcx.typeck(typeck_root_def_id);
112 }
113
114 let id = tcx.local_def_id_to_hir_id(def_id);
115 let node = tcx.hir_node(id);
116 let span = tcx.def_span(def_id);
117
118 let body_id = node.body_id().unwrap_or_else(|| {
120 span_bug!(span, "can't type-check body of {:?}", def_id);
121 });
122 let body = tcx.hir_body(body_id);
123
124 let param_env = tcx.param_env(def_id);
125
126 let root_ctxt = TypeckRootCtxt::new(tcx, def_id);
127 if let Some(inspector) = inspector {
128 root_ctxt.infcx.attach_obligation_inspector(inspector);
129 }
130 let mut fcx = FnCtxt::new(&root_ctxt, param_env, def_id);
131
132 if let hir::Node::Item(hir::Item { kind: hir::ItemKind::GlobalAsm { .. }, .. }) = node {
133 let ty = fcx.check_expr(body.value);
136 fcx.write_ty(id, ty);
137 } else if let Some(hir::FnSig { header, decl, span: fn_sig_span }) = node.fn_sig() {
138 let fn_sig = if decl.output.is_suggestable_infer_ty().is_some() {
139 fcx.lowerer().lower_fn_ty(id, header.safety(), header.abi, decl, None, None)
144 } else {
145 tcx.fn_sig(def_id).instantiate_identity()
146 };
147
148 check_abi(tcx, id, span, fn_sig.abi());
149 check_custom_abi(tcx, def_id, fn_sig.skip_binder(), *fn_sig_span);
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), 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()
190 };
191
192 loops::check(tcx, def_id, body);
193
194 let expected_type = fcx.normalize(body.value.span, 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(body.value, expected_type, None);
208
209 fcx.write_ty(id, expected_type);
210 };
211
212 fcx.check_repeat_exprs();
223
224 if fcx.next_trait_solver() {
227 fcx.try_handle_opaque_type_uses_next();
228 }
229
230 fcx.type_inference_fallback();
231
232 fcx.check_casts();
235 fcx.select_obligations_where_possible(|_| {});
236
237 fcx.closure_analyze(body);
240 assert!(fcx.deferred_call_resolutions.borrow().is_empty());
241
242 for (ty, span, code) in fcx.deferred_sized_obligations.borrow_mut().drain(..) {
243 let ty = fcx.normalize(span, ty);
244 fcx.require_type_is_sized(ty, span, code);
245 }
246
247 fcx.select_obligations_where_possible(|_| {});
248
249 debug!(pending_obligations = ?fcx.fulfillment_cx.borrow().pending_obligations());
250
251 if fcx.next_trait_solver() {
254 fcx.handle_opaque_type_uses_next();
255 }
256
257 fcx.drain_stalled_coroutine_obligations();
260 if fcx.infcx.tainted_by_errors().is_none() {
261 fcx.report_ambiguity_errors();
262 }
263
264 fcx.check_asms();
265
266 let typeck_results = fcx.resolve_type_vars_in_body(body);
267
268 fcx.detect_opaque_types_added_during_writeback();
269
270 assert_eq!(typeck_results.hir_owner, id.owner);
273
274 typeck_results
275}
276
277fn infer_type_if_missing<'tcx>(fcx: &FnCtxt<'_, 'tcx>, node: Node<'tcx>) -> Option<Ty<'tcx>> {
278 let tcx = fcx.tcx;
279 let def_id = fcx.body_id;
280 let expected_type = if let Some(&hir::Ty { kind: hir::TyKind::Infer(()), span, .. }) = node.ty()
281 {
282 if let Some(item) = tcx.opt_associated_item(def_id.into())
283 && let ty::AssocKind::Const { .. } = item.kind
284 && let ty::AssocContainer::TraitImpl(Ok(trait_item_def_id)) = item.container
285 {
286 let impl_def_id = item.container_id(tcx);
287 let impl_trait_ref = tcx.impl_trait_ref(impl_def_id).instantiate_identity();
288 let args = ty::GenericArgs::identity_for_item(tcx, def_id).rebase_onto(
289 tcx,
290 impl_def_id,
291 impl_trait_ref.args,
292 );
293 tcx.check_args_compatible(trait_item_def_id, args)
294 .then(|| tcx.type_of(trait_item_def_id).instantiate(tcx, args))
295 } else {
296 Some(fcx.next_ty_var(span))
297 }
298 } else if let Node::AnonConst(_) = node {
299 let id = tcx.local_def_id_to_hir_id(def_id);
300 match tcx.parent_hir_node(id) {
301 Node::Expr(&hir::Expr { kind: hir::ExprKind::InlineAsm(asm), span, .. })
302 | Node::Item(&hir::Item { kind: hir::ItemKind::GlobalAsm { asm, .. }, span, .. }) => {
303 asm.operands.iter().find_map(|(op, _op_sp)| match op {
304 hir::InlineAsmOperand::Const { anon_const } if anon_const.hir_id == id => {
305 Some(fcx.next_ty_var(span))
306 }
307 _ => None,
308 })
309 }
310 _ => None,
311 }
312 } else {
313 None
314 };
315 expected_type
316}
317
318#[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::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]
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)]
322struct CoroutineTypes<'tcx> {
323 resume_ty: Ty<'tcx>,
325
326 yield_ty: Ty<'tcx>,
328}
329
330#[derive(#[automatically_derived]
impl ::core::marker::Copy for Needs { }Copy, #[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::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)]
331pub enum Needs {
332 MutPlace,
333 None,
334}
335
336impl Needs {
337 fn maybe_mut_place(m: hir::Mutability) -> Self {
338 match m {
339 hir::Mutability::Mut => Needs::MutPlace,
340 hir::Mutability::Not => Needs::None,
341 }
342 }
343}
344
345#[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]
impl ::core::clone::Clone for PlaceOp {
#[inline]
fn clone(&self) -> PlaceOp { *self }
}Clone)]
346pub enum PlaceOp {
347 Deref,
348 Index,
349}
350
351pub struct BreakableCtxt<'tcx> {
352 may_break: bool,
353
354 coerce: Option<CoerceMany<'tcx>>,
357}
358
359pub struct EnclosingBreakables<'tcx> {
360 stack: Vec<BreakableCtxt<'tcx>>,
361 by_id: HirIdMap<usize>,
362}
363
364impl<'tcx> EnclosingBreakables<'tcx> {
365 fn find_breakable(&mut self, target_id: HirId) -> &mut BreakableCtxt<'tcx> {
366 self.opt_find_breakable(target_id).unwrap_or_else(|| {
367 ::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);
368 })
369 }
370
371 fn opt_find_breakable(&mut self, target_id: HirId) -> Option<&mut BreakableCtxt<'tcx>> {
372 match self.by_id.get(&target_id) {
373 Some(ix) => Some(&mut self.stack[*ix]),
374 None => None,
375 }
376 }
377}
378
379fn report_unexpected_variant_res(
380 tcx: TyCtxt<'_>,
381 res: Res,
382 expr: Option<&hir::Expr<'_>>,
383 qpath: &hir::QPath<'_>,
384 span: Span,
385 err_code: ErrCode,
386 expected: &str,
387) -> ErrorGuaranteed {
388 let res_descr = match res {
389 Res::Def(DefKind::Variant, _) => "struct variant",
390 _ => res.descr(),
391 };
392 let path_str = rustc_hir_pretty::qpath_to_string(&tcx, qpath);
393 let mut err = tcx
394 .dcx()
395 .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}`"))
396 .with_code(err_code);
397 match res {
398 Res::Def(DefKind::Fn | DefKind::AssocFn, _) if err_code == E0164 => {
399 let patterns_url = "https://doc.rust-lang.org/book/ch19-00-patterns.html";
400 err.with_span_label(span, "`fn` calls are not allowed in patterns")
401 .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}"))
402 }
403 Res::Def(DefKind::Variant, _) if let Some(expr) = expr => {
404 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("not a {0}", expected))
})format!("not a {expected}"));
405 let variant = tcx.expect_variant_res(res);
406 let sugg = if variant.fields.is_empty() {
407 " {}".to_string()
408 } else {
409 ::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!(
410 " {{ {} }}",
411 variant
412 .fields
413 .iter()
414 .map(|f| format!("{}: /* value */", f.name))
415 .collect::<Vec<_>>()
416 .join(", ")
417 )
418 };
419 let descr = "you might have meant to create a new value of the struct";
420 let mut suggestion = ::alloc::vec::Vec::new()vec![];
421 match tcx.parent_hir_node(expr.hir_id) {
422 hir::Node::Expr(hir::Expr {
423 kind: hir::ExprKind::Call(..),
424 span: call_span,
425 ..
426 }) => {
427 suggestion.push((span.shrink_to_hi().with_hi(call_span.hi()), sugg));
428 }
429 hir::Node::Expr(hir::Expr { kind: hir::ExprKind::Binary(..), hir_id, .. }) => {
430 suggestion.push((expr.span.shrink_to_lo(), "(".to_string()));
431 if let hir::Node::Expr(parent) = tcx.parent_hir_node(*hir_id)
432 && let hir::ExprKind::If(condition, block, None) = parent.kind
433 && condition.hir_id == *hir_id
434 && let hir::ExprKind::Block(block, _) = block.kind
435 && block.stmts.is_empty()
436 && let Some(expr) = block.expr
437 && let hir::ExprKind::Path(..) = expr.kind
438 {
439 suggestion.push((block.span.shrink_to_hi(), ")".to_string()));
444 } else {
445 suggestion.push((span.shrink_to_hi().with_hi(expr.span.hi()), sugg));
446 }
447 }
448 _ => {
449 suggestion.push((span.shrink_to_hi(), sugg));
450 }
451 }
452
453 err.multipart_suggestion(descr, suggestion, Applicability::HasPlaceholders);
454 err
455 }
456 Res::Def(DefKind::Variant, _) if expr.is_none() => {
457 err.span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("not a {0}", expected))
})format!("not a {expected}"));
458
459 let fields = &tcx.expect_variant_res(res).fields.raw;
460 let span = qpath.span().shrink_to_hi().to(span.shrink_to_hi());
461 let (msg, sugg) = if fields.is_empty() {
462 ("use the struct variant pattern syntax".to_string(), " {}".to_string())
463 } else {
464 let msg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("the struct variant\'s field{0} {1} being ignored",
if fields.len() == 1 { "" } else { "s" },
if fields.len() == 1 { "is" } else { "are" }))
})format!(
465 "the struct variant's field{s} {are} being ignored",
466 s = pluralize!(fields.len()),
467 are = pluralize!("is", fields.len())
468 );
469 let fields = fields
470 .iter()
471 .map(|field| ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("{0}: _", field.ident(tcx)))
})format!("{}: _", field.ident(tcx)))
472 .collect::<Vec<_>>()
473 .join(", ");
474 let sugg = ::alloc::__export::must_use({
::alloc::fmt::format(format_args!(" {{ {0} }}", fields))
})format!(" {{ {} }}", fields);
475 (msg, sugg)
476 };
477
478 err.span_suggestion_verbose(
479 qpath.span().shrink_to_hi().to(span.shrink_to_hi()),
480 msg,
481 sugg,
482 Applicability::HasPlaceholders,
483 );
484 err
485 }
486 _ => err.with_span_label(span, ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("not a {0}", expected))
})format!("not a {expected}")),
487 }
488 .emit()
489}
490
491#[derive(#[automatically_derived]
impl ::core::marker::Copy for TupleArgumentsFlag { }Copy, #[automatically_derived]
impl ::core::clone::Clone for TupleArgumentsFlag {
#[inline]
fn clone(&self) -> TupleArgumentsFlag { *self }
}Clone, #[automatically_derived]
impl ::core::cmp::Eq for TupleArgumentsFlag {
#[inline]
#[doc(hidden)]
#[coverage(off)]
fn assert_fields_are_eq(&self) {}
}Eq, #[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
}
}PartialEq)]
511enum TupleArgumentsFlag {
512 DontTupleArguments,
513 TupleArguments,
514}
515
516fn fatally_break_rust(tcx: TyCtxt<'_>, span: Span) -> ! {
517 let dcx = tcx.dcx();
518 let mut diag = dcx.struct_span_bug(
519 span,
520 "It looks like you're trying to break rust; would you like some ICE?",
521 );
522 diag.note("the compiler expectedly panicked. this is a feature.");
523 diag.note(
524 "we would appreciate a joke overview: \
525 https://github.com/rust-lang/rust/issues/43162#issuecomment-320764675",
526 );
527 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(),));
528 if let Some((flags, excluded_cargo_defaults)) = rustc_session::utils::extra_compiler_flags() {
529 diag.note(::alloc::__export::must_use({
::alloc::fmt::format(format_args!("compiler flags: {0}",
flags.join(" ")))
})format!("compiler flags: {}", flags.join(" ")));
530 if excluded_cargo_defaults {
531 diag.note("some of the compiler flags provided by cargo are hidden");
532 }
533 }
534 diag.emit()
535}
536
537pub fn provide(providers: &mut Providers) {
539 *providers = Providers {
540 method_autoderef_steps: method::probe::method_autoderef_steps,
541 typeck,
542 used_trait_imports,
543 check_transmutes: intrinsicck::check_transmutes,
544 ..*providers
545 };
546}