Skip to content

Commit

Permalink
Slightly improve parse_method_calls()
Browse files Browse the repository at this point in the history
This commit tweaks the code introduced with the `syn` 2.0 migration so
iteration short-circuits as soon as it finds the `name` attribute. This
acts as a safeguard that ensures we only ever act on, at most, a single
`name` identifier, while also shortening the code's length by 1 line.
  • Loading branch information
ebkalderon committed Aug 11, 2023
1 parent 5ac05eb commit 5973ae3
Showing 1 changed file with 17 additions and 18 deletions.
35 changes: 17 additions & 18 deletions tower-lsp-macros/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ use syn::{parse_macro_input, FnArg, ItemTrait, LitStr, ReturnType, TraitItem};
/// as RPC handlers.
#[proc_macro_attribute]
pub fn rpc(attr: TokenStream, item: TokenStream) -> TokenStream {
// It will be checked later in `parse_method_calls()`.
// Attribute will be parsed later in `parse_method_calls()`.
if !attr.is_empty() {
return item;
}
Expand Down Expand Up @@ -48,24 +48,23 @@ fn parse_method_calls(lang_server_trait: &ItemTrait) -> Vec<MethodCall> {
_ => continue,
};

let mut rpc_name: Option<String> = None;

for attr in &method.attrs {
if attr.meta.path().is_ident("rpc") {
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("name") {
let s: LitStr = meta.value()?.parse()?;
rpc_name = Some(s.value());
Ok(())
} else {
Err(meta.error("expected `name`"))
}
})
.unwrap();
let attr = method
.attrs
.iter()
.find(|attr| attr.meta.path().is_ident("rpc"))
.expect("expected `#[rpc(name = \"foo\")]` attribute");

let mut rpc_name = String::new();
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("name") {
let s: LitStr = meta.value().and_then(|v| v.parse())?;
rpc_name = s.value();
Ok(())
} else {
Err(meta.error("expected `name` identifier in `#[rpc]`"))
}
}

let rpc_name = rpc_name.expect("expected `#[rpc(name = \"foo\")]` attribute");
})
.unwrap();

let params = method.sig.inputs.iter().nth(1).and_then(|arg| match arg {
FnArg::Typed(pat) => Some(&*pat.ty),
Expand Down

0 comments on commit 5973ae3

Please sign in to comment.