-
Notifications
You must be signed in to change notification settings - Fork 13.7k
Implement #[derive(From)]
#144922
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
Open
Kobzol
wants to merge
4
commits into
rust-lang:master
Choose a base branch
from
Kobzol:derive-from
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+582
−3
Open
Implement #[derive(From)]
#144922
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,132 @@ | ||
use rustc_ast as ast; | ||
use rustc_ast::{ItemKind, VariantData}; | ||
use rustc_errors::MultiSpan; | ||
use rustc_expand::base::{Annotatable, DummyResult, ExtCtxt}; | ||
use rustc_span::{Ident, Span, kw, sym}; | ||
use thin_vec::thin_vec; | ||
|
||
use crate::deriving::generic::ty::{Bounds, Path, PathKind, Ty}; | ||
use crate::deriving::generic::{ | ||
BlockOrExpr, FieldlessVariantsStrategy, MethodDef, SubstructureFields, TraitDef, | ||
combine_substructure, | ||
}; | ||
use crate::deriving::pathvec_std; | ||
use crate::errors; | ||
|
||
/// Generate an implementation of the `From` trait, provided that `item` | ||
/// is a struct or a tuple struct with exactly one field. | ||
pub(crate) fn expand_deriving_from( | ||
cx: &ExtCtxt<'_>, | ||
span: Span, | ||
mitem: &ast::MetaItem, | ||
annotatable: &Annotatable, | ||
push: &mut dyn FnMut(Annotatable), | ||
is_const: bool, | ||
) { | ||
let Annotatable::Item(item) = &annotatable else { | ||
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 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, | ||
}; | ||
let path = | ||
Path::new_(pathvec_std!(convert::From), vec![Box::new(from_type.clone())], PathKind::Std); | ||
|
||
// Generate code like this: | ||
// | ||
// struct S(u32); | ||
// #[automatically_derived] | ||
// impl ::core::convert::From<u32> for S { | ||
// #[inline] | ||
// fn from(value: u32) -> S { | ||
// Self(value) | ||
// } | ||
// } | ||
let from_trait_def = TraitDef { | ||
span, | ||
path, | ||
skip_path_as_bound: true, | ||
needs_copy_as_bound_if_packed: false, | ||
additional_bounds: Vec::new(), | ||
supports_unions: false, | ||
methods: vec![MethodDef { | ||
name: sym::from, | ||
generics: Bounds { bounds: vec![] }, | ||
explicit_self: false, | ||
nonself_args: vec![(from_type, sym::value)], | ||
ret_ty: Ty::Self_, | ||
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 self_kw = Ident::new(kw::SelfUpper, span); | ||
let expr: Box<ast::Expr> = match substructure.fields { | ||
SubstructureFields::StaticStruct(variant, _) => match variant { | ||
// Self { | ||
// field: value | ||
// } | ||
VariantData::Struct { .. } => cx.expr_struct_ident( | ||
span, | ||
self_kw, | ||
thin_vec![cx.field_imm( | ||
span, | ||
field.ident.unwrap(), | ||
cx.expr_ident(span, Ident::new(sym::value, span)) | ||
)], | ||
), | ||
// Self(value) | ||
VariantData::Tuple(_, _) => cx.expr_call_ident( | ||
span, | ||
self_kw, | ||
thin_vec![cx.expr_ident(span, Ident::new(sym::value, span))], | ||
), | ||
variant => { | ||
cx.dcx().bug(format!("Invalid derive(From) ADT variant: {variant:?}")); | ||
} | ||
}, | ||
_ => cx.dcx().bug("Invalid derive(From) ADT input"), | ||
}; | ||
BlockOrExpr::new_expr(expr) | ||
})), | ||
}], | ||
associated_types: Vec::new(), | ||
is_const, | ||
is_staged_api_crate: cx.ecfg.features.staged_api(), | ||
}; | ||
|
||
from_trait_def.expand(cx, mitem, annotatable, push); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.