rustc_hir_analysis/collect/type_of/
opaque.rs1use rustc_hir::def::DefKind;
2use rustc_hir::def_id::LocalDefId;
3use rustc_hir::intravisit::{self, Visitor};
4use rustc_hir::{self as hir, Expr, ImplItem, Item, Node, TraitItem, def};
5use rustc_middle::bug;
6use rustc_middle::hir::nested_filter;
7use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt};
8use rustc_span::DUMMY_SP;
9use tracing::{debug, instrument, trace};
10
11use crate::errors::{TaitForwardCompat, TaitForwardCompat2, UnconstrainedOpaqueType};
12
13#[instrument(skip(tcx), level = "debug")]
16pub(super) fn find_opaque_ty_constraints_for_impl_trait_in_assoc_type(
17 tcx: TyCtxt<'_>,
18 def_id: LocalDefId,
19) -> Ty<'_> {
20 let mut parent_def_id = def_id;
21 while tcx.def_kind(parent_def_id) == def::DefKind::OpaqueTy {
22 parent_def_id = tcx.local_parent(parent_def_id);
24 }
25 let impl_def_id = tcx.local_parent(parent_def_id);
26 match tcx.def_kind(impl_def_id) {
27 DefKind::Impl { .. } => {}
28 other => bug!("invalid impl trait in assoc type parent: {other:?}"),
29 }
30
31 let mut locator = TaitConstraintLocator { def_id, tcx, found: None, typeck_types: vec![] };
32
33 for &assoc_id in tcx.associated_item_def_ids(impl_def_id) {
34 let assoc = tcx.associated_item(assoc_id);
35 match assoc.kind {
36 ty::AssocKind::Const | ty::AssocKind::Fn => locator.check(assoc_id.expect_local()),
37 ty::AssocKind::Type => {}
39 }
40 }
41
42 if let Some(hidden) = locator.found {
43 if !hidden.ty.references_error() {
45 for concrete_type in locator.typeck_types {
46 if concrete_type.ty != tcx.erase_regions(hidden.ty) {
47 if let Ok(d) = hidden.build_mismatch_error(&concrete_type, tcx) {
48 d.emit();
49 }
50 }
51 }
52 }
53
54 hidden.ty
55 } else {
56 let reported = tcx.dcx().emit_err(UnconstrainedOpaqueType {
57 span: tcx.def_span(def_id),
58 name: tcx.item_ident(parent_def_id.to_def_id()),
59 what: "impl",
60 });
61 Ty::new_error(tcx, reported)
62 }
63}
64
65#[instrument(skip(tcx), level = "debug")]
84pub(super) fn find_opaque_ty_constraints_for_tait(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Ty<'_> {
85 let hir_id = tcx.local_def_id_to_hir_id(def_id);
86 let scope = tcx.hir().get_defining_scope(hir_id);
87 let mut locator = TaitConstraintLocator { def_id, tcx, found: None, typeck_types: vec![] };
88
89 debug!(?scope);
90
91 if scope == hir::CRATE_HIR_ID {
92 tcx.hir().walk_toplevel_module(&mut locator);
93 } else {
94 trace!("scope={:#?}", tcx.hir_node(scope));
95 match tcx.hir_node(scope) {
96 Node::Item(it) => locator.visit_item(it),
111 Node::ImplItem(it) => locator.visit_impl_item(it),
112 Node::TraitItem(it) => locator.visit_trait_item(it),
113 Node::ForeignItem(it) => locator.visit_foreign_item(it),
114 other => bug!("{:?} is not a valid scope for an opaque type item", other),
115 }
116 }
117
118 if let Some(hidden) = locator.found {
119 if !hidden.ty.references_error() {
121 for concrete_type in locator.typeck_types {
122 if concrete_type.ty != tcx.erase_regions(hidden.ty) {
123 if let Ok(d) = hidden.build_mismatch_error(&concrete_type, tcx) {
124 d.emit();
125 }
126 }
127 }
128 }
129
130 hidden.ty
131 } else {
132 let mut parent_def_id = def_id;
133 while tcx.def_kind(parent_def_id) == def::DefKind::OpaqueTy {
134 parent_def_id = tcx.local_parent(parent_def_id);
136 }
137 let reported = tcx.dcx().emit_err(UnconstrainedOpaqueType {
138 span: tcx.def_span(def_id),
139 name: tcx.item_ident(parent_def_id.to_def_id()),
140 what: match tcx.hir_node(scope) {
141 _ if scope == hir::CRATE_HIR_ID => "module",
142 Node::Item(hir::Item { kind: hir::ItemKind::Mod(_), .. }) => "module",
143 Node::Item(hir::Item { kind: hir::ItemKind::Impl(_), .. }) => "impl",
144 _ => "item",
145 },
146 });
147 Ty::new_error(tcx, reported)
148 }
149}
150
151struct TaitConstraintLocator<'tcx> {
152 tcx: TyCtxt<'tcx>,
153
154 def_id: LocalDefId,
156
157 found: Option<ty::OpaqueHiddenType<'tcx>>,
163
164 typeck_types: Vec<ty::OpaqueHiddenType<'tcx>>,
168}
169
170impl TaitConstraintLocator<'_> {
171 #[instrument(skip(self), level = "debug")]
172 fn check(&mut self, item_def_id: LocalDefId) {
173 if !self.tcx.has_typeck_results(item_def_id) {
175 debug!("no constraint: no typeck results");
176 return;
177 }
178
179 let hir_node = self.tcx.hir_node_by_def_id(item_def_id);
184 debug_assert!(
185 !matches!(hir_node, Node::ForeignItem(..)),
186 "foreign items cannot constrain opaque types",
187 );
188 if let Some(hir_sig) = hir_node.fn_sig()
189 && hir_sig.decl.output.is_suggestable_infer_ty().is_some()
190 {
191 let guar = self.tcx.dcx().span_delayed_bug(
192 hir_sig.decl.output.span(),
193 "inferring return types and opaque types do not mix well",
194 );
195 self.found =
196 Some(ty::OpaqueHiddenType { span: DUMMY_SP, ty: Ty::new_error(self.tcx, guar) });
197 return;
198 }
199
200 let tables = self.tcx.typeck(item_def_id);
212 if let Some(guar) = tables.tainted_by_errors {
213 self.found =
214 Some(ty::OpaqueHiddenType { span: DUMMY_SP, ty: Ty::new_error(self.tcx, guar) });
215 return;
216 }
217
218 let opaque_types_defined_by = self.tcx.opaque_types_defined_by(item_def_id);
219
220 let mut constrained = false;
221 for (&opaque_type_key, &hidden_type) in &tables.concrete_opaque_types {
222 if opaque_type_key.def_id != self.def_id {
223 continue;
224 }
225 constrained = true;
226
227 if !opaque_types_defined_by.contains(&self.def_id) {
228 let guar = self.tcx.dcx().emit_err(TaitForwardCompat {
229 span: hidden_type.span,
230 item_span: self
231 .tcx
232 .def_ident_span(item_def_id)
233 .unwrap_or_else(|| self.tcx.def_span(item_def_id)),
234 });
235 self.found = Some(ty::OpaqueHiddenType {
237 span: DUMMY_SP,
238 ty: Ty::new_error(self.tcx, guar),
239 });
240 }
241 let concrete_type =
242 self.tcx.erase_regions(hidden_type.remap_generic_params_to_declaration_params(
243 opaque_type_key,
244 self.tcx,
245 true,
246 ));
247 if self.typeck_types.iter().all(|prev| prev.ty != concrete_type.ty) {
248 self.typeck_types.push(concrete_type);
249 }
250 }
251
252 if !constrained {
253 debug!("no constraints in typeck results");
254 if opaque_types_defined_by.contains(&self.def_id) {
255 let guar = self.tcx.dcx().emit_err(TaitForwardCompat2 {
256 span: self
257 .tcx
258 .def_ident_span(item_def_id)
259 .unwrap_or_else(|| self.tcx.def_span(item_def_id)),
260 opaque_type_span: self.tcx.def_span(self.def_id),
261 opaque_type: self.tcx.def_path_str(self.def_id),
262 });
263 self.found = Some(ty::OpaqueHiddenType {
265 span: DUMMY_SP,
266 ty: Ty::new_error(self.tcx, guar),
267 });
268 }
269 return;
270 };
271
272 let borrowck_results = &self.tcx.mir_borrowck(item_def_id);
274
275 if let Some(guar) = borrowck_results.tainted_by_errors {
277 self.found =
278 Some(ty::OpaqueHiddenType { span: DUMMY_SP, ty: Ty::new_error(self.tcx, guar) });
279 return;
280 }
281
282 debug!(?borrowck_results.concrete_opaque_types);
283 if let Some(&concrete_type) = borrowck_results.concrete_opaque_types.get(&self.def_id) {
284 debug!(?concrete_type, "found constraint");
285 if let Some(prev) = &mut self.found {
286 if concrete_type.ty != prev.ty {
287 let (Ok(guar) | Err(guar)) =
288 prev.build_mismatch_error(&concrete_type, self.tcx).map(|d| d.emit());
289 prev.ty = Ty::new_error(self.tcx, guar);
290 }
291 } else {
292 self.found = Some(concrete_type);
293 }
294 }
295 }
296}
297
298impl<'tcx> intravisit::Visitor<'tcx> for TaitConstraintLocator<'tcx> {
299 type NestedFilter = nested_filter::All;
300
301 fn nested_visit_map(&mut self) -> Self::Map {
302 self.tcx.hir()
303 }
304 fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
305 if let hir::ExprKind::Closure(closure) = ex.kind {
306 self.check(closure.def_id);
307 }
308 intravisit::walk_expr(self, ex);
309 }
310 fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
311 trace!(?it.owner_id);
312 if it.owner_id.def_id != self.def_id {
314 self.check(it.owner_id.def_id);
315 intravisit::walk_item(self, it);
316 }
317 }
318 fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
319 trace!(?it.owner_id);
320 if it.owner_id.def_id != self.def_id {
322 self.check(it.owner_id.def_id);
323 intravisit::walk_impl_item(self, it);
324 }
325 }
326 fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
327 trace!(?it.owner_id);
328 self.check(it.owner_id.def_id);
329 intravisit::walk_trait_item(self, it);
330 }
331 fn visit_foreign_item(&mut self, it: &'tcx hir::ForeignItem<'tcx>) {
332 trace!(?it.owner_id);
333 assert_ne!(it.owner_id.def_id, self.def_id);
334 intravisit::walk_foreign_item(self, it);
336 }
337}
338
339pub(super) fn find_opaque_ty_constraints_for_rpit<'tcx>(
340 tcx: TyCtxt<'tcx>,
341 def_id: LocalDefId,
342 owner_def_id: LocalDefId,
343) -> Ty<'tcx> {
344 let tables = tcx.typeck(owner_def_id);
345
346 let mut hir_opaque_ty: Option<ty::OpaqueHiddenType<'tcx>> = None;
352 if tables.tainted_by_errors.is_none() {
353 for (&opaque_type_key, &hidden_type) in &tables.concrete_opaque_types {
354 if opaque_type_key.def_id != def_id {
355 continue;
356 }
357 let concrete_type = tcx.erase_regions(
358 hidden_type.remap_generic_params_to_declaration_params(opaque_type_key, tcx, true),
359 );
360 if let Some(prev) = &mut hir_opaque_ty {
361 if concrete_type.ty != prev.ty {
362 if let Ok(d) = prev.build_mismatch_error(&concrete_type, tcx) {
363 d.emit();
364 }
365 }
366 } else {
367 hir_opaque_ty = Some(concrete_type);
368 }
369 }
370 }
371
372 let mir_opaque_ty = tcx.mir_borrowck(owner_def_id).concrete_opaque_types.get(&def_id).copied();
373 if let Some(mir_opaque_ty) = mir_opaque_ty {
374 if mir_opaque_ty.references_error() {
375 return mir_opaque_ty.ty;
376 }
377
378 debug!(?owner_def_id);
379 let mut locator = RpitConstraintChecker { def_id, tcx, found: mir_opaque_ty };
380
381 match tcx.hir_node_by_def_id(owner_def_id) {
382 Node::Item(it) => intravisit::walk_item(&mut locator, it),
383 Node::ImplItem(it) => intravisit::walk_impl_item(&mut locator, it),
384 Node::TraitItem(it) => intravisit::walk_trait_item(&mut locator, it),
385 other => bug!("{:?} is not a valid scope for an opaque type item", other),
386 }
387
388 mir_opaque_ty.ty
389 } else if let Some(guar) = tables.tainted_by_errors {
390 Ty::new_error(tcx, guar)
393 } else {
394 if let Some(hir_opaque_ty) = hir_opaque_ty {
396 hir_opaque_ty.ty
397 } else {
398 Ty::new_diverging_default(tcx)
405 }
406 }
407}
408
409struct RpitConstraintChecker<'tcx> {
410 tcx: TyCtxt<'tcx>,
411
412 def_id: LocalDefId,
414
415 found: ty::OpaqueHiddenType<'tcx>,
416}
417
418impl RpitConstraintChecker<'_> {
419 #[instrument(skip(self), level = "debug")]
420 fn check(&self, def_id: LocalDefId) {
421 let concrete_opaque_types = &self.tcx.mir_borrowck(def_id).concrete_opaque_types;
423 debug!(?concrete_opaque_types);
424 for (&def_id, &concrete_type) in concrete_opaque_types {
425 if def_id != self.def_id {
426 continue;
428 }
429
430 debug!(?concrete_type, "found constraint");
431
432 if concrete_type.ty != self.found.ty {
433 if let Ok(d) = self.found.build_mismatch_error(&concrete_type, self.tcx) {
434 d.emit();
435 }
436 }
437 }
438 }
439}
440
441impl<'tcx> intravisit::Visitor<'tcx> for RpitConstraintChecker<'tcx> {
442 type NestedFilter = nested_filter::OnlyBodies;
443
444 fn nested_visit_map(&mut self) -> Self::Map {
445 self.tcx.hir()
446 }
447 fn visit_expr(&mut self, ex: &'tcx Expr<'tcx>) {
448 if let hir::ExprKind::Closure(closure) = ex.kind {
449 self.check(closure.def_id);
450 }
451 intravisit::walk_expr(self, ex);
452 }
453 fn visit_item(&mut self, it: &'tcx Item<'tcx>) {
454 trace!(?it.owner_id);
455 if it.owner_id.def_id != self.def_id {
457 self.check(it.owner_id.def_id);
458 intravisit::walk_item(self, it);
459 }
460 }
461 fn visit_impl_item(&mut self, it: &'tcx ImplItem<'tcx>) {
462 trace!(?it.owner_id);
463 if it.owner_id.def_id != self.def_id {
465 self.check(it.owner_id.def_id);
466 intravisit::walk_impl_item(self, it);
467 }
468 }
469 fn visit_trait_item(&mut self, it: &'tcx TraitItem<'tcx>) {
470 trace!(?it.owner_id);
471 self.check(it.owner_id.def_id);
472 intravisit::walk_trait_item(self, it);
473 }
474}