From 95fd20a46fe50fecf156859887d7ca29de603465 Mon Sep 17 00:00:00 2001 From: naskya Date: Fri, 10 May 2024 06:54:26 +0900 Subject: [PATCH] feat (macro-rs): add ts_only_warn macro --- packages/backend-rs/src/lib.rs | 2 +- packages/macro-rs/src/lib.rs | 48 ++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+), 1 deletion(-) diff --git a/packages/backend-rs/src/lib.rs b/packages/backend-rs/src/lib.rs index 0dcc4e6251..f4d9b431f9 100644 --- a/packages/backend-rs/src/lib.rs +++ b/packages/backend-rs/src/lib.rs @@ -1,4 +1,4 @@ -pub use macro_rs::export; +pub use macro_rs::{export, ts_only_warn}; pub mod config; pub mod database; diff --git a/packages/macro-rs/src/lib.rs b/packages/macro-rs/src/lib.rs index c1a24a93cf..3481d0cd87 100644 --- a/packages/macro-rs/src/lib.rs +++ b/packages/macro-rs/src/lib.rs @@ -2,6 +2,7 @@ use convert_case::{Case, Casing}; use proc_macro2::{TokenStream, TokenTree}; use quote::{quote, ToTokens}; +/// Export this function, struct, enum, const, etc. to TypeScript. #[proc_macro_attribute] pub fn export( attr: proc_macro::TokenStream, @@ -17,6 +18,53 @@ pub fn export( .into() } +/// Denotes that this function should only be used in TypeScript. +/// +/// # Example +/// ``` +/// # use macro_rs::ts_only_warn; +/// # use std::fmt::{Display, Formatter, Result}; +/// # pub struct Thing {} +/// # impl Display for Thing { fn fmt(&self, fmt: &mut Formatter) -> Result { Ok(()) } } // dummy +/// #[ts_only_warn("Use `thing.to_string()` instead.")] +/// pub fn thing_to_string(thing: Thing) -> String { +/// thing.to_string() +/// } +/// ``` +/// generates +/// ``` +/// # use macro_rs::ts_only_warn; +/// # use std::fmt::{Display, Formatter, Result}; +/// # pub struct Thing {} +/// # impl Display for Thing { fn fmt(&self, fmt: &mut Formatter) -> Result { Ok(()) } } // dummy +/// #[cfg_attr(not(feature = "napi"), deprecated = "This function is only for TypeScript export. Use `thing.to_string()` instead.")] +/// pub fn thing_to_string(thing: Thing) -> String { +/// thing.to_string() +/// } +/// ``` +#[proc_macro_attribute] +pub fn ts_only_warn( + attr: proc_macro::TokenStream, + item: proc_macro::TokenStream, +) -> proc_macro::TokenStream { + let item: TokenStream = item.into(); + + let attr_str = Into::::into(attr).to_string(); + let msg = { + let mut chars = attr_str.as_str().chars(); + chars.next(); + chars.next_back(); + chars.as_str() + }; + let prefixed_msg = format!("This function is only for TypeScript export. {}", msg); + + quote! { + #[cfg_attr(not(feature = "napi"), deprecated = #prefixed_msg)] + #item + } + .into() +} + /// Creates extra wrapper function for napi. /// /// The macro is simply converted into `napi_derive::napi(...)`