vtcode-macros 0.185.5

Procedural macros for VT Code
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
#![allow(
    missing_docs,
    reason = "Intentional compatibility, platform, or test-only suppression."
)]
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use syn::{Data, DataEnum, DeriveInput, Fields, parse_macro_input};

/// Minimum variant count before an enum uses the concatenated-name `Debug`
/// strategy. The strategy has a fixed cost (name string + byte scan), so it only
/// wins once the per-arm costs of the built-in derive dominate.
const CONCATENATED_NAMES_THRESHOLD: usize = 8;

/// Derive macro that generates the same boilerplate as the `string_newtype!`
/// declarative macro. Apply to a tuple struct wrapping a single `String` field.
///
/// Generates:
/// - Inherent methods: `new()`, `as_str()`, `into_inner()`
/// - `Deref<Target = str>`
/// - `Borrow<str>`
/// - `AsRef<str>`
/// - `Display`
/// - `From<String>`, `From<&str>`, `From<Self> for String`
///
/// # Example
///
/// ```rust,ignore
/// #[derive(Debug, Clone, Serialize, Deserialize, StringNewtype)]
/// #[serde(transparent)]
/// pub struct SessionId(String);
/// ```
#[proc_macro_derive(StringNewtype)]
pub fn derive_string_newtype(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    impl_string_newtype(&input).unwrap_or_else(|err| err.to_compile_error().into())
}

fn impl_string_newtype(input: &DeriveInput) -> syn::Result<TokenStream> {
    let name = &input.ident;

    // Validate: must be a tuple struct with exactly one String field.
    let field_type = match &input.data {
        Data::Struct(data) => match &data.fields {
            Fields::Unnamed(fields) => {
                if fields.unnamed.len() != 1 {
                    return Err(syn::Error::new_spanned(
                        name,
                        "StringNewtype requires a tuple struct with exactly one field",
                    ));
                }
                let Some(field) = fields.unnamed.first() else {
                    return Err(syn::Error::new_spanned(
                        name,
                        "StringNewtype requires a tuple struct with exactly one field",
                    ));
                };
                &field.ty
            }
            _ => {
                return Err(syn::Error::new_spanned(name, "StringNewtype can only be derived for tuple structs"));
            }
        },
        _ => {
            return Err(syn::Error::new_spanned(name, "StringNewtype can only be derived for structs"));
        }
    };

    // Verify the inner type is String.
    if !is_string_type(field_type) {
        return Err(syn::Error::new_spanned(field_type, "StringNewtype requires the inner type to be String"));
    }

    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

    let output = quote! {
        impl #impl_generics #name #ty_generics #where_clause {
            /// Create a new instance from any value that converts to `String`.
            pub fn new(value: impl Into<String>) -> Self {
                Self(value.into())
            }

            /// Borrow the inner string as a `&str`.
            pub fn as_str(&self) -> &str {
                &self.0
            }

            /// Consume the wrapper and return the inner `String`.
            pub fn into_inner(self) -> String {
                self.0
            }
        }

        impl #impl_generics std::ops::Deref for #name #ty_generics #where_clause {
            type Target = str;

            fn deref(&self) -> &Self::Target {
                &self.0
            }
        }

        impl #impl_generics std::borrow::Borrow<str> for #name #ty_generics #where_clause {
            fn borrow(&self) -> &str {
                &self.0
            }
        }

        impl #impl_generics AsRef<str> for #name #ty_generics #where_clause {
            fn as_ref(&self) -> &str {
                &self.0
            }
        }

        impl #impl_generics std::fmt::Display for #name #ty_generics #where_clause {
            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
                self.0.fmt(f)
            }
        }

        impl #impl_generics From<String> for #name #ty_generics #where_clause {
            fn from(value: String) -> Self {
                Self(value)
            }
        }

        impl #impl_generics From<&str> for #name #ty_generics #where_clause {
            fn from(value: &str) -> Self {
                Self(value.to_string())
            }
        }

        impl #impl_generics From<#name #ty_generics> for String #where_clause {
            fn from(value: #name #ty_generics) -> Self {
                value.0
            }
        }
    };

    Ok(output.into())
}

fn is_string_type(ty: &syn::Type) -> bool {
    if let syn::Type::Path(type_path) = ty
        && type_path.qself.is_none()
        && type_path.path.segments.len() == 1
    {
        return type_path.path.segments.first().is_some_and(|segment| segment.ident == "String");
    }
    false
}

/// Derive macro equivalent to `#[derive(Debug)]` but with `#[inline(never)]` on
/// the generated `fmt` implementation.
///
/// Rust's built-in `Debug` derive emits `#[inline]` on `fmt`. For large or deeply
/// nested types — typically error enums formatted on fan-out paths — that lets
/// `rustc` inline the whole `Debug` tree into every `{:?}` / `?err` call site,
/// which can bloat binary size. This derive preserves the exact `Debug` output;
/// it changes the inlining hint and, for large enums, the shape of the generated
/// body (see below).
///
/// Enums with at least `CONCATENATED_NAMES_THRESHOLD` variants additionally emit
/// one space-delimited name string and look variant names up by byte offset,
/// instead of one `"<name>"` literal per arm. This removes the per-arm string
/// literals and temporary locals that make derived `Debug` expensive to compile
/// and large in the binary; the output is still byte-identical to the built-in
/// derive. Data-carrying variants keep their normal `debug_tuple`/`debug_struct`
/// formatting, with the name passed in from the shared string.
///
/// Use it for large/nested types whose `Debug` is formatted in hot or fan-out
/// paths; keep `#[derive(Debug)]` for small, hot, leaf types. See
/// `docs/development/rust-performance-principles.md`, "Derived trait impls are
/// `#[inline]`".
///
/// # Example
///
/// ```rust,ignore
/// use vtcode_macros::DebugNoInline;
///
/// #[derive(DebugNoInline)]
/// pub struct Widgets {
///     foo: u32,
///     bar: usize,
/// }
///
/// assert_eq!(
///     format!("{:?}", Widgets { foo: 1, bar: 2 }),
///     "Widgets { foo: 1, bar: 2 }"
/// );
/// ```
#[proc_macro_derive(DebugNoInline)]
pub fn derive_debug_no_inline(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    match impl_debug_no_inline(&input) {
        Ok(tokens) => tokens.into(),
        Err(err) => err.to_compile_error().into(),
    }
}

fn impl_debug_no_inline(input: &DeriveInput) -> syn::Result<TokenStream2> {
    let name = &input.ident;

    // Mirror the built-in derive: bound every type parameter on `Debug`.
    let mut generics = input.generics.clone();
    for param in generics.type_params_mut() {
        param.bounds.push(syn::parse_quote!(::core::fmt::Debug));
    }
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    let body = match &input.data {
        Data::Struct(data) => fmt_body_struct(&name.to_string(), &data.fields),
        Data::Enum(data) => fmt_body_enum(data),
        Data::Union(_) => {
            return Err(syn::Error::new_spanned(name, "DebugNoInline cannot be derived for unions"));
        }
    };

    Ok(quote! {
        #[automatically_derived]
        impl #impl_generics ::core::fmt::Debug for #name #ty_generics #where_clause {
            #[inline(never)]
            fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                #body
            }
        }
    })
}

/// Debug name for a field: strip a raw-identifier prefix so `r#type` renders as
/// `type`, matching the built-in derive.
fn field_name(ident: &syn::Ident) -> String {
    let raw = ident.to_string();
    raw.trim_prefix("r#").to_string()
}

fn fmt_body_struct(type_name: &str, fields: &Fields) -> TokenStream2 {
    match fields {
        Fields::Unit => quote! { f.write_str(#type_name) },
        Fields::Named(named) => {
            let calls = named.named.iter().filter_map(|field| {
                let ident = field.ident.as_ref()?;
                let field_name = field_name(ident);
                Some(quote! { __debug_builder.field(#field_name, &self.#ident); })
            });
            let builder = debug_builder_init("debug_struct", type_name);
            quote! {
                #builder
                #(#calls)*
                __debug_builder.finish()
            }
        }
        Fields::Unnamed(unnamed) => {
            let calls = unnamed.unnamed.iter().enumerate().map(|(index, _)| {
                let index = syn::Index::from(index);
                quote! { __debug_builder.field(&self.#index); }
            });
            let builder = debug_builder_init("debug_tuple", type_name);
            quote! {
                #builder
                #(#calls)*
                __debug_builder.finish()
            }
        }
    }
}

fn fmt_body_enum(data: &DataEnum) -> TokenStream2 {
    // An uninhabited enum has no variants to match. `match self {}` is not
    // exhaustive because `&Never` is inhabited, so dereference: `match *self {}`.
    if data.variants.is_empty() {
        return quote! { match *self {} };
    }

    // Large enums are the pathological case for the built-in derive: match
    // checking is quadratic in arm count and borrow checking allocates a temp
    // local for every string-literal arm. Emit one name string plus byte offsets
    // instead (the strategy upstream adopted for `derive(Debug)`). Keep a match
    // rather than using `discriminant_value`: attribute macros such as `bitflags`
    // can rewrite discriminants after the derive runs, which would make offsets
    // point at the wrong names.
    if data.variants.len() >= CONCATENATED_NAMES_THRESHOLD {
        if data.variants.iter().all(|variant| matches!(variant.fields, Fields::Unit)) {
            return fmt_body_c_like_enum(data);
        }
        return fmt_body_mixed_enum(data);
    }

    let arms = data.variants.iter().map(|variant| {
        let variant_ident = &variant.ident;
        let variant_name = field_name(variant_ident);
        match &variant.fields {
            Fields::Unit => quote! {
                Self::#variant_ident => f.write_str(#variant_name),
            },
            Fields::Named(named) => {
                let pairs: Vec<(syn::Ident, syn::Ident)> = named
                    .named
                    .iter()
                    .enumerate()
                    .filter_map(|(index, field)| {
                        let ident = field.ident.as_ref()?.clone();
                        Some((ident, format_ident!("__self_{index}")))
                    })
                    .collect();
                let pattern = pairs.iter().map(|(ident, binding)| quote! { #ident: #binding });
                let calls = pairs.iter().map(|(ident, binding)| {
                    let field_name = field_name(ident);
                    quote! { __debug_builder.field(#field_name, #binding); }
                });
                let builder = debug_builder_init("debug_struct", &variant_name);
                quote! {
                    Self::#variant_ident { #(#pattern),* } => {
                        #builder
                        #(#calls)*
                        __debug_builder.finish()
                    }
                }
            }
            Fields::Unnamed(unnamed) => {
                let bindings: Vec<syn::Ident> = (0..unnamed.unnamed.len())
                    .map(|index| format_ident!("__self_{index}"))
                    .collect();
                let calls = bindings.iter().map(|binding| quote! { __debug_builder.field(#binding); });
                let builder = debug_builder_init("debug_tuple", &variant_name);
                quote! {
                    Self::#variant_ident( #(#bindings),* ) => {
                        #builder
                        #(#calls)*
                        __debug_builder.finish()
                    }
                }
            }
        }
    });
    quote! {
        match self {
            #(#arms)*
        }
    }
}

/// `Debug` body for a unit-only enum: write a name sliced out of one
/// space-delimited string. Offsets are byte offsets computed from the variant
/// names, and the delimiter is found with an ASCII byte scan (no UTF-8 iterator
/// or panic-formatting machinery). Raw-identifier prefixes are stripped so the
/// output matches the built-in derive.
fn fmt_body_c_like_enum(data: &DataEnum) -> TokenStream2 {
    let mut names = String::new();
    let mut offset = 0usize;
    let mut arms = Vec::with_capacity(data.variants.len());
    for variant in &data.variants {
        let variant_ident = &variant.ident;
        let name = field_name(variant_ident);
        if !names.is_empty() {
            names.push(' ');
        }
        names.push_str(&name);
        arms.push(quote! { Self::#variant_ident => #offset, });
        offset += name.len() + 1;
    }

    let lookup = name_lookup(&names);
    quote! {
        #lookup
        let __start: usize = match self {
            #(#arms)*
        };
        f.write_str(__name_at(__start))
    }
}

/// Shared name table plus a panic-free ASCII byte-scan lookup for both large-enum
/// paths. `Option::get` avoids the UTF-8 error formatting that string indexing
/// pulls into embedded binaries (upstream issue #165189).
fn name_lookup(names: &str) -> TokenStream2 {
    quote! {
        const __NAMES: &str = #names;
        fn __name_at(__start: usize) -> &'static str {
            let __tail = __NAMES.get(__start..).unwrap_or_default();
            let __end = __tail
                .as_bytes()
                .iter()
                .position(|byte| *byte == b' ')
                .unwrap_or(__tail.len());
            __tail.get(..__end).unwrap_or_default()
        }
    }
}

/// `Debug` body for a large enum with at least one data-carrying variant. Like
/// the unit-only path, variant names live in one space-delimited string and the
/// name is recovered by an ASCII byte scan; each arm then hands that name to the
/// matching `std` builder. The name must be passed to the builder rather than
/// written separately: `debug_tuple("")` adds a trailing comma for a single
/// field, so an empty-name builder would diverge from the built-in derive.
fn fmt_body_mixed_enum(data: &DataEnum) -> TokenStream2 {
    let mut names = String::new();
    let mut arms = Vec::with_capacity(data.variants.len());
    for variant in &data.variants {
        let variant_ident = &variant.ident;
        if !names.is_empty() {
            names.push(' ');
        }
        let start = names.len();
        names.push_str(&field_name(variant_ident));

        let arm = match &variant.fields {
            Fields::Unit => quote! {
                Self::#variant_ident => {
                    let __variant_name = __name_at(#start);
                    f.write_str(__variant_name)
                }
            },
            Fields::Named(named) => {
                let pairs: Vec<(syn::Ident, syn::Ident)> = named
                    .named
                    .iter()
                    .enumerate()
                    .filter_map(|(index, field)| {
                        let ident = field.ident.as_ref()?.clone();
                        Some((ident, format_ident!("__self_{index}")))
                    })
                    .collect();
                let pattern = pairs.iter().map(|(ident, binding)| quote! { #ident: #binding });
                let calls = pairs.iter().map(|(ident, binding)| {
                    let field_name = field_name(ident);
                    quote! { __debug_builder.field(#field_name, #binding); }
                });
                quote! {
                    Self::#variant_ident { #(#pattern),* } => {
                        let __variant_name = __name_at(#start);
                        let mut __debug_builder = f.debug_struct(__variant_name);
                        #(#calls)*
                        __debug_builder.finish()
                    }
                }
            }
            Fields::Unnamed(unnamed) => {
                let bindings: Vec<syn::Ident> = (0..unnamed.unnamed.len())
                    .map(|index| format_ident!("__self_{index}"))
                    .collect();
                let calls = bindings.iter().map(|binding| quote! { __debug_builder.field(#binding); });
                quote! {
                    Self::#variant_ident( #(#bindings),* ) => {
                        let __variant_name = __name_at(#start);
                        let mut __debug_builder = f.debug_tuple(__variant_name);
                        #(#calls)*
                        __debug_builder.finish()
                    }
                }
            }
        };
        arms.push(arm);
    }

    let lookup = name_lookup(&names);
    quote! {
        #lookup
        match self {
            #(#arms)*
        }
    }
}

/// Emit `let mut __debug_builder = f.<kind>("<name>");`. The builder is always
/// `mut` because `field(...)` and `finish(...)` both take `&mut self`.
fn debug_builder_init(kind: &str, name: &str) -> TokenStream2 {
    let kind = format_ident!("{kind}");
    quote! { let mut __debug_builder = f.#kind(#name); }
}