Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not rely on type_var_origin in OrphanCheckErr::NonLocalInputType #138727

Merged
merged 1 commit into from
Mar 21, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 16 additions & 47 deletions compiler/rustc_hir_analysis/src/coherence/orphan.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,10 @@

use rustc_data_structures::fx::FxIndexSet;
use rustc_errors::ErrorGuaranteed;
use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
use rustc_infer::infer::{DefineOpaqueTypes, InferCtxt, TyCtxtInferExt};
use rustc_lint_defs::builtin::UNCOVERED_PARAM_IN_PROJECTION;
use rustc_middle::ty::{
self, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeSuperVisitable,
TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
self, Ty, TyCtxt, TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode,
};
use rustc_middle::{bug, span_bug};
use rustc_span::def_id::{DefId, LocalDefId};
Expand Down Expand Up @@ -356,13 +355,20 @@ fn orphan_check<'tcx>(
})
}
OrphanCheckErr::NonLocalInputType(tys) => {
let generics = tcx.generics_of(impl_def_id);
let tys = tys
.into_iter()
.map(|(ty, is_target_ty)| {
(ty.fold_with(&mut TyVarReplacer { infcx: &infcx, generics }), is_target_ty)
})
.collect();
let tys = infcx.probe(|_| {
// Map the unconstrained args back to their params,
// ignoring any type unification errors.
for (arg, id_arg) in
std::iter::zip(args, ty::GenericArgs::identity_for_item(tcx, impl_def_id))
{
let _ = infcx.at(&cause, ty::ParamEnv::empty()).eq(
DefineOpaqueTypes::No,
arg,
id_arg,
);
}
infcx.resolve_vars_if_possible(tys)
});
OrphanCheckErr::NonLocalInputType(tys)
}
})
Expand Down Expand Up @@ -536,40 +542,3 @@ impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for UncoveredTyParamCollector<'_, 'tcx> {
}
}
}

struct TyVarReplacer<'cx, 'tcx> {
infcx: &'cx InferCtxt<'tcx>,
generics: &'tcx ty::Generics,
}

impl<'cx, 'tcx> TypeFolder<TyCtxt<'tcx>> for TyVarReplacer<'cx, 'tcx> {
fn cx(&self) -> TyCtxt<'tcx> {
self.infcx.tcx
}

fn fold_ty(&mut self, ty: Ty<'tcx>) -> Ty<'tcx> {
if !ty.has_type_flags(ty::TypeFlags::HAS_TY_INFER) {
return ty;
}
let ty::Infer(ty::TyVar(vid)) = *ty.kind() else {
return ty.super_fold_with(self);
};
let origin = self.infcx.type_var_origin(vid);
if let Some(def_id) = origin.param_def_id {
// The generics of an `impl` don't have a parent, we can index directly.
let index = self.generics.param_def_id_to_index[&def_id];
let name = self.generics.own_params[index as usize].name;

Ty::new_param(self.infcx.tcx, index, name)
} else {
ty
}
}

fn fold_const(&mut self, ct: ty::Const<'tcx>) -> ty::Const<'tcx> {
if !ct.has_type_flags(ty::TypeFlags::HAS_TY_INFER) {
return ct;
}
ct.super_fold_with(self)
}
}
5 changes: 4 additions & 1 deletion compiler/rustc_next_trait_solver/src/coherence.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@ use std::ops::ControlFlow;
use derive_where::derive_where;
use rustc_type_ir::inherent::*;
use rustc_type_ir::{
self as ty, InferCtxtLike, Interner, TypeVisitable, TypeVisitableExt, TypeVisitor,
self as ty, InferCtxtLike, Interner, TrivialTypeTraversalImpls, TypeVisitable,
TypeVisitableExt, TypeVisitor,
};
use tracing::instrument;

Expand Down Expand Up @@ -95,6 +96,8 @@ pub fn trait_ref_is_local_or_fundamental<I: Interner>(tcx: I, trait_ref: ty::Tra
trait_ref.def_id.is_local() || tcx.trait_is_fundamental(trait_ref.def_id)
}

TrivialTypeTraversalImpls! { IsFirstInputType, }

#[derive(Debug, Copy, Clone)]
pub enum IsFirstInputType {
No,
Expand Down
13 changes: 7 additions & 6 deletions compiler/rustc_type_ir/src/macros.rs
Original file line number Diff line number Diff line change
@@ -1,33 +1,34 @@
/// Used for types that are `Copy` and which **do not care arena
/// allocated data** (i.e., don't need to be folded).
#[macro_export]
macro_rules! TrivialTypeTraversalImpls {
($($ty:ty,)+) => {
$(
impl<I: $crate::Interner> $crate::fold::TypeFoldable<I> for $ty {
fn try_fold_with<F: $crate::fold::FallibleTypeFolder<I>>(
impl<I: $crate::Interner> $crate::TypeFoldable<I> for $ty {
fn try_fold_with<F: $crate::FallibleTypeFolder<I>>(
self,
_: &mut F,
) -> ::std::result::Result<Self, F::Error> {
Ok(self)
}

#[inline]
fn fold_with<F: $crate::fold::TypeFolder<I>>(
fn fold_with<F: $crate::TypeFolder<I>>(
self,
_: &mut F,
) -> Self {
self
}
}

impl<I: $crate::Interner> $crate::visit::TypeVisitable<I> for $ty {
impl<I: $crate::Interner> $crate::TypeVisitable<I> for $ty {
#[inline]
fn visit_with<F: $crate::visit::TypeVisitor<I>>(
fn visit_with<F: $crate::TypeVisitor<I>>(
&self,
_: &mut F)
-> F::Result
{
<F::Result as rustc_ast_ir::visit::VisitorResult>::output()
<F::Result as $crate::VisitorResult>::output()
}
}
)+
Expand Down
10 changes: 0 additions & 10 deletions tests/crashes/132826.rs

This file was deleted.

17 changes: 17 additions & 0 deletions tests/ui/coherence/orphan-check-error-reporting-ty-var.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
// Regression test for #132826.

// Make sure we don't try to resolve the variable `K1` in the generics of the impl
// (which only has `K2`).

pub trait MyTrait {
type Item;
}

impl<K1> MyTrait for Vec<K1> {
type Item = Vec<K1>;
}

impl<K2> From<Vec<K2>> for <Vec<K2> as MyTrait>::Item {}
//~^ ERROR only traits defined in the current crate can be implemented for arbitrary types

fn main() {}
16 changes: 16 additions & 0 deletions tests/ui/coherence/orphan-check-error-reporting-ty-var.stderr
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
error[E0117]: only traits defined in the current crate can be implemented for arbitrary types
--> $DIR/orphan-check-error-reporting-ty-var.rs:14:1
|
LL | impl<K2> From<Vec<K2>> for <Vec<K2> as MyTrait>::Item {}
| ^^^^^^^^^-------------^^^^^--------------------------
| | |
| | `Vec` is not defined in the current crate
| `Vec` is not defined in the current crate
|
= note: impl doesn't have any local type before any uncovered type parameters
= note: for more information see https://doc.rust-lang.org/reference/items/implementations.html#orphan-rules
= note: define and implement a trait or new type instead

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0117`.
Loading