Skip to main content

vtcode_macros/
lib.rs

1#![allow(
2    missing_docs,
3    reason = "Intentional compatibility, platform, or test-only suppression."
4)]
5use proc_macro::TokenStream;
6use proc_macro2::TokenStream as TokenStream2;
7use quote::{format_ident, quote};
8use syn::{Data, DataEnum, DeriveInput, Fields, parse_macro_input};
9
10/// Minimum variant count before a unit-only enum uses the concatenated-name
11/// `Debug` strategy. The strategy has a fixed cost (name string + byte scan), so
12/// it only wins once the per-arm costs of the built-in derive dominate.
13const C_LIKE_ENUM_THRESHOLD: usize = 8;
14
15/// Derive macro that generates the same boilerplate as the `string_newtype!`
16/// declarative macro. Apply to a tuple struct wrapping a single `String` field.
17///
18/// Generates:
19/// - Inherent methods: `new()`, `as_str()`, `into_inner()`
20/// - `Deref<Target = str>`
21/// - `Borrow<str>`
22/// - `AsRef<str>`
23/// - `Display`
24/// - `From<String>`, `From<&str>`, `From<Self> for String`
25///
26/// # Example
27///
28/// ```rust,ignore
29/// #[derive(Debug, Clone, Serialize, Deserialize, StringNewtype)]
30/// #[serde(transparent)]
31/// pub struct SessionId(String);
32/// ```
33#[proc_macro_derive(StringNewtype)]
34pub fn derive_string_newtype(input: TokenStream) -> TokenStream {
35    let input = parse_macro_input!(input as DeriveInput);
36    impl_string_newtype(&input).unwrap_or_else(|err| err.to_compile_error().into())
37}
38
39fn impl_string_newtype(input: &DeriveInput) -> syn::Result<TokenStream> {
40    let name = &input.ident;
41
42    // Validate: must be a tuple struct with exactly one String field.
43    let field_type = match &input.data {
44        Data::Struct(data) => match &data.fields {
45            Fields::Unnamed(fields) => {
46                if fields.unnamed.len() != 1 {
47                    return Err(syn::Error::new_spanned(
48                        name,
49                        "StringNewtype requires a tuple struct with exactly one field",
50                    ));
51                }
52                let Some(field) = fields.unnamed.first() else {
53                    return Err(syn::Error::new_spanned(
54                        name,
55                        "StringNewtype requires a tuple struct with exactly one field",
56                    ));
57                };
58                &field.ty
59            }
60            _ => {
61                return Err(syn::Error::new_spanned(name, "StringNewtype can only be derived for tuple structs"));
62            }
63        },
64        _ => {
65            return Err(syn::Error::new_spanned(name, "StringNewtype can only be derived for structs"));
66        }
67    };
68
69    // Verify the inner type is String.
70    if !is_string_type(field_type) {
71        return Err(syn::Error::new_spanned(field_type, "StringNewtype requires the inner type to be String"));
72    }
73
74    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
75
76    let output = quote! {
77        impl #impl_generics #name #ty_generics #where_clause {
78            /// Create a new instance from any value that converts to `String`.
79            pub fn new(value: impl Into<String>) -> Self {
80                Self(value.into())
81            }
82
83            /// Borrow the inner string as a `&str`.
84            pub fn as_str(&self) -> &str {
85                &self.0
86            }
87
88            /// Consume the wrapper and return the inner `String`.
89            pub fn into_inner(self) -> String {
90                self.0
91            }
92        }
93
94        impl #impl_generics std::ops::Deref for #name #ty_generics #where_clause {
95            type Target = str;
96
97            fn deref(&self) -> &Self::Target {
98                &self.0
99            }
100        }
101
102        impl #impl_generics std::borrow::Borrow<str> for #name #ty_generics #where_clause {
103            fn borrow(&self) -> &str {
104                &self.0
105            }
106        }
107
108        impl #impl_generics AsRef<str> for #name #ty_generics #where_clause {
109            fn as_ref(&self) -> &str {
110                &self.0
111            }
112        }
113
114        impl #impl_generics std::fmt::Display for #name #ty_generics #where_clause {
115            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
116                self.0.fmt(f)
117            }
118        }
119
120        impl #impl_generics From<String> for #name #ty_generics #where_clause {
121            fn from(value: String) -> Self {
122                Self(value)
123            }
124        }
125
126        impl #impl_generics From<&str> for #name #ty_generics #where_clause {
127            fn from(value: &str) -> Self {
128                Self(value.to_string())
129            }
130        }
131
132        impl #impl_generics From<#name #ty_generics> for String #where_clause {
133            fn from(value: #name #ty_generics) -> Self {
134                value.0
135            }
136        }
137    };
138
139    Ok(output.into())
140}
141
142fn is_string_type(ty: &syn::Type) -> bool {
143    if let syn::Type::Path(type_path) = ty
144        && type_path.qself.is_none()
145        && type_path.path.segments.len() == 1
146    {
147        return type_path.path.segments.first().is_some_and(|segment| segment.ident == "String");
148    }
149    false
150}
151
152/// Derive macro equivalent to `#[derive(Debug)]` but with `#[inline(never)]` on
153/// the generated `fmt` implementation.
154///
155/// Rust's built-in `Debug` derive emits `#[inline]` on `fmt`. For large or deeply
156/// nested types — typically error enums formatted on fan-out paths — that lets
157/// `rustc` inline the whole `Debug` tree into every `{:?}` / `?err` call site,
158/// which can bloat binary size. This derive preserves the exact `Debug` output;
159/// it changes the inlining hint and, for large unit-only enums, the shape of the
160/// generated body (see below).
161///
162/// C-like enums (all unit variants) with at least `C_LIKE_ENUM_THRESHOLD`
163/// variants additionally emit one space-delimited name string and a match that
164/// yields byte offsets, instead of one `write_str("<name>")` call per arm. This
165/// removes the per-arm string literals and temporary locals that make derived
166/// `Debug` expensive to compile and large in the binary; the output is still
167/// byte-identical to the built-in derive.
168///
169/// Use it for large/nested types whose `Debug` is formatted in hot or fan-out
170/// paths; keep `#[derive(Debug)]` for small, hot, leaf types. See
171/// `docs/development/rust-performance-principles.md`, "Derived trait impls are
172/// `#[inline]`".
173///
174/// # Example
175///
176/// ```rust,ignore
177/// use vtcode_macros::DebugNoInline;
178///
179/// #[derive(DebugNoInline)]
180/// pub struct Widgets {
181///     foo: u32,
182///     bar: usize,
183/// }
184///
185/// assert_eq!(
186///     format!("{:?}", Widgets { foo: 1, bar: 2 }),
187///     "Widgets { foo: 1, bar: 2 }"
188/// );
189/// ```
190#[proc_macro_derive(DebugNoInline)]
191pub fn derive_debug_no_inline(input: TokenStream) -> TokenStream {
192    let input = parse_macro_input!(input as DeriveInput);
193    match impl_debug_no_inline(&input) {
194        Ok(tokens) => tokens.into(),
195        Err(err) => err.to_compile_error().into(),
196    }
197}
198
199fn impl_debug_no_inline(input: &DeriveInput) -> syn::Result<TokenStream2> {
200    let name = &input.ident;
201
202    // Mirror the built-in derive: bound every type parameter on `Debug`.
203    let mut generics = input.generics.clone();
204    for param in generics.type_params_mut() {
205        param.bounds.push(syn::parse_quote!(::core::fmt::Debug));
206    }
207    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
208
209    let body = match &input.data {
210        Data::Struct(data) => fmt_body_struct(&name.to_string(), &data.fields),
211        Data::Enum(data) => fmt_body_enum(data),
212        Data::Union(_) => {
213            return Err(syn::Error::new_spanned(name, "DebugNoInline cannot be derived for unions"));
214        }
215    };
216
217    Ok(quote! {
218        #[automatically_derived]
219        impl #impl_generics ::core::fmt::Debug for #name #ty_generics #where_clause {
220            #[inline(never)]
221            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
222                #body
223            }
224        }
225    })
226}
227
228/// Debug name for a field: strip a raw-identifier prefix so `r#type` renders as
229/// `type`, matching the built-in derive.
230fn field_name(ident: &syn::Ident) -> String {
231    let raw = ident.to_string();
232    raw.trim_prefix("r#").to_string()
233}
234
235fn fmt_body_struct(type_name: &str, fields: &Fields) -> TokenStream2 {
236    match fields {
237        Fields::Unit => quote! { f.write_str(#type_name) },
238        Fields::Named(named) => {
239            let calls = named.named.iter().filter_map(|field| {
240                let ident = field.ident.as_ref()?;
241                let field_name = field_name(ident);
242                Some(quote! { __debug_builder.field(#field_name, &self.#ident); })
243            });
244            let builder = debug_builder_init("debug_struct", type_name);
245            quote! {
246                #builder
247                #(#calls)*
248                __debug_builder.finish()
249            }
250        }
251        Fields::Unnamed(unnamed) => {
252            let calls = unnamed.unnamed.iter().enumerate().map(|(index, _)| {
253                let index = syn::Index::from(index);
254                quote! { __debug_builder.field(&self.#index); }
255            });
256            let builder = debug_builder_init("debug_tuple", type_name);
257            quote! {
258                #builder
259                #(#calls)*
260                __debug_builder.finish()
261            }
262        }
263    }
264}
265
266fn fmt_body_enum(data: &DataEnum) -> TokenStream2 {
267    // An uninhabited enum has no variants to match. `match self {}` is not
268    // exhaustive because `&Never` is inhabited, so dereference: `match *self {}`.
269    if data.variants.is_empty() {
270        return quote! { match *self {} };
271    }
272
273    // Large unit-only enums are the pathological case for the built-in derive:
274    // match checking is quadratic in arm count and borrow checking allocates a
275    // temp local for every string-literal arm. Emit one name string plus a match
276    // of integer offsets instead (the strategy upstream adopted for
277    // `derive(Debug)`). Keep a match rather than using `discriminant_value`:
278    // attribute macros such as `bitflags` can rewrite discriminants after the
279    // derive runs, which would make offsets point at the wrong names.
280    if data.variants.len() >= C_LIKE_ENUM_THRESHOLD
281        && data.variants.iter().all(|variant| matches!(variant.fields, Fields::Unit))
282    {
283        return fmt_body_c_like_enum(data);
284    }
285
286    let arms = data.variants.iter().map(|variant| {
287        let variant_ident = &variant.ident;
288        let variant_name = field_name(variant_ident);
289        match &variant.fields {
290            Fields::Unit => quote! {
291                Self::#variant_ident => f.write_str(#variant_name),
292            },
293            Fields::Named(named) => {
294                let pairs: Vec<(syn::Ident, syn::Ident)> = named
295                    .named
296                    .iter()
297                    .enumerate()
298                    .filter_map(|(index, field)| {
299                        let ident = field.ident.as_ref()?.clone();
300                        Some((ident, format_ident!("__self_{index}")))
301                    })
302                    .collect();
303                let pattern = pairs.iter().map(|(ident, binding)| quote! { #ident: #binding });
304                let calls = pairs.iter().map(|(ident, binding)| {
305                    let field_name = field_name(ident);
306                    quote! { __debug_builder.field(#field_name, #binding); }
307                });
308                let builder = debug_builder_init("debug_struct", &variant_name);
309                quote! {
310                    Self::#variant_ident { #(#pattern),* } => {
311                        #builder
312                        #(#calls)*
313                        __debug_builder.finish()
314                    }
315                }
316            }
317            Fields::Unnamed(unnamed) => {
318                let bindings: Vec<syn::Ident> = (0..unnamed.unnamed.len())
319                    .map(|index| format_ident!("__self_{index}"))
320                    .collect();
321                let calls = bindings.iter().map(|binding| quote! { __debug_builder.field(#binding); });
322                let builder = debug_builder_init("debug_tuple", &variant_name);
323                quote! {
324                    Self::#variant_ident( #(#bindings),* ) => {
325                        #builder
326                        #(#calls)*
327                        __debug_builder.finish()
328                    }
329                }
330            }
331        }
332    });
333    quote! {
334        match self {
335            #(#arms)*
336        }
337    }
338}
339
340/// `Debug` body for a unit-only enum: write a name sliced out of one
341/// space-delimited string. Offsets are byte offsets computed from the variant
342/// names, and the delimiter is found with an ASCII byte scan (no UTF-8 iterator
343/// or panic-formatting machinery). Raw-identifier prefixes are stripped so the
344/// output matches the built-in derive.
345fn fmt_body_c_like_enum(data: &DataEnum) -> TokenStream2 {
346    let mut names = String::new();
347    let mut offset = 0usize;
348    let mut arms = Vec::with_capacity(data.variants.len());
349    for variant in &data.variants {
350        let variant_ident = &variant.ident;
351        let name = field_name(variant_ident);
352        if !names.is_empty() {
353            names.push(' ');
354        }
355        names.push_str(&name);
356        arms.push(quote! { Self::#variant_ident => #offset, });
357        offset += name.len() + 1;
358    }
359
360    quote! {
361        const __NAMES: &str = #names;
362        let __start: usize = match self {
363            #(#arms)*
364        };
365        let __tail = __NAMES.get(__start..).unwrap_or_default();
366        let __end = __tail
367            .as_bytes()
368            .iter()
369            .position(|byte| *byte == b' ')
370            .unwrap_or(__tail.len());
371        f.write_str(__tail.get(..__end).unwrap_or_default())
372    }
373}
374
375/// Emit `let mut __debug_builder = f.<kind>("<name>");`. The builder is always
376/// `mut` because `field(...)` and `finish(...)` both take `&mut self`.
377fn debug_builder_init(kind: &str, name: &str) -> TokenStream2 {
378    let kind = format_ident!("{kind}");
379    quote! { let mut __debug_builder = f.#kind(#name); }
380}