Skip to content

Commit 5efcc19

Browse files
authored
Rollup merge of rust-lang#144922 - Kobzol:derive-from, r=nnethercote
Implement `#[derive(From)]` Implements the `#[derive(From)]` feature ([tracking issue](rust-lang#144889), [RFC](rust-lang/rfcs#3809)). It allows deriving the `From` impl on structs and tuple structs with exactly one field. Some implementation notes: - I wasn't exactly sure which spans to use in the derive generating code, so I just used `span` everywhere. I don't know if it's the Right Thing To Do. In particular the errors when `#[derive(From)]` is used on a struct with an unsized field are weirdly duplicated. - I had to solve an import stability problem, where if I just added the unstable `macro From` to `core::convert`, previously working code like `use std::convert::From` would suddenly require an unstable feature gate, because rustc would think that you're trying to import the unstable macro. `@petrochenkov` suggested that I add the macro the the core prelude instead. This has worked well, although it only works in edition 2021+. Not sure if I botched the prelude somehow and it should live elsewhere (?). - I had to add `Ty::AstTy`, because the `from` function receives an argument with the type of the single field, and the existing variants of the `Ty` enum couldn't represent an arbitrary type.
2 parents 57454b2 + a953cc8 commit 5efcc19

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

core/src/macros/mod.rs

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1770,4 +1770,15 @@ pub(crate) mod builtin {
17701770
pub macro deref($pat:pat) {
17711771
builtin # deref($pat)
17721772
}
1773+
1774+
/// Derive macro generating an impl of the trait `From`.
1775+
/// Currently, it can only be used on single-field structs.
1776+
// Note that the macro is in a different module than the `From` trait,
1777+
// to avoid triggering an unstable feature being used if someone imports
1778+
// `std::convert::From`.
1779+
#[rustc_builtin_macro]
1780+
#[unstable(feature = "derive_from", issue = "144889")]
1781+
pub macro From($item: item) {
1782+
/* compiler built-in */
1783+
}
17731784
}

core/src/prelude/v1.rs

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -117,3 +117,10 @@ pub use crate::macros::builtin::deref;
117117
reason = "`type_alias_impl_trait` has open design concerns"
118118
)]
119119
pub use crate::macros::builtin::define_opaque;
120+
121+
#[unstable(
122+
feature = "derive_from",
123+
issue = "144889",
124+
reason = "`derive(From)` is unstable"
125+
)]
126+
pub use crate::macros::builtin::From;

0 commit comments

Comments
 (0)