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

Add proc macro package for automatic IndexList<T> implementation #737

Merged
merged 8 commits into from
Jul 17, 2022
Merged
Show file tree
Hide file tree
Changes from 5 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
35 changes: 23 additions & 12 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

21 changes: 21 additions & 0 deletions packages/storage-macro/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
[package]
name = "cw-storage-macro"
version = "0.13.4"
authors = ["yoisha <48324733+y-pakorn@users.noreply.github.com>"]
edition = "2018"
description = "Macro helper for storage package"
y-pakorn marked this conversation as resolved.
Show resolved Hide resolved
license = "Apache-2.0"
repository = "https://github.com/CosmWasm/cw-plus"
homepage = "https://cosmwasm.com"
documentation = "https://docs.cosmwasm.com"

[lib]
proc-macro = true

[dependencies]
syn = { version = "1.0.96", features = ["full"] }

[dev-dependencies]
cw-storage-plus = { version = "0.13.4", path = "../storage-plus" }
cosmwasm-std = { version = "1.0.0", default-features = false }
serde = { version = "1.0.103", default-features = false, features = ["derive"] }
14 changes: 14 additions & 0 deletions packages/storage-macro/NOTICE
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
CW-Storage-Macro: Macro helper for storage package
Copyright (C) 2020 Confio OÜ
y-pakorn marked this conversation as resolved.
Show resolved Hide resolved

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
22 changes: 22 additions & 0 deletions packages/storage-macro/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# CW-Storage-Plus: Macro helper for storage package
y-pakorn marked this conversation as resolved.
Show resolved Hide resolved

Procedural macros helper for interacting with cw-storage-plus and cosmwasm-storage.

## Current features

Auto generate IndexList impl for your indexes struct.
y-pakorn marked this conversation as resolved.
Show resolved Hide resolved

```rust
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
struct TestStruct {
id: u64,
id2: u32,
addr: Addr,
}

#[index_list(TestStruct)] // <- Add this line right here,.
y-pakorn marked this conversation as resolved.
Show resolved Hide resolved
struct TestIndexes<'a> {
id: MultiIndex<'a, u32, TestStruct, u64>,
addr: UniqueIndex<'a, Addr, TestStruct>,
}
```
37 changes: 37 additions & 0 deletions packages/storage-macro/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use proc_macro::TokenStream;
use syn::{
Ident,
__private::{quote::quote, Span},
parse_macro_input, ItemStruct,
};

#[proc_macro_attribute]
pub fn index_list(attr: TokenStream, item: TokenStream) -> TokenStream {
let input = parse_macro_input!(item as ItemStruct);

let ty = Ident::new(&attr.to_string(), Span::call_site());
let struct_ty = input.ident.clone();

let names = input
.fields
.clone()
.into_iter()
.map(|e| {
let name = e.ident.unwrap();
quote! { &self.#name }
})
.collect::<Vec<_>>();

let expanded = quote! {
#input

impl cw_storage_plus::IndexList<#ty> for #struct_ty<'_> {
fn get_indexes(&'_ self) -> Box<dyn Iterator<Item = &'_ dyn cw_storage_plus::Index<#ty>> + '_> {
let v: Vec<&dyn cw_storage_plus::Index<#ty>> = vec![#(#names),*];
Box::new(v.into_iter())
}
}
};

TokenStream::from(expanded)
}
73 changes: 73 additions & 0 deletions packages/storage-macro/tests/index_list.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
use cosmwasm_std::{testing::MockStorage, Addr};
use cw_storage_macro::index_list;
use cw_storage_plus::{IndexedMap, MultiIndex, UniqueIndex};
use serde::{Deserialize, Serialize};

#[test]
fn compile() {
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
struct TestStruct {
id: u64,
id2: u32,
addr: Addr,
}

#[index_list(TestStruct)]
struct TestIndexes<'a> {
id: MultiIndex<'a, u32, TestStruct, u64>,
addr: UniqueIndex<'a, Addr, TestStruct>,
}

let _: IndexedMap<u64, TestStruct, TestIndexes> = IndexedMap::new(
"t",
TestIndexes {
id: MultiIndex::new(|t| t.id2, "t", "t_2"),
y-pakorn marked this conversation as resolved.
Show resolved Hide resolved
addr: UniqueIndex::new(|t| t.addr.clone(), "t_addr"),
},
);
}

#[test]
fn works() {
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
struct TestStruct {
id: u64,
id2: u32,
addr: Addr,
}

#[index_list(TestStruct)]
struct TestIndexes<'a> {
id: MultiIndex<'a, u32, TestStruct, u64>,
addr: UniqueIndex<'a, Addr, TestStruct>,
}

let mut storage = MockStorage::new();
let idm: IndexedMap<u64, TestStruct, TestIndexes> = IndexedMap::new(
"t",
TestIndexes {
id: MultiIndex::new(|t| t.id2, "t", "t_2"),
addr: UniqueIndex::new(|t| t.addr.clone(), "t_addr"),
},
);

idm.save(
&mut storage,
0,
&TestStruct {
id: 0,
id2: 100,
addr: Addr::unchecked("1"),
},
)
.unwrap();

assert_eq!(
idm.load(&storage, 0).unwrap(),
TestStruct {
id: 0,
id2: 100,
addr: Addr::unchecked("1"),
}
);
}
2 changes: 2 additions & 0 deletions packages/storage-plus/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ homepage = "https://cosmwasm.com"
[features]
default = ["iterator"]
iterator = ["cosmwasm-std/iterator"]
macro = ["cw-storage-macro"]

[lib]
# See https://bheisler.github.io/criterion.rs/book/faq.html#cargo-bench-gives-unrecognized-option-errors-for-valid-command-line-options
Expand All @@ -20,6 +21,7 @@ bench = false
cosmwasm-std = { version = "1.0.0", default-features = false }
schemars = "0.8.1"
serde = { version = "1.0.103", default-features = false, features = ["derive"] }
cw-storage-macro = { version = "0.13.4", optional = true, path = "../storage-macro" }
maurolacy marked this conversation as resolved.
Show resolved Hide resolved

[dev-dependencies]
criterion = { version = "0.3", features = [ "html_reports" ] }
Expand Down
7 changes: 7 additions & 0 deletions packages/storage-plus/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,10 @@ pub use path::Path;
pub use prefix::{range_with_prefix, Prefix};
#[cfg(feature = "iterator")]
pub use snapshot::{SnapshotItem, SnapshotMap, Strategy};

#[cfg(all(feature = "iterator", feature = "macro"))]
#[macro_use]
extern crate cw_storage_macro;
#[cfg(all(feature = "iterator", feature = "macro"))]
#[doc(hidden)]
pub use cw_storage_macro::*;