rustc_hir_analysis/collect/type_of/
opaque.rs

1use 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/// Checks "defining uses" of opaque `impl Trait` in associated types.
14/// These can only be defined by associated items of the same trait.
15#[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        // Account for `type Alias = impl Trait<Foo = impl Trait>;` (#116031)
23        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            // Associated types don't have bodies, so they can't constrain hidden types
38            ty::AssocKind::Type => {}
39        }
40    }
41
42    if let Some(hidden) = locator.found {
43        // Only check against typeck if we didn't already error
44        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/// Checks "defining uses" of opaque `impl Trait` types to ensure that they meet the restrictions
66/// laid for "higher-order pattern unification".
67/// This ensures that inference is tractable.
68/// In particular, definitions of opaque types can only use other generics as arguments,
69/// and they cannot repeat an argument. Example:
70///
71/// ```ignore (illustrative)
72/// type Foo<A, B> = impl Bar<A, B>;
73///
74/// // Okay -- `Foo` is applied to two distinct, generic types.
75/// fn a<T, U>() -> Foo<T, U> { .. }
76///
77/// // Not okay -- `Foo` is applied to `T` twice.
78/// fn b<T>() -> Foo<T, T> { .. }
79///
80/// // Not okay -- `Foo` is applied to a non-generic type.
81/// fn b<T>() -> Foo<T, u32> { .. }
82/// ```
83#[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            // We explicitly call `visit_*` methods, instead of using `intravisit::walk_*` methods
97            // This allows our visitor to process the defining item itself, causing
98            // it to pick up any 'sibling' defining uses.
99            //
100            // For example, this code:
101            // ```
102            // fn foo() {
103            //     type Blah = impl Debug;
104            //     let my_closure = || -> Blah { true };
105            // }
106            // ```
107            //
108            // requires us to explicitly process `foo()` in order
109            // to notice the defining usage of `Blah`.
110            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        // Only check against typeck if we didn't already error
120        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            // Account for `type Alias = impl Trait<Foo = impl Trait>;` (#116031)
135            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 of the opaque type whose defining uses are being checked
155    def_id: LocalDefId,
156
157    /// as we walk the defining uses, we are checking that all of them
158    /// define the same hidden type. This variable is set to `Some`
159    /// with the first type that we find, and then later types are
160    /// checked against it (we also carry the span of that first
161    /// type).
162    found: Option<ty::OpaqueHiddenType<'tcx>>,
163
164    /// In the presence of dead code, typeck may figure out a hidden type
165    /// while borrowck will not. We collect these cases here and check at
166    /// the end that we actually found a type that matches (modulo regions).
167    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        // Don't try to check items that cannot possibly constrain the type.
174        if !self.tcx.has_typeck_results(item_def_id) {
175            debug!("no constraint: no typeck results");
176            return;
177        }
178
179        // Function items with `_` in their return type already emit an error, skip any
180        // "non-defining use" errors for them.
181        // Note that we use `Node::fn_sig` instead of `Node::fn_decl` here, because the former
182        // excludes closures, which are allowed to have `_` in their return type.
183        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        // Calling `mir_borrowck` can lead to cycle errors through
201        // const-checking, avoid calling it if we don't have to.
202        // ```rust
203        // type Foo = impl Fn() -> usize; // when computing type for this
204        // const fn bar() -> Foo {
205        //     || 0usize
206        // }
207        // const BAZR: Foo = bar(); // we would mir-borrowck this, causing cycles
208        // // because we again need to reveal `Foo` so we can check whether the
209        // // constant does not contain interior mutability.
210        // ```
211        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                // Avoid "opaque type not constrained" errors on the opaque itself.
236                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                // Avoid "opaque type not constrained" errors on the opaque itself.
264                self.found = Some(ty::OpaqueHiddenType {
265                    span: DUMMY_SP,
266                    ty: Ty::new_error(self.tcx, guar),
267                });
268            }
269            return;
270        };
271
272        // Use borrowck to get the type with unerased regions.
273        let borrowck_results = &self.tcx.mir_borrowck(item_def_id);
274
275        // If the body was tainted, then assume the opaque may have been constrained and just set it to error.
276        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        // The opaque type itself or its children are not within its reveal scope.
313        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        // The opaque type itself or its children are not within its reveal scope.
321        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        // No need to call `check`, as we do not run borrowck on foreign items.
335        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    // Check that all of the opaques we inferred during HIR are compatible.
347    // FIXME: We explicitly don't check that the types inferred during HIR
348    // typeck are compatible with the one that we infer during borrowck,
349    // because that one actually sometimes has consts evaluated eagerly so
350    // using strict type equality will fail.
351    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        // Some error in the owner fn prevented us from populating
391        // the `concrete_opaque_types` table.
392        Ty::new_error(tcx, guar)
393    } else {
394        // Fall back to the RPIT we inferred during HIR typeck
395        if let Some(hir_opaque_ty) = hir_opaque_ty {
396            hir_opaque_ty.ty
397        } else {
398            // We failed to resolve the opaque type or it
399            // resolves to itself. We interpret this as the
400            // no values of the hidden type ever being constructed,
401            // so we can just make the hidden type be `!`.
402            // For backwards compatibility reasons, we fall back to
403            // `()` until we the diverging default is changed.
404            Ty::new_diverging_default(tcx)
405        }
406    }
407}
408
409struct RpitConstraintChecker<'tcx> {
410    tcx: TyCtxt<'tcx>,
411
412    /// def_id of the opaque type whose defining uses are being checked
413    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        // Use borrowck to get the type with unerased regions.
422        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                // Ignore constraints for other opaque types.
427                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        // The opaque type itself or its children are not within its reveal scope.
456        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        // The opaque type itself or its children are not within its reveal scope.
464        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}