From 269acc9a152379c453fed76090a3bc69d680edbe Mon Sep 17 00:00:00 2001 From: Roland Fredenhagen Date: Mon, 7 Aug 2023 15:31:24 +0700 Subject: [PATCH] verify supported protocol in parsing step --- crates/rune-macros/src/context.rs | 25 ++++++++++++++++--------- crates/rune-macros/src/lib.rs | 2 +- 2 files changed, 17 insertions(+), 10 deletions(-) diff --git a/crates/rune-macros/src/context.rs b/crates/rune-macros/src/context.rs index d5503312d..4914b64d4 100644 --- a/crates/rune-macros/src/context.rs +++ b/crates/rune-macros/src/context.rs @@ -135,36 +135,43 @@ impl TypeProtocol { module.associated_function(rune::runtime::Protocol::ADD, |this: Self, other: Self| this + other)?; }, "STRING_DISPLAY" => quote_spanned! {self.protocol.span()=> - module.associated_function(rune::runtime::Protocol::STRING_DISPLAY, |this: &Self, buf: &mut String| { + module.associated_function(rune::runtime::Protocol::STRING_DISPLAY, |this: &Self, buf: &mut ::std::string::String| { use ::core::fmt::Write as _; ::core::write!(buf, "{this}") })?; }, "STRING_DEBUG" => quote_spanned! {self.protocol.span()=> - module.associated_function(rune::runtime::Protocol::STRING_DEBUG, |this: &Self, buf: &mut String| { + module.associated_function(rune::runtime::Protocol::STRING_DEBUG, |this: &Self, buf: &mut ::std::string::String| { use ::core::fmt::Write as _; ::core::write!(buf, "{this:?}") })?; }, - _ => syn::Error::new_spanned( - &self.protocol, - format!("Rune protocol `{}` cannot be derived", self.protocol), - ) - .to_compile_error(), + _ => unreachable!("`parse()` ensures only supported protocols") } } } impl Parse for TypeProtocol { fn parse(input: ParseStream) -> syn::Result { - Ok(Self { + let it = Self { protocol: input.parse()?, handler: if input.parse::().is_ok() { Some(input.parse()?) } else { None }, - }) + }; + + if it.handler.is_some() + || ["ADD", "STRING_DISPLAY", "STRING_DEBUG"].contains(&it.protocol.to_string().as_str()) + { + Ok(it) + } else { + Err(syn::Error::new_spanned( + &it.protocol, + format!("Rune protocol `{}` cannot be derived", it.protocol), + )) + } } } diff --git a/crates/rune-macros/src/lib.rs b/crates/rune-macros/src/lib.rs index daf934386..165f7e123 100644 --- a/crates/rune-macros/src/lib.rs +++ b/crates/rune-macros/src/lib.rs @@ -155,7 +155,7 @@ pub fn to_value(input: proc_macro::TokenStream) -> proc_macro::TokenStream { .into() } -#[proc_macro_derive(Any, attributes(rune))] +#[proc_macro_derive(Any, attributes(rune, rune_derive, rune_functions))] pub fn any(input: proc_macro::TokenStream) -> proc_macro::TokenStream { let derive = syn::parse_macro_input!(input as any::Derive); derive.expand().unwrap_or_else(to_compile_errors).into()