2019-12-05 08:10:33 -06:00
|
|
|
//! Builtin derives.
|
|
|
|
|
2023-05-03 05:44:47 -05:00
|
|
|
use ::tt::Ident;
|
2022-05-20 09:42:28 -05:00
|
|
|
use base_db::{CrateOrigin, LangCrateOrigin};
|
2023-05-03 05:44:47 -05:00
|
|
|
use itertools::izip;
|
|
|
|
use mbe::TokenMap;
|
2023-06-07 04:37:09 -05:00
|
|
|
use rustc_hash::FxHashSet;
|
2023-05-03 05:44:47 -05:00
|
|
|
use stdx::never;
|
2021-08-15 07:46:13 -05:00
|
|
|
use tracing::debug;
|
2019-12-05 12:29:57 -06:00
|
|
|
|
2023-06-07 04:37:09 -05:00
|
|
|
use crate::{
|
|
|
|
name::{AsName, Name},
|
|
|
|
tt::{self, TokenId},
|
|
|
|
};
|
|
|
|
use syntax::ast::{
|
|
|
|
self, AstNode, FieldList, HasAttrs, HasGenericParams, HasModuleItem, HasName, HasTypeBounds,
|
2019-12-05 12:29:57 -06:00
|
|
|
};
|
|
|
|
|
2023-03-13 10:33:52 -05:00
|
|
|
use crate::{db::ExpandDatabase, name, quote, ExpandError, ExpandResult, MacroCallId};
|
2019-12-05 08:10:33 -06:00
|
|
|
|
|
|
|
macro_rules! register_builtin {
|
2019-12-13 14:43:53 -06:00
|
|
|
( $($trait:ident => $expand:ident),* ) => {
|
2019-12-05 08:10:33 -06:00
|
|
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
|
|
|
pub enum BuiltinDeriveExpander {
|
2019-12-13 14:43:53 -06:00
|
|
|
$($trait),*
|
2019-12-05 08:10:33 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
impl BuiltinDeriveExpander {
|
|
|
|
pub fn expand(
|
|
|
|
&self,
|
2023-03-13 10:33:52 -05:00
|
|
|
db: &dyn ExpandDatabase,
|
2021-05-19 13:19:08 -05:00
|
|
|
id: MacroCallId,
|
2019-12-05 08:10:33 -06:00
|
|
|
tt: &tt::Subtree,
|
2021-08-20 07:28:36 -05:00
|
|
|
) -> ExpandResult<tt::Subtree> {
|
2019-12-05 08:10:33 -06:00
|
|
|
let expander = match *self {
|
2019-12-13 14:43:53 -06:00
|
|
|
$( BuiltinDeriveExpander::$trait => $expand, )*
|
2019-12-05 08:10:33 -06:00
|
|
|
};
|
|
|
|
expander(db, id, tt)
|
|
|
|
}
|
|
|
|
|
2020-12-15 13:33:05 -06:00
|
|
|
fn find_by_name(name: &name::Name) -> Option<Self> {
|
|
|
|
match name {
|
|
|
|
$( id if id == &name::name![$trait] => Some(BuiltinDeriveExpander::$trait), )*
|
|
|
|
_ => None,
|
|
|
|
}
|
|
|
|
}
|
2019-12-05 08:10:33 -06:00
|
|
|
}
|
2020-12-15 13:33:05 -06:00
|
|
|
|
2019-12-05 08:10:33 -06:00
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
register_builtin! {
|
2019-12-13 14:43:53 -06:00
|
|
|
Copy => copy_expand,
|
|
|
|
Clone => clone_expand,
|
|
|
|
Default => default_expand,
|
|
|
|
Debug => debug_expand,
|
|
|
|
Hash => hash_expand,
|
|
|
|
Ord => ord_expand,
|
|
|
|
PartialOrd => partial_ord_expand,
|
|
|
|
Eq => eq_expand,
|
|
|
|
PartialEq => partial_eq_expand
|
2019-12-05 08:10:33 -06:00
|
|
|
}
|
|
|
|
|
2022-03-08 14:41:19 -06:00
|
|
|
pub fn find_builtin_derive(ident: &name::Name) -> Option<BuiltinDeriveExpander> {
|
|
|
|
BuiltinDeriveExpander::find_by_name(ident)
|
2020-12-15 13:33:05 -06:00
|
|
|
}
|
|
|
|
|
2023-05-03 05:44:47 -05:00
|
|
|
enum VariantShape {
|
|
|
|
Struct(Vec<tt::Ident>),
|
|
|
|
Tuple(usize),
|
|
|
|
Unit,
|
|
|
|
}
|
|
|
|
|
|
|
|
fn tuple_field_iterator(n: usize) -> impl Iterator<Item = tt::Ident> {
|
|
|
|
(0..n).map(|x| Ident::new(format!("f{x}"), tt::TokenId::unspecified()))
|
|
|
|
}
|
|
|
|
|
|
|
|
impl VariantShape {
|
|
|
|
fn as_pattern(&self, path: tt::Subtree) -> tt::Subtree {
|
|
|
|
self.as_pattern_map(path, |x| quote!(#x))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn field_names(&self) -> Vec<tt::Ident> {
|
|
|
|
match self {
|
|
|
|
VariantShape::Struct(s) => s.clone(),
|
|
|
|
VariantShape::Tuple(n) => tuple_field_iterator(*n).collect(),
|
|
|
|
VariantShape::Unit => vec![],
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn as_pattern_map(
|
|
|
|
&self,
|
|
|
|
path: tt::Subtree,
|
|
|
|
field_map: impl Fn(&tt::Ident) -> tt::Subtree,
|
|
|
|
) -> tt::Subtree {
|
|
|
|
match self {
|
|
|
|
VariantShape::Struct(fields) => {
|
|
|
|
let fields = fields.iter().map(|x| {
|
|
|
|
let mapped = field_map(x);
|
|
|
|
quote! { #x : #mapped , }
|
|
|
|
});
|
|
|
|
quote! {
|
|
|
|
#path { ##fields }
|
|
|
|
}
|
|
|
|
}
|
|
|
|
&VariantShape::Tuple(n) => {
|
|
|
|
let fields = tuple_field_iterator(n).map(|x| {
|
|
|
|
let mapped = field_map(&x);
|
|
|
|
quote! {
|
|
|
|
#mapped ,
|
|
|
|
}
|
|
|
|
});
|
|
|
|
quote! {
|
|
|
|
#path ( ##fields )
|
|
|
|
}
|
|
|
|
}
|
|
|
|
VariantShape::Unit => path,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn from(value: Option<FieldList>, token_map: &TokenMap) -> Result<Self, ExpandError> {
|
|
|
|
let r = match value {
|
|
|
|
None => VariantShape::Unit,
|
|
|
|
Some(FieldList::RecordFieldList(x)) => VariantShape::Struct(
|
|
|
|
x.fields()
|
|
|
|
.map(|x| x.name())
|
|
|
|
.map(|x| name_to_token(token_map, x))
|
|
|
|
.collect::<Result<_, _>>()?,
|
|
|
|
),
|
|
|
|
Some(FieldList::TupleFieldList(x)) => VariantShape::Tuple(x.fields().count()),
|
|
|
|
};
|
|
|
|
Ok(r)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
enum AdtShape {
|
|
|
|
Struct(VariantShape),
|
|
|
|
Enum { variants: Vec<(tt::Ident, VariantShape)>, default_variant: Option<usize> },
|
|
|
|
Union,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl AdtShape {
|
|
|
|
fn as_pattern(&self, name: &tt::Ident) -> Vec<tt::Subtree> {
|
|
|
|
self.as_pattern_map(name, |x| quote!(#x))
|
|
|
|
}
|
|
|
|
|
|
|
|
fn field_names(&self) -> Vec<Vec<tt::Ident>> {
|
|
|
|
match self {
|
|
|
|
AdtShape::Struct(s) => {
|
|
|
|
vec![s.field_names()]
|
|
|
|
}
|
|
|
|
AdtShape::Enum { variants, .. } => {
|
|
|
|
variants.iter().map(|(_, fields)| fields.field_names()).collect()
|
|
|
|
}
|
|
|
|
AdtShape::Union => {
|
|
|
|
never!("using fields of union in derive is always wrong");
|
|
|
|
vec![]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn as_pattern_map(
|
|
|
|
&self,
|
|
|
|
name: &tt::Ident,
|
|
|
|
field_map: impl Fn(&tt::Ident) -> tt::Subtree,
|
|
|
|
) -> Vec<tt::Subtree> {
|
|
|
|
match self {
|
|
|
|
AdtShape::Struct(s) => {
|
|
|
|
vec![s.as_pattern_map(quote! { #name }, field_map)]
|
|
|
|
}
|
|
|
|
AdtShape::Enum { variants, .. } => variants
|
|
|
|
.iter()
|
|
|
|
.map(|(v, fields)| fields.as_pattern_map(quote! { #name :: #v }, &field_map))
|
|
|
|
.collect(),
|
|
|
|
AdtShape::Union => {
|
|
|
|
never!("pattern matching on union is always wrong");
|
|
|
|
vec![quote! { un }]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2019-12-05 12:29:57 -06:00
|
|
|
struct BasicAdtInfo {
|
|
|
|
name: tt::Ident,
|
2023-05-03 05:44:47 -05:00
|
|
|
shape: AdtShape,
|
2023-04-07 11:03:14 -05:00
|
|
|
/// first field is the name, and
|
|
|
|
/// second field is `Some(ty)` if it's a const param of type `ty`, `None` if it's a type param.
|
|
|
|
/// third fields is where bounds, if any
|
|
|
|
param_types: Vec<(tt::Subtree, Option<tt::Subtree>, Option<tt::Subtree>)>,
|
|
|
|
associated_types: Vec<tt::Subtree>,
|
2019-12-05 12:29:57 -06:00
|
|
|
}
|
|
|
|
|
2022-02-21 12:14:06 -06:00
|
|
|
fn parse_adt(tt: &tt::Subtree) -> Result<BasicAdtInfo, ExpandError> {
|
|
|
|
let (parsed, token_map) = mbe::token_tree_to_syntax_node(tt, mbe::TopEntryPoint::MacroItems);
|
2019-12-05 12:29:57 -06:00
|
|
|
let macro_items = ast::MacroItems::cast(parsed.syntax_node()).ok_or_else(|| {
|
|
|
|
debug!("derive node didn't parse");
|
2022-02-21 12:14:06 -06:00
|
|
|
ExpandError::Other("invalid item definition".into())
|
2019-12-05 12:29:57 -06:00
|
|
|
})?;
|
|
|
|
let item = macro_items.items().next().ok_or_else(|| {
|
|
|
|
debug!("no module item parsed");
|
2022-02-21 12:14:06 -06:00
|
|
|
ExpandError::Other("no item found".into())
|
2019-12-05 12:29:57 -06:00
|
|
|
})?;
|
2023-06-07 04:37:09 -05:00
|
|
|
let adt = ast::Adt::cast(item.syntax().clone()).ok_or_else(|| {
|
|
|
|
debug!("expected adt, found: {:?}", item);
|
|
|
|
ExpandError::Other("expected struct, enum or union".into())
|
|
|
|
})?;
|
|
|
|
let (name, generic_param_list, shape) = match &adt {
|
|
|
|
ast::Adt::Struct(it) => (
|
|
|
|
it.name(),
|
|
|
|
it.generic_param_list(),
|
|
|
|
AdtShape::Struct(VariantShape::from(it.field_list(), &token_map)?),
|
|
|
|
),
|
|
|
|
ast::Adt::Enum(it) => {
|
|
|
|
let default_variant = it
|
|
|
|
.variant_list()
|
|
|
|
.into_iter()
|
|
|
|
.flat_map(|x| x.variants())
|
|
|
|
.position(|x| x.attrs().any(|x| x.simple_name() == Some("default".into())));
|
|
|
|
(
|
|
|
|
it.name(),
|
|
|
|
it.generic_param_list(),
|
|
|
|
AdtShape::Enum {
|
|
|
|
default_variant,
|
|
|
|
variants: it
|
|
|
|
.variant_list()
|
|
|
|
.into_iter()
|
|
|
|
.flat_map(|x| x.variants())
|
|
|
|
.map(|x| {
|
|
|
|
Ok((
|
|
|
|
name_to_token(&token_map, x.name())?,
|
|
|
|
VariantShape::from(x.field_list(), &token_map)?,
|
|
|
|
))
|
|
|
|
})
|
|
|
|
.collect::<Result<_, ExpandError>>()?,
|
|
|
|
},
|
|
|
|
)
|
2019-12-05 12:29:57 -06:00
|
|
|
}
|
2023-06-07 04:37:09 -05:00
|
|
|
ast::Adt::Union(it) => (it.name(), it.generic_param_list(), AdtShape::Union),
|
2019-12-05 12:29:57 -06:00
|
|
|
};
|
2023-06-07 04:37:09 -05:00
|
|
|
|
|
|
|
let mut param_type_set: FxHashSet<Name> = FxHashSet::default();
|
|
|
|
let param_types = generic_param_list
|
2022-10-22 03:49:38 -05:00
|
|
|
.into_iter()
|
|
|
|
.flat_map(|param_list| param_list.type_or_const_params())
|
|
|
|
.map(|param| {
|
2023-04-07 11:03:14 -05:00
|
|
|
let name = {
|
|
|
|
let this = param.name();
|
|
|
|
match this {
|
|
|
|
Some(x) => {
|
2023-06-07 04:37:09 -05:00
|
|
|
param_type_set.insert(x.as_name());
|
2023-04-07 11:03:14 -05:00
|
|
|
mbe::syntax_node_to_token_tree(x.syntax()).0
|
|
|
|
}
|
|
|
|
None => tt::Subtree::empty(),
|
|
|
|
}
|
|
|
|
};
|
|
|
|
let bounds = match ¶m {
|
|
|
|
ast::TypeOrConstParam::Type(x) => {
|
|
|
|
x.type_bound_list().map(|x| mbe::syntax_node_to_token_tree(x.syntax()).0)
|
|
|
|
}
|
|
|
|
ast::TypeOrConstParam::Const(_) => None,
|
|
|
|
};
|
|
|
|
let ty = if let ast::TypeOrConstParam::Const(param) = param {
|
2022-10-22 03:49:38 -05:00
|
|
|
let ty = param
|
|
|
|
.ty()
|
|
|
|
.map(|ty| mbe::syntax_node_to_token_tree(ty.syntax()).0)
|
2023-01-31 04:49:49 -06:00
|
|
|
.unwrap_or_else(tt::Subtree::empty);
|
2022-10-22 03:49:38 -05:00
|
|
|
Some(ty)
|
|
|
|
} else {
|
|
|
|
None
|
2023-04-07 11:03:14 -05:00
|
|
|
};
|
|
|
|
(name, ty, bounds)
|
2019-12-12 07:47:54 -06:00
|
|
|
})
|
2022-10-22 03:49:38 -05:00
|
|
|
.collect();
|
2023-06-07 04:37:09 -05:00
|
|
|
|
|
|
|
// For a generic parameter `T`, when shorthand associated type `T::Assoc` appears in field
|
|
|
|
// types (of any variant for enums), we generate trait bound for it. It sounds reasonable to
|
|
|
|
// also generate trait bound for qualified associated type `<T as Trait>::Assoc`, but rustc
|
|
|
|
// does not do that for some unknown reason.
|
|
|
|
//
|
|
|
|
// See the analogous function in rustc [find_type_parameters()] and rust-lang/rust#50730.
|
|
|
|
// [find_type_parameters()]: https://github.com/rust-lang/rust/blob/1.70.0/compiler/rustc_builtin_macros/src/deriving/generic/mod.rs#L378
|
|
|
|
|
|
|
|
// It's cumbersome to deal with the distinct structures of ADTs, so let's just get untyped
|
|
|
|
// `SyntaxNode` that contains fields and look for descendant `ast::PathType`s. Of note is that
|
|
|
|
// we should not inspect `ast::PathType`s in parameter bounds and where clauses.
|
|
|
|
let field_list = match adt {
|
|
|
|
ast::Adt::Enum(it) => it.variant_list().map(|list| list.syntax().clone()),
|
|
|
|
ast::Adt::Struct(it) => it.field_list().map(|list| list.syntax().clone()),
|
|
|
|
ast::Adt::Union(it) => it.record_field_list().map(|list| list.syntax().clone()),
|
2023-04-07 11:03:14 -05:00
|
|
|
};
|
2023-06-07 04:37:09 -05:00
|
|
|
let associated_types = field_list
|
|
|
|
.into_iter()
|
|
|
|
.flat_map(|it| it.descendants())
|
|
|
|
.filter_map(ast::PathType::cast)
|
|
|
|
.filter_map(|p| {
|
|
|
|
let name = p.path()?.qualifier()?.as_single_name_ref()?.as_name();
|
|
|
|
param_type_set.contains(&name).then_some(p)
|
|
|
|
})
|
2023-04-07 11:03:14 -05:00
|
|
|
.map(|x| mbe::syntax_node_to_token_tree(x.syntax()).0)
|
2023-06-07 04:37:09 -05:00
|
|
|
.collect();
|
2023-05-03 05:44:47 -05:00
|
|
|
let name_token = name_to_token(&token_map, name)?;
|
|
|
|
Ok(BasicAdtInfo { name: name_token, shape, param_types, associated_types })
|
|
|
|
}
|
|
|
|
|
|
|
|
fn name_to_token(token_map: &TokenMap, name: Option<ast::Name>) -> Result<tt::Ident, ExpandError> {
|
2023-04-07 11:03:14 -05:00
|
|
|
let name = name.ok_or_else(|| {
|
|
|
|
debug!("parsed item has no name");
|
|
|
|
ExpandError::Other("missing name".into())
|
|
|
|
})?;
|
|
|
|
let name_token_id =
|
|
|
|
token_map.token_by_range(name.syntax().text_range()).unwrap_or_else(TokenId::unspecified);
|
|
|
|
let name_token = tt::Ident { span: name_token_id, text: name.text().into() };
|
2023-05-03 05:44:47 -05:00
|
|
|
Ok(name_token)
|
2019-12-05 12:29:57 -06:00
|
|
|
}
|
|
|
|
|
2023-04-07 11:03:14 -05:00
|
|
|
/// Given that we are deriving a trait `DerivedTrait` for a type like:
|
|
|
|
///
|
|
|
|
/// ```ignore (only-for-syntax-highlight)
|
|
|
|
/// struct Struct<'a, ..., 'z, A, B: DeclaredTrait, C, ..., Z> where C: WhereTrait {
|
|
|
|
/// a: A,
|
|
|
|
/// b: B::Item,
|
|
|
|
/// b1: <B as DeclaredTrait>::Item,
|
|
|
|
/// c1: <C as WhereTrait>::Item,
|
|
|
|
/// c2: Option<<C as WhereTrait>::Item>,
|
|
|
|
/// ...
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// create an impl like:
|
|
|
|
///
|
|
|
|
/// ```ignore (only-for-syntax-highlight)
|
|
|
|
/// impl<'a, ..., 'z, A, B: DeclaredTrait, C, ... Z> where
|
|
|
|
/// C: WhereTrait,
|
|
|
|
/// A: DerivedTrait + B1 + ... + BN,
|
|
|
|
/// B: DerivedTrait + B1 + ... + BN,
|
|
|
|
/// C: DerivedTrait + B1 + ... + BN,
|
|
|
|
/// B::Item: DerivedTrait + B1 + ... + BN,
|
|
|
|
/// <C as WhereTrait>::Item: DerivedTrait + B1 + ... + BN,
|
|
|
|
/// ...
|
|
|
|
/// {
|
|
|
|
/// ...
|
|
|
|
/// }
|
|
|
|
/// ```
|
|
|
|
///
|
2023-06-07 04:37:09 -05:00
|
|
|
/// where B1, ..., BN are the bounds given by `bounds_paths`. Z is a phantom type, and
|
2023-04-07 11:03:14 -05:00
|
|
|
/// therefore does not get bound by the derived trait.
|
2023-05-03 05:44:47 -05:00
|
|
|
fn expand_simple_derive(
|
|
|
|
tt: &tt::Subtree,
|
|
|
|
trait_path: tt::Subtree,
|
2023-06-07 04:37:09 -05:00
|
|
|
make_trait_body: impl FnOnce(&BasicAdtInfo) -> tt::Subtree,
|
2023-05-03 05:44:47 -05:00
|
|
|
) -> ExpandResult<tt::Subtree> {
|
2021-08-20 07:28:36 -05:00
|
|
|
let info = match parse_adt(tt) {
|
|
|
|
Ok(info) => info,
|
2023-04-16 12:20:48 -05:00
|
|
|
Err(e) => return ExpandResult::new(tt::Subtree::empty(), e),
|
2021-08-20 07:28:36 -05:00
|
|
|
};
|
2023-06-07 04:37:09 -05:00
|
|
|
let trait_body = make_trait_body(&info);
|
2023-04-07 11:03:14 -05:00
|
|
|
let mut where_block = vec![];
|
2022-10-22 03:49:38 -05:00
|
|
|
let (params, args): (Vec<_>, Vec<_>) = info
|
|
|
|
.param_types
|
|
|
|
.into_iter()
|
2023-04-07 11:03:14 -05:00
|
|
|
.map(|(ident, param_ty, bound)| {
|
2022-10-22 03:49:38 -05:00
|
|
|
let ident_ = ident.clone();
|
2023-04-07 11:03:14 -05:00
|
|
|
if let Some(b) = bound {
|
|
|
|
let ident = ident.clone();
|
|
|
|
where_block.push(quote! { #ident : #b , });
|
|
|
|
}
|
2022-10-22 03:49:38 -05:00
|
|
|
if let Some(ty) = param_ty {
|
|
|
|
(quote! { const #ident : #ty , }, quote! { #ident_ , })
|
|
|
|
} else {
|
|
|
|
let bound = trait_path.clone();
|
|
|
|
(quote! { #ident : #bound , }, quote! { #ident_ , })
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.unzip();
|
2023-04-07 11:03:14 -05:00
|
|
|
|
|
|
|
where_block.extend(info.associated_types.iter().map(|x| {
|
|
|
|
let x = x.clone();
|
|
|
|
let bound = trait_path.clone();
|
|
|
|
quote! { #x : #bound , }
|
|
|
|
}));
|
|
|
|
|
2019-12-05 12:29:57 -06:00
|
|
|
let name = info.name;
|
2019-12-05 08:10:33 -06:00
|
|
|
let expanded = quote! {
|
2023-05-03 05:44:47 -05:00
|
|
|
impl < ##params > #trait_path for #name < ##args > where ##where_block { #trait_body }
|
2019-12-05 08:10:33 -06:00
|
|
|
};
|
2021-08-20 07:28:36 -05:00
|
|
|
ExpandResult::ok(expanded)
|
2019-12-05 08:10:33 -06:00
|
|
|
}
|
|
|
|
|
2023-03-13 10:33:52 -05:00
|
|
|
fn find_builtin_crate(db: &dyn ExpandDatabase, id: MacroCallId) -> tt::TokenTree {
|
2020-04-27 12:48:55 -05:00
|
|
|
// FIXME: make hygiene works for builtin derive macro
|
|
|
|
// such that $crate can be used here.
|
|
|
|
let cg = db.crate_graph();
|
2021-11-14 09:25:40 -06:00
|
|
|
let krate = db.lookup_intern_macro_call(id).krate;
|
2020-04-27 12:48:55 -05:00
|
|
|
|
2022-05-20 09:42:28 -05:00
|
|
|
let tt = if matches!(cg[krate].origin, CrateOrigin::Lang(LangCrateOrigin::Core)) {
|
2021-10-10 08:13:45 -05:00
|
|
|
cov_mark::hit!(test_copy_expand_in_core);
|
2020-04-27 15:11:24 -05:00
|
|
|
quote! { crate }
|
2022-05-20 09:42:28 -05:00
|
|
|
} else {
|
|
|
|
quote! { core }
|
2020-04-27 12:48:55 -05:00
|
|
|
};
|
|
|
|
|
|
|
|
tt.token_trees[0].clone()
|
|
|
|
}
|
|
|
|
|
2019-12-05 12:52:52 -06:00
|
|
|
fn copy_expand(
|
2023-03-13 10:33:52 -05:00
|
|
|
db: &dyn ExpandDatabase,
|
2021-05-19 13:19:08 -05:00
|
|
|
id: MacroCallId,
|
2019-12-05 12:52:52 -06:00
|
|
|
tt: &tt::Subtree,
|
2021-08-20 07:28:36 -05:00
|
|
|
) -> ExpandResult<tt::Subtree> {
|
2020-04-27 12:48:55 -05:00
|
|
|
let krate = find_builtin_crate(db, id);
|
2023-05-03 05:44:47 -05:00
|
|
|
expand_simple_derive(tt, quote! { #krate::marker::Copy }, |_| quote! {})
|
2019-12-05 12:52:52 -06:00
|
|
|
}
|
|
|
|
|
2019-12-05 08:10:33 -06:00
|
|
|
fn clone_expand(
|
2023-03-13 10:33:52 -05:00
|
|
|
db: &dyn ExpandDatabase,
|
2021-05-19 13:19:08 -05:00
|
|
|
id: MacroCallId,
|
2019-12-05 12:29:57 -06:00
|
|
|
tt: &tt::Subtree,
|
2021-08-20 07:28:36 -05:00
|
|
|
) -> ExpandResult<tt::Subtree> {
|
2020-04-27 12:48:55 -05:00
|
|
|
let krate = find_builtin_crate(db, id);
|
2023-05-03 05:44:47 -05:00
|
|
|
expand_simple_derive(tt, quote! { #krate::clone::Clone }, |adt| {
|
|
|
|
if matches!(adt.shape, AdtShape::Union) {
|
|
|
|
let star = tt::Punct {
|
|
|
|
char: '*',
|
|
|
|
spacing: ::tt::Spacing::Alone,
|
|
|
|
span: tt::TokenId::unspecified(),
|
|
|
|
};
|
|
|
|
return quote! {
|
|
|
|
fn clone(&self) -> Self {
|
|
|
|
#star self
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
if matches!(&adt.shape, AdtShape::Enum { variants, .. } if variants.is_empty()) {
|
|
|
|
let star = tt::Punct {
|
|
|
|
char: '*',
|
|
|
|
spacing: ::tt::Spacing::Alone,
|
|
|
|
span: tt::TokenId::unspecified(),
|
|
|
|
};
|
|
|
|
return quote! {
|
|
|
|
fn clone(&self) -> Self {
|
|
|
|
match #star self {}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
let name = &adt.name;
|
|
|
|
let patterns = adt.shape.as_pattern(name);
|
|
|
|
let exprs = adt.shape.as_pattern_map(name, |x| quote! { #x .clone() });
|
|
|
|
let arms = patterns.into_iter().zip(exprs.into_iter()).map(|(pat, expr)| {
|
|
|
|
let fat_arrow = fat_arrow();
|
|
|
|
quote! {
|
|
|
|
#pat #fat_arrow #expr,
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
quote! {
|
|
|
|
fn clone(&self) -> Self {
|
|
|
|
match self {
|
|
|
|
##arms
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
/// This function exists since `quote! { => }` doesn't work.
|
|
|
|
fn fat_arrow() -> ::tt::Subtree<TokenId> {
|
|
|
|
let eq =
|
|
|
|
tt::Punct { char: '=', spacing: ::tt::Spacing::Joint, span: tt::TokenId::unspecified() };
|
|
|
|
quote! { #eq> }
|
|
|
|
}
|
|
|
|
|
|
|
|
/// This function exists since `quote! { && }` doesn't work.
|
|
|
|
fn and_and() -> ::tt::Subtree<TokenId> {
|
|
|
|
let and =
|
|
|
|
tt::Punct { char: '&', spacing: ::tt::Spacing::Joint, span: tt::TokenId::unspecified() };
|
|
|
|
quote! { #and& }
|
2019-12-05 12:52:52 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
fn default_expand(
|
2023-03-13 10:33:52 -05:00
|
|
|
db: &dyn ExpandDatabase,
|
2021-05-19 13:19:08 -05:00
|
|
|
id: MacroCallId,
|
2019-12-05 12:52:52 -06:00
|
|
|
tt: &tt::Subtree,
|
2021-08-20 07:28:36 -05:00
|
|
|
) -> ExpandResult<tt::Subtree> {
|
2023-05-03 05:44:47 -05:00
|
|
|
let krate = &find_builtin_crate(db, id);
|
|
|
|
expand_simple_derive(tt, quote! { #krate::default::Default }, |adt| {
|
|
|
|
let body = match &adt.shape {
|
|
|
|
AdtShape::Struct(fields) => {
|
|
|
|
let name = &adt.name;
|
|
|
|
fields
|
|
|
|
.as_pattern_map(quote!(#name), |_| quote!(#krate::default::Default::default()))
|
|
|
|
}
|
|
|
|
AdtShape::Enum { default_variant, variants } => {
|
|
|
|
if let Some(d) = default_variant {
|
|
|
|
let (name, fields) = &variants[*d];
|
|
|
|
let adt_name = &adt.name;
|
|
|
|
fields.as_pattern_map(
|
|
|
|
quote!(#adt_name :: #name),
|
|
|
|
|_| quote!(#krate::default::Default::default()),
|
|
|
|
)
|
|
|
|
} else {
|
|
|
|
// FIXME: Return expand error here
|
|
|
|
quote!()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
AdtShape::Union => {
|
|
|
|
// FIXME: Return expand error here
|
|
|
|
quote!()
|
|
|
|
}
|
|
|
|
};
|
|
|
|
quote! {
|
|
|
|
fn default() -> Self {
|
|
|
|
#body
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
2019-12-05 12:52:52 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
fn debug_expand(
|
2023-03-13 10:33:52 -05:00
|
|
|
db: &dyn ExpandDatabase,
|
2021-05-19 13:19:08 -05:00
|
|
|
id: MacroCallId,
|
2019-12-05 12:52:52 -06:00
|
|
|
tt: &tt::Subtree,
|
2021-08-20 07:28:36 -05:00
|
|
|
) -> ExpandResult<tt::Subtree> {
|
2023-05-03 05:44:47 -05:00
|
|
|
let krate = &find_builtin_crate(db, id);
|
|
|
|
expand_simple_derive(tt, quote! { #krate::fmt::Debug }, |adt| {
|
|
|
|
let for_variant = |name: String, v: &VariantShape| match v {
|
|
|
|
VariantShape::Struct(fields) => {
|
|
|
|
let for_fields = fields.iter().map(|x| {
|
|
|
|
let x_string = x.to_string();
|
|
|
|
quote! {
|
2023-05-12 04:06:57 -05:00
|
|
|
.field(#x_string, & #x)
|
2023-05-03 05:44:47 -05:00
|
|
|
}
|
|
|
|
});
|
|
|
|
quote! {
|
|
|
|
f.debug_struct(#name) ##for_fields .finish()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
VariantShape::Tuple(n) => {
|
|
|
|
let for_fields = tuple_field_iterator(*n).map(|x| {
|
|
|
|
quote! {
|
2023-05-12 04:06:57 -05:00
|
|
|
.field( & #x)
|
2023-05-03 05:44:47 -05:00
|
|
|
}
|
|
|
|
});
|
|
|
|
quote! {
|
|
|
|
f.debug_tuple(#name) ##for_fields .finish()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
VariantShape::Unit => quote! {
|
|
|
|
f.write_str(#name)
|
|
|
|
},
|
|
|
|
};
|
|
|
|
if matches!(&adt.shape, AdtShape::Enum { variants, .. } if variants.is_empty()) {
|
|
|
|
let star = tt::Punct {
|
|
|
|
char: '*',
|
|
|
|
spacing: ::tt::Spacing::Alone,
|
|
|
|
span: tt::TokenId::unspecified(),
|
|
|
|
};
|
|
|
|
return quote! {
|
|
|
|
fn fmt(&self, f: &mut #krate::fmt::Formatter) -> #krate::fmt::Result {
|
|
|
|
match #star self {}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
let arms = match &adt.shape {
|
|
|
|
AdtShape::Struct(fields) => {
|
|
|
|
let fat_arrow = fat_arrow();
|
|
|
|
let name = &adt.name;
|
|
|
|
let pat = fields.as_pattern(quote!(#name));
|
|
|
|
let expr = for_variant(name.to_string(), fields);
|
|
|
|
vec![quote! { #pat #fat_arrow #expr }]
|
|
|
|
}
|
|
|
|
AdtShape::Enum { variants, .. } => variants
|
|
|
|
.iter()
|
|
|
|
.map(|(name, v)| {
|
|
|
|
let fat_arrow = fat_arrow();
|
|
|
|
let adt_name = &adt.name;
|
|
|
|
let pat = v.as_pattern(quote!(#adt_name :: #name));
|
|
|
|
let expr = for_variant(name.to_string(), v);
|
|
|
|
quote! {
|
|
|
|
#pat #fat_arrow #expr ,
|
|
|
|
}
|
|
|
|
})
|
|
|
|
.collect(),
|
|
|
|
AdtShape::Union => {
|
|
|
|
// FIXME: Return expand error here
|
|
|
|
vec![]
|
|
|
|
}
|
|
|
|
};
|
|
|
|
quote! {
|
|
|
|
fn fmt(&self, f: &mut #krate::fmt::Formatter) -> #krate::fmt::Result {
|
|
|
|
match self {
|
|
|
|
##arms
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
2019-12-05 12:52:52 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
fn hash_expand(
|
2023-03-13 10:33:52 -05:00
|
|
|
db: &dyn ExpandDatabase,
|
2021-05-19 13:19:08 -05:00
|
|
|
id: MacroCallId,
|
2019-12-05 12:52:52 -06:00
|
|
|
tt: &tt::Subtree,
|
2021-08-20 07:28:36 -05:00
|
|
|
) -> ExpandResult<tt::Subtree> {
|
2023-05-03 05:44:47 -05:00
|
|
|
let krate = &find_builtin_crate(db, id);
|
|
|
|
expand_simple_derive(tt, quote! { #krate::hash::Hash }, |adt| {
|
|
|
|
if matches!(adt.shape, AdtShape::Union) {
|
|
|
|
// FIXME: Return expand error here
|
|
|
|
return quote! {};
|
|
|
|
}
|
|
|
|
if matches!(&adt.shape, AdtShape::Enum { variants, .. } if variants.is_empty()) {
|
|
|
|
let star = tt::Punct {
|
|
|
|
char: '*',
|
|
|
|
spacing: ::tt::Spacing::Alone,
|
|
|
|
span: tt::TokenId::unspecified(),
|
|
|
|
};
|
|
|
|
return quote! {
|
|
|
|
fn hash<H: #krate::hash::Hasher>(&self, state: &mut H) {
|
|
|
|
match #star self {}
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|
|
|
|
let arms = adt.shape.as_pattern(&adt.name).into_iter().zip(adt.shape.field_names()).map(
|
|
|
|
|(pat, names)| {
|
|
|
|
let expr = {
|
|
|
|
let it = names.iter().map(|x| quote! { #x . hash(state); });
|
|
|
|
quote! { {
|
|
|
|
##it
|
|
|
|
} }
|
|
|
|
};
|
|
|
|
let fat_arrow = fat_arrow();
|
|
|
|
quote! {
|
|
|
|
#pat #fat_arrow #expr ,
|
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
quote! {
|
|
|
|
fn hash<H: #krate::hash::Hasher>(&self, state: &mut H) {
|
|
|
|
#krate::mem::discriminant(self).hash(state);
|
|
|
|
match self {
|
|
|
|
##arms
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
2019-12-05 12:52:52 -06:00
|
|
|
}
|
|
|
|
|
2023-03-13 10:33:52 -05:00
|
|
|
fn eq_expand(
|
|
|
|
db: &dyn ExpandDatabase,
|
|
|
|
id: MacroCallId,
|
|
|
|
tt: &tt::Subtree,
|
|
|
|
) -> ExpandResult<tt::Subtree> {
|
2020-04-27 12:48:55 -05:00
|
|
|
let krate = find_builtin_crate(db, id);
|
2023-05-03 05:44:47 -05:00
|
|
|
expand_simple_derive(tt, quote! { #krate::cmp::Eq }, |_| quote! {})
|
2019-12-05 12:52:52 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
fn partial_eq_expand(
|
2023-03-13 10:33:52 -05:00
|
|
|
db: &dyn ExpandDatabase,
|
2021-05-19 13:19:08 -05:00
|
|
|
id: MacroCallId,
|
2019-12-05 12:52:52 -06:00
|
|
|
tt: &tt::Subtree,
|
2021-08-20 07:28:36 -05:00
|
|
|
) -> ExpandResult<tt::Subtree> {
|
2020-04-27 12:48:55 -05:00
|
|
|
let krate = find_builtin_crate(db, id);
|
2023-05-03 05:44:47 -05:00
|
|
|
expand_simple_derive(tt, quote! { #krate::cmp::PartialEq }, |adt| {
|
|
|
|
if matches!(adt.shape, AdtShape::Union) {
|
|
|
|
// FIXME: Return expand error here
|
|
|
|
return quote! {};
|
|
|
|
}
|
|
|
|
let name = &adt.name;
|
|
|
|
|
|
|
|
let (self_patterns, other_patterns) = self_and_other_patterns(adt, name);
|
|
|
|
let arms = izip!(self_patterns, other_patterns, adt.shape.field_names()).map(
|
|
|
|
|(pat1, pat2, names)| {
|
|
|
|
let fat_arrow = fat_arrow();
|
|
|
|
let body = match &*names {
|
|
|
|
[] => {
|
|
|
|
quote!(true)
|
|
|
|
}
|
|
|
|
[first, rest @ ..] => {
|
|
|
|
let rest = rest.iter().map(|x| {
|
|
|
|
let t1 = Ident::new(format!("{}_self", x.text), x.span);
|
|
|
|
let t2 = Ident::new(format!("{}_other", x.text), x.span);
|
|
|
|
let and_and = and_and();
|
|
|
|
quote!(#and_and #t1 .eq( #t2 ))
|
|
|
|
});
|
|
|
|
let first = {
|
|
|
|
let t1 = Ident::new(format!("{}_self", first.text), first.span);
|
|
|
|
let t2 = Ident::new(format!("{}_other", first.text), first.span);
|
|
|
|
quote!(#t1 .eq( #t2 ))
|
|
|
|
};
|
|
|
|
quote!(#first ##rest)
|
|
|
|
}
|
|
|
|
};
|
|
|
|
quote! { ( #pat1 , #pat2 ) #fat_arrow #body , }
|
|
|
|
},
|
|
|
|
);
|
|
|
|
|
|
|
|
let fat_arrow = fat_arrow();
|
|
|
|
quote! {
|
|
|
|
fn eq(&self, other: &Self) -> bool {
|
|
|
|
match (self, other) {
|
|
|
|
##arms
|
|
|
|
_unused #fat_arrow false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
fn self_and_other_patterns(
|
|
|
|
adt: &BasicAdtInfo,
|
|
|
|
name: &tt::Ident,
|
|
|
|
) -> (Vec<tt::Subtree>, Vec<tt::Subtree>) {
|
|
|
|
let self_patterns = adt.shape.as_pattern_map(name, |x| {
|
|
|
|
let t = Ident::new(format!("{}_self", x.text), x.span);
|
|
|
|
quote!(#t)
|
|
|
|
});
|
|
|
|
let other_patterns = adt.shape.as_pattern_map(name, |x| {
|
|
|
|
let t = Ident::new(format!("{}_other", x.text), x.span);
|
|
|
|
quote!(#t)
|
|
|
|
});
|
|
|
|
(self_patterns, other_patterns)
|
2019-12-05 12:52:52 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
fn ord_expand(
|
2023-03-13 10:33:52 -05:00
|
|
|
db: &dyn ExpandDatabase,
|
2021-05-19 13:19:08 -05:00
|
|
|
id: MacroCallId,
|
2019-12-05 12:52:52 -06:00
|
|
|
tt: &tt::Subtree,
|
2021-08-20 07:28:36 -05:00
|
|
|
) -> ExpandResult<tt::Subtree> {
|
2023-05-03 05:44:47 -05:00
|
|
|
let krate = &find_builtin_crate(db, id);
|
|
|
|
expand_simple_derive(tt, quote! { #krate::cmp::Ord }, |adt| {
|
|
|
|
fn compare(
|
|
|
|
krate: &tt::TokenTree,
|
|
|
|
left: tt::Subtree,
|
|
|
|
right: tt::Subtree,
|
|
|
|
rest: tt::Subtree,
|
|
|
|
) -> tt::Subtree {
|
|
|
|
let fat_arrow1 = fat_arrow();
|
|
|
|
let fat_arrow2 = fat_arrow();
|
|
|
|
quote! {
|
|
|
|
match #left.cmp(&#right) {
|
|
|
|
#krate::cmp::Ordering::Equal #fat_arrow1 {
|
|
|
|
#rest
|
|
|
|
}
|
|
|
|
c #fat_arrow2 return c,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if matches!(adt.shape, AdtShape::Union) {
|
|
|
|
// FIXME: Return expand error here
|
|
|
|
return quote!();
|
|
|
|
}
|
|
|
|
let left = quote!(#krate::intrinsics::discriminant_value(self));
|
|
|
|
let right = quote!(#krate::intrinsics::discriminant_value(other));
|
|
|
|
|
|
|
|
let (self_patterns, other_patterns) = self_and_other_patterns(adt, &adt.name);
|
|
|
|
let arms = izip!(self_patterns, other_patterns, adt.shape.field_names()).map(
|
|
|
|
|(pat1, pat2, fields)| {
|
|
|
|
let mut body = quote!(#krate::cmp::Ordering::Equal);
|
|
|
|
for f in fields.into_iter().rev() {
|
|
|
|
let t1 = Ident::new(format!("{}_self", f.text), f.span);
|
|
|
|
let t2 = Ident::new(format!("{}_other", f.text), f.span);
|
|
|
|
body = compare(krate, quote!(#t1), quote!(#t2), body);
|
|
|
|
}
|
|
|
|
let fat_arrow = fat_arrow();
|
|
|
|
quote! { ( #pat1 , #pat2 ) #fat_arrow #body , }
|
|
|
|
},
|
|
|
|
);
|
|
|
|
let fat_arrow = fat_arrow();
|
|
|
|
let body = compare(
|
|
|
|
krate,
|
|
|
|
left,
|
|
|
|
right,
|
|
|
|
quote! {
|
|
|
|
match (self, other) {
|
|
|
|
##arms
|
|
|
|
_unused #fat_arrow #krate::cmp::Ordering::Equal
|
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
quote! {
|
|
|
|
fn cmp(&self, other: &Self) -> #krate::cmp::Ordering {
|
|
|
|
#body
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
2019-12-05 12:52:52 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
fn partial_ord_expand(
|
2023-03-13 10:33:52 -05:00
|
|
|
db: &dyn ExpandDatabase,
|
2021-05-19 13:19:08 -05:00
|
|
|
id: MacroCallId,
|
2019-12-05 12:52:52 -06:00
|
|
|
tt: &tt::Subtree,
|
2021-08-20 07:28:36 -05:00
|
|
|
) -> ExpandResult<tt::Subtree> {
|
2023-05-03 05:44:47 -05:00
|
|
|
let krate = &find_builtin_crate(db, id);
|
|
|
|
expand_simple_derive(tt, quote! { #krate::cmp::PartialOrd }, |adt| {
|
|
|
|
fn compare(
|
|
|
|
krate: &tt::TokenTree,
|
|
|
|
left: tt::Subtree,
|
|
|
|
right: tt::Subtree,
|
|
|
|
rest: tt::Subtree,
|
|
|
|
) -> tt::Subtree {
|
|
|
|
let fat_arrow1 = fat_arrow();
|
|
|
|
let fat_arrow2 = fat_arrow();
|
|
|
|
quote! {
|
|
|
|
match #left.partial_cmp(&#right) {
|
|
|
|
#krate::option::Option::Some(#krate::cmp::Ordering::Equal) #fat_arrow1 {
|
|
|
|
#rest
|
|
|
|
}
|
|
|
|
c #fat_arrow2 return c,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if matches!(adt.shape, AdtShape::Union) {
|
|
|
|
// FIXME: Return expand error here
|
|
|
|
return quote!();
|
|
|
|
}
|
|
|
|
let left = quote!(#krate::intrinsics::discriminant_value(self));
|
|
|
|
let right = quote!(#krate::intrinsics::discriminant_value(other));
|
|
|
|
|
|
|
|
let (self_patterns, other_patterns) = self_and_other_patterns(adt, &adt.name);
|
|
|
|
let arms = izip!(self_patterns, other_patterns, adt.shape.field_names()).map(
|
|
|
|
|(pat1, pat2, fields)| {
|
|
|
|
let mut body = quote!(#krate::option::Option::Some(#krate::cmp::Ordering::Equal));
|
|
|
|
for f in fields.into_iter().rev() {
|
|
|
|
let t1 = Ident::new(format!("{}_self", f.text), f.span);
|
|
|
|
let t2 = Ident::new(format!("{}_other", f.text), f.span);
|
|
|
|
body = compare(krate, quote!(#t1), quote!(#t2), body);
|
|
|
|
}
|
|
|
|
let fat_arrow = fat_arrow();
|
|
|
|
quote! { ( #pat1 , #pat2 ) #fat_arrow #body , }
|
|
|
|
},
|
|
|
|
);
|
|
|
|
let fat_arrow = fat_arrow();
|
|
|
|
let body = compare(
|
|
|
|
krate,
|
|
|
|
left,
|
|
|
|
right,
|
|
|
|
quote! {
|
|
|
|
match (self, other) {
|
|
|
|
##arms
|
|
|
|
_unused #fat_arrow #krate::option::Option::Some(#krate::cmp::Ordering::Equal)
|
|
|
|
}
|
|
|
|
},
|
|
|
|
);
|
|
|
|
quote! {
|
|
|
|
fn partial_cmp(&self, other: &Self) -> #krate::option::Option::Option<#krate::cmp::Ordering> {
|
|
|
|
#body
|
|
|
|
}
|
|
|
|
}
|
|
|
|
})
|
2019-12-05 08:10:33 -06:00
|
|
|
}
|