rustc_trait_selection/traits/specialize/
specialization_graph.rs
1use rustc_errors::ErrorGuaranteed;
2use rustc_hir::def_id::DefId;
3use rustc_macros::extension;
4use rustc_middle::bug;
5pub use rustc_middle::traits::specialization_graph::*;
6use rustc_middle::ty::fast_reject::{self, SimplifiedType, TreatParams};
7use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt};
8use tracing::{debug, instrument};
9
10use super::OverlapError;
11use crate::traits;
12
13#[derive(Copy, Clone, Debug)]
14pub enum FutureCompatOverlapErrorKind {
15 OrderDepTraitObjects,
16 LeakCheck,
17}
18
19#[derive(Debug)]
20pub struct FutureCompatOverlapError<'tcx> {
21 pub error: OverlapError<'tcx>,
22 pub kind: FutureCompatOverlapErrorKind,
23}
24
25#[derive(Debug)]
27enum Inserted<'tcx> {
28 BecameNewSibling(Option<FutureCompatOverlapError<'tcx>>),
30
31 ReplaceChildren(Vec<DefId>),
33
34 ShouldRecurseOn(DefId),
36}
37
38#[extension(trait ChildrenExt<'tcx>)]
39impl<'tcx> Children {
40 fn insert_blindly(&mut self, tcx: TyCtxt<'tcx>, impl_def_id: DefId) {
42 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().skip_binder();
43 if let Some(st) =
44 fast_reject::simplify_type(tcx, trait_ref.self_ty(), TreatParams::InstantiateWithInfer)
45 {
46 debug!("insert_blindly: impl_def_id={:?} st={:?}", impl_def_id, st);
47 self.non_blanket_impls.entry(st).or_default().push(impl_def_id)
48 } else {
49 debug!("insert_blindly: impl_def_id={:?} st=None", impl_def_id);
50 self.blanket_impls.push(impl_def_id)
51 }
52 }
53
54 fn remove_existing(&mut self, tcx: TyCtxt<'tcx>, impl_def_id: DefId) {
58 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().skip_binder();
59 let vec: &mut Vec<DefId>;
60 if let Some(st) =
61 fast_reject::simplify_type(tcx, trait_ref.self_ty(), TreatParams::InstantiateWithInfer)
62 {
63 debug!("remove_existing: impl_def_id={:?} st={:?}", impl_def_id, st);
64 vec = self.non_blanket_impls.get_mut(&st).unwrap();
65 } else {
66 debug!("remove_existing: impl_def_id={:?} st=None", impl_def_id);
67 vec = &mut self.blanket_impls;
68 }
69
70 let index = vec.iter().position(|d| *d == impl_def_id).unwrap();
71 vec.remove(index);
72 }
73
74 #[instrument(level = "debug", skip(self, tcx), ret)]
77 fn insert(
78 &mut self,
79 tcx: TyCtxt<'tcx>,
80 impl_def_id: DefId,
81 simplified_self: Option<SimplifiedType>,
82 overlap_mode: OverlapMode,
83 ) -> Result<Inserted<'tcx>, OverlapError<'tcx>> {
84 let mut last_lint = None;
85 let mut replace_children = Vec::new();
86
87 let possible_siblings = match simplified_self {
88 Some(st) => PotentialSiblings::Filtered(filtered_children(self, st)),
89 None => PotentialSiblings::Unfiltered(iter_children(self)),
90 };
91
92 for possible_sibling in possible_siblings {
93 debug!(?possible_sibling);
94
95 let create_overlap_error = |overlap: traits::coherence::OverlapResult<'tcx>| {
96 let trait_ref = overlap.impl_header.trait_ref.unwrap();
97 let self_ty = trait_ref.self_ty();
98
99 OverlapError {
100 with_impl: possible_sibling,
101 trait_ref,
102 self_ty: self_ty.has_concrete_skeleton().then_some(self_ty),
106 intercrate_ambiguity_causes: overlap.intercrate_ambiguity_causes,
107 involves_placeholder: overlap.involves_placeholder,
108 overflowing_predicates: overlap.overflowing_predicates,
109 }
110 };
111
112 let report_overlap_error = |overlap: traits::coherence::OverlapResult<'tcx>,
113 last_lint: &mut _| {
114 let should_err = traits::overlapping_impls(
118 tcx,
119 possible_sibling,
120 impl_def_id,
121 traits::SkipLeakCheck::default(),
122 overlap_mode,
123 )
124 .is_some();
125
126 let error = create_overlap_error(overlap);
127
128 if should_err {
129 Err(error)
130 } else {
131 *last_lint = Some(FutureCompatOverlapError {
132 error,
133 kind: FutureCompatOverlapErrorKind::LeakCheck,
134 });
135
136 Ok((false, false))
137 }
138 };
139
140 let last_lint_mut = &mut last_lint;
141 let (le, ge) = traits::overlapping_impls(
142 tcx,
143 possible_sibling,
144 impl_def_id,
145 traits::SkipLeakCheck::Yes,
146 overlap_mode,
147 )
148 .map_or(Ok((false, false)), |overlap| {
149 if let Some(overlap_kind) =
150 tcx.impls_are_allowed_to_overlap(impl_def_id, possible_sibling)
151 {
152 match overlap_kind {
153 ty::ImplOverlapKind::Permitted { marker: _ } => {}
154 ty::ImplOverlapKind::FutureCompatOrderDepTraitObjects => {
155 *last_lint_mut = Some(FutureCompatOverlapError {
156 error: create_overlap_error(overlap),
157 kind: FutureCompatOverlapErrorKind::OrderDepTraitObjects,
158 });
159 }
160 }
161
162 return Ok((false, false));
163 }
164
165 let le = tcx.specializes((impl_def_id, possible_sibling));
166 let ge = tcx.specializes((possible_sibling, impl_def_id));
167
168 if le == ge { report_overlap_error(overlap, last_lint_mut) } else { Ok((le, ge)) }
169 })?;
170
171 if le && !ge {
172 debug!(
173 "descending as child of TraitRef {:?}",
174 tcx.impl_trait_ref(possible_sibling).unwrap().instantiate_identity()
175 );
176
177 return Ok(Inserted::ShouldRecurseOn(possible_sibling));
179 } else if ge && !le {
180 debug!(
181 "placing as parent of TraitRef {:?}",
182 tcx.impl_trait_ref(possible_sibling).unwrap().instantiate_identity()
183 );
184
185 replace_children.push(possible_sibling);
186 } else {
187 }
190 }
191
192 if !replace_children.is_empty() {
193 return Ok(Inserted::ReplaceChildren(replace_children));
194 }
195
196 debug!("placing as new sibling");
198 self.insert_blindly(tcx, impl_def_id);
199 Ok(Inserted::BecameNewSibling(last_lint))
200 }
201}
202
203fn iter_children(children: &Children) -> impl Iterator<Item = DefId> + '_ {
204 let nonblanket = children.non_blanket_impls.iter().flat_map(|(_, v)| v.iter());
205 children.blanket_impls.iter().chain(nonblanket).cloned()
206}
207
208fn filtered_children(
209 children: &mut Children,
210 st: SimplifiedType,
211) -> impl Iterator<Item = DefId> + '_ {
212 let nonblanket = children.non_blanket_impls.entry(st).or_default().iter();
213 children.blanket_impls.iter().chain(nonblanket).cloned()
214}
215
216enum PotentialSiblings<I, J>
218where
219 I: Iterator<Item = DefId>,
220 J: Iterator<Item = DefId>,
221{
222 Unfiltered(I),
223 Filtered(J),
224}
225
226impl<I, J> Iterator for PotentialSiblings<I, J>
227where
228 I: Iterator<Item = DefId>,
229 J: Iterator<Item = DefId>,
230{
231 type Item = DefId;
232
233 fn next(&mut self) -> Option<Self::Item> {
234 match *self {
235 PotentialSiblings::Unfiltered(ref mut iter) => iter.next(),
236 PotentialSiblings::Filtered(ref mut iter) => iter.next(),
237 }
238 }
239}
240
241#[extension(pub trait GraphExt<'tcx>)]
242impl<'tcx> Graph {
243 fn insert(
247 &mut self,
248 tcx: TyCtxt<'tcx>,
249 impl_def_id: DefId,
250 overlap_mode: OverlapMode,
251 ) -> Result<Option<FutureCompatOverlapError<'tcx>>, OverlapError<'tcx>> {
252 assert!(impl_def_id.is_local());
253
254 let trait_ref = tcx.impl_trait_ref(impl_def_id).unwrap().skip_binder();
256 let trait_def_id = trait_ref.def_id;
257
258 debug!(
259 "insert({:?}): inserting TraitRef {:?} into specialization graph",
260 impl_def_id, trait_ref
261 );
262
263 if trait_ref.references_error() {
268 debug!(
269 "insert: inserting dummy node for erroneous TraitRef {:?}, \
270 impl_def_id={:?}, trait_def_id={:?}",
271 trait_ref, impl_def_id, trait_def_id
272 );
273
274 self.parent.insert(impl_def_id, trait_def_id);
275 self.children.entry(trait_def_id).or_default().insert_blindly(tcx, impl_def_id);
276 return Ok(None);
277 }
278
279 let mut parent = trait_def_id;
280 let mut last_lint = None;
281 let simplified =
282 fast_reject::simplify_type(tcx, trait_ref.self_ty(), TreatParams::InstantiateWithInfer);
283
284 loop {
286 use self::Inserted::*;
287
288 let insert_result = self.children.entry(parent).or_default().insert(
289 tcx,
290 impl_def_id,
291 simplified,
292 overlap_mode,
293 )?;
294
295 match insert_result {
296 BecameNewSibling(opt_lint) => {
297 last_lint = opt_lint;
298 break;
299 }
300 ReplaceChildren(grand_children_to_be) => {
301 {
317 let siblings = self.children.get_mut(&parent).unwrap();
318 for &grand_child_to_be in &grand_children_to_be {
319 siblings.remove_existing(tcx, grand_child_to_be);
320 }
321 siblings.insert_blindly(tcx, impl_def_id);
322 }
323
324 for &grand_child_to_be in &grand_children_to_be {
326 self.parent.insert(grand_child_to_be, impl_def_id);
327 }
328 self.parent.insert(impl_def_id, parent);
329
330 for &grand_child_to_be in &grand_children_to_be {
332 self.children
333 .entry(impl_def_id)
334 .or_default()
335 .insert_blindly(tcx, grand_child_to_be);
336 }
337 break;
338 }
339 ShouldRecurseOn(new_parent) => {
340 parent = new_parent;
341 }
342 }
343 }
344
345 self.parent.insert(impl_def_id, parent);
346 Ok(last_lint)
347 }
348
349 fn record_impl_from_cstore(&mut self, tcx: TyCtxt<'tcx>, parent: DefId, child: DefId) {
351 if self.parent.insert(child, parent).is_some() {
352 bug!(
353 "When recording an impl from the crate store, information about its parent \
354 was already present."
355 );
356 }
357
358 self.children.entry(parent).or_default().insert_blindly(tcx, child);
359 }
360}
361
362pub(crate) fn assoc_def(
365 tcx: TyCtxt<'_>,
366 impl_def_id: DefId,
367 assoc_def_id: DefId,
368) -> Result<LeafDef, ErrorGuaranteed> {
369 let trait_def_id = tcx.trait_id_of_impl(impl_def_id).unwrap();
370 let trait_def = tcx.trait_def(trait_def_id);
371
372 if let Some(&impl_item_id) = tcx.impl_item_implementor_ids(impl_def_id).get(&assoc_def_id) {
379 if let Some(impl_def_id) = impl_def_id.as_local() {
382 tcx.ensure_ok().enforce_impl_non_lifetime_params_are_constrained(impl_def_id)?;
383 }
384
385 let item = tcx.associated_item(impl_item_id);
386 let impl_node = Node::Impl(impl_def_id);
387 return Ok(LeafDef {
388 item,
389 defining_node: impl_node,
390 finalizing_node: if item.defaultness(tcx).is_default() {
391 None
392 } else {
393 Some(impl_node)
394 },
395 });
396 }
397
398 let ancestors = trait_def.ancestors(tcx, impl_def_id)?;
399 if let Some(assoc_item) = ancestors.leaf_def(tcx, assoc_def_id) {
400 if assoc_item.item.container == ty::AssocItemContainer::Impl
403 && let Some(impl_def_id) = assoc_item.item.container_id(tcx).as_local()
404 {
405 tcx.ensure_ok().enforce_impl_non_lifetime_params_are_constrained(impl_def_id)?;
406 }
407
408 Ok(assoc_item)
409 } else {
410 bug!(
417 "No associated type `{}` for {}",
418 tcx.item_name(assoc_def_id),
419 tcx.def_path_str(impl_def_id)
420 )
421 }
422}