Skip to content
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

chore: Refactor multitest generation for contract macro #286

Closed
Closed
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
101 changes: 101 additions & 0 deletions sylvia-derive/src/associated_types.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
use itertools::Itertools;
use proc_macro2::{Ident, TokenStream};
use proc_macro_error::emit_error;
use quote::quote;
use syn::{
parse_quote, ImplItem, ImplItemType, ItemImpl, ItemTrait, TraitItem, TraitItemType, Type,
WhereClause, WherePredicate,
};

use crate::crate_module;

const RESERVED_TYPES: [&str; 3] = ["Error", "QueryC", "ExecC"];

#[derive(Default)]
Expand Down Expand Up @@ -50,6 +54,16 @@ impl<'a> AssociatedTypes<'a> {
self.0.iter().map(|associated| &associated.ident).collect()
}

pub fn as_self_names(&self) -> Vec<Type> {
self.0
.iter()
.map(|associated| {
let name = &associated.ident;
parse_quote! { Self:: #name }
})
.collect()
}

pub fn as_types_declaration(&self) -> &Vec<&TraitItemType> {
&self.0
}
Expand Down Expand Up @@ -158,3 +172,90 @@ impl EmitAssociated for WhereClause {
.collect()
}
}

#[derive(Debug)]
pub struct TraitErrorType<'a> {
error: Option<&'a TraitItemType>,
}

impl<'a> TraitErrorType<'a> {
pub fn new(item: &'a ItemTrait) -> Self {
let error = item.items.iter().find_map(|item| match item {
TraitItem::Type(ty) => Some(ty),
_ => None,
});

if error.is_none() {
emit_error!(
item.ident.span(), "Missing `Error` type defined for trait.";
note = "Error is an error type returned by generated types dispatch function. Messages handling function have to return an error type convertible to this Error type.";
note = "A trait error type should be bound to implement `From<cosmwasm_std::StdError>`.";
);
}

Self { error }
}

pub fn as_item_type(&'a self) -> Option<TraitItemType> {
let anyhow_error_bounds = [
parse_quote! { Send },
parse_quote! { Sync },
parse_quote! { std::fmt::Display },
parse_quote! { std::fmt::Debug },
];

self.error.map(|error| {
let bounds = error
.bounds
.iter()
.chain(anyhow_error_bounds.iter())
.unique()
.cloned()
.collect();
TraitItemType {
bounds,
..error.clone()
}
})
}

pub fn as_self_type(&self) -> Type {
let sylvia = crate_module();

match self.error {
Some(error) => {
let error_name = &error.ident;
parse_quote! { Self:: #error_name }
}
None => parse_quote! { #sylvia ::cw_std::StdError },
}
}
}

#[derive(Debug)]
pub struct ImplErrorType<'a> {
error: Option<&'a ImplItemType>,
}

impl<'a> ImplErrorType<'a> {
pub fn new(item: &'a ItemImpl) -> Self {
let error = item.items.iter().find_map(|item| match item {
ImplItem::Type(ty) => Some(ty),
_ => None,
});

Self { error }
}

pub fn as_type(&self) -> Type {
let sylvia = crate_module();

match self.error {
Some(error) => {
let error_type = &error.ty;
parse_quote! { #error_type}
}
None => parse_quote! { #sylvia ::cw_std::StdError },
}
}
}
57 changes: 32 additions & 25 deletions sylvia-derive/src/input.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
use proc_macro2::TokenStream;
use proc_macro_error::emit_error;
use quote::quote;
use syn::{GenericParam, Ident, ItemImpl, ItemTrait, TraitItem};
use syn::{GenericParam, ItemImpl, ItemTrait};

use crate::associated_types::{AssociatedTypes, ImplAssociatedTypes};
use crate::associated_types::{AssociatedTypes, ImplAssociatedTypes, TraitErrorType};
use crate::interfaces::Interfaces;
use crate::message::{
ContractApi, ContractEnumMessage, EnumMessage, GlueMessage, InterfaceApi, MsgVariants,
StructMessage,
};
use crate::multitest::{MultitestHelpers, TraitMultitestHelpers};
use crate::multitest::{ImplMultitestHelpers, MultitestHelpers, TraitMultitestHelpers};
use crate::parser::{ContractArgs, ContractErrorAttr, Custom, MsgType, OverrideEntryPoints};
use crate::querier::{ContractQuerier, ImplQuerier, TraitQuerier};
use crate::remote::{ContractRemote, InterfaceRemote};
Expand All @@ -21,6 +21,7 @@ pub struct TraitInput<'a> {
item: &'a ItemTrait,
custom: Custom<'a>,
associated_types: AssociatedTypes<'a>,
error: TraitErrorType<'a>,
}

/// Preprocessed `contract` macro input for non-trait impl block
Expand All @@ -44,25 +45,15 @@ impl<'a> TraitInput<'a> {
);
}

if !item
.items
.iter()
.any(|item| matches!(item, TraitItem::Type(ty) if ty.ident == Ident::new("Error", ty.ident.span())))
{
emit_error!(
item.ident.span(), "Missing `Error` type defined for trait.";
note = "Error is an error type returned by generated types dispatch function. Messages handling function have to return an error type convertible to this Error type.";
note = "A trait error type should be bound to implement `From<cosmwasm_std::StdError>`.";
);
}

let error = TraitErrorType::new(item);
let custom = Custom::new(&item.attrs);
let associated_types = AssociatedTypes::new(item);

Self {
item,
custom,
associated_types,
error,
}
}

Expand All @@ -71,6 +62,7 @@ impl<'a> TraitInput<'a> {
associated_types,
item,
custom,
..
} = self;
let messages = self.emit_messages();
let multitest_helpers = self.emit_helpers();
Expand All @@ -88,6 +80,7 @@ impl<'a> TraitInput<'a> {
quote! {
pub mod sv {
use super::*;

#messages

#multitest_helpers
Expand All @@ -104,7 +97,12 @@ impl<'a> TraitInput<'a> {

fn emit_helpers(&self) -> TokenStream {
if cfg!(feature = "mt") {
let multitest_helpers = TraitMultitestHelpers::new(self.item, &self.associated_types);
let multitest_helpers = TraitMultitestHelpers::new(
self.item,
&self.associated_types,
&self.custom,
&self.error,
);
multitest_helpers.emit()
} else {
quote! {}
Expand Down Expand Up @@ -304,14 +302,23 @@ impl<'a> ImplInput<'a> {
let contract_module = self.attributes.module.as_ref();
let generic_params = &self.generics;

MultitestHelpers::new(
item,
generic_params,
custom,
override_entry_points,
interfaces,
&contract_module,
)
.emit()
match is_trait(self.item) {
true => ImplMultitestHelpers::new(
item,
interfaces,
custom,
generic_params,
&contract_module,
)
.emit(),
false => MultitestHelpers::new(
item,
generic_params,
custom,
override_entry_points,
interfaces,
)
.emit(),
}
}
}
11 changes: 7 additions & 4 deletions sylvia-derive/src/message.rs
Original file line number Diff line number Diff line change
Expand Up @@ -717,14 +717,17 @@ impl<'a> MsgVariant<'a> {
}
}

pub fn emit_proxy_methods_declarations(
pub fn emit_proxy_methods_declarations<Generic>(
&self,
msg_ty: &MsgType,
custom_msg: &Type,
error_type: &Type,
interface_enum: &TokenStream,
generics: &[&Ident],
) -> TokenStream {
generics: &[&Generic],
) -> TokenStream
where
Generic: GetPath + ToTokens,
{
let sylvia = crate_module();
let Self {
name,
Expand Down Expand Up @@ -924,7 +927,7 @@ where
custom_msg: &Type,
error_type: &Type,
interface_enum: &TokenStream,
generics: &[&Ident],
generics: &[&Generic],
) -> Vec<TokenStream> {
self.variants
.iter()
Expand Down
Loading
Loading