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

[proc macros]: support generic type params #436

Merged
merged 34 commits into from
Aug 27, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
Show all changes
34 commits
Select commit Hold shift + click to select a range
faf78f1
PoC support generic type params
niklasad1 Aug 20, 2021
351acaf
more annoying example
niklasad1 Aug 20, 2021
66640e7
add trait bounds for generic params in proc macros
niklasad1 Aug 20, 2021
1f91aac
add compile-time test for complicated trait
niklasad1 Aug 20, 2021
230613e
smarter trait bounds in proc macros
niklasad1 Aug 23, 2021
4ed5b58
add non-working example for now
niklasad1 Aug 24, 2021
f442612
revert nits
niklasad1 Aug 24, 2021
834990e
Update examples/proc_macro.rs
niklasad1 Aug 25, 2021
fbb6f00
Update proc-macros/src/helpers.rs
niklasad1 Aug 25, 2021
6e5bcf1
add messy code but works
niklasad1 Aug 25, 2021
ab0b2ec
cleanup
niklasad1 Aug 25, 2021
63c48bd
add some simple compile check in tests
niklasad1 Aug 25, 2021
c7ce163
Merge branch 'na-proc-macros-generics' of github.com:paritytech/jsonr…
niklasad1 Aug 25, 2021
c843a99
Merge remote-tracking branch 'origin/master' into na-proc-macros-gene…
niklasad1 Aug 25, 2021
f04aeaf
fix doc link
niklasad1 Aug 25, 2021
52f61b2
fix doc link last time
niklasad1 Aug 25, 2021
64b33fb
address grumbles
niklasad1 Aug 26, 2021
c9b00c8
docs
niklasad1 Aug 26, 2021
8bff2e9
Update proc-macros/src/helpers.rs
niklasad1 Aug 26, 2021
fbd9683
Update proc-macros/src/helpers.rs
niklasad1 Aug 26, 2021
9f0b300
Update proc-macros/src/helpers.rs
niklasad1 Aug 26, 2021
3065c04
Update proc-macros/src/helpers.rs
niklasad1 Aug 27, 2021
6971610
Update proc-macros/src/visitor.rs
niklasad1 Aug 27, 2021
6f3fed9
fix nit: | -> ||
niklasad1 Aug 27, 2021
6abda51
Update proc-macros/src/helpers.rs
niklasad1 Aug 27, 2021
d86752a
Update proc-macros/src/helpers.rs
niklasad1 Aug 27, 2021
4c83ecc
Update proc-macros/src/helpers.rs
niklasad1 Aug 27, 2021
6ad7bc2
add issues to introduced TODOs
niklasad1 Aug 27, 2021
f8facb2
generics support where clause on trait
niklasad1 Aug 27, 2021
e197af5
Update proc-macros/src/helpers.rs
niklasad1 Aug 27, 2021
27c3a15
Update proc-macros/src/helpers.rs
niklasad1 Aug 27, 2021
ebd7147
address grumbles
niklasad1 Aug 27, 2021
3626e15
Merge branch 'na-proc-macros-generics' of github.com:paritytech/jsonr…
niklasad1 Aug 27, 2021
ba52568
add more docs
niklasad1 Aug 27, 2021
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
31 changes: 12 additions & 19 deletions examples/proc_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,32 +28,30 @@ use jsonrpsee::{
proc_macros::rpc,
types::{async_trait, error::Error},
ws_client::WsClientBuilder,
ws_server::{RpcModule, SubscriptionSink, WsServerBuilder},
ws_server::{SubscriptionSink, WsServerBuilder},
};
use serde::de::DeserializeOwned;
use serde::ser::Serialize;
use std::net::SocketAddr;

#[rpc(server, client, namespace = "state")]
pub trait Rpc {
pub trait Rpc<
Hash: DeserializeOwned + Serialize + Send + Sync + 'static,
niklasad1 marked this conversation as resolved.
Show resolved Hide resolved
Prefix: DeserializeOwned + Serialize + Send + Sync + 'static,
>
{
/// Async method call example.
#[method(name = "getPairs")]
async fn storage_pairs(&self, prefix: usize, hash: Option<u128>) -> Result<Vec<usize>, Error>;

/// Subscription that take `Option<Vec<u8>>` as input and produces output `Vec<usize>`.
#[subscription(name = "subscribeStorage", unsub = "unsubscribeStorage", item = Vec<usize>)]
fn subscribe_storage(&self, keys: Option<Vec<u8>>);
async fn storage_pairs(&self, prefix: Prefix, hash: Hash) -> Result<Vec<usize>, Error>;
}

pub struct RpcServerImpl;

#[async_trait]
impl RpcServer for RpcServerImpl {
async fn storage_pairs(&self, _prefix: usize, _hash: Option<u128>) -> Result<Vec<usize>, Error> {
impl RpcServer<Vec<u8>, usize> for RpcServerImpl {
async fn storage_pairs(&self, _prefix: usize, _hash: Vec<u8>) -> Result<Vec<usize>, Error> {
Ok(vec![1, 2, 3, 4])
}

fn subscribe_storage(&self, mut sink: SubscriptionSink, keys: Option<Vec<u8>>) {
sink.send(&keys.unwrap_or_default()).unwrap();
}
}

#[tokio::main]
Expand All @@ -64,18 +62,13 @@ async fn main() -> anyhow::Result<()> {
let url = format!("ws://{}", server_addr);

let client = WsClientBuilder::default().build(&url).await?;
assert_eq!(client.storage_pairs(10, None).await.unwrap(), vec![1, 2, 3, 4]);

let mut sub = client.subscribe_storage(None).await.unwrap();
assert_eq!(Some(vec![]), sub.next().await.unwrap());
assert_eq!(client.storage_pairs(10, vec![1, 2, 3, 4]).await.unwrap(), vec![1, 2, 3, 4]);

Ok(())
}

async fn run_server() -> anyhow::Result<SocketAddr> {
let server = WsServerBuilder::default().build("127.0.0.1:0").await?;
let mut module = RpcModule::new(());
module.register_method("state_getPairs", |_, _| Ok(vec![1, 2, 3]))?;

let addr = server.local_addr()?;
tokio::spawn(async move { server.start(RpcServerImpl.into_rpc()).await });
Expand Down
12 changes: 10 additions & 2 deletions proc-macros/src/new/render_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ impl RpcDescription {
let jsonrpsee = self.jsonrpsee_client_path.as_ref().unwrap();

let trait_name = quote::format_ident!("{}Client", &self.trait_def.ident);
let generics = self.trait_def.generics.clone();

let mut type_idents = Vec::new();
for param in generics.type_params() {
type_idents.push(param);
}

let (_, type_generics, where_clause) = generics.split_for_impl();

let super_trait = if self.subscriptions.is_empty() {
quote! { #jsonrpsee::types::traits::Client }
Expand All @@ -26,12 +34,12 @@ impl RpcDescription {
let trait_impl = quote! {
#[#async_trait]
#[doc = #doc_comment]
pub trait #trait_name: #super_trait {
pub trait #trait_name #generics: #super_trait {
#(#method_impls)*
#(#sub_impls)*
}

impl<T> #trait_name for T where T: #super_trait {}
impl<T #(,#type_idents)*> #trait_name #type_generics for T where T: #super_trait {}
};

Ok(trait_impl)
Expand Down
9 changes: 5 additions & 4 deletions proc-macros/src/new/render_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::collections::HashSet;
impl RpcDescription {
pub(super) fn render_server(&self) -> Result<TokenStream2, syn::Error> {
let trait_name = quote::format_ident!("{}Server", &self.trait_def.ident);
let generics = self.trait_def.generics.clone();

let method_impls = self.render_methods()?;
let into_rpc_impl = self.render_into_rpc()?;
Expand All @@ -19,7 +20,7 @@ impl RpcDescription {
let trait_impl = quote! {
#[#async_trait]
#[doc = #doc_comment]
pub trait #trait_name: Sized + Send + Sync + 'static {
pub trait #trait_name #generics: Sized + Send + Sync + 'static {
#method_impls
#into_rpc_impl
}
Expand Down Expand Up @@ -176,7 +177,6 @@ impl RpcDescription {
quote! {
let mut seq = params.sequence();
#(#decode_fields);*
(#params_fields)
}
};

Expand Down Expand Up @@ -220,11 +220,12 @@ impl RpcDescription {

// Parsing of `serde_json::Value`.
let parsing = quote! {
let (#params_fields) = if params.is_object() {
/*let (#params_fields) = if params.is_object() {
#decode_map
niklasad1 marked this conversation as resolved.
Show resolved Hide resolved
} else {
#decode_array
};
};*/
#decode_array;
};

(parsing, params_fields)
Expand Down