Skip to content

Commit 0241b52

Browse files
committed
Add bounds for fields in derive macro
1 parent e739c99 commit 0241b52

File tree

3 files changed

+66
-27
lines changed

3 files changed

+66
-27
lines changed

crates/hir-def/src/macro_expansion_tests/builtin_derive_macro.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ struct Foo;
1616
#[derive(Copy)]
1717
struct Foo;
1818
19-
impl < > core::marker::Copy for Foo< > {}"#]],
19+
impl < > core::marker::Copy for Foo< > where {}"#]],
2020
);
2121
}
2222

@@ -41,7 +41,7 @@ macro Copy {}
4141
#[derive(Copy)]
4242
struct Foo;
4343
44-
impl < > crate ::marker::Copy for Foo< > {}"#]],
44+
impl < > crate ::marker::Copy for Foo< > where {}"#]],
4545
);
4646
}
4747

@@ -57,7 +57,7 @@ struct Foo<A, B>;
5757
#[derive(Copy)]
5858
struct Foo<A, B>;
5959
60-
impl <T0: core::marker::Copy, T1: core::marker::Copy, > core::marker::Copy for Foo<T0, T1, > {}"#]],
60+
impl <A: core::marker::Copy, B: core::marker::Copy, > core::marker::Copy for Foo<A, B, > where {}"#]],
6161
);
6262
}
6363

@@ -74,7 +74,7 @@ struct Foo<A, B, 'a, 'b>;
7474
#[derive(Copy)]
7575
struct Foo<A, B, 'a, 'b>;
7676
77-
impl <T0: core::marker::Copy, T1: core::marker::Copy, > core::marker::Copy for Foo<T0, T1, > {}"#]],
77+
impl <A: core::marker::Copy, B: core::marker::Copy, > core::marker::Copy for Foo<A, B, > where {}"#]],
7878
);
7979
}
8080

@@ -90,7 +90,7 @@ struct Foo<A, B>;
9090
#[derive(Clone)]
9191
struct Foo<A, B>;
9292
93-
impl <T0: core::clone::Clone, T1: core::clone::Clone, > core::clone::Clone for Foo<T0, T1, > {}"#]],
93+
impl <A: core::clone::Clone, B: core::clone::Clone, > core::clone::Clone for Foo<A, B, > where {}"#]],
9494
);
9595
}
9696

@@ -106,6 +106,6 @@ struct Foo<const X: usize, T>(u32);
106106
#[derive(Clone)]
107107
struct Foo<const X: usize, T>(u32);
108108
109-
impl <const T0: usize, T1: core::clone::Clone, > core::clone::Clone for Foo<T0, T1, > {}"#]],
109+
impl <const X: usize, T: core::clone::Clone, > core::clone::Clone for Foo<X, T, > where u32: core::clone::Clone, {}"#]],
110110
);
111111
}

crates/hir-expand/src/builtin_derive_macro.rs

Lines changed: 56 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,12 @@
11
//! Builtin derives.
22
33
use base_db::{CrateOrigin, LangCrateOrigin};
4+
use either::Either;
45
use tracing::debug;
56

67
use crate::tt::{self, TokenId};
78
use syntax::{
8-
ast::{self, AstNode, HasGenericParams, HasModuleItem, HasName},
9+
ast::{self, AstNode, HasGenericParams, HasModuleItem, HasName, HasTypeBounds},
910
match_ast,
1011
};
1112

@@ -60,8 +61,11 @@ pub fn find_builtin_derive(ident: &name::Name) -> Option<BuiltinDeriveExpander>
6061

6162
struct BasicAdtInfo {
6263
name: tt::Ident,
63-
/// `Some(ty)` if it's a const param of type `ty`, `None` if it's a type param.
64-
param_types: Vec<Option<tt::Subtree>>,
64+
/// first field is the name, and
65+
/// second field is `Some(ty)` if it's a const param of type `ty`, `None` if it's a type param.
66+
/// third fields is where bounds, if any
67+
param_types: Vec<(tt::Subtree, Option<tt::Subtree>, Option<tt::Subtree>)>,
68+
field_types: Vec<tt::Subtree>,
6569
}
6670

6771
fn parse_adt(tt: &tt::Subtree) -> Result<BasicAdtInfo, ExpandError> {
@@ -75,17 +79,34 @@ fn parse_adt(tt: &tt::Subtree) -> Result<BasicAdtInfo, ExpandError> {
7579
ExpandError::Other("no item found".into())
7680
})?;
7781
let node = item.syntax();
78-
let (name, params) = match_ast! {
82+
let (name, params, fields) = match_ast! {
7983
match node {
80-
ast::Struct(it) => (it.name(), it.generic_param_list()),
81-
ast::Enum(it) => (it.name(), it.generic_param_list()),
82-
ast::Union(it) => (it.name(), it.generic_param_list()),
84+
ast::Struct(it) => {
85+
(it.name(), it.generic_param_list(), it.field_list().into_iter().collect::<Vec<_>>())
86+
},
87+
ast::Enum(it) => (it.name(), it.generic_param_list(), it.variant_list().into_iter().flat_map(|x| x.variants()).filter_map(|x| x.field_list()).collect()),
88+
ast::Union(it) => (it.name(), it.generic_param_list(), it.record_field_list().into_iter().map(|x| ast::FieldList::RecordFieldList(x)).collect()),
8389
_ => {
8490
debug!("unexpected node is {:?}", node);
8591
return Err(ExpandError::Other("expected struct, enum or union".into()))
8692
},
8793
}
8894
};
95+
let field_types = fields
96+
.into_iter()
97+
.flat_map(|f| match f {
98+
ast::FieldList::RecordFieldList(x) => Either::Left(
99+
x.fields()
100+
.filter_map(|x| x.ty())
101+
.map(|x| mbe::syntax_node_to_token_tree(x.syntax()).0),
102+
),
103+
ast::FieldList::TupleFieldList(x) => Either::Right(
104+
x.fields()
105+
.filter_map(|x| x.ty())
106+
.map(|x| mbe::syntax_node_to_token_tree(x.syntax()).0),
107+
),
108+
})
109+
.collect::<Vec<_>>();
89110
let name = name.ok_or_else(|| {
90111
debug!("parsed item has no name");
91112
ExpandError::Other("missing name".into())
@@ -97,35 +118,46 @@ fn parse_adt(tt: &tt::Subtree) -> Result<BasicAdtInfo, ExpandError> {
97118
.into_iter()
98119
.flat_map(|param_list| param_list.type_or_const_params())
99120
.map(|param| {
100-
if let ast::TypeOrConstParam::Const(param) = param {
121+
let name = param
122+
.name()
123+
.map(|x| mbe::syntax_node_to_token_tree(x.syntax()).0)
124+
.unwrap_or_else(tt::Subtree::empty);
125+
let bounds = match &param {
126+
ast::TypeOrConstParam::Type(x) => {
127+
x.type_bound_list().map(|x| mbe::syntax_node_to_token_tree(x.syntax()).0)
128+
}
129+
ast::TypeOrConstParam::Const(_) => None,
130+
};
131+
let ty = if let ast::TypeOrConstParam::Const(param) = param {
101132
let ty = param
102133
.ty()
103134
.map(|ty| mbe::syntax_node_to_token_tree(ty.syntax()).0)
104135
.unwrap_or_else(tt::Subtree::empty);
105136
Some(ty)
106137
} else {
107138
None
108-
}
139+
};
140+
(name, ty, bounds)
109141
})
110142
.collect();
111-
Ok(BasicAdtInfo { name: name_token, param_types })
143+
Ok(BasicAdtInfo { name: name_token, param_types, field_types })
112144
}
113145

114146
fn expand_simple_derive(tt: &tt::Subtree, trait_path: tt::Subtree) -> ExpandResult<tt::Subtree> {
115147
let info = match parse_adt(tt) {
116148
Ok(info) => info,
117149
Err(e) => return ExpandResult::with_err(tt::Subtree::empty(), e),
118150
};
151+
let mut where_block = vec![];
119152
let (params, args): (Vec<_>, Vec<_>) = info
120153
.param_types
121154
.into_iter()
122-
.enumerate()
123-
.map(|(idx, param_ty)| {
124-
let ident = tt::Leaf::Ident(tt::Ident {
125-
span: tt::TokenId::unspecified(),
126-
text: format!("T{idx}").into(),
127-
});
155+
.map(|(ident, param_ty, bound)| {
128156
let ident_ = ident.clone();
157+
if let Some(b) = bound {
158+
let ident = ident.clone();
159+
where_block.push(quote! { #ident : #b , });
160+
}
129161
if let Some(ty) = param_ty {
130162
(quote! { const #ident : #ty , }, quote! { #ident_ , })
131163
} else {
@@ -134,9 +166,16 @@ fn expand_simple_derive(tt: &tt::Subtree, trait_path: tt::Subtree) -> ExpandResu
134166
}
135167
})
136168
.unzip();
169+
170+
where_block.extend(info.field_types.iter().map(|x| {
171+
let x = x.clone();
172+
let bound = trait_path.clone();
173+
quote! { #x : #bound , }
174+
}));
175+
137176
let name = info.name;
138177
let expanded = quote! {
139-
impl < ##params > #trait_path for #name < ##args > {}
178+
impl < ##params > #trait_path for #name < ##args > where ##where_block {}
140179
};
141180
ExpandResult::ok(expanded)
142181
}

crates/ide/src/expand_macro.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -471,7 +471,7 @@ struct Foo {}
471471
"#,
472472
expect![[r#"
473473
Clone
474-
impl < >core::clone::Clone for Foo< >{}
474+
impl < >core::clone::Clone for Foo< >where{}
475475
"#]],
476476
);
477477
}
@@ -488,7 +488,7 @@ struct Foo {}
488488
"#,
489489
expect![[r#"
490490
Copy
491-
impl < >core::marker::Copy for Foo< >{}
491+
impl < >core::marker::Copy for Foo< >where{}
492492
"#]],
493493
);
494494
}
@@ -504,7 +504,7 @@ struct Foo {}
504504
"#,
505505
expect![[r#"
506506
Copy
507-
impl < >core::marker::Copy for Foo< >{}
507+
impl < >core::marker::Copy for Foo< >where{}
508508
"#]],
509509
);
510510
check(
@@ -516,7 +516,7 @@ struct Foo {}
516516
"#,
517517
expect![[r#"
518518
Clone
519-
impl < >core::clone::Clone for Foo< >{}
519+
impl < >core::clone::Clone for Foo< >where{}
520520
"#]],
521521
);
522522
}

0 commit comments

Comments
 (0)