rustc_trait_selection/
opaque_types.rs

1use rustc_data_structures::fx::FxIndexMap;
2use rustc_hir::OpaqueTyOrigin;
3use rustc_hir::def_id::LocalDefId;
4use rustc_infer::infer::outlives::env::OutlivesEnvironment;
5use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
6use rustc_middle::ty::{
7    self, DefiningScopeKind, GenericArgKind, GenericArgs, OpaqueTypeKey, Ty, TyCtxt,
8    TypeVisitableExt, TypingMode, fold_regions,
9};
10use rustc_span::{ErrorGuaranteed, Span};
11
12use crate::errors::NonGenericOpaqueTypeParam;
13use crate::regions::OutlivesEnvironmentBuildExt;
14use crate::traits::ObligationCtxt;
15
16#[derive(Debug)]
17pub enum NonDefiningUseReason<'tcx> {
18    Tainted(ErrorGuaranteed),
19    NotAParam { opaque_type_key: OpaqueTypeKey<'tcx>, param_index: usize, span: Span },
20    DuplicateParam { opaque_type_key: OpaqueTypeKey<'tcx>, param_indices: Vec<usize>, span: Span },
21}
22impl From<ErrorGuaranteed> for NonDefiningUseReason<'_> {
23    fn from(guar: ErrorGuaranteed) -> Self {
24        NonDefiningUseReason::Tainted(guar)
25    }
26}
27impl<'tcx> NonDefiningUseReason<'tcx> {
28    pub fn report(self, infcx: &InferCtxt<'tcx>) -> ErrorGuaranteed {
29        let tcx = infcx.tcx;
30        match self {
31            NonDefiningUseReason::Tainted(guar) => guar,
32            NonDefiningUseReason::NotAParam { opaque_type_key, param_index, span } => {
33                let opaque_generics = tcx.generics_of(opaque_type_key.def_id);
34                let opaque_param = opaque_generics.param_at(param_index, tcx);
35                let kind = opaque_param.kind.descr();
36                infcx.dcx().emit_err(NonGenericOpaqueTypeParam {
37                    arg: opaque_type_key.args[param_index],
38                    kind,
39                    span,
40                    param_span: tcx.def_span(opaque_param.def_id),
41                })
42            }
43            NonDefiningUseReason::DuplicateParam { opaque_type_key, param_indices, span } => {
44                let opaque_generics = tcx.generics_of(opaque_type_key.def_id);
45                let descr = opaque_generics.param_at(param_indices[0], tcx).kind.descr();
46                let spans: Vec<_> = param_indices
47                    .into_iter()
48                    .map(|i| tcx.def_span(opaque_generics.param_at(i, tcx).def_id))
49                    .collect();
50                infcx
51                    .dcx()
52                    .struct_span_err(span, "non-defining opaque type use in defining scope")
53                    .with_span_note(spans, format!("{descr} used multiple times"))
54                    .emit()
55            }
56        }
57    }
58}
59
60/// Opaque type parameter validity check as documented in the [rustc-dev-guide chapter].
61/// With the new solver, uses which fail this check are simply treated as non-defining
62/// and we only emit an error if no defining use exists.
63///
64/// [rustc-dev-guide chapter]:
65/// https://rustc-dev-guide.rust-lang.org/opaque-types-region-infer-restrictions.html
66pub fn opaque_type_has_defining_use_args<'tcx>(
67    infcx: &InferCtxt<'tcx>,
68    opaque_type_key: OpaqueTypeKey<'tcx>,
69    span: Span,
70    defining_scope_kind: DefiningScopeKind,
71) -> Result<(), NonDefiningUseReason<'tcx>> {
72    let tcx = infcx.tcx;
73    let opaque_env = LazyOpaqueTyEnv::new(tcx, opaque_type_key.def_id);
74    let mut seen_params: FxIndexMap<_, Vec<_>> = FxIndexMap::default();
75
76    // Avoid duplicate errors in case the opaque has already been malformed in
77    // HIR typeck.
78    if let DefiningScopeKind::MirBorrowck = defining_scope_kind {
79        infcx
80            .tcx
81            .type_of_opaque_hir_typeck(opaque_type_key.def_id)
82            .instantiate_identity()
83            .error_reported()?;
84    }
85
86    for (i, arg) in opaque_type_key.iter_captured_args(tcx) {
87        let arg_is_param = match arg.kind() {
88            GenericArgKind::Lifetime(lt) => match defining_scope_kind {
89                DefiningScopeKind::HirTypeck => continue,
90                DefiningScopeKind::MirBorrowck => {
91                    matches!(lt.kind(), ty::ReEarlyParam(_) | ty::ReLateParam(_))
92                        || (lt.is_static() && opaque_env.param_equal_static(i))
93                }
94            },
95            GenericArgKind::Type(ty) => matches!(ty.kind(), ty::Param(_)),
96            GenericArgKind::Const(ct) => matches!(ct.kind(), ty::ConstKind::Param(_)),
97        };
98
99        if arg_is_param {
100            // Register if the same lifetime appears multiple times in the generic args.
101            // There is an exception when the opaque type *requires* the lifetimes to be equal.
102            // See [rustc-dev-guide chapter] ยง "An exception to uniqueness rule".
103            let seen_where = seen_params.entry(arg).or_default();
104            if !seen_where.first().is_some_and(|&prev_i| opaque_env.params_equal(i, prev_i)) {
105                seen_where.push(i);
106            }
107        } else {
108            // Prevent `fn foo() -> Foo<u32>` from being defining.
109            opaque_env.param_is_error(i)?;
110            return Err(NonDefiningUseReason::NotAParam { opaque_type_key, param_index: i, span });
111        }
112    }
113
114    for (_, param_indices) in seen_params {
115        if param_indices.len() > 1 {
116            return Err(NonDefiningUseReason::DuplicateParam {
117                opaque_type_key,
118                param_indices,
119                span,
120            });
121        }
122    }
123
124    Ok(())
125}
126
127/// Computes if an opaque type requires a lifetime parameter to be equal to
128/// another one or to the `'static` lifetime.
129/// These requirements are derived from the explicit and implied bounds.
130struct LazyOpaqueTyEnv<'tcx> {
131    tcx: TyCtxt<'tcx>,
132    def_id: LocalDefId,
133
134    /// Equal parameters will have the same name. Computed Lazily.
135    /// Example:
136    ///     `type Opaque<'a: 'static, 'b: 'c, 'c: 'b> = impl Sized;`
137    ///     Identity args: `['a, 'b, 'c]`
138    ///     Canonical args: `['static, 'b, 'b]`
139    canonical_args: std::cell::OnceCell<ty::GenericArgsRef<'tcx>>,
140}
141
142impl<'tcx> LazyOpaqueTyEnv<'tcx> {
143    fn new(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> Self {
144        Self { tcx, def_id, canonical_args: std::cell::OnceCell::new() }
145    }
146
147    fn param_equal_static(&self, param_index: usize) -> bool {
148        self.get_canonical_args()[param_index].expect_region().is_static()
149    }
150
151    fn params_equal(&self, param1: usize, param2: usize) -> bool {
152        let canonical_args = self.get_canonical_args();
153        canonical_args[param1] == canonical_args[param2]
154    }
155
156    fn param_is_error(&self, param_index: usize) -> Result<(), ErrorGuaranteed> {
157        self.get_canonical_args()[param_index].error_reported()
158    }
159
160    fn get_canonical_args(&self) -> ty::GenericArgsRef<'tcx> {
161        if let Some(&canonical_args) = self.canonical_args.get() {
162            return canonical_args;
163        }
164
165        let &Self { tcx, def_id, .. } = self;
166        let origin = tcx.local_opaque_ty_origin(def_id);
167        let parent = match origin {
168            OpaqueTyOrigin::FnReturn { parent, .. }
169            | OpaqueTyOrigin::AsyncFn { parent, .. }
170            | OpaqueTyOrigin::TyAlias { parent, .. } => parent,
171        };
172        let param_env = tcx.param_env(parent);
173        let args = GenericArgs::identity_for_item(tcx, parent).extend_to(
174            tcx,
175            def_id.to_def_id(),
176            |param, _| {
177                tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local()).into()
178            },
179        );
180
181        // FIXME(#132279): It feels wrong to use `non_body_analysis` here given that we're
182        // in a body here.
183        let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
184        let ocx = ObligationCtxt::new(&infcx);
185
186        let wf_tys = ocx.assumed_wf_types(param_env, parent).unwrap_or_else(|_| {
187            tcx.dcx().span_delayed_bug(tcx.def_span(def_id), "error getting implied bounds");
188            Default::default()
189        });
190        let outlives_env = OutlivesEnvironment::new(&infcx, parent, param_env, wf_tys);
191
192        let mut seen = vec![tcx.lifetimes.re_static];
193        let canonical_args = fold_regions(tcx, args, |r1, _| {
194            if r1.is_error() {
195                r1
196            } else if let Some(&r2) = seen.iter().find(|&&r2| {
197                let free_regions = outlives_env.free_region_map();
198                free_regions.sub_free_regions(tcx, r1, r2)
199                    && free_regions.sub_free_regions(tcx, r2, r1)
200            }) {
201                r2
202            } else {
203                seen.push(r1);
204                r1
205            }
206        });
207        self.canonical_args.set(canonical_args).unwrap();
208        canonical_args
209    }
210}
211
212pub fn report_item_does_not_constrain_error<'tcx>(
213    tcx: TyCtxt<'tcx>,
214    item_def_id: LocalDefId,
215    def_id: LocalDefId,
216    non_defining_use: Option<(OpaqueTypeKey<'tcx>, Span)>,
217) -> ErrorGuaranteed {
218    let span = tcx.def_ident_span(item_def_id).unwrap_or_else(|| tcx.def_span(item_def_id));
219    let opaque_type_span = tcx.def_span(def_id);
220    let opaque_type_name = tcx.def_path_str(def_id);
221
222    let mut err =
223        tcx.dcx().struct_span_err(span, format!("item does not constrain `{opaque_type_name}`"));
224    err.note("consider removing `#[define_opaque]` or adding an empty `#[define_opaque()]`");
225    err.span_note(opaque_type_span, "this opaque type is supposed to be constrained");
226    if let Some((key, span)) = non_defining_use {
227        let opaque_ty = Ty::new_opaque(tcx, key.def_id.into(), key.args);
228        err.span_note(
229            span,
230            format!("this use of `{opaque_ty}` does not have unique universal generic arguments"),
231        );
232    }
233    err.emit()
234}