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

Array syntax aliases #557

Merged
merged 2 commits into from
Nov 11, 2021
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
16 changes: 16 additions & 0 deletions proc-macros/src/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ pub struct Resource {
pub value: syn::LitInt,
}

pub struct Aliases {
pub list: Punctuated<syn::LitStr, Token![,]>,
}

impl Parse for Argument {
fn parse(input: ParseStream) -> syn::Result<Self> {
let label = input.parse()?;
Expand Down Expand Up @@ -87,6 +91,18 @@ impl Parse for Resource {
}
}

impl Parse for Aliases {
fn parse(input: ParseStream) -> syn::Result<Self> {
let content;

syn::bracketed!(content in input);

let list = content.parse_terminated(Parse::parse)?;

Ok(Aliases { list })
}
}

fn parenthesized<T: Parse>(input: ParseStream) -> syn::Result<Punctuated<T, Token![,]>> {
let content;

Expand Down
9 changes: 3 additions & 6 deletions proc-macros/src/render_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,8 +205,7 @@ impl RpcDescription {
.aliases
.iter()
.map(|alias| {
let alias = alias.trim().to_string();
check_name(&alias, rust_method_name.span());
check_name(alias, rust_method_name.span());
handle_register_result(quote! {
rpc.register_alias(#alias, #rpc_name)
})
Expand All @@ -229,8 +228,7 @@ impl RpcDescription {
.aliases
.iter()
.map(|alias| {
let alias = alias.trim().to_string();
check_name(&alias, rust_method_name.span());
check_name(alias, rust_method_name.span());
handle_register_result(quote! {
rpc.register_alias(#alias, #sub_name)
})
Expand All @@ -240,8 +238,7 @@ impl RpcDescription {
.unsubscribe_aliases
.iter()
.map(|alias| {
let alias = alias.trim().to_string();
check_name(&alias, rust_method_name.span());
check_name(alias, rust_method_name.span());
handle_register_result(quote! {
rpc.register_alias(#alias, #unsub_name)
})
Expand Down
24 changes: 9 additions & 15 deletions proc-macros/src/rpc_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,13 @@
//! Declaration of the JSON RPC generator procedural macros.

use crate::{
attributes::{optional, parse_param_kind, Argument, AttributeMeta, MissingArgument, ParamKind, Resource},
attributes::{optional, parse_param_kind, Aliases, Argument, AttributeMeta, MissingArgument, ParamKind, Resource},
helpers::extract_doc_comments,
};

use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use std::borrow::Cow;
use syn::spanned::Spanned;
use syn::{punctuated::Punctuated, Attribute, Token};

Expand Down Expand Up @@ -276,32 +277,25 @@ impl RpcDescription {
/// Examples:
/// For namespace `foo` and method `makeSpam`, result will be `foo_makeSpam`.
/// For no namespace and method `makeSpam` it will be just `makeSpam.
pub(crate) fn rpc_identifier(&self, method: &str) -> String {
pub(crate) fn rpc_identifier<'a>(&self, method: &'a str) -> Cow<'a, str> {
if let Some(ns) = &self.namespace {
format!("{}_{}", ns, method.trim())
format!("{}_{}", ns, method).into()
} else {
method.to_string()
Cow::Borrowed(method)
}
}
}

fn parse_aliases(arg: Result<Argument, MissingArgument>) -> syn::Result<Vec<String>> {
let aliases = optional(arg, Argument::string)?;
let aliases = optional(arg, Argument::value::<Aliases>)?;

Ok(aliases.map(|a| a.split(',').map(Into::into).collect()).unwrap_or_default())
Ok(aliases.map(|a| a.list.into_iter().map(|lit| lit.value()).collect()).unwrap_or_default())
}

fn find_attr<'a>(attrs: &'a [Attribute], ident: &str) -> Option<&'a Attribute> {
attrs.iter().find(|a| a.path.is_ident(ident))
}

fn build_unsubscribe_method(existing_method: &str) -> String {
let method = existing_method.trim();
let mut new_method = String::from("unsubscribe");
if method.starts_with("subscribe") {
new_method.extend(method.chars().skip(9));
} else {
new_method.push_str(method);
}
new_method
fn build_unsubscribe_method(method: &str) -> String {
format!("unsubscribe{}", method.strip_prefix("subscribe").unwrap_or(method))
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍

}
4 changes: 2 additions & 2 deletions proc-macros/tests/ui/correct/alias_doesnt_use_namespace.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ use jsonrpsee::{proc_macros::rpc, types::RpcResult};
#[rpc(client, server, namespace = "myapi")]
pub trait Rpc {
/// Alias doesn't use the namespace so not duplicated.
#[method(name = "getTemp", aliases = "getTemp")]
#[method(name = "getTemp", aliases = ["getTemp"])]
async fn async_method(&self, param_a: u8, param_b: String) -> RpcResult<u16>;

#[subscription(name = "getFood", item = String, aliases = "getFood", unsubscribe_aliases = "unsubscribegetFood")]
#[subscription(name = "getFood", item = String, aliases = ["getFood"], unsubscribe_aliases = ["unsubscribegetFood"])]
fn sub(&self) -> RpcResult<()>;
}

Expand Down
4 changes: 2 additions & 2 deletions proc-macros/tests/ui/correct/basic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ use std::net::SocketAddr;

#[rpc(client, server, namespace = "foo")]
pub trait Rpc {
#[method(name = "foo", aliases = "fooAlias, Other")]
#[method(name = "foo", aliases = ["fooAlias", "Other"])]
async fn async_method(&self, param_a: u8, param_b: String) -> RpcResult<u16>;

#[method(name = "optional_params")]
Expand All @@ -29,7 +29,7 @@ pub trait Rpc {
#[subscription(name = "sub", item = String)]
fn sub(&self) -> RpcResult<()>;

#[subscription(name = "echo", aliases = "ECHO", item = u32, unsubscribe_aliases = "NotInterested, listenNoMore")]
#[subscription(name = "echo", aliases = ["ECHO"], item = u32, unsubscribe_aliases = ["NotInterested", "listenNoMore"])]
fn sub_with_params(&self, val: u32) -> RpcResult<()>;
}

Expand Down
6 changes: 3 additions & 3 deletions proc-macros/tests/ui/correct/parse_angle_brackets.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,12 @@ fn main() {
pub trait Rpc {
#[subscription(
name = "submitAndWatchExtrinsic",
aliases = "author_extrinsicUpdate",
unsubscribe_aliases = "author_unwatchExtrinsic",
aliases = ["author_extrinsicUpdate"],
unsubscribe_aliases = ["author_unwatchExtrinsic"],
// Arguments are being parsed the nearest comma,
// angle braces need to be accounted for manually.
item = TransactionStatus<Hash, BlockHash>,
)]
fn dummy_subscription(&self) -> RpcResult<()>;
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use jsonrpsee::proc_macros::rpc;
use jsonrpsee::types::RpcResult;
#[rpc(client, server)]
pub trait DuplicatedAlias {
#[method(name = "foo", aliases = "foo_dup, foo_dup")]
#[method(name = "foo", aliases = ["foo_dup", "foo_dup"])]
async fn async_method(&self) -> RpcResult<u8>;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ use jsonrpsee::{proc_macros::rpc, types::RpcResult};

#[rpc(client, server)]
pub trait DuplicatedSubAlias {
#[subscription(name = "alias", item = String, aliases = "hello_is_goodbye", unsubscribe_aliases = "hello_is_goodbye")]
#[subscription(name = "alias", item = String, aliases = ["hello_is_goodbye"], unsubscribe_aliases = ["hello_is_goodbye"])]
fn async_method(&self) -> RpcResult<()>;
}

Expand Down
2 changes: 1 addition & 1 deletion tests/tests/proc_macros.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ mod rpc_impl {
#[subscription(name = "sub", item = String)]
fn sub(&self) -> RpcResult<()>;

#[subscription(name = "echo", aliases = "alias_echo", item = u32)]
#[subscription(name = "echo", aliases = ["alias_echo"], item = u32)]
fn sub_with_params(&self, val: u32) -> RpcResult<()>;

#[method(name = "params")]
Expand Down