Skip to content

Avoid using () in derive(From) output. #145550

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

Merged
merged 1 commit into from
Aug 20, 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
71 changes: 36 additions & 35 deletions compiler/rustc_builtin_macros/src/deriving/from.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,21 +27,39 @@ pub(crate) fn expand_deriving_from(
cx.dcx().bug("derive(From) used on something else than an item");
};

// #[derive(From)] is currently usable only on structs with exactly one field.
let field = if let ItemKind::Struct(_, _, data) = &item.kind
&& let [field] = data.fields()
{
Some(field.clone())
} else {
None
let err_span = || {
let item_span = item.kind.ident().map(|ident| ident.span).unwrap_or(item.span);
MultiSpan::from_spans(vec![span, item_span])
};

let from_type = match &field {
Some(field) => Ty::AstTy(field.ty.clone()),
// We don't have a type to put into From<...> if we don't have a single field, so just put
// unit there.
None => Ty::Unit,
// `#[derive(From)]` is currently usable only on structs with exactly one field.
let field = match &item.kind {
ItemKind::Struct(_, _, data) => {
if let [field] = data.fields() {
Ok(field.clone())
} else {
let guar = cx.dcx().emit_err(errors::DeriveFromWrongFieldCount {
span: err_span(),
multiple_fields: data.fields().len() > 1,
});
Err(guar)
}
}
ItemKind::Enum(_, _, _) | ItemKind::Union(_, _, _) => {
let guar = cx.dcx().emit_err(errors::DeriveFromWrongTarget {
span: err_span(),
kind: &format!("{} {}", item.kind.article(), item.kind.descr()),
});
Err(guar)
}
_ => cx.dcx().bug("Invalid derive(From) ADT input"),
};

let from_type = Ty::AstTy(match field {
Ok(ref field) => field.ty.clone(),
Err(guar) => cx.ty(span, ast::TyKind::Err(guar)),
});

let path =
Path::new_(pathvec_std!(convert::From), vec![Box::new(from_type.clone())], PathKind::Std);

Expand Down Expand Up @@ -71,34 +89,17 @@ pub(crate) fn expand_deriving_from(
attributes: thin_vec![cx.attr_word(sym::inline, span)],
fieldless_variants_strategy: FieldlessVariantsStrategy::Default,
combine_substructure: combine_substructure(Box::new(|cx, span, substructure| {
let Some(field) = &field else {
let item_span = item.kind.ident().map(|ident| ident.span).unwrap_or(item.span);
let err_span = MultiSpan::from_spans(vec![span, item_span]);
let error = match &item.kind {
ItemKind::Struct(_, _, data) => {
cx.dcx().emit_err(errors::DeriveFromWrongFieldCount {
span: err_span,
multiple_fields: data.fields().len() > 1,
})
}
ItemKind::Enum(_, _, _) | ItemKind::Union(_, _, _) => {
cx.dcx().emit_err(errors::DeriveFromWrongTarget {
span: err_span,
kind: &format!("{} {}", item.kind.article(), item.kind.descr()),
})
}
_ => cx.dcx().bug("Invalid derive(From) ADT input"),
};

return BlockOrExpr::new_expr(DummyResult::raw_expr(span, Some(error)));
let field = match field {
Ok(ref field) => field,
Err(guar) => {
return BlockOrExpr::new_expr(DummyResult::raw_expr(span, Some(guar)));
}
};

let self_kw = Ident::new(kw::SelfUpper, span);
let expr: Box<ast::Expr> = match substructure.fields {
SubstructureFields::StaticStruct(variant, _) => match variant {
// Self {
// field: value
// }
// Self { field: value }
VariantData::Struct { .. } => cx.expr_struct_ident(
span,
self_kw,
Expand Down
2 changes: 0 additions & 2 deletions tests/ui/deriving/deriving-from-wrong-target.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,6 @@ struct S4 {
enum E1 {}

#[derive(From)]
//~^ ERROR the size for values of type `T` cannot be known at compilation time [E0277]
//~| ERROR the size for values of type `T` cannot be known at compilation time [E0277]
struct SUnsizedField<T: ?Sized> {
last: T,
//~^ ERROR the size for values of type `T` cannot be known at compilation time [E0277]
Expand Down
42 changes: 2 additions & 40 deletions tests/ui/deriving/deriving-from-wrong-target.stderr
Original file line number Diff line number Diff line change
Expand Up @@ -54,45 +54,7 @@ LL | enum E1 {}
= note: `#[derive(From)]` can only be used on structs with exactly one field

error[E0277]: the size for values of type `T` cannot be known at compilation time
--> $DIR/deriving-from-wrong-target.rs:31:10
|
LL | #[derive(From)]
| ^^^^ doesn't have a size known at compile-time
...
LL | struct SUnsizedField<T: ?Sized> {
| - this type parameter needs to be `Sized`
|
note: required by an implicit `Sized` bound in `From`
--> $SRC_DIR/core/src/convert/mod.rs:LL:COL
help: consider removing the `?Sized` bound to make the type parameter `Sized`
|
LL - struct SUnsizedField<T: ?Sized> {
LL + struct SUnsizedField<T> {
|

error[E0277]: the size for values of type `T` cannot be known at compilation time
--> $DIR/deriving-from-wrong-target.rs:31:10
|
LL | #[derive(From)]
| ^^^^ doesn't have a size known at compile-time
...
LL | struct SUnsizedField<T: ?Sized> {
| - this type parameter needs to be `Sized`
|
note: required because it appears within the type `SUnsizedField<T>`
--> $DIR/deriving-from-wrong-target.rs:34:8
|
LL | struct SUnsizedField<T: ?Sized> {
| ^^^^^^^^^^^^^
= note: the return type of a function must have a statically known size
help: consider removing the `?Sized` bound to make the type parameter `Sized`
|
LL - struct SUnsizedField<T: ?Sized> {
LL + struct SUnsizedField<T> {
|

error[E0277]: the size for values of type `T` cannot be known at compilation time
--> $DIR/deriving-from-wrong-target.rs:35:11
--> $DIR/deriving-from-wrong-target.rs:33:11
|
LL | struct SUnsizedField<T: ?Sized> {
| - this type parameter needs to be `Sized`
Expand All @@ -110,6 +72,6 @@ help: function arguments must have a statically known size, borrowed types alway
LL | last: &T,
| +

error: aborting due to 8 previous errors
error: aborting due to 6 previous errors

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