rustc_next_trait_solver/solve/normalizes_to/
opaque_types.rs

1//! Computes a normalizes-to (projection) goal for opaque types. This goal
2//! behaves differently depending on the current `TypingMode`.
3
4use rustc_index::bit_set::GrowableBitSet;
5use rustc_type_ir::fold::fold_regions;
6use rustc_type_ir::inherent::*;
7use rustc_type_ir::{self as ty, Interner, TypingMode};
8
9use crate::delegate::SolverDelegate;
10use crate::solve::{Certainty, EvalCtxt, Goal, NoSolution, QueryResult, inspect};
11
12impl<D, I> EvalCtxt<'_, D>
13where
14    D: SolverDelegate<Interner = I>,
15    I: Interner,
16{
17    pub(super) fn normalize_opaque_type(
18        &mut self,
19        goal: Goal<I, ty::NormalizesTo<I>>,
20    ) -> QueryResult<I> {
21        let cx = self.cx();
22        let opaque_ty = goal.predicate.alias;
23        let expected = goal.predicate.term.as_type().expect("no such thing as an opaque const");
24
25        match self.typing_mode() {
26            TypingMode::Coherence => {
27                // An impossible opaque type bound is the only way this goal will fail
28                // e.g. assigning `impl Copy := NotCopy`
29                self.add_item_bounds_for_hidden_type(
30                    opaque_ty.def_id,
31                    opaque_ty.args,
32                    goal.param_env,
33                    expected,
34                );
35                self.evaluate_added_goals_and_make_canonical_response(Certainty::AMBIGUOUS)
36            }
37            TypingMode::Analysis { defining_opaque_types } => {
38                let Some(def_id) = opaque_ty
39                    .def_id
40                    .as_local()
41                    .filter(|&def_id| defining_opaque_types.contains(&def_id))
42                else {
43                    self.structurally_instantiate_normalizes_to_term(goal, goal.predicate.alias);
44                    return self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes);
45                };
46
47                // FIXME: This may have issues when the args contain aliases...
48                match uses_unique_placeholders_ignoring_regions(self.cx(), opaque_ty.args) {
49                    Err(NotUniqueParam::NotParam(param)) if param.is_non_region_infer() => {
50                        return self.evaluate_added_goals_and_make_canonical_response(
51                            Certainty::AMBIGUOUS,
52                        );
53                    }
54                    Err(_) => {
55                        return Err(NoSolution);
56                    }
57                    Ok(()) => {}
58                }
59                // Prefer opaques registered already.
60                let opaque_type_key = ty::OpaqueTypeKey { def_id, args: opaque_ty.args };
61                // FIXME: This also unifies the previous hidden type with the expected.
62                //
63                // If that fails, we insert `expected` as a new hidden type instead of
64                // eagerly emitting an error.
65                let existing = self.probe_existing_opaque_ty(opaque_type_key);
66                if let Some((candidate_key, candidate_ty)) = existing {
67                    return self
68                        .probe(|result| inspect::ProbeKind::OpaqueTypeStorageLookup {
69                            result: *result,
70                        })
71                        .enter(|ecx| {
72                            for (a, b) in std::iter::zip(
73                                candidate_key.args.iter(),
74                                opaque_type_key.args.iter(),
75                            ) {
76                                ecx.eq(goal.param_env, a, b)?;
77                            }
78                            ecx.eq(goal.param_env, candidate_ty, expected)?;
79                            ecx.add_item_bounds_for_hidden_type(
80                                def_id.into(),
81                                candidate_key.args,
82                                goal.param_env,
83                                candidate_ty,
84                            );
85                            ecx.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
86                        });
87                }
88
89                // Otherwise, define a new opaque type
90                // FIXME: should we use `inject_hidden_type_unchecked` here?
91                self.insert_hidden_type(opaque_type_key, goal.param_env, expected)?;
92                self.add_item_bounds_for_hidden_type(
93                    def_id.into(),
94                    opaque_ty.args,
95                    goal.param_env,
96                    expected,
97                );
98                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
99            }
100            TypingMode::PostBorrowckAnalysis { defined_opaque_types } => {
101                let Some(def_id) = opaque_ty
102                    .def_id
103                    .as_local()
104                    .filter(|&def_id| defined_opaque_types.contains(&def_id))
105                else {
106                    self.structurally_instantiate_normalizes_to_term(goal, goal.predicate.alias);
107                    return self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes);
108                };
109
110                let actual = cx.type_of(def_id.into()).instantiate(cx, opaque_ty.args);
111                // FIXME: Actually use a proper binder here instead of relying on `ReErased`.
112                //
113                // This is also probably unsound or sth :shrug:
114                let actual = fold_regions(cx, actual, |re, _dbi| match re.kind() {
115                    ty::ReErased => self.next_region_var(),
116                    _ => re,
117                });
118                self.eq(goal.param_env, expected, actual)?;
119                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
120            }
121            TypingMode::PostAnalysis => {
122                // FIXME: Add an assertion that opaque type storage is empty.
123                let actual = cx.type_of(opaque_ty.def_id).instantiate(cx, opaque_ty.args);
124                self.eq(goal.param_env, expected, actual)?;
125                self.evaluate_added_goals_and_make_canonical_response(Certainty::Yes)
126            }
127        }
128    }
129}
130
131/// Checks whether each generic argument is simply a unique generic placeholder.
132///
133/// FIXME: Interner argument is needed to constrain the `I` parameter.
134fn uses_unique_placeholders_ignoring_regions<I: Interner>(
135    _cx: I,
136    args: I::GenericArgs,
137) -> Result<(), NotUniqueParam<I>> {
138    let mut seen = GrowableBitSet::default();
139    for arg in args.iter() {
140        match arg.kind() {
141            // Ignore regions, since we can't resolve those in a canonicalized
142            // query in the trait solver.
143            ty::GenericArgKind::Lifetime(_) => {}
144            ty::GenericArgKind::Type(t) => match t.kind() {
145                ty::Placeholder(p) => {
146                    if !seen.insert(p.var()) {
147                        return Err(NotUniqueParam::DuplicateParam(t.into()));
148                    }
149                }
150                _ => return Err(NotUniqueParam::NotParam(t.into())),
151            },
152            ty::GenericArgKind::Const(c) => match c.kind() {
153                ty::ConstKind::Placeholder(p) => {
154                    if !seen.insert(p.var()) {
155                        return Err(NotUniqueParam::DuplicateParam(c.into()));
156                    }
157                }
158                _ => return Err(NotUniqueParam::NotParam(c.into())),
159            },
160        }
161    }
162
163    Ok(())
164}
165
166// FIXME: This should check for dupes and non-params first, then infer vars.
167enum NotUniqueParam<I: Interner> {
168    DuplicateParam(I::GenericArg),
169    NotParam(I::GenericArg),
170}