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 StorageKeys derive macro #926

Merged
merged 22 commits into from
Jan 10, 2023
Merged
Show file tree
Hide file tree
Changes from 14 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
1 change: 1 addition & 0 deletions Cargo.lock

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

3 changes: 2 additions & 1 deletion macros/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,5 +10,6 @@ version = "0.12.0"
proc-macro = true

[dependencies]
proc-macro2 = "1.0"
quote = "1.0"
syn = "1.0"
syn = {version="1.0", features = ["full", "extra-traits"]}
232 changes: 230 additions & 2 deletions macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
#![deny(rustdoc::private_intra_doc_links)]

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, ItemFn};
use proc_macro2::{Span as Span2, TokenStream as TokenStream2};
use quote::{quote, ToTokens};
use syn::punctuated::Punctuated;
use syn::{parse_macro_input, ItemFn, ItemStruct};
sug0 marked this conversation as resolved.
Show resolved Hide resolved

/// Generate WASM binding for a transaction main entrypoint function.
///
Expand Down Expand Up @@ -149,3 +151,229 @@ pub fn validity_predicate(
};
TokenStream::from(gen)
}

#[proc_macro_derive(StorageKeys)]
pub fn derive_storage_keys(struct_def: TokenStream) -> TokenStream {
derive_storage_keys_inner(struct_def.into()).into()
}

#[inline]
// TODO: use this crate for errors: https://crates.io/crates/proc-macro-error
fn derive_storage_keys_inner(struct_def: TokenStream2) -> TokenStream2 {
let struct_def: ItemStruct = syn::parse2(struct_def)
.expect("Expected a struct in the StorageKeys derive");

// type check the struct - all fields must be of type `&'static str`
let fields = match &struct_def.fields {
syn::Fields::Named(fields) => &fields.named,
_ => panic!(
"Only named struct fields are accepted in StorageKeys derives"
),
};

let mut idents = vec![];

for field in fields {
let field_type = field.ty.to_token_stream().to_string();
if field_type != "& 'static str" {
panic!(
"Expected `&'static str` field type in StorageKeys derive, \
but got `{field_type}` instead"
);
}
idents.push(field.ident.clone().expect("Expected a named field"));
}

idents.sort();

let ident_list = create_punctuated(&idents, |ident| ident.clone());
let values_list = create_punctuated(&idents, |ident| {
let storage_key = ident.to_token_stream().to_string();
syn::FieldValue {
attrs: vec![],
member: syn::Member::Named(ident.clone()),
colon_token: Some(syn::token::Colon {
spans: [Span2::call_site()],
}),
expr: syn::Expr::Lit(syn::ExprLit {
attrs: vec![],
lit: syn::Lit::Str(syn::LitStr::new(
storage_key.as_str(),
Span2::call_site(),
)),
}),
}
});

let struct_def_ident = &struct_def.ident;

quote! {
impl #struct_def_ident {
#[allow(dead_code)]
const ALL: &[&'static str] = {
let #struct_def_ident {
#ident_list
} = Self::VALUES;

&[ #ident_list ]
};

const VALUES: #struct_def_ident = Self {
#values_list
};
}
}
}

#[inline]
fn create_punctuated<F, M>(
idents: &[syn::Ident],
mut map: F,
) -> Punctuated<M, syn::token::Comma>
where
F: FnMut(&syn::Ident) -> M,
{
idents.iter().fold(Punctuated::new(), |mut accum, ident| {
accum.push(map(ident));
accum
})
}

#[cfg(test)]
mod test_proc_macros {
use syn::ItemImpl;

use super::*;

/// Test if we reject enums in `StorageKeys` derives.
#[test]
#[should_panic(expected = "Expected a struct in the StorageKeys derive")]
fn test_storage_keys_panics_on_enum() {
derive_storage_keys_inner(quote! {
enum What {
The,
Funk,
}
});
}

/// Test if we reject unit structs in `StorageKeys` derives.
#[test]
#[should_panic(expected = "Only named struct fields are accepted in \
StorageKeys derives")]
fn test_storage_keys_panics_on_unit_structs() {
derive_storage_keys_inner(quote! {
struct WhatTheFunk;
});
}

/// Test if we reject tuple structs in `StorageKeys` derives.
#[test]
#[should_panic(expected = "Only named struct fields are accepted in \
StorageKeys derives")]
fn test_storage_keys_panics_on_tuple_structs() {
derive_storage_keys_inner(quote! {
struct WhatTheFunk(&'static str);
});
}

/// Test if the `ALL` slice generated in `StorageKeys` macro
/// derives is sorted in ascending order.
#[test]
fn test_storage_keys_derive_sorted_slice() {
let test_struct = quote! {
struct Keys {
word: &'static str,
is: &'static str,
bird: &'static str,
the: &'static str,
tzemanovic marked this conversation as resolved.
Show resolved Hide resolved
}
};
let test_impl: ItemImpl =
syn::parse2(derive_storage_keys_inner(test_struct))
.expect("Test failed");

let expected_impl = quote! {
impl Keys {
#[allow(dead_code)]
const ALL: &[&'static str] = {
let Keys { bird, is, the, word } = Self::VALUES;
&[bird, is, the, word]
};
const VALUES: Keys = Self {
bird: "bird",
is: "is",
the: "the",
word: "word"
};
}
};
let expected_impl: ItemImpl =
syn::parse2(expected_impl).expect("Test failed");

assert_eq!(test_impl, expected_impl);
}

/// Test if we reject structs with non static string fields in
/// `StorageKeys` macro derives.
#[test]
#[should_panic(
expected = "Expected `&'static str` field type in StorageKeys derive"
)]
fn test_typecheck_storage_keys_derive() {
derive_storage_keys_inner(quote! {
struct Keys {
x: &'static str,
y: i32,
z: u64,
}
});
}

/// Test if we reject structs with non static lifetimes.
#[test]
#[should_panic(
expected = "Expected `&'static str` field type in StorageKeys derive"
)]
fn test_storage_keys_derive_with_non_static_str() {
derive_storage_keys_inner(quote! {
struct Keys<'a> {
x: &'static str,
y: &'a str,
}
});
}

/// Test that the create storage keys produces
/// the expected code.
#[test]
fn test_derive_storage_keys() {
let test_struct = quote! {
struct Keys {
param1: &'static str,
param2: &'static str,
}
};
let test_impl: ItemImpl =
syn::parse2(derive_storage_keys_inner(test_struct))
.expect("Test failed");

let expected_impl = quote! {
impl Keys {
#[allow(dead_code)]
const ALL: &[&'static str] = {
let Keys { param1, param2 } = Self::VALUES;
&[param1, param2]
};
const VALUES: Keys = Self {
param1: "param1",
param2: "param2"
};
}
};
let expected_impl: ItemImpl =
syn::parse2(expected_impl).expect("Test failed");

assert_eq!(test_impl, expected_impl);
}
}
1 change: 1 addition & 0 deletions wasm/Cargo.lock

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