Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 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
2 changes: 1 addition & 1 deletion proc-macros/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ proc-macro = true
[dependencies]
proc-macro2 = "1.0"
quote = "1.0"
syn = { version = "1.0", default-features = false, features = ["extra-traits", "full", "visit", "parsing", "printing", "clone-impls", "proc-macro"] }
syn = { version = "2.0", default-features = false, features = ["extra-traits", "full", "visit", "parsing", "printing", "clone-impls", "proc-macro"] }
proc-macro-crate = "3"
heck = "0.4.0"

Expand Down
9 changes: 5 additions & 4 deletions proc-macros/src/attributes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ impl<T: Parse> Parse for Bracketed<T> {

syn::bracketed!(content in input);

let list = content.parse_terminated(Parse::parse)?;
let list = content.parse_terminated(Parse::parse, Token![,])?;

Ok(Bracketed { list })
}
Expand All @@ -119,15 +119,16 @@ fn parenthesized<T: Parse>(input: ParseStream) -> syn::Result<Punctuated<T, Toke

syn::parenthesized!(content in input);

content.parse_terminated(T::parse)
content.parse_terminated(T::parse, Token![,])
}

impl AttributeMeta {
/// Parses `Attribute` with plain `TokenStream` into a more robust `AttributeMeta` with
/// a collection `Arguments`.
pub fn parse(attr: Attribute) -> syn::Result<AttributeMeta> {
let path = attr.path;
let arguments = parenthesized.parse2(attr.tokens)?;
let path = attr.path().clone();

let arguments = attr.parse_args_with(|input: ParseStream| input.parse_terminated(Parse::parse, Token![,]))?;

Ok(AttributeMeta { path, arguments })
}
Expand Down
12 changes: 6 additions & 6 deletions proc-macros/src/helpers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,12 +198,12 @@ pub(crate) fn is_option(ty: &syn::Type) -> bool {
/// Note that `doc comments` are expanded into `#[doc = "some comment"]`
/// Thus, if the attribute starts with `doc` => it's regarded as a doc comment.
pub(crate) fn extract_doc_comments(attrs: &[syn::Attribute]) -> TokenStream2 {
let docs = attrs.iter().filter(|attr| {
attr.path.is_ident("doc")
&& match attr.parse_meta() {
Ok(syn::Meta::NameValue(meta)) => matches!(&meta.lit, syn::Lit::Str(_)),
_ => false,
}
let docs = attrs.iter().filter(|attr| match &attr.meta {
syn::Meta::NameValue(meta) => {
meta.path.is_ident("doc")
&& matches!(meta.value, syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(_), .. }))
}
_ => false,
});
quote! ( #(#docs)* )
}
Expand Down
11 changes: 5 additions & 6 deletions proc-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@
extern crate proc_macro;

use proc_macro::TokenStream;
use quote::quote;
use rpc_macro::RpcDescription;

mod attributes;
Expand Down Expand Up @@ -388,16 +387,16 @@ pub(crate) mod visitor;
/// ```
#[proc_macro_attribute]
pub fn rpc(attr: TokenStream, item: TokenStream) -> TokenStream {
let attr = proc_macro2::TokenStream::from(attr);

let rebuilt_rpc_attribute = syn::Attribute {
pound_token: syn::token::Pound::default(),
style: syn::AttrStyle::Outer,
bracket_token: syn::token::Bracket::default(),
path: syn::Ident::new("rpc", proc_macro2::Span::call_site()).into(),
tokens: quote! { (#attr) },
meta: syn::Meta::List(syn::MetaList {
path: syn::Ident::new("rpc", proc_macro2::Span::call_site()).into(),
delimiter: syn::MacroDelimiter::Paren(syn::token::Paren(proc_macro2::Span::call_site())),
tokens: attr.into(),
}),
};

match rpc_impl(rebuilt_rpc_attribute, item) {
Ok(tokens) => tokens,
Err(err) => err.to_compile_error(),
Expand Down
2 changes: 1 addition & 1 deletion proc-macros/src/render_client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ impl RpcDescription {
&self,
params: &[(syn::PatIdent, syn::Type)],
param_kind: &ParamKind,
signature: &syn::TraitItemMethod,
signature: &syn::TraitItemFn,
) -> TokenStream2 {
let jsonrpsee = self.jsonrpsee_client_path.as_ref().unwrap();

Expand Down
16 changes: 4 additions & 12 deletions proc-macros/src/render_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,7 @@ use super::RpcDescription;
use crate::helpers::{generate_where_clause, is_option};
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::{quote, quote_spanned};
use syn::punctuated::Punctuated;
use syn::{token, AttrStyle, Attribute, Path, PathSegment};
use syn::Attribute;

impl RpcDescription {
pub(super) fn render_server(&self) -> Result<TokenStream2, syn::Error> {
Expand Down Expand Up @@ -379,17 +378,10 @@ impl RpcDescription {
heck::ToLowerCamelCase::to_lower_camel_case(name.ident.to_string().as_str())
));

let mut punc_attr = Punctuated::new();
let alias = TokenStream2::from_str(alias_vals.as_str()).unwrap();

punc_attr
.push_value(PathSegment { ident: quote::format_ident!("serde"), arguments: Default::default() });

let serde_alias = Attribute {
pound_token: token::Pound::default(),
style: AttrStyle::Outer,
bracket_token: Default::default(),
path: Path { leading_colon: None, segments: punc_attr },
tokens: TokenStream2::from_str(&format!("({})", alias_vals.as_str())).unwrap(),
let serde_alias: Attribute = syn::parse_quote! {
#[serde(#alias)]
};

quote! {
Expand Down
12 changes: 6 additions & 6 deletions proc-macros/src/rpc_macro.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,12 @@ pub struct RpcMethod {
pub params: Vec<(syn::PatIdent, syn::Type)>,
pub param_kind: ParamKind,
pub returns: Option<syn::Type>,
pub signature: syn::TraitItemMethod,
pub signature: syn::TraitItemFn,
pub aliases: Vec<String>,
}

impl RpcMethod {
pub fn from_item(attr: Attribute, mut method: syn::TraitItemMethod) -> syn::Result<Self> {
pub fn from_item(attr: Attribute, mut method: syn::TraitItemFn) -> syn::Result<Self> {
let [aliases, blocking, name, param_kind] =
AttributeMeta::parse(attr)?.retain(["aliases", "blocking", "name", "param_kind"])?;

Expand Down Expand Up @@ -117,13 +117,13 @@ pub struct RpcSubscription {
pub params: Vec<(syn::PatIdent, syn::Type)>,
pub param_kind: ParamKind,
pub item: syn::Type,
pub signature: syn::TraitItemMethod,
pub signature: syn::TraitItemFn,
pub aliases: Vec<String>,
pub unsubscribe_aliases: Vec<String>,
}

impl RpcSubscription {
pub fn from_item(attr: syn::Attribute, mut sub: syn::TraitItemMethod) -> syn::Result<Self> {
pub fn from_item(attr: syn::Attribute, mut sub: syn::TraitItemFn) -> syn::Result<Self> {
let [aliases, item, name, param_kind, unsubscribe, unsubscribe_aliases] = AttributeMeta::parse(attr)?
.retain(["aliases", "item", "name", "param_kind", "unsubscribe", "unsubscribe_aliases"])?;

Expand Down Expand Up @@ -249,7 +249,7 @@ impl RpcDescription {
// Go through all the methods in the trait and collect methods and
// subscriptions.
for entry in item.items.iter() {
if let syn::TraitItem::Method(method) = entry {
if let syn::TraitItem::Fn(method) = entry {
if method.sig.receiver().is_none() {
return Err(syn::Error::new_spanned(&method.sig, "First argument of the trait must be '&self'"));
}
Expand Down Expand Up @@ -354,7 +354,7 @@ fn parse_subscribe(arg: Result<Argument, MissingArgument>) -> syn::Result<Option
}

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

fn build_unsubscribe_method(method: &str) -> Option<String> {
Expand Down
8 changes: 3 additions & 5 deletions proc-macros/src/visitor.rs
Original file line number Diff line number Diff line change
Expand Up @@ -186,10 +186,8 @@ impl FindSubscriptionParams {
for arg in &arguments.args {
match arg {
syn::GenericArgument::Type(arg) => self.visit_type(arg),
syn::GenericArgument::Binding(arg) => self.visit_type(&arg.ty),
syn::GenericArgument::Lifetime(_)
| syn::GenericArgument::Constraint(_)
| syn::GenericArgument::Const(_) => {}
syn::GenericArgument::AssocType(arg) => self.visit_type(&arg.ty),
_ => {}
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This is needed now because the enum became non_exhaustive

}
}
}
Expand All @@ -214,7 +212,7 @@ impl FindSubscriptionParams {
fn visit_type_param_bound(&mut self, bound: &syn::TypeParamBound) {
match bound {
Copy link
Contributor

Choose a reason for hiding this comment

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

you use if let here to make clippy happy

syn::TypeParamBound::Trait(bound) => self.visit_path(&bound.path),
syn::TypeParamBound::Lifetime(_) => {}
_ => {}
}
}

Expand Down
1 change: 0 additions & 1 deletion tests/tests/rpc_module.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,6 @@ use jsonrpsee::core::EmptyServerParams;
use jsonrpsee::core::{server::*, RpcResult};
use jsonrpsee::types::error::{ErrorCode, ErrorObject, INVALID_PARAMS_MSG, PARSE_ERROR_CODE};
use jsonrpsee::types::{ErrorObjectOwned, Params, Response, ResponsePayload};
use jsonrpsee::SubscriptionMessage;
use serde::{Deserialize, Serialize};
use tokio::sync::mpsc;
use tokio::time::interval;
Expand Down