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 an enum uses the concatenated-name `Debug`
11/// strategy. The strategy has a fixed cost (name string + byte scan), so it only
12/// wins once the per-arm costs of the built-in derive dominate.
13const CONCATENATED_NAMES_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 enums, the shape of the generated
160/// body (see below).
161///
162/// Enums with at least `CONCATENATED_NAMES_THRESHOLD` variants additionally emit
163/// one space-delimited name string and look variant names up by byte offset,
164/// instead of one `"<name>"` literal per arm. This removes the per-arm string
165/// literals and temporary locals that make derived `Debug` expensive to compile
166/// and large in the binary; the output is still byte-identical to the built-in
167/// derive. Data-carrying variants keep their normal `debug_tuple`/`debug_struct`
168/// formatting, with the name passed in from the shared string.
169///
170/// Use it for large/nested types whose `Debug` is formatted in hot or fan-out
171/// paths; keep `#[derive(Debug)]` for small, hot, leaf types. See
172/// `docs/development/rust-performance-principles.md`, "Derived trait impls are
173/// `#[inline]`".
174///
175/// # Example
176///
177/// ```rust,ignore
178/// use vtcode_macros::DebugNoInline;
179///
180/// #[derive(DebugNoInline)]
181/// pub struct Widgets {
182///     foo: u32,
183///     bar: usize,
184/// }
185///
186/// assert_eq!(
187///     format!("{:?}", Widgets { foo: 1, bar: 2 }),
188///     "Widgets { foo: 1, bar: 2 }"
189/// );
190/// ```
191#[proc_macro_derive(DebugNoInline)]
192pub fn derive_debug_no_inline(input: TokenStream) -> TokenStream {
193    let input = parse_macro_input!(input as DeriveInput);
194    match impl_debug_no_inline(&input) {
195        Ok(tokens) => tokens.into(),
196        Err(err) => err.to_compile_error().into(),
197    }
198}
199
200fn impl_debug_no_inline(input: &DeriveInput) -> syn::Result<TokenStream2> {
201    let name = &input.ident;
202
203    // Mirror the built-in derive: bound every type parameter on `Debug`.
204    let mut generics = input.generics.clone();
205    for param in generics.type_params_mut() {
206        param.bounds.push(syn::parse_quote!(::core::fmt::Debug));
207    }
208    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
209
210    let body = match &input.data {
211        Data::Struct(data) => fmt_body_struct(&name.to_string(), &data.fields),
212        Data::Enum(data) => fmt_body_enum(data),
213        Data::Union(_) => {
214            return Err(syn::Error::new_spanned(name, "DebugNoInline cannot be derived for unions"));
215        }
216    };
217
218    Ok(quote! {
219        #[automatically_derived]
220        impl #impl_generics ::core::fmt::Debug for #name #ty_generics #where_clause {
221            #[inline(never)]
222            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
223                #body
224            }
225        }
226    })
227}
228
229/// Debug name for a field: strip a raw-identifier prefix so `r#type` renders as
230/// `type`, matching the built-in derive.
231fn field_name(ident: &syn::Ident) -> String {
232    let raw = ident.to_string();
233    raw.trim_prefix("r#").to_string()
234}
235
236fn fmt_body_struct(type_name: &str, fields: &Fields) -> TokenStream2 {
237    match fields {
238        Fields::Unit => quote! { f.write_str(#type_name) },
239        Fields::Named(named) => {
240            let calls = named.named.iter().filter_map(|field| {
241                let ident = field.ident.as_ref()?;
242                let field_name = field_name(ident);
243                Some(quote! { __debug_builder.field(#field_name, &self.#ident); })
244            });
245            let builder = debug_builder_init("debug_struct", type_name);
246            quote! {
247                #builder
248                #(#calls)*
249                __debug_builder.finish()
250            }
251        }
252        Fields::Unnamed(unnamed) => {
253            let calls = unnamed.unnamed.iter().enumerate().map(|(index, _)| {
254                let index = syn::Index::from(index);
255                quote! { __debug_builder.field(&self.#index); }
256            });
257            let builder = debug_builder_init("debug_tuple", type_name);
258            quote! {
259                #builder
260                #(#calls)*
261                __debug_builder.finish()
262            }
263        }
264    }
265}
266
267fn fmt_body_enum(data: &DataEnum) -> TokenStream2 {
268    // An uninhabited enum has no variants to match. `match self {}` is not
269    // exhaustive because `&Never` is inhabited, so dereference: `match *self {}`.
270    if data.variants.is_empty() {
271        return quote! { match *self {} };
272    }
273
274    // Large enums are the pathological case for the built-in derive: match
275    // checking is quadratic in arm count and borrow checking allocates a temp
276    // local for every string-literal arm. Emit one name string plus byte offsets
277    // instead (the strategy upstream adopted for `derive(Debug)`). Keep a match
278    // rather than using `discriminant_value`: attribute macros such as `bitflags`
279    // can rewrite discriminants after the derive runs, which would make offsets
280    // point at the wrong names.
281    if data.variants.len() >= CONCATENATED_NAMES_THRESHOLD {
282        if data.variants.iter().all(|variant| matches!(variant.fields, Fields::Unit)) {
283            return fmt_body_c_like_enum(data);
284        }
285        return fmt_body_mixed_enum(data);
286    }
287
288    let arms = data.variants.iter().map(|variant| {
289        let variant_ident = &variant.ident;
290        let variant_name = field_name(variant_ident);
291        match &variant.fields {
292            Fields::Unit => quote! {
293                Self::#variant_ident => f.write_str(#variant_name),
294            },
295            Fields::Named(named) => {
296                let pairs: Vec<(syn::Ident, syn::Ident)> = named
297                    .named
298                    .iter()
299                    .enumerate()
300                    .filter_map(|(index, field)| {
301                        let ident = field.ident.as_ref()?.clone();
302                        Some((ident, format_ident!("__self_{index}")))
303                    })
304                    .collect();
305                let pattern = pairs.iter().map(|(ident, binding)| quote! { #ident: #binding });
306                let calls = pairs.iter().map(|(ident, binding)| {
307                    let field_name = field_name(ident);
308                    quote! { __debug_builder.field(#field_name, #binding); }
309                });
310                let builder = debug_builder_init("debug_struct", &variant_name);
311                quote! {
312                    Self::#variant_ident { #(#pattern),* } => {
313                        #builder
314                        #(#calls)*
315                        __debug_builder.finish()
316                    }
317                }
318            }
319            Fields::Unnamed(unnamed) => {
320                let bindings: Vec<syn::Ident> = (0..unnamed.unnamed.len())
321                    .map(|index| format_ident!("__self_{index}"))
322                    .collect();
323                let calls = bindings.iter().map(|binding| quote! { __debug_builder.field(#binding); });
324                let builder = debug_builder_init("debug_tuple", &variant_name);
325                quote! {
326                    Self::#variant_ident( #(#bindings),* ) => {
327                        #builder
328                        #(#calls)*
329                        __debug_builder.finish()
330                    }
331                }
332            }
333        }
334    });
335    quote! {
336        match self {
337            #(#arms)*
338        }
339    }
340}
341
342/// `Debug` body for a unit-only enum: write a name sliced out of one
343/// space-delimited string. Offsets are byte offsets computed from the variant
344/// names, and the delimiter is found with an ASCII byte scan (no UTF-8 iterator
345/// or panic-formatting machinery). Raw-identifier prefixes are stripped so the
346/// output matches the built-in derive.
347fn fmt_body_c_like_enum(data: &DataEnum) -> TokenStream2 {
348    let mut names = String::new();
349    let mut offset = 0usize;
350    let mut arms = Vec::with_capacity(data.variants.len());
351    for variant in &data.variants {
352        let variant_ident = &variant.ident;
353        let name = field_name(variant_ident);
354        if !names.is_empty() {
355            names.push(' ');
356        }
357        names.push_str(&name);
358        arms.push(quote! { Self::#variant_ident => #offset, });
359        offset += name.len() + 1;
360    }
361
362    let lookup = name_lookup(&names);
363    quote! {
364        #lookup
365        let __start: usize = match self {
366            #(#arms)*
367        };
368        f.write_str(__name_at(__start))
369    }
370}
371
372/// Shared name table plus a panic-free ASCII byte-scan lookup for both large-enum
373/// paths. `Option::get` avoids the UTF-8 error formatting that string indexing
374/// pulls into embedded binaries (upstream issue #165189).
375fn name_lookup(names: &str) -> TokenStream2 {
376    quote! {
377        const __NAMES: &str = #names;
378        fn __name_at(__start: usize) -> &'static str {
379            let __tail = __NAMES.get(__start..).unwrap_or_default();
380            let __end = __tail
381                .as_bytes()
382                .iter()
383                .position(|byte| *byte == b' ')
384                .unwrap_or(__tail.len());
385            __tail.get(..__end).unwrap_or_default()
386        }
387    }
388}
389
390/// `Debug` body for a large enum with at least one data-carrying variant. Like
391/// the unit-only path, variant names live in one space-delimited string and the
392/// name is recovered by an ASCII byte scan; each arm then hands that name to the
393/// matching `std` builder. The name must be passed to the builder rather than
394/// written separately: `debug_tuple("")` adds a trailing comma for a single
395/// field, so an empty-name builder would diverge from the built-in derive.
396fn fmt_body_mixed_enum(data: &DataEnum) -> TokenStream2 {
397    let mut names = String::new();
398    let mut arms = Vec::with_capacity(data.variants.len());
399    for variant in &data.variants {
400        let variant_ident = &variant.ident;
401        if !names.is_empty() {
402            names.push(' ');
403        }
404        let start = names.len();
405        names.push_str(&field_name(variant_ident));
406
407        let arm = match &variant.fields {
408            Fields::Unit => quote! {
409                Self::#variant_ident => {
410                    let __variant_name = __name_at(#start);
411                    f.write_str(__variant_name)
412                }
413            },
414            Fields::Named(named) => {
415                let pairs: Vec<(syn::Ident, syn::Ident)> = named
416                    .named
417                    .iter()
418                    .enumerate()
419                    .filter_map(|(index, field)| {
420                        let ident = field.ident.as_ref()?.clone();
421                        Some((ident, format_ident!("__self_{index}")))
422                    })
423                    .collect();
424                let pattern = pairs.iter().map(|(ident, binding)| quote! { #ident: #binding });
425                let calls = pairs.iter().map(|(ident, binding)| {
426                    let field_name = field_name(ident);
427                    quote! { __debug_builder.field(#field_name, #binding); }
428                });
429                quote! {
430                    Self::#variant_ident { #(#pattern),* } => {
431                        let __variant_name = __name_at(#start);
432                        let mut __debug_builder = f.debug_struct(__variant_name);
433                        #(#calls)*
434                        __debug_builder.finish()
435                    }
436                }
437            }
438            Fields::Unnamed(unnamed) => {
439                let bindings: Vec<syn::Ident> = (0..unnamed.unnamed.len())
440                    .map(|index| format_ident!("__self_{index}"))
441                    .collect();
442                let calls = bindings.iter().map(|binding| quote! { __debug_builder.field(#binding); });
443                quote! {
444                    Self::#variant_ident( #(#bindings),* ) => {
445                        let __variant_name = __name_at(#start);
446                        let mut __debug_builder = f.debug_tuple(__variant_name);
447                        #(#calls)*
448                        __debug_builder.finish()
449                    }
450                }
451            }
452        };
453        arms.push(arm);
454    }
455
456    let lookup = name_lookup(&names);
457    quote! {
458        #lookup
459        match self {
460            #(#arms)*
461        }
462    }
463}
464
465/// Emit `let mut __debug_builder = f.<kind>("<name>");`. The builder is always
466/// `mut` because `field(...)` and `finish(...)` both take `&mut self`.
467fn debug_builder_init(kind: &str, name: &str) -> TokenStream2 {
468    let kind = format_ident!("{kind}");
469    quote! { let mut __debug_builder = f.#kind(#name); }
470}