-
Notifications
You must be signed in to change notification settings - Fork 12.7k
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
WIP: PoC for derive(SmartPointer)
#123472
Closed
Closed
Changes from all commits
Commits
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 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
113 changes: 113 additions & 0 deletions
113
compiler/rustc_builtin_macros/src/deriving/smart_ptr.rs
This file contains 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,113 @@ | ||
use rustc_ast::{ | ||
self as ast, GenericArg, GenericBound, GenericParamKind, ItemKind, MetaItem, | ||
TraitBoundModifiers, | ||
}; | ||
use rustc_expand::base::{Annotatable, ExtCtxt}; | ||
use rustc_span::symbol::{sym, Ident}; | ||
use rustc_span::Span; | ||
use thin_vec::{thin_vec, ThinVec}; | ||
|
||
macro_rules! path { | ||
($span:expr, $($part:ident)::*) => { vec![$(Ident::new(sym::$part, $span),)*] } | ||
} | ||
|
||
pub fn expand_deriving_smart_ptr( | ||
cx: &ExtCtxt<'_>, | ||
span: Span, | ||
_mitem: &MetaItem, | ||
item: &Annotatable, | ||
push: &mut dyn FnMut(Annotatable), | ||
_is_const: bool, | ||
) { | ||
let (name_ident, generics) = match item { | ||
Annotatable::Item(aitem) => match &aitem.kind { | ||
ItemKind::Struct(_, g) => (aitem.ident, g), | ||
// FIXME: Improve error reporting. | ||
_ => cx.dcx().span_bug(span, "`#[derive(SmartPointer)]` on wrong kind"), | ||
}, | ||
_ => cx.dcx().span_bug(span, "`#[derive(SmartPointer)]` on wrong item"), | ||
}; | ||
|
||
// Convert generic parameters (from the struct) into generic args. | ||
let self_params = generics | ||
.params | ||
.iter() | ||
.map(|p| match p.kind { | ||
GenericParamKind::Lifetime => GenericArg::Lifetime(cx.lifetime(span, p.ident)), | ||
GenericParamKind::Type { .. } => GenericArg::Type(cx.ty_ident(span, p.ident)), | ||
GenericParamKind::Const { .. } => GenericArg::Const(cx.const_ident(span, p.ident)), | ||
}) | ||
.collect::<Vec<_>>(); | ||
|
||
// Create the type of `self`. | ||
let path = cx.path_all(span, false, vec![name_ident], self_params.clone()); | ||
let self_type = cx.ty_path(path); | ||
|
||
// Declare helper function that adds implementation blocks. | ||
// FIXME: Copy attrs from struct? | ||
let attrs = thin_vec![cx.attr_word(sym::automatically_derived, span),]; | ||
let mut add_impl_block = |generics, trait_symbol, trait_args| { | ||
let mut parts = path!(span, core::ops); | ||
parts.push(Ident::new(trait_symbol, span)); | ||
let trait_path = cx.path_all(span, true, parts, trait_args); | ||
let trait_ref = cx.trait_ref(trait_path); | ||
let item = cx.item( | ||
span, | ||
Ident::empty(), | ||
attrs.clone(), | ||
ast::ItemKind::Impl(Box::new(ast::Impl { | ||
unsafety: ast::Unsafe::No, | ||
polarity: ast::ImplPolarity::Positive, | ||
defaultness: ast::Defaultness::Final, | ||
constness: ast::Const::No, | ||
generics, | ||
of_trait: Some(trait_ref), | ||
self_ty: self_type.clone(), | ||
items: ThinVec::new(), | ||
})), | ||
); | ||
push(Annotatable::Item(item)); | ||
}; | ||
|
||
// Create unsized `self`, that is, one where the first type arg is replace with `__S`. For | ||
// example, instead of `MyType<'a, T>`, it will be `MyType<'a, __S>`. | ||
let s_ty = cx.ty_ident(span, Ident::new(sym::__S, span)); | ||
let mut alt_self_params = self_params; | ||
for a in &mut alt_self_params { | ||
if matches!(*a, GenericArg::Type(_)) { | ||
*a = GenericArg::Type(s_ty.clone()); | ||
break; | ||
} | ||
} | ||
let alt_self_type = cx.ty_path(cx.path_all(span, false, vec![name_ident], alt_self_params)); | ||
|
||
// Find the first type parameter and add an `Unsize<__S>` bound to it. | ||
let mut impl_generics = generics.clone(); | ||
for p in &mut impl_generics.params { | ||
if matches!(p.kind, ast::GenericParamKind::Type { .. }) { | ||
let arg = GenericArg::Type(s_ty.clone()); | ||
let unsize = cx.path_all(span, true, path!(span, core::marker::Unsize), vec![arg]); | ||
p.bounds.push(cx.trait_bound(unsize, false)); | ||
break; | ||
} | ||
} | ||
|
||
// Add the `__S: ?Sized` extra parameter to the impl block. | ||
let sized = cx.path_global(span, path!(span, core::marker::Sized)); | ||
let bound = GenericBound::Trait( | ||
cx.poly_trait_ref(span, sized), | ||
TraitBoundModifiers { | ||
polarity: ast::BoundPolarity::Maybe(span), | ||
constness: ast::BoundConstness::Never, | ||
asyncness: ast::BoundAsyncness::Normal, | ||
}, | ||
); | ||
let extra_param = cx.typaram(span, Ident::new(sym::__S, span), vec![bound], None); | ||
impl_generics.params.push(extra_param); | ||
|
||
// Add the impl blocks for `DispatchFromDyn`, `CoerceUnsized`, and `Receiver`. | ||
let gen_args = vec![GenericArg::Type(alt_self_type.clone())]; | ||
add_impl_block(impl_generics.clone(), sym::DispatchFromDyn, gen_args.clone()); | ||
add_impl_block(impl_generics.clone(), sym::CoerceUnsized, gen_args.clone()); | ||
add_impl_block(generics.clone(), sym::Receiver, Vec::new()); | ||
} |
This file contains 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 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 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 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 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,53 @@ | ||
//@ run-pass | ||
#![feature(derive_smart_pointer)] | ||
|
||
#[derive(SmartPointer)] | ||
struct MyPointer<'a, T: ?Sized> { | ||
ptr: &'a T, | ||
} | ||
|
||
impl<T: ?Sized> Copy for MyPointer<'_, T> {} | ||
impl<T: ?Sized> Clone for MyPointer<'_, T> { | ||
fn clone(&self) -> Self { | ||
Self { ptr: self.ptr } | ||
} | ||
} | ||
|
||
impl<'a, T: ?Sized> core::ops::Deref for MyPointer<'a, T> { | ||
type Target = T; | ||
fn deref(&self) -> &'a T { | ||
self.ptr | ||
} | ||
} | ||
|
||
struct MyValue(u32); | ||
impl MyValue { | ||
fn through_pointer(self: MyPointer<'_, Self>) -> u32 { | ||
self.ptr.0 | ||
} | ||
} | ||
|
||
trait MyTrait { | ||
fn through_trait(&self) -> u32; | ||
fn through_trait_and_pointer(self: MyPointer<'_, Self>) -> u32; | ||
} | ||
|
||
impl MyTrait for MyValue { | ||
fn through_trait(&self) -> u32 { | ||
self.0 | ||
} | ||
|
||
fn through_trait_and_pointer(self: MyPointer<'_, Self>) -> u32 { | ||
self.ptr.0 | ||
} | ||
} | ||
|
||
pub fn main() { | ||
let v = MyValue(10); | ||
let ptr = MyPointer { ptr: &v }; | ||
assert_eq!(v.0, ptr.through_pointer()); | ||
assert_eq!(v.0, ptr.through_pointer()); | ||
let dptr = ptr as MyPointer<dyn MyTrait>; | ||
assert_eq!(v.0, dptr.through_trait()); | ||
assert_eq!(v.0, dptr.through_trait_and_pointer()); | ||
} |
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This macro definitely should not go into the root module of the core crate. Please look at other derive macros to see what the precedent is.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@rustbot author