Skip to content
Merged
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
67 changes: 67 additions & 0 deletions crates/af-move-type-derive/src/move_struct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,9 @@ fn impl_type_tag(type_tag_params: TypeTagParameters, thecrate: Path) -> TokenStr
struct_tag_const_vals,
struct_tag_consts_checks,
mut type_param_idents,
address_const,
module_const,
name_const,
} = type_tag_params;

let attr_declarations: Vec<_> = attr_idents
Expand All @@ -114,6 +117,17 @@ fn impl_type_tag(type_tag_params: TypeTagParameters, thecrate: Path) -> TokenStr
.map(|(ident, val)| quote!(#ident: #val))
.collect();

// Pascal-cased generic type param idents (e.g. `T`), in declaration order.
// Needed BEFORE we reverse `type_param_idents` below for `unpack_type_params`.
let type_param_pascals: Vec<Ident> = generics
.params
.iter()
.filter_map(|p| match p {
GenericParam::Type(t) => Some(t.ident.clone()),
_ => None,
})
.collect();

type_param_idents.reverse();
let unpack_type_params = quote!(
// Unwrap here since we already checked the vector length
Expand Down Expand Up @@ -143,6 +157,48 @@ fn impl_type_tag(type_tag_params: TypeTagParameters, thecrate: Path) -> TokenStr
};
let serde_with_crate = quote!(#thecrate::external::serde_with).to_string();

// Emit a non-allocating `matches` override when address, module, and name
// are all compile-time constants. Otherwise fall back to the default body
// (which delegates to `TryFrom`).
let move_type_tag_impl = match (&address_const, &module_const, &name_const) {
(Some(addr), Some(module), Some(name)) => {
let n_type_params = type_param_pascals.len();
let type_param_checks = type_param_pascals.iter().enumerate().map(|(i, t)| {
quote!(
<<#t as #thecrate::MoveType>::TypeTag as #thecrate::MoveTypeTag>::matches(
&type_params[#i]
)
)
});
quote! {
impl #impl_generics #thecrate::MoveTypeTag for #ident #type_generics
#where_clause
{
fn matches(tag: &#type_tag_type) -> bool {
const EXPECTED_ADDRESS: #thecrate::external::Address =
<#thecrate::external::Address>::from_static(#addr);
let #type_tag_type::Struct(stag) = tag else {
return false;
};
let type_params = stag.type_params();
if type_params.len() != #n_type_params {
return false;
}
stag.address() == &EXPECTED_ADDRESS
&& stag.module().as_str() == #module
&& stag.name().as_str() == #name
#(&& #type_param_checks)*
}
}
}
}
_ => quote! {
impl #impl_generics #thecrate::MoveTypeTag for #ident #type_generics
#where_clause
{}
},
};

quote! {
#[derive(
Clone,
Expand Down Expand Up @@ -239,6 +295,8 @@ fn impl_type_tag(type_tag_params: TypeTagParameters, thecrate: Path) -> TokenStr
#result_type::Ok(stag.try_into()?)
}
}

#move_type_tag_impl
}
}

Expand Down Expand Up @@ -310,6 +368,9 @@ struct TypeTagParameters {
struct_tag_const_vals: Vec<TokenStream>,
struct_tag_consts_checks: TokenStream,
type_param_idents: Vec<Ident>,
address_const: Option<String>,
module_const: Option<String>,
name_const: Option<String>,
}

fn type_tag_parameters(
Expand All @@ -330,6 +391,9 @@ fn type_tag_parameters(
struct_tag_const_vals: vec![],
struct_tag_consts_checks: quote!(),
type_param_idents: vec![],
address_const: None,
module_const: None,
name_const: None,
};

let address_check = if let Some(address) = address {
Expand All @@ -342,6 +406,7 @@ fn type_tag_parameters(
}
);
params.struct_tag_const_vals.push(value);
params.address_const = Some(address);
check
} else {
params.attr_idents.push(quote!(address));
Expand All @@ -360,6 +425,7 @@ fn type_tag_parameters(
}
);
params.struct_tag_const_vals.push(value);
params.module_const = Some(module);
check
} else {
params.attr_idents.push(quote!(module));
Expand Down Expand Up @@ -388,6 +454,7 @@ fn type_tag_parameters(
}
);
params.struct_tag_const_vals.push(value);
params.name_const = Some(name);
check
};

Expand Down
4 changes: 3 additions & 1 deletion crates/af-move-type/src/any.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use std::str::FromStr;
use af_sui_types::TypeTag;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::{MoveType, ParseTypeTagError, TypeTagError};
use crate::{MoveType, MoveTypeTag, ParseTypeTagError, TypeTagError};

/// Generic type that accepts **any** Move type argument in its slot,
/// including phantom-paramed generics such as `VENDOR<X>` as well as
Expand Down Expand Up @@ -69,6 +69,8 @@ impl TryFrom<TypeTag> for AnyTTypeTag {
}
}

impl MoveTypeTag for AnyTTypeTag {}

impl FromStr for AnyTTypeTag {
type Err = ParseTypeTagError;

Expand Down
23 changes: 7 additions & 16 deletions crates/af-move-type/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -103,22 +103,13 @@ pub trait MoveTypeTag:
+ Ord
+ Serialize
{
}

impl<T> MoveTypeTag for T where
T: Into<TypeTag>
+ TryFrom<TypeTag, Error = TypeTagError>
+ FromStr
+ Clone
+ Debug
+ PartialEq
+ Eq
+ Hash
+ for<'de> Deserialize<'de>
+ PartialOrd
+ Ord
+ Serialize
{
/// Returns whether `tag` is the runtime representation of `Self`.
///
/// Equivalent to `Self::try_from(tag.clone()).is_ok()` but implementors are
/// expected to override this to avoid materializing `Self` or cloning `tag`.
fn matches(tag: &TypeTag) -> bool {
Self::try_from(tag.clone()).is_ok()
}
}

// =============================================================================
Expand Down
8 changes: 7 additions & 1 deletion crates/af-move-type/src/primitives.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use std::str::FromStr;
use af_sui_types::{Address, TypeTag, U256};
use serde::{Deserialize, Serialize};

use crate::{MoveType, ParseTypeTagError, StaticTypeTag, TypeTagError};
use crate::{MoveType, MoveTypeTag, ParseTypeTagError, StaticTypeTag, TypeTagError};

macro_rules! impl_primitive_type_tags {
($($typ:ty: ($type_:ident, $variant:ident)),*) => {
Expand Down Expand Up @@ -41,6 +41,12 @@ macro_rules! impl_primitive_type_tags {
}
}

impl MoveTypeTag for $type_ {
fn matches(tag: &TypeTag) -> bool {
matches!(tag, TypeTag::$variant)
}
}

impl FromStr for $type_ {
type Err = ParseTypeTagError;

Expand Down
20 changes: 17 additions & 3 deletions crates/af-move-type/src/string.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,12 @@ use std::str::FromStr;
use af_sui_types::{Address, IdentStr, Identifier, StructTag, TypeTag};
use serde::{Deserialize, Serialize};

use af_sui_types::MOVE_STDLIB_ADDRESS;

use crate::{
MoveStruct, MoveType, ParseStructTagError, StaticAddress, StaticModule, StaticName,
StaticStructTag as _, StaticTypeParams, StaticTypeTag, StructTagError, TypeParamsError,
TypeTagError,
MoveStruct, MoveType, MoveTypeTag, ParseStructTagError, StaticAddress, StaticModule,
StaticName, StaticStructTag as _, StaticTypeParams, StaticTypeTag, StructTagError,
TypeParamsError, TypeTagError,
};

#[derive(Clone, Debug, PartialEq, Eq, Hash, Deserialize, PartialOrd, Ord, Serialize)]
Expand Down Expand Up @@ -72,6 +74,18 @@ impl TryFrom<StructTag> for StringTypeTag {
}
}

impl MoveTypeTag for StringTypeTag {
fn matches(tag: &TypeTag) -> bool {
let TypeTag::Struct(stag) = tag else {
return false;
};
stag.address() == &MOVE_STDLIB_ADDRESS
&& stag.module().as_str() == "string"
&& stag.name().as_str() == "String"
&& stag.type_params().is_empty()
}
}

impl FromStr for StringTypeTag {
type Err = ParseStructTagError;

Expand Down
11 changes: 10 additions & 1 deletion crates/af-move-type/src/vector.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ use derive_more::{Deref, DerefMut, From, Into};
use derive_where::derive_where;
use serde::{Deserialize, Serialize};

use crate::{MoveType, ParseTypeTagError, StaticTypeTag, TypeTagError};
use crate::{MoveType, MoveTypeTag, ParseTypeTagError, StaticTypeTag, TypeTagError};

#[derive(
Clone, Debug, Deref, DerefMut, Deserialize, From, Into, Serialize, PartialEq, Eq, Hash,
Expand Down Expand Up @@ -72,6 +72,15 @@ impl<T: MoveType> TryFrom<TypeTag> for VecTypeTag<T> {
}
}

impl<T: MoveType> MoveTypeTag for VecTypeTag<T> {
fn matches(tag: &TypeTag) -> bool {
let TypeTag::Vector(inner) = tag else {
return false;
};
T::TypeTag::matches(inner)
}
}

impl<T: MoveType> std::str::FromStr for VecTypeTag<T> {
type Err = ParseTypeTagError;

Expand Down
Loading