Skip to content
This repository was archived by the owner on May 28, 2025. It is now read-only.

Commit 6e4538a

Browse files
committed
Auto merge of rust-lang#15891 - Veykril:orphan-impls, r=Veykril
feat: Diagnose some orphan trait impl cases
2 parents 416e9c8 + d5faad1 commit 6e4538a

File tree

23 files changed

+378
-155
lines changed

23 files changed

+378
-155
lines changed

crates/hir-def/src/body/pretty.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ pub(super) fn print_body_hir(db: &dyn DefDatabase, body: &Body, owner: DefWithBo
5454
let mut p = Printer { db, body, buf: header, indent_level: 0, needs_indent: false };
5555
if let DefWithBodyId::FunctionId(it) = owner {
5656
p.buf.push('(');
57-
body.params.iter().zip(&db.function_data(it).params).for_each(|(&param, ty)| {
57+
body.params.iter().zip(db.function_data(it).params.iter()).for_each(|(&param, ty)| {
5858
p.print_pat(param);
5959
p.buf.push(':');
6060
p.print_type_ref(ty);

crates/hir-def/src/data.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ use crate::{
3434
#[derive(Debug, Clone, PartialEq, Eq)]
3535
pub struct FunctionData {
3636
pub name: Name,
37-
pub params: Vec<Interned<TypeRef>>,
37+
pub params: Box<[Interned<TypeRef>]>,
3838
pub ret_type: Interned<TypeRef>,
3939
pub attrs: Attrs,
4040
pub visibility: RawVisibility,
@@ -177,7 +177,7 @@ pub struct TypeAliasData {
177177
pub rustc_has_incoherent_inherent_impls: bool,
178178
pub rustc_allow_incoherent_impl: bool,
179179
/// Bounds restricting the type alias itself (eg. `type Ty: Bound;` in a trait or impl).
180-
pub bounds: Vec<Interned<TypeBound>>,
180+
pub bounds: Box<[Interned<TypeBound>]>,
181181
}
182182

183183
impl TypeAliasData {
@@ -210,7 +210,7 @@ impl TypeAliasData {
210210
is_extern: matches!(loc.container, ItemContainerId::ExternBlockId(_)),
211211
rustc_has_incoherent_inherent_impls,
212212
rustc_allow_incoherent_impl,
213-
bounds: typ.bounds.to_vec(),
213+
bounds: typ.bounds.clone(),
214214
})
215215
}
216216
}

crates/hir-def/src/generics.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ impl GenericParams {
227227
let mut expander = Lazy::new(|| {
228228
(module.def_map(db), Expander::new(db, loc.source(db).file_id, module))
229229
});
230-
for param in &func_data.params {
230+
for param in func_data.params.iter() {
231231
generic_params.fill_implicit_impl_trait_args(db, &mut expander, param);
232232
}
233233

crates/hir-def/src/item_tree/lower.rs

Lines changed: 3 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -396,14 +396,7 @@ impl<'a> Ctx<'a> {
396396
let bounds = self.lower_type_bounds(type_alias);
397397
let generic_params = self.lower_generic_params(HasImplicitSelf::No, type_alias);
398398
let ast_id = self.source_ast_id_map.ast_id(type_alias);
399-
let res = TypeAlias {
400-
name,
401-
visibility,
402-
bounds: bounds.into_boxed_slice(),
403-
generic_params,
404-
type_ref,
405-
ast_id,
406-
};
399+
let res = TypeAlias { name, visibility, bounds, generic_params, type_ref, ast_id };
407400
Some(id(self.data().type_aliases.alloc(res)))
408401
}
409402

@@ -637,13 +630,13 @@ impl<'a> Ctx<'a> {
637630
Interned::new(generics)
638631
}
639632

640-
fn lower_type_bounds(&mut self, node: &dyn ast::HasTypeBounds) -> Vec<Interned<TypeBound>> {
633+
fn lower_type_bounds(&mut self, node: &dyn ast::HasTypeBounds) -> Box<[Interned<TypeBound>]> {
641634
match node.type_bound_list() {
642635
Some(bound_list) => bound_list
643636
.bounds()
644637
.map(|it| Interned::new(TypeBound::from_ast(&self.body_ctx, it)))
645638
.collect(),
646-
None => Vec::new(),
639+
None => Box::default(),
647640
}
648641
}
649642

crates/hir-ty/src/db.rs

Lines changed: 11 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,8 @@ use crate::{
2020
method_resolution::{InherentImpls, TraitImpls, TyFingerprint},
2121
mir::{BorrowckResult, MirBody, MirLowerError},
2222
Binders, CallableDefId, ClosureId, Const, FnDefId, GenericArg, ImplTraitId, InferenceResult,
23-
Interner, PolyFnSig, QuantifiedWhereClause, ReturnTypeImplTraits, Substitution, TraitRef, Ty,
24-
TyDefId, ValueTyDefId,
23+
Interner, PolyFnSig, QuantifiedWhereClause, ReturnTypeImplTraits, Substitution,
24+
TraitEnvironment, TraitRef, Ty, TyDefId, ValueTyDefId,
2525
};
2626
use hir_expand::name::Name;
2727

@@ -47,15 +47,15 @@ pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> {
4747
&self,
4848
def: DefWithBodyId,
4949
subst: Substitution,
50-
env: Arc<crate::TraitEnvironment>,
50+
env: Arc<TraitEnvironment>,
5151
) -> Result<Arc<MirBody>, MirLowerError>;
5252

5353
#[salsa::invoke(crate::mir::monomorphized_mir_body_for_closure_query)]
5454
fn monomorphized_mir_body_for_closure(
5555
&self,
5656
def: ClosureId,
5757
subst: Substitution,
58-
env: Arc<crate::TraitEnvironment>,
58+
env: Arc<TraitEnvironment>,
5959
) -> Result<Arc<MirBody>, MirLowerError>;
6060

6161
#[salsa::invoke(crate::mir::borrowck_query)]
@@ -81,7 +81,7 @@ pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> {
8181
&self,
8282
def: GeneralConstId,
8383
subst: Substitution,
84-
trait_env: Option<Arc<crate::TraitEnvironment>>,
84+
trait_env: Option<Arc<TraitEnvironment>>,
8585
) -> Result<Const, ConstEvalError>;
8686

8787
#[salsa::invoke(crate::consteval::const_eval_static_query)]
@@ -104,24 +104,20 @@ pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> {
104104
&self,
105105
def: AdtId,
106106
subst: Substitution,
107-
env: Arc<crate::TraitEnvironment>,
107+
env: Arc<TraitEnvironment>,
108108
) -> Result<Arc<Layout>, LayoutError>;
109109

110110
#[salsa::invoke(crate::layout::layout_of_ty_query)]
111111
#[salsa::cycle(crate::layout::layout_of_ty_recover)]
112-
fn layout_of_ty(
113-
&self,
114-
ty: Ty,
115-
env: Arc<crate::TraitEnvironment>,
116-
) -> Result<Arc<Layout>, LayoutError>;
112+
fn layout_of_ty(&self, ty: Ty, env: Arc<TraitEnvironment>) -> Result<Arc<Layout>, LayoutError>;
117113

118114
#[salsa::invoke(crate::layout::target_data_layout_query)]
119115
fn target_data_layout(&self, krate: CrateId) -> Option<Arc<TargetDataLayout>>;
120116

121117
#[salsa::invoke(crate::method_resolution::lookup_impl_method_query)]
122118
fn lookup_impl_method(
123119
&self,
124-
env: Arc<crate::TraitEnvironment>,
120+
env: Arc<TraitEnvironment>,
125121
func: FunctionId,
126122
fn_subst: Substitution,
127123
) -> (FunctionId, Substitution);
@@ -149,10 +145,10 @@ pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> {
149145

150146
#[salsa::invoke(crate::lower::trait_environment_for_body_query)]
151147
#[salsa::transparent]
152-
fn trait_environment_for_body(&self, def: DefWithBodyId) -> Arc<crate::TraitEnvironment>;
148+
fn trait_environment_for_body(&self, def: DefWithBodyId) -> Arc<TraitEnvironment>;
153149

154150
#[salsa::invoke(crate::lower::trait_environment_query)]
155-
fn trait_environment(&self, def: GenericDefId) -> Arc<crate::TraitEnvironment>;
151+
fn trait_environment(&self, def: GenericDefId) -> Arc<TraitEnvironment>;
156152

157153
#[salsa::invoke(crate::lower::generic_defaults_query)]
158154
#[salsa::cycle(crate::lower::generic_defaults_recover)]
@@ -249,7 +245,7 @@ pub trait HirDatabase: DefDatabase + Upcast<dyn DefDatabase> {
249245
fn normalize_projection(
250246
&self,
251247
projection: crate::ProjectionTy,
252-
env: Arc<crate::TraitEnvironment>,
248+
env: Arc<TraitEnvironment>,
253249
) -> Ty;
254250

255251
#[salsa::invoke(trait_solve_wait)]

crates/hir-ty/src/diagnostics.rs

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,9 +11,3 @@ pub use crate::diagnostics::{
1111
},
1212
unsafe_check::{missing_unsafe, unsafe_expressions, UnsafeExpr},
1313
};
14-
15-
#[derive(Debug, PartialEq, Eq)]
16-
pub struct IncoherentImpl {
17-
pub file_id: hir_expand::HirFileId,
18-
pub impl_: syntax::AstPtr<syntax::ast::Impl>,
19-
}

crates/hir-ty/src/layout.rs

Lines changed: 37 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
//! Compute the binary representation of a type
22
3+
use std::fmt;
4+
35
use chalk_ir::{AdtId, FloatTy, IntTy, TyKind, UintTy};
46
use hir_def::{
57
layout::{
@@ -26,12 +28,6 @@ pub use self::{
2628
target::target_data_layout_query,
2729
};
2830

29-
macro_rules! user_error {
30-
($it: expr) => {
31-
return Err(LayoutError::UserError(format!($it).into()))
32-
};
33-
}
34-
3531
mod adt;
3632
mod target;
3733

@@ -73,13 +69,38 @@ pub type Variants = hir_def::layout::Variants<RustcFieldIdx, RustcEnumVariantIdx
7369

7470
#[derive(Debug, PartialEq, Eq, Clone)]
7571
pub enum LayoutError {
76-
UserError(Box<str>),
77-
SizeOverflow,
78-
TargetLayoutNotAvailable,
79-
HasPlaceholder,
72+
HasErrorConst,
8073
HasErrorType,
74+
HasPlaceholder,
75+
InvalidSimdType,
8176
NotImplemented,
77+
RecursiveTypeWithoutIndirection,
78+
SizeOverflow,
79+
TargetLayoutNotAvailable,
8280
Unknown,
81+
UserReprTooSmall,
82+
}
83+
84+
impl std::error::Error for LayoutError {}
85+
impl fmt::Display for LayoutError {
86+
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87+
match self {
88+
LayoutError::HasErrorConst => write!(f, "type contains an unevaluatable const"),
89+
LayoutError::HasErrorType => write!(f, "type contains an error"),
90+
LayoutError::HasPlaceholder => write!(f, "type contains placeholders"),
91+
LayoutError::InvalidSimdType => write!(f, "invalid simd type definition"),
92+
LayoutError::NotImplemented => write!(f, "not implemented"),
93+
LayoutError::RecursiveTypeWithoutIndirection => {
94+
write!(f, "recursive type without indirection")
95+
}
96+
LayoutError::SizeOverflow => write!(f, "size overflow"),
97+
LayoutError::TargetLayoutNotAvailable => write!(f, "target layout not available"),
98+
LayoutError::Unknown => write!(f, "unknown"),
99+
LayoutError::UserReprTooSmall => {
100+
write!(f, "the `#[repr]` hint is too small to hold the discriminants of the enum")
101+
}
102+
}
103+
}
83104
}
84105

85106
struct LayoutCx<'a> {
@@ -118,9 +139,7 @@ fn layout_of_simd_ty(
118139

119140
let f0_ty = match fields.iter().next() {
120141
Some(it) => it.1.clone().substitute(Interner, subst),
121-
None => {
122-
user_error!("simd type with zero fields");
123-
}
142+
None => return Err(LayoutError::InvalidSimdType),
124143
};
125144

126145
// The element type and number of elements of the SIMD vector
@@ -134,7 +153,7 @@ fn layout_of_simd_ty(
134153
// Extract the number of elements from the layout of the array field:
135154
let FieldsShape::Array { count, .. } = db.layout_of_ty(f0_ty.clone(), env.clone())?.fields
136155
else {
137-
user_error!("Array with non array layout");
156+
return Err(LayoutError::Unknown);
138157
};
139158

140159
(e_ty.clone(), count, true)
@@ -146,7 +165,7 @@ fn layout_of_simd_ty(
146165
// Compute the ABI of the element type:
147166
let e_ly = db.layout_of_ty(e_ty, env.clone())?;
148167
let Abi::Scalar(e_abi) = e_ly.abi else {
149-
user_error!("simd type with inner non scalar type");
168+
return Err(LayoutError::Unknown);
150169
};
151170

152171
// Compute the size and alignment of the vector:
@@ -259,9 +278,7 @@ pub fn layout_of_ty_query(
259278
cx.univariant(dl, &fields, &ReprOptions::default(), kind).ok_or(LayoutError::Unknown)?
260279
}
261280
TyKind::Array(element, count) => {
262-
let count = try_const_usize(db, &count).ok_or(LayoutError::UserError(Box::from(
263-
"unevaluated or mistyped const generic parameter",
264-
)))? as u64;
281+
let count = try_const_usize(db, &count).ok_or(LayoutError::HasErrorConst)? as u64;
265282
let element = db.layout_of_ty(element.clone(), trait_env.clone())?;
266283
let size = element.size.checked_mul(count, dl).ok_or(LayoutError::SizeOverflow)?;
267284

@@ -352,7 +369,7 @@ pub fn layout_of_ty_query(
352369
let mut unit = layout_of_unit(&cx, dl)?;
353370
match unit.abi {
354371
Abi::Aggregate { ref mut sized } => *sized = false,
355-
_ => user_error!("bug"),
372+
_ => return Err(LayoutError::Unknown),
356373
}
357374
unit
358375
}
@@ -418,7 +435,7 @@ pub fn layout_of_ty_recover(
418435
_: &Ty,
419436
_: &Arc<TraitEnvironment>,
420437
) -> Result<Arc<Layout>, LayoutError> {
421-
user_error!("infinite sized recursive type");
438+
Err(LayoutError::RecursiveTypeWithoutIndirection)
422439
}
423440

424441
fn layout_of_unit(cx: &LayoutCx<'_>, dl: &TargetDataLayout) -> Result<Layout, LayoutError> {

crates/hir-ty/src/layout/adt.rs

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ pub fn layout_of_adt_recover(
145145
_: &Substitution,
146146
_: &Arc<TraitEnvironment>,
147147
) -> Result<Arc<Layout>, LayoutError> {
148-
user_error!("infinite sized recursive type");
148+
Err(LayoutError::RecursiveTypeWithoutIndirection)
149149
}
150150

151151
/// Finds the appropriate Integer type and signedness for the given
@@ -169,11 +169,7 @@ fn repr_discr(
169169
let discr = Integer::from_attr(dl, ity);
170170
let fit = if ity.is_signed() { signed_fit } else { unsigned_fit };
171171
if discr < fit {
172-
return Err(LayoutError::UserError(
173-
"Integer::repr_discr: `#[repr]` hint too small for \
174-
discriminant range of enum "
175-
.into(),
176-
));
172+
return Err(LayoutError::UserReprTooSmall);
177173
}
178174
return Ok((discr, ity.is_signed()));
179175
}

crates/hir-ty/src/layout/tests.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -210,16 +210,13 @@ fn recursive() {
210210
struct BoxLike<T: ?Sized>(*mut T);
211211
struct Goal(BoxLike<Goal>);
212212
}
213-
check_fail(
214-
r#"struct Goal(Goal);"#,
215-
LayoutError::UserError("infinite sized recursive type".into()),
216-
);
213+
check_fail(r#"struct Goal(Goal);"#, LayoutError::RecursiveTypeWithoutIndirection);
217214
check_fail(
218215
r#"
219216
struct Foo<T>(Foo<T>);
220217
struct Goal(Foo<i32>);
221218
"#,
222-
LayoutError::UserError("infinite sized recursive type".into()),
219+
LayoutError::RecursiveTypeWithoutIndirection,
223220
);
224221
}
225222

crates/hir-ty/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ pub use mapping::{
8080
lt_from_placeholder_idx, to_assoc_type_id, to_chalk_trait_id, to_foreign_def_id,
8181
to_placeholder_idx,
8282
};
83+
pub use method_resolution::check_orphan_rules;
8384
pub use traits::TraitEnvironment;
8485
pub use utils::{all_super_traits, is_fn_unsafe_to_call};
8586

0 commit comments

Comments
 (0)