Skip to content
Open
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
33 changes: 20 additions & 13 deletions crates/hir-def/src/builtin_derive.rs
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ declare_enum!(
PartialEq => [eq],
CoerceUnsized => [],
DispatchFromDyn => [],
Reborrow => [],
);

impl BuiltinDeriveImplTrait {
Expand All @@ -102,10 +103,15 @@ impl BuiltinDeriveImplTrait {
BuiltinDeriveImplTrait::CoerceUnsized | BuiltinDeriveImplTrait::DispatchFromDyn => {
lang_items.CoercePointeeDerive
}
BuiltinDeriveImplTrait::Reborrow => lang_items.ReborrowDerive,
}
}
}

pub(crate) fn has_builtin_derive_impl(derive: BuiltinDeriveExpander) -> bool {
!matches!(derive, BuiltinDeriveExpander::CoerceShared)
}

impl BuiltinDeriveImplMethod {
pub fn trait_method(
self,
Expand All @@ -123,23 +129,24 @@ pub(crate) fn with_derive_traits(
derive: BuiltinDeriveExpander,
mut f: impl FnMut(BuiltinDeriveImplTrait),
) {
let trait_ = match derive {
BuiltinDeriveExpander::Copy => BuiltinDeriveImplTrait::Copy,
BuiltinDeriveExpander::Clone => BuiltinDeriveImplTrait::Clone,
BuiltinDeriveExpander::Default => BuiltinDeriveImplTrait::Default,
BuiltinDeriveExpander::Debug => BuiltinDeriveImplTrait::Debug,
BuiltinDeriveExpander::Hash => BuiltinDeriveImplTrait::Hash,
BuiltinDeriveExpander::Ord => BuiltinDeriveImplTrait::Ord,
BuiltinDeriveExpander::PartialOrd => BuiltinDeriveImplTrait::PartialOrd,
BuiltinDeriveExpander::Eq => BuiltinDeriveImplTrait::Eq,
BuiltinDeriveExpander::PartialEq => BuiltinDeriveImplTrait::PartialEq,
debug_assert!(has_builtin_derive_impl(derive));
match derive {
BuiltinDeriveExpander::Copy => f(BuiltinDeriveImplTrait::Copy),
BuiltinDeriveExpander::Clone => f(BuiltinDeriveImplTrait::Clone),
BuiltinDeriveExpander::Default => f(BuiltinDeriveImplTrait::Default),
BuiltinDeriveExpander::Debug => f(BuiltinDeriveImplTrait::Debug),
BuiltinDeriveExpander::Hash => f(BuiltinDeriveImplTrait::Hash),
BuiltinDeriveExpander::Ord => f(BuiltinDeriveImplTrait::Ord),
BuiltinDeriveExpander::PartialOrd => f(BuiltinDeriveImplTrait::PartialOrd),
BuiltinDeriveExpander::Eq => f(BuiltinDeriveImplTrait::Eq),
BuiltinDeriveExpander::PartialEq => f(BuiltinDeriveImplTrait::PartialEq),
BuiltinDeriveExpander::CoercePointee => {
f(BuiltinDeriveImplTrait::CoerceUnsized);
f(BuiltinDeriveImplTrait::DispatchFromDyn);
return;
}
};
f(trait_);
BuiltinDeriveExpander::Reborrow => f(BuiltinDeriveImplTrait::Reborrow),
BuiltinDeriveExpander::CoerceShared => {}
}
}

impl BuiltinDeriveImplLoc {
Expand Down
4 changes: 4 additions & 0 deletions crates/hir-def/src/lang_item.rs
Original file line number Diff line number Diff line change
Expand Up @@ -455,6 +455,8 @@ language_item_table! { LangItems =>

CoerceUnsized, sym::coerce_unsized, TraitId;
DispatchFromDyn, sym::dispatch_from_dyn, TraitId;
Reborrow, sym::reborrow, TraitId;
CoerceShared, sym::coerce_shared, TraitId;

// language items relating to transmutability
TransmuteOpts, sym::transmute_opts, StructId;
Expand Down Expand Up @@ -662,7 +664,9 @@ language_item_table! { LangItems =>
core::cmp, PartialEq, PartialEqDerive;
core::cmp, Eq, EqDerive;
core::marker, CoercePointee, CoercePointeeDerive;
core::marker, CoerceShared, CoerceSharedDerive;
core::marker, Copy, CopyDerive;
core::marker, Reborrow, ReborrowDerive;
core::clone, Clone, CloneDerive;

@resolve_manually:
Expand Down
93 changes: 93 additions & 0 deletions crates/hir-def/src/macro_expansion_tests/builtin_derive_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -747,6 +747,99 @@ struct Struct9<#[pointee] T, U>(T) where T: ?Sized;
);
}

#[test]
fn reborrow_expansion() {
check(
r#"
//- minicore: reborrow

use core::marker::Reborrow;

#[derive(Reborrow)]
struct Foo<'a, 'b, T, const N: usize>
where
T: 'a + 'b,
{
left: &'a mut T,
right: &'b mut T,
}"#,
expect![[r#"

use core::marker::Reborrow;

#[derive(Reborrow)]
struct Foo<'a, 'b, T, const N: usize>
where
T: 'a + 'b,
{
left: &'a mut T,
right: &'b mut T,
}
impl <T, const N: usize, > $crate::marker::Reborrow for Foo<T, N, > where T:'a+'b, {}"#]],
);
}

#[test]
fn coerce_shared_expansion() {
check(
r#"
//- minicore: reborrow

use core::marker::CoerceShared;

mod shared {
pub struct Shared<'a, 'b, T, const N: usize>(&'a T, &'b T, [(); N]);
}

#[derive(CoerceShared)]
#[coerce_shared(shared::Shared<'a, 'b, (T, u8), N>)]
struct Foo<'a, 'b, T, const N: usize>(&'a mut T, &'b mut T)
where
T: 'a + 'b;"#,
expect![[r#"

use core::marker::CoerceShared;

mod shared {
pub struct Shared<'a, 'b, T, const N: usize>(&'a T, &'b T, [(); N]);
}

#[derive(CoerceShared)]
#[coerce_shared(shared::Shared<'a, 'b, (T, u8), N>)]
struct Foo<'a, 'b, T, const N: usize>(&'a mut T, &'b mut T)
where
T: 'a + 'b;
impl <T, const N: usize, > $crate::marker::CoerceShared<shared::Shared<'a, 'b, (T, u8), N>> for Foo<T, N, > where T:'a+'b, {}"#]],
);
}

#[test]
fn coerce_shared_errors() {
check_errors(
r#"
//- minicore: reborrow

use core::marker::CoerceShared;

#[derive(CoerceShared)]
struct Missing<'a>(&'a mut ());

#[derive(CoerceShared)]
#[coerce_shared(Target<'a>)]
#[coerce_shared(Target<'a>)]
struct Duplicate<'a>(&'a mut ());

#[derive(CoerceShared)]
#[coerce_shared(Target<'a>, Other<'a>)]
struct Malformed<'a>(&'a mut ());
"#,
expect![[r#"
34..89: `derive(CoerceShared)` requires exactly one `#[coerce_shared(Target)]` attribute
91..206: `derive(CoerceShared)` requires exactly one `#[coerce_shared(Target)]` attribute
208..305: `derive(CoerceShared)` requires exactly one `#[coerce_shared(Target)]` attribute"#]],
);
}

#[test]
fn union_derive() {
check_errors(
Expand Down
3 changes: 3 additions & 0 deletions crates/hir-def/src/nameres/collector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1586,6 +1586,9 @@ impl<'db> DefCollector<'db> {
if super::enable_builtin_derive_fast_path()
&& let MacroDefKind::BuiltInDerive(_, builtin_derive) =
def_id.kind
&& crate::builtin_derive::has_builtin_derive_impl(
builtin_derive,
)
{
self.deferred_builtin_derives
.entry(ast_id_without_path.upcast())
Expand Down
132 changes: 131 additions & 1 deletion crates/hir-expand/src/builtin/derive_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use either::Either;
use intern::sym;
use itertools::{Itertools, izip};
use parser::SyntaxKind;
use rustc_hash::FxHashSet;
use rustc_hash::{FxHashMap, FxHashSet};
use span::{Edition, Span};
use stdx::never;
use syntax_bridge::DocCommentDesugarMode;
Expand Down Expand Up @@ -76,6 +76,8 @@ register_builtin! {
Eq => eq_expand,
PartialEq => partial_eq_expand,
CoercePointee => coerce_pointee_expand,
Reborrow => reborrow_expand,
CoerceShared => coerce_shared_expand,
}

pub fn find_builtin_derive(ident: &name::Name) -> Option<BuiltinDeriveExpander> {
Expand Down Expand Up @@ -547,6 +549,134 @@ fn copy_expand(
)
}

fn reborrow_expand(
db: &dyn ExpandDatabase,
span: Span,
tt: &tt::TopSubtree,
) -> ExpandResult<tt::TopSubtree> {
let krate = dollar_crate(span);
expand_reborrow_marker_derive(
db,
span,
tt,
quote! {span => #krate::marker::Reborrow },
"Reborrow",
)
}

fn coerce_shared_expand(
db: &dyn ExpandDatabase,
span: Span,
tt: &tt::TopSubtree,
) -> ExpandResult<tt::TopSubtree> {
let (adt, span_map) = match to_adt_syntax(db, tt, span) {
Ok(it) => it,
Err(err) => {
return ExpandResult::new(tt::TopSubtree::empty(tt::DelimSpan::from_single(span)), err);
}
};
let ast::Adt::Struct(strukt) = &adt else {
return ExpandResult::new(
tt::TopSubtree::empty(tt::DelimSpan::from_single(span)),
ExpandError::other(span, "`CoerceShared` can only be derived on `struct`s"),
);
};
let Some(target) = coerce_shared_target(db, span, strukt) else {
return ExpandResult::new(
tt::TopSubtree::empty(tt::DelimSpan::from_single(span)),
ExpandError::other(
span,
"`derive(CoerceShared)` requires exactly one `#[coerce_shared(Target)]` attribute",
),
);
};
let info = match parse_adt_from_syntax(&adt, &span_map, span) {
Ok(it) => it,
Err(err) => {
return ExpandResult::new(tt::TopSubtree::empty(tt::DelimSpan::from_single(span)), err);
}
};

let krate = dollar_crate(span);
ExpandResult::ok(expand_simple_derive_with_parsed(
span,
info,
quote! {span => #krate::marker::CoerceShared<#target> },
|_| quote! {span => },
false,
tt::TopSubtree::empty(tt::DelimSpan::from_single(span)),
))
}

fn expand_reborrow_marker_derive(
db: &dyn ExpandDatabase,
span: Span,
tt: &tt::TopSubtree,
trait_path: tt::TopSubtree,
trait_name: &'static str,
) -> ExpandResult<tt::TopSubtree> {
let info = match parse_adt(db, tt, span) {
Ok(info) => info,
Err(err) => {
return ExpandResult::new(tt::TopSubtree::empty(tt::DelimSpan::from_single(span)), err);
}
};
if !matches!(info.shape, AdtShape::Struct(_)) {
return ExpandResult::new(
tt::TopSubtree::empty(tt::DelimSpan::from_single(span)),
ExpandError::other(span, format!("`{trait_name}` can only be derived on `struct`s")),
);
}

ExpandResult::ok(expand_simple_derive_with_parsed(
span,
info,
trait_path,
|_| quote! {span => },
false,
tt::TopSubtree::empty(tt::DelimSpan::from_single(span)),
))
}

fn coerce_shared_target(
db: &dyn ExpandDatabase,
span: Span,
strukt: &ast::Struct,
) -> Option<tt::TopSubtree> {
let mut attrs = strukt
.attrs()
.filter(|attr| attr.as_simple_call().is_some_and(|(name, _)| name == "coerce_shared"));
let attr = attrs.next()?;
if attrs.next().is_some() {
return None;
}
let (_, target_tokens) = attr.as_simple_call()?;
let l_paren = target_tokens.l_paren_token()?;
let r_paren = target_tokens.r_paren_token()?;

let mut span_map = span::SpanMap::empty();
span_map.push(target_tokens.syntax().text_range().start(), span);
span_map.push(target_tokens.syntax().text_range().end(), span);

let remove = FxHashSet::from_iter([l_paren.into(), r_paren.into()]);
let target = syntax_bridge::syntax_node_to_token_tree_modified(
target_tokens.syntax(),
&span_map,
FxHashMap::default(),
remove,
span,
DocCommentDesugarMode::ProcMacro,
|_, _| (true, Vec::new()),
);

let (parse, _) = crate::db::token_tree_to_syntax_node(db, &target, crate::ExpandTo::Type);
if !parse.errors().is_empty() {
return None;
}
ast::Type::cast(parse.syntax_node())?;
Some(target)
}

fn clone_expand(
db: &dyn ExpandDatabase,
span: Span,
Expand Down
Loading
Loading