1 // Type resolution: the phase that finds all the types in the AST with
2 // unresolved type variables and replaces "ty_var" types with their
5 use crate::check::FnCtxt;
7 use hir::def_id::LocalDefId;
8 use rustc_data_structures::stable_map::FxHashMap;
9 use rustc_errors::ErrorGuaranteed;
11 use rustc_hir::def_id::DefId;
12 use rustc_hir::intravisit::{self, Visitor};
13 use rustc_infer::infer::error_reporting::TypeAnnotationNeeded::E0282;
14 use rustc_infer::infer::InferCtxt;
15 use rustc_middle::hir::place::Place as HirPlace;
16 use rustc_middle::mir::FakeReadCause;
17 use rustc_middle::ty::adjustment::{Adjust, Adjustment, PointerCast};
18 use rustc_middle::ty::fold::{TypeFoldable, TypeFolder, TypeSuperFoldable};
19 use rustc_middle::ty::visit::{TypeSuperVisitable, TypeVisitable};
20 use rustc_middle::ty::{self, ClosureSizeProfileData, Ty, TyCtxt};
21 use rustc_span::symbol::sym;
25 use std::ops::ControlFlow;
27 ///////////////////////////////////////////////////////////////////////////
30 // During type inference, partially inferred types are
31 // represented using Type variables (ty::Infer). These don't appear in
32 // the final TypeckResults since all of the types should have been
33 // inferred once typeck is done.
34 // When type inference is running however, having to update the typeck
35 // typeck results every time a new type is inferred would be unreasonably slow,
36 // so instead all of the replacement happens at the end in
37 // resolve_type_vars_in_body, which creates a new TypeTables which
38 // doesn't contain any inference types.
39 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
40 pub fn resolve_type_vars_in_body(
42 body: &'tcx hir::Body<'tcx>,
43 ) -> &'tcx ty::TypeckResults<'tcx> {
44 let item_id = self.tcx.hir().body_owner(body.id());
45 let item_def_id = self.tcx.hir().local_def_id(item_id);
47 // This attribute causes us to dump some writeback information
48 // in the form of errors, which is used for unit tests.
49 let rustc_dump_user_substs =
50 self.tcx.has_attr(item_def_id.to_def_id(), sym::rustc_dump_user_substs);
52 let mut wbcx = WritebackCx::new(self, body, rustc_dump_user_substs);
53 for param in body.params {
54 wbcx.visit_node_id(param.pat.span, param.hir_id);
56 // Type only exists for constants and statics, not functions.
57 match self.tcx.hir().body_owner_kind(item_def_id) {
58 hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => {
59 wbcx.visit_node_id(body.value.span, item_id);
61 hir::BodyOwnerKind::Closure | hir::BodyOwnerKind::Fn => (),
63 wbcx.visit_body(body);
64 wbcx.visit_min_capture_map();
65 wbcx.eval_closure_size();
66 wbcx.visit_fake_reads_map();
67 wbcx.visit_closures();
68 wbcx.visit_liberated_fn_sigs();
69 wbcx.visit_fru_field_types();
70 wbcx.visit_opaque_types();
71 wbcx.visit_coercion_casts();
72 wbcx.visit_user_provided_tys();
73 wbcx.visit_user_provided_sigs();
74 wbcx.visit_generator_interior_types();
76 wbcx.typeck_results.rvalue_scopes =
77 mem::take(&mut self.typeck_results.borrow_mut().rvalue_scopes);
79 let used_trait_imports =
80 mem::take(&mut self.typeck_results.borrow_mut().used_trait_imports);
81 debug!("used_trait_imports({:?}) = {:?}", item_def_id, used_trait_imports);
82 wbcx.typeck_results.used_trait_imports = used_trait_imports;
84 wbcx.typeck_results.treat_byte_string_as_slice =
85 mem::take(&mut self.typeck_results.borrow_mut().treat_byte_string_as_slice);
87 if self.is_tainted_by_errors() {
88 // FIXME(eddyb) keep track of `ErrorGuaranteed` from where the error was emitted.
89 wbcx.typeck_results.tainted_by_errors =
90 Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
93 debug!("writeback: typeck results for {:?} are {:#?}", item_def_id, wbcx.typeck_results);
95 self.tcx.arena.alloc(wbcx.typeck_results)
99 ///////////////////////////////////////////////////////////////////////////
100 // The Writeback context. This visitor walks the HIR, checking the
101 // fn-specific typeck results to find references to types or regions. It
102 // resolves those regions to remove inference variables and writes the
103 // final result back into the master typeck results in the tcx. Here and
104 // there, it applies a few ad-hoc checks that were not convenient to
107 struct WritebackCx<'cx, 'tcx> {
108 fcx: &'cx FnCtxt<'cx, 'tcx>,
110 typeck_results: ty::TypeckResults<'tcx>,
112 body: &'tcx hir::Body<'tcx>,
114 rustc_dump_user_substs: bool,
117 impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
119 fcx: &'cx FnCtxt<'cx, 'tcx>,
120 body: &'tcx hir::Body<'tcx>,
121 rustc_dump_user_substs: bool,
122 ) -> WritebackCx<'cx, 'tcx> {
123 let owner = body.id().hir_id.owner;
127 typeck_results: ty::TypeckResults::new(owner),
129 rustc_dump_user_substs,
133 fn tcx(&self) -> TyCtxt<'tcx> {
137 fn write_ty_to_typeck_results(&mut self, hir_id: hir::HirId, ty: Ty<'tcx>) {
138 debug!("write_ty_to_typeck_results({:?}, {:?})", hir_id, ty);
139 assert!(!ty.needs_infer() && !ty.has_placeholders() && !ty.has_free_regions());
140 self.typeck_results.node_types_mut().insert(hir_id, ty);
143 // Hacky hack: During type-checking, we treat *all* operators
144 // as potentially overloaded. But then, during writeback, if
145 // we observe that something like `a+b` is (known to be)
146 // operating on scalars, we clear the overload.
147 fn fix_scalar_builtin_expr(&mut self, e: &hir::Expr<'_>) {
149 hir::ExprKind::Unary(hir::UnOp::Neg | hir::UnOp::Not, inner) => {
150 let inner_ty = self.fcx.node_ty(inner.hir_id);
151 let inner_ty = self.fcx.resolve_vars_if_possible(inner_ty);
153 if inner_ty.is_scalar() {
154 let mut typeck_results = self.fcx.typeck_results.borrow_mut();
155 typeck_results.type_dependent_defs_mut().remove(e.hir_id);
156 typeck_results.node_substs_mut().remove(e.hir_id);
159 hir::ExprKind::Binary(ref op, lhs, rhs) | hir::ExprKind::AssignOp(ref op, lhs, rhs) => {
160 let lhs_ty = self.fcx.node_ty(lhs.hir_id);
161 let lhs_ty = self.fcx.resolve_vars_if_possible(lhs_ty);
163 let rhs_ty = self.fcx.node_ty(rhs.hir_id);
164 let rhs_ty = self.fcx.resolve_vars_if_possible(rhs_ty);
166 if lhs_ty.is_scalar() && rhs_ty.is_scalar() {
167 let mut typeck_results = self.fcx.typeck_results.borrow_mut();
168 typeck_results.type_dependent_defs_mut().remove(e.hir_id);
169 typeck_results.node_substs_mut().remove(e.hir_id);
172 hir::ExprKind::Binary(..) => {
173 if !op.node.is_by_value() {
174 let mut adjustments = typeck_results.adjustments_mut();
175 if let Some(a) = adjustments.get_mut(lhs.hir_id) {
178 if let Some(a) = adjustments.get_mut(rhs.hir_id) {
183 hir::ExprKind::AssignOp(..)
184 if let Some(a) = typeck_results.adjustments_mut().get_mut(lhs.hir_id) =>
196 // Similar to operators, indexing is always assumed to be overloaded
197 // Here, correct cases where an indexing expression can be simplified
198 // to use builtin indexing because the index type is known to be
200 fn fix_index_builtin_expr(&mut self, e: &hir::Expr<'_>) {
201 if let hir::ExprKind::Index(ref base, ref index) = e.kind {
202 let mut typeck_results = self.fcx.typeck_results.borrow_mut();
204 // All valid indexing looks like this; might encounter non-valid indexes at this point.
205 let base_ty = typeck_results
206 .expr_ty_adjusted_opt(base)
207 .map(|t| self.fcx.resolve_vars_if_possible(t).kind());
208 if base_ty.is_none() {
209 // When encountering `return [0][0]` outside of a `fn` body we can encounter a base
210 // that isn't in the type table. We assume more relevant errors have already been
211 // emitted, so we delay an ICE if none have. (#64638)
212 self.tcx().sess.delay_span_bug(e.span, &format!("bad base: `{:?}`", base));
214 if let Some(ty::Ref(_, base_ty, _)) = base_ty {
215 let index_ty = typeck_results.expr_ty_adjusted_opt(index).unwrap_or_else(|| {
216 // When encountering `return [0][0]` outside of a `fn` body we would attempt
217 // to access an nonexistent index. We assume that more relevant errors will
218 // already have been emitted, so we only gate on this with an ICE if no
219 // error has been emitted. (#64638)
220 self.fcx.tcx.ty_error_with_message(
222 &format!("bad index {:?} for base: `{:?}`", index, base),
225 let index_ty = self.fcx.resolve_vars_if_possible(index_ty);
227 if base_ty.builtin_index().is_some() && index_ty == self.fcx.tcx.types.usize {
228 // Remove the method call record
229 typeck_results.type_dependent_defs_mut().remove(e.hir_id);
230 typeck_results.node_substs_mut().remove(e.hir_id);
232 if let Some(a) = typeck_results.adjustments_mut().get_mut(base.hir_id) {
233 // Discard the need for a mutable borrow
235 // Extra adjustment made when indexing causes a drop
236 // of size information - we need to get rid of it
237 // Since this is "after" the other adjustment to be
238 // discarded, we do an extra `pop()`
239 if let Some(Adjustment {
240 kind: Adjust::Pointer(PointerCast::Unsize), ..
243 // So the borrow discard actually happens here
253 ///////////////////////////////////////////////////////////////////////////
254 // Impl of Visitor for Resolver
256 // This is the master code which walks the AST. It delegates most of
257 // the heavy lifting to the generic visit and resolve functions
258 // below. In general, a function is made into a `visitor` if it must
259 // traffic in node-ids or update typeck results in the type context etc.
261 impl<'cx, 'tcx> Visitor<'tcx> for WritebackCx<'cx, 'tcx> {
262 fn visit_expr(&mut self, e: &'tcx hir::Expr<'tcx>) {
263 self.fix_scalar_builtin_expr(e);
264 self.fix_index_builtin_expr(e);
267 hir::ExprKind::Closure(&hir::Closure { body, .. }) => {
268 let body = self.fcx.tcx.hir().body(body);
269 for param in body.params {
270 self.visit_node_id(e.span, param.hir_id);
273 self.visit_body(body);
275 hir::ExprKind::Struct(_, fields, _) => {
276 for field in fields {
277 self.visit_field_id(field.hir_id);
280 hir::ExprKind::Field(..) => {
281 self.visit_field_id(e.hir_id);
283 hir::ExprKind::ConstBlock(anon_const) => {
284 self.visit_node_id(e.span, anon_const.hir_id);
286 let body = self.tcx().hir().body(anon_const.body);
287 self.visit_body(body);
292 self.visit_node_id(e.span, e.hir_id);
293 intravisit::walk_expr(self, e);
296 fn visit_block(&mut self, b: &'tcx hir::Block<'tcx>) {
297 self.visit_node_id(b.span, b.hir_id);
298 intravisit::walk_block(self, b);
301 fn visit_pat(&mut self, p: &'tcx hir::Pat<'tcx>) {
303 hir::PatKind::Binding(..) => {
304 let typeck_results = self.fcx.typeck_results.borrow();
306 typeck_results.extract_binding_mode(self.tcx().sess, p.hir_id, p.span)
308 self.typeck_results.pat_binding_modes_mut().insert(p.hir_id, bm);
311 hir::PatKind::Struct(_, fields, _) => {
312 for field in fields {
313 self.visit_field_id(field.hir_id);
319 self.visit_pat_adjustments(p.span, p.hir_id);
321 self.visit_node_id(p.span, p.hir_id);
322 intravisit::walk_pat(self, p);
325 fn visit_local(&mut self, l: &'tcx hir::Local<'tcx>) {
326 intravisit::walk_local(self, l);
327 let var_ty = self.fcx.local_ty(l.span, l.hir_id).decl_ty;
328 let var_ty = self.resolve(var_ty, &l.span);
329 self.write_ty_to_typeck_results(l.hir_id, var_ty);
332 fn visit_ty(&mut self, hir_ty: &'tcx hir::Ty<'tcx>) {
333 intravisit::walk_ty(self, hir_ty);
334 let ty = self.fcx.node_ty(hir_ty.hir_id);
335 let ty = self.resolve(ty, &hir_ty.span);
336 self.write_ty_to_typeck_results(hir_ty.hir_id, ty);
339 fn visit_infer(&mut self, inf: &'tcx hir::InferArg) {
340 intravisit::walk_inf(self, inf);
341 // Ignore cases where the inference is a const.
342 if let Some(ty) = self.fcx.node_ty_opt(inf.hir_id) {
343 let ty = self.resolve(ty, &inf.span);
344 self.write_ty_to_typeck_results(inf.hir_id, ty);
349 impl<'cx, 'tcx> WritebackCx<'cx, 'tcx> {
350 fn eval_closure_size(&mut self) {
351 let mut res: FxHashMap<DefId, ClosureSizeProfileData<'tcx>> = Default::default();
352 for (closure_def_id, data) in self.fcx.typeck_results.borrow().closure_size_eval.iter() {
354 self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local());
356 let data = self.resolve(*data, &closure_hir_id);
358 res.insert(*closure_def_id, data);
361 self.typeck_results.closure_size_eval = res;
363 fn visit_min_capture_map(&mut self) {
364 let mut min_captures_wb = ty::MinCaptureInformationMap::with_capacity_and_hasher(
365 self.fcx.typeck_results.borrow().closure_min_captures.len(),
368 for (closure_def_id, root_min_captures) in
369 self.fcx.typeck_results.borrow().closure_min_captures.iter()
371 let mut root_var_map_wb = ty::RootVariableMinCaptureList::with_capacity_and_hasher(
372 root_min_captures.len(),
375 for (var_hir_id, min_list) in root_min_captures.iter() {
376 let min_list_wb = min_list
378 .map(|captured_place| {
379 let locatable = captured_place.info.path_expr_id.unwrap_or_else(|| {
380 self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local())
383 self.resolve(captured_place.clone(), &locatable)
386 root_var_map_wb.insert(*var_hir_id, min_list_wb);
388 min_captures_wb.insert(*closure_def_id, root_var_map_wb);
391 self.typeck_results.closure_min_captures = min_captures_wb;
394 fn visit_fake_reads_map(&mut self) {
395 let mut resolved_closure_fake_reads: FxHashMap<
397 Vec<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>,
398 > = Default::default();
399 for (closure_def_id, fake_reads) in
400 self.fcx.typeck_results.borrow().closure_fake_reads.iter()
402 let mut resolved_fake_reads = Vec::<(HirPlace<'tcx>, FakeReadCause, hir::HirId)>::new();
403 for (place, cause, hir_id) in fake_reads.iter() {
405 self.tcx().hir().local_def_id_to_hir_id(closure_def_id.expect_local());
407 let resolved_fake_read = self.resolve(place.clone(), &locatable);
408 resolved_fake_reads.push((resolved_fake_read, *cause, *hir_id));
410 resolved_closure_fake_reads.insert(*closure_def_id, resolved_fake_reads);
412 self.typeck_results.closure_fake_reads = resolved_closure_fake_reads;
415 fn visit_closures(&mut self) {
416 let fcx_typeck_results = self.fcx.typeck_results.borrow();
417 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
418 let common_hir_owner = fcx_typeck_results.hir_owner;
420 for (id, origin) in fcx_typeck_results.closure_kind_origins().iter() {
421 let hir_id = hir::HirId { owner: common_hir_owner, local_id: *id };
422 let place_span = origin.0;
423 let place = self.resolve(origin.1.clone(), &place_span);
424 self.typeck_results.closure_kind_origins_mut().insert(hir_id, (place_span, place));
428 fn visit_coercion_casts(&mut self) {
429 let fcx_typeck_results = self.fcx.typeck_results.borrow();
430 let fcx_coercion_casts = fcx_typeck_results.coercion_casts();
431 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
433 for local_id in fcx_coercion_casts {
434 self.typeck_results.set_coercion_cast(*local_id);
438 fn visit_user_provided_tys(&mut self) {
439 let fcx_typeck_results = self.fcx.typeck_results.borrow();
440 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
441 let common_hir_owner = fcx_typeck_results.hir_owner;
443 let mut errors_buffer = Vec::new();
444 for (&local_id, c_ty) in fcx_typeck_results.user_provided_types().iter() {
445 let hir_id = hir::HirId { owner: common_hir_owner, local_id };
447 if cfg!(debug_assertions) && c_ty.needs_infer() {
449 hir_id.to_span(self.fcx.tcx),
450 "writeback: `{:?}` has inference variables",
455 self.typeck_results.user_provided_types_mut().insert(hir_id, *c_ty);
457 if let ty::UserType::TypeOf(_, user_substs) = c_ty.value {
458 if self.rustc_dump_user_substs {
459 // This is a unit-testing mechanism.
460 let span = self.tcx().hir().span(hir_id);
461 // We need to buffer the errors in order to guarantee a consistent
462 // order when emitting them.
466 .struct_span_err(span, &format!("user substs: {:?}", user_substs));
467 err.buffer(&mut errors_buffer);
472 if !errors_buffer.is_empty() {
473 errors_buffer.sort_by_key(|diag| diag.span.primary_span());
474 for mut diag in errors_buffer.drain(..) {
475 self.tcx().sess.diagnostic().emit_diagnostic(&mut diag);
480 fn visit_user_provided_sigs(&mut self) {
481 let fcx_typeck_results = self.fcx.typeck_results.borrow();
482 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
484 for (&def_id, c_sig) in fcx_typeck_results.user_provided_sigs.iter() {
485 if cfg!(debug_assertions) && c_sig.needs_infer() {
487 self.fcx.tcx.hir().span_if_local(def_id).unwrap(),
488 "writeback: `{:?}` has inference variables",
493 self.typeck_results.user_provided_sigs.insert(def_id, *c_sig);
497 fn visit_generator_interior_types(&mut self) {
498 let fcx_typeck_results = self.fcx.typeck_results.borrow();
499 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
500 self.typeck_results.generator_interior_types =
501 fcx_typeck_results.generator_interior_types.clone();
504 #[instrument(skip(self), level = "debug")]
505 fn visit_opaque_types(&mut self) {
507 self.fcx.infcx.inner.borrow_mut().opaque_type_storage.take_opaque_types();
508 for (opaque_type_key, decl) in opaque_types {
509 let hidden_type = match decl.origin {
510 hir::OpaqueTyOrigin::FnReturn(_) | hir::OpaqueTyOrigin::AsyncFn(_) => {
511 let ty = self.resolve(decl.hidden_type.ty, &decl.hidden_type.span);
512 struct RecursionChecker {
515 impl<'tcx> ty::TypeVisitor<'tcx> for RecursionChecker {
517 fn visit_ty(&mut self, t: Ty<'tcx>) -> ControlFlow<Self::BreakTy> {
518 if let ty::Opaque(def_id, _) = *t.kind() {
519 if def_id == self.def_id.to_def_id() {
520 return ControlFlow::Break(());
523 t.super_visit_with(self)
527 .visit_with(&mut RecursionChecker { def_id: opaque_type_key.def_id })
534 hir::OpaqueTyOrigin::TyAlias => None,
536 self.typeck_results.concrete_opaque_types.insert(opaque_type_key.def_id, hidden_type);
540 fn visit_field_id(&mut self, hir_id: hir::HirId) {
541 if let Some(index) = self.fcx.typeck_results.borrow_mut().field_indices_mut().remove(hir_id)
543 self.typeck_results.field_indices_mut().insert(hir_id, index);
547 #[instrument(skip(self, span), level = "debug")]
548 fn visit_node_id(&mut self, span: Span, hir_id: hir::HirId) {
549 // Export associated path extensions and method resolutions.
551 self.fcx.typeck_results.borrow_mut().type_dependent_defs_mut().remove(hir_id)
553 self.typeck_results.type_dependent_defs_mut().insert(hir_id, def);
556 // Resolve any borrowings for the node with id `node_id`
557 self.visit_adjustments(span, hir_id);
559 // Resolve the type of the node with id `node_id`
560 let n_ty = self.fcx.node_ty(hir_id);
561 let n_ty = self.resolve(n_ty, &span);
562 self.write_ty_to_typeck_results(hir_id, n_ty);
565 // Resolve any substitutions
566 if let Some(substs) = self.fcx.typeck_results.borrow().node_substs_opt(hir_id) {
567 let substs = self.resolve(substs, &span);
568 debug!("write_substs_to_tcx({:?}, {:?})", hir_id, substs);
569 assert!(!substs.needs_infer() && !substs.has_placeholders());
570 self.typeck_results.node_substs_mut().insert(hir_id, substs);
574 #[instrument(skip(self, span), level = "debug")]
575 fn visit_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
576 let adjustment = self.fcx.typeck_results.borrow_mut().adjustments_mut().remove(hir_id);
579 debug!("no adjustments for node");
582 Some(adjustment) => {
583 let resolved_adjustment = self.resolve(adjustment, &span);
584 debug!(?resolved_adjustment);
585 self.typeck_results.adjustments_mut().insert(hir_id, resolved_adjustment);
590 #[instrument(skip(self, span), level = "debug")]
591 fn visit_pat_adjustments(&mut self, span: Span, hir_id: hir::HirId) {
592 let adjustment = self.fcx.typeck_results.borrow_mut().pat_adjustments_mut().remove(hir_id);
595 debug!("no pat_adjustments for node");
598 Some(adjustment) => {
599 let resolved_adjustment = self.resolve(adjustment, &span);
600 debug!(?resolved_adjustment);
601 self.typeck_results.pat_adjustments_mut().insert(hir_id, resolved_adjustment);
606 fn visit_liberated_fn_sigs(&mut self) {
607 let fcx_typeck_results = self.fcx.typeck_results.borrow();
608 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
609 let common_hir_owner = fcx_typeck_results.hir_owner;
611 for (&local_id, &fn_sig) in fcx_typeck_results.liberated_fn_sigs().iter() {
612 let hir_id = hir::HirId { owner: common_hir_owner, local_id };
613 let fn_sig = self.resolve(fn_sig, &hir_id);
614 self.typeck_results.liberated_fn_sigs_mut().insert(hir_id, fn_sig);
618 fn visit_fru_field_types(&mut self) {
619 let fcx_typeck_results = self.fcx.typeck_results.borrow();
620 assert_eq!(fcx_typeck_results.hir_owner, self.typeck_results.hir_owner);
621 let common_hir_owner = fcx_typeck_results.hir_owner;
623 for (&local_id, ftys) in fcx_typeck_results.fru_field_types().iter() {
624 let hir_id = hir::HirId { owner: common_hir_owner, local_id };
625 let ftys = self.resolve(ftys.clone(), &hir_id);
626 self.typeck_results.fru_field_types_mut().insert(hir_id, ftys);
630 fn resolve<T>(&mut self, x: T, span: &dyn Locatable) -> T
632 T: TypeFoldable<'tcx>,
634 let mut resolver = Resolver::new(self.fcx, span, self.body);
635 let x = x.fold_with(&mut resolver);
636 if cfg!(debug_assertions) && x.needs_infer() {
637 span_bug!(span.to_span(self.fcx.tcx), "writeback: `{:?}` has inference variables", x);
640 // We may have introduced e.g. `ty::Error`, if inference failed, make sure
641 // to mark the `TypeckResults` as tainted in that case, so that downstream
642 // users of the typeck results don't produce extra errors, or worse, ICEs.
643 if resolver.replaced_with_error {
644 // FIXME(eddyb) keep track of `ErrorGuaranteed` from where the error was emitted.
645 self.typeck_results.tainted_by_errors =
646 Some(ErrorGuaranteed::unchecked_claim_error_was_emitted());
653 pub(crate) trait Locatable {
654 fn to_span(&self, tcx: TyCtxt<'_>) -> Span;
657 impl Locatable for Span {
658 fn to_span(&self, _: TyCtxt<'_>) -> Span {
663 impl Locatable for hir::HirId {
664 fn to_span(&self, tcx: TyCtxt<'_>) -> Span {
665 tcx.hir().span(*self)
669 /// The Resolver. This is the type folding engine that detects
670 /// unresolved types and so forth.
671 struct Resolver<'cx, 'tcx> {
673 infcx: &'cx InferCtxt<'cx, 'tcx>,
674 span: &'cx dyn Locatable,
675 body: &'tcx hir::Body<'tcx>,
677 /// Set to `true` if any `Ty` or `ty::Const` had to be replaced with an `Error`.
678 replaced_with_error: bool,
681 impl<'cx, 'tcx> Resolver<'cx, 'tcx> {
683 fcx: &'cx FnCtxt<'cx, 'tcx>,
684 span: &'cx dyn Locatable,
685 body: &'tcx hir::Body<'tcx>,
686 ) -> Resolver<'cx, 'tcx> {
687 Resolver { tcx: fcx.tcx, infcx: fcx, span, body, replaced_with_error: false }
690 fn report_type_error(&self, t: Ty<'tcx>) {
691 if !self.tcx.sess.has_errors().is_some() {
693 .emit_inference_failure_err(
694 Some(self.body.id()),
695 self.span.to_span(self.tcx),
704 fn report_const_error(&self, c: ty::Const<'tcx>) {
705 if self.tcx.sess.has_errors().is_none() {
707 .emit_inference_failure_err(
708 Some(self.body.id()),
709 self.span.to_span(self.tcx),
719 struct EraseEarlyRegions<'tcx> {
723 impl<'tcx> TypeFolder<'tcx> for EraseEarlyRegions<'tcx> {
724 fn tcx<'b>(&'b self) -> TyCtxt<'tcx> {
727 fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
728 if ty.has_type_flags(ty::TypeFlags::HAS_FREE_REGIONS) {
729 ty.super_fold_with(self)
734 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
735 if r.is_late_bound() { r } else { self.tcx.lifetimes.re_erased }
739 impl<'cx, 'tcx> TypeFolder<'tcx> for Resolver<'cx, 'tcx> {
740 fn tcx<'a>(&'a self) -> TyCtxt<'tcx> {
744 fn fold_ty(&mut self, t: Ty<'tcx>) -> Ty<'tcx> {
745 match self.infcx.fully_resolve(t) {
747 // Do not anonymize late-bound regions
748 // (e.g. keep `for<'a>` named `for<'a>`).
749 // This allows NLL to generate error messages that
750 // refer to the higher-ranked lifetime names written by the user.
751 EraseEarlyRegions { tcx: self.infcx.tcx }.fold_ty(t)
754 debug!("Resolver::fold_ty: input type `{:?}` not fully resolvable", t);
755 self.report_type_error(t);
756 self.replaced_with_error = true;
757 self.tcx().ty_error()
762 fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
763 debug_assert!(!r.is_late_bound(), "Should not be resolving bound region.");
764 self.tcx.lifetimes.re_erased
767 fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
768 match self.infcx.fully_resolve(ct) {
769 Ok(ct) => self.infcx.tcx.erase_regions(ct),
771 debug!("Resolver::fold_const: input const `{:?}` not fully resolvable", ct);
772 self.report_const_error(ct);
773 self.replaced_with_error = true;
774 self.tcx().const_error(ct.ty())
780 ///////////////////////////////////////////////////////////////////////////
781 // During type check, we store promises with the result of trait
782 // lookup rather than the actual results (because the results are not
783 // necessarily available immediately). These routines unwind the
784 // promises. It is expected that we will have already reported any
785 // errors that may be encountered, so if the promises store an error,
786 // a dummy result is returned.