macroforge_ts 0.1.78

TypeScript macro expansion engine - write compile-time macros in Rust
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
//! # Default Macro Implementation
//!
//! The `Default` macro generates a static `defaultValue()` factory method that creates
//! instances with default values. This is analogous to Rust's `Default` trait, providing
//! a standard way to create "zero" or "empty" instances of types.
//!
//! ## Generated Output
//!
//! | Type | Generated Code | Description |
//! |------|----------------|-------------|
//! | Class | `static defaultValue()` + `{className}DefaultValue()` | Static factory method + standalone function |
//! | Enum | `{enumName}DefaultValue(): EnumName` | Standalone function returning `@default` variant |
//! | Interface | `{ifaceName}DefaultValue(): InterfaceName` | Standalone function returning object literal |
//! | Type Alias | `{typeName}DefaultValue(): TypeName` | Standalone function with type-appropriate default |
//!
//! Names use **camelCase** conversion (e.g., `UserSettings` → `userSettingsDefaultValue`).
//!
//!
//! ## Default Values by Type
//!
//! The macro uses Rust-like default semantics:
//!
//! | Type | Default Value |
//! |------|---------------|
//! | `string` | `""` (empty string) |
//! | `number` | `0` |
//! | `boolean` | `false` |
//! | `bigint` | `0n` |
//! | `T[]` | `[]` (empty array) |
//! | `Array<T>` | `[]` (empty array) |
//! | `Map<K,V>` | `new Map()` |
//! | `Set<T>` | `new Set()` |
//! | `Date` | `new Date()` (current time) |
//! | `T \| null` | `null` |
//! | `CustomType` | `CustomType.defaultValue()` (recursive) |
//!
//! ## Field-Level Options
//!
//! The `@default` decorator allows specifying explicit default values:
//!
//! - `@default(42)` - Use 42 as the default
//! - `@default("hello")` - Use "hello" as the default
//! - `@default([])` - Use empty array as the default
//! - `@default({ value: "test" })` - Named form for complex values
//!
//! ## Example
//!
//! ```typescript
//! /** @derive(Default) */
//! class UserSettings {
//!     /** @default("light") */
//!     theme: string;
//!
//!     /** @default(10) */
//!     pageSize: number;
//!
//!     notifications: boolean;  // Uses type default: false
//! }
//! ```
//!
//! Generated output:
//!
//! ```typescript
//! class UserSettings {
//!     theme: string;
//!
//!     pageSize: number;
//!
//!     notifications: boolean; // Uses type default: false
//!
//!     static defaultValue(): UserSettings {
//!         const instance = new UserSettings();
//!         instance.theme = 'light';
//!         instance.pageSize = 10;
//!         instance.notifications = false;
//!         return instance;
//!     }
//! }
//!
//! export function userSettingsDefaultValue(): UserSettings {
//!     return UserSettings.defaultValue();
//! }
//! ```
//!
//! ## Enum Defaults
//!
//! For enums, mark one variant with `@default`:
//!
//! ```typescript
//! /** @derive(Default) */
//! enum Status {
//!     /** @default */
//!     Pending,
//!     Active,
//!     Completed
//! }
//! ```
//!
//! Generated output:
//!
//! ```typescript
//! enum Status {
//!     /** @default */
//!     Pending,
//!     Active,
//!     Completed
//! }
//!
//! export function statusDefaultValue(): Status {
//!     return Status.Pending;
//! }
//! ```
//!
//! ## Error Handling
//!
//! The macro will return an error if:
//!
//! - A non-primitive field lacks `@default` and has no known default
//! - An enum has no variant marked with `@default`
//! - A union type has no `@default` on a variant

use convert_case::{Case, Casing};

use crate::builtin::derive_common::{
    DefaultFieldOptions, get_type_default, has_known_default, is_primitive_type, type_has_derive,
};
use crate::macros::{ts_macro_derive, ts_template};
use crate::swc_ecma_ast::{Expr, Ident};
use crate::ts_syn::abi::ir::type_registry::TypeRegistry;
use crate::ts_syn::ts_ident;
use crate::ts_syn::{
    Data, DeriveInput, MacroforgeError, TsStream, emit_expr, parse_ts_expr, parse_ts_macro_input,
};

/// Contains field information needed for default value generation.
///
/// Each non-optional field that needs a default value is represented by this struct,
/// capturing both the field name and the expression to use as its default value.
struct DefaultField {
    /// The field name as it appears in the source TypeScript class.
    /// Used to generate assignment statements like `instance.name = value`.
    name: String,

    /// The JavaScript expression for the default value.
    /// This can be a literal (`0`, `""`, `[]`), a constructor call (`new Date()`),
    /// or a recursive `defaultValue()` call for custom types.
    value: String,
}

/// Emit compile-time warnings for fields whose types are in the type registry
/// but do not derive `Default`. The generated code will still call `typeNameDefaultValue()`,
/// which may fail at runtime if the type doesn't actually provide that function.
fn validate_default_fields(
    fields: &[(String, String)], // (field_name, ts_type)
    parent_name: &str,
    registry: Option<&TypeRegistry>,
) {
    let registry = match registry {
        Some(r) => r,
        None => return,
    };

    for (field_name, ts_type) in fields {
        let t = ts_type.trim();
        // Only check non-primitive, non-collection types
        if is_primitive_type(t)
            || t.ends_with("[]")
            || t.starts_with("Array<")
            || t.starts_with("Map<")
            || t.starts_with("Set<")
            || t == "Date"
            || t.contains('|')
        {
            continue;
        }

        // Check if the type is in the registry (use get or get_all for ambiguous names)
        let type_known = registry.get(t).is_some() || registry.get_all(t).next().is_some();
        if type_known && !type_has_derive(registry, t, "Default") {
            eprintln!(
                "[macroforge] warning: field `{field_name}` in `{parent_name}` has type `{t}` \
                 which does not derive Default — generated code may fail at runtime"
            );
        }
    }
}

#[ts_macro_derive(
    Default,
    description = "Generates a static defaultValue() factory method",
    attributes(default)
)]
pub fn derive_default_macro(mut input: TsStream) -> Result<TsStream, MacroforgeError> {
    let input = parse_ts_macro_input!(input as DeriveInput);
    let type_registry = input.context.type_registry.as_ref();

    match &input.data {
        Data::Class(class) => {
            let class_name = input.name();
            let class_ident = ts_ident!(class_name);
            let class_expr: Expr = class_ident.clone().into();

            // Validate fields against type registry (emit warnings for types missing Default)
            let fields_to_validate: Vec<(String, String)> = class
                .fields()
                .iter()
                .filter(|f| {
                    !f.optional && !DefaultFieldOptions::from_decorators(&f.decorators).has_default
                })
                .map(|f| (f.name.clone(), f.ts_type.clone()))
                .collect();
            validate_default_fields(&fields_to_validate, class_name, type_registry);

            // Check for required non-primitive fields missing @default (like Rust's derive(Default))
            let missing_defaults: Vec<&str> = class
                .fields()
                .iter()
                .filter(|field| {
                    // Skip optional fields
                    if field.optional {
                        return false;
                    }
                    // Skip if has explicit @default
                    if DefaultFieldOptions::from_decorators(&field.decorators).has_default {
                        return false;
                    }
                    // Skip if type has known default (primitives, collections, nullable)
                    if has_known_default(&field.ts_type) {
                        return false;
                    }
                    // This field needs @default but doesn't have it
                    true
                })
                .map(|f| f.name.as_str())
                .collect();

            if !missing_defaults.is_empty() {
                return Err(MacroforgeError::new(
                    input.decorator_span(),
                    format!(
                        "@derive(Default) cannot determine default for non-primitive fields. Add @default(value) to: {}",
                        missing_defaults.join(", ")
                    ),
                ));
            }

            // Build defaults for ALL non-optional fields by parsing expressions and generating class body
            // Parse all field default expressions upfront for validation (before template generation)
            let field_data: Vec<(Ident, Expr)> = class
                .fields()
                .iter()
                .filter(|field| !field.optional)
                .map(|field| {
                    let opts = DefaultFieldOptions::from_decorators(&field.decorators);
                    let default_value = opts
                        .value
                        .unwrap_or_else(|| get_type_default(&field.ts_type));

                    let value_expr = parse_ts_expr(&default_value).map_err(|err| {
                        MacroforgeError::new(
                            input.decorator_span(),
                            format!(
                                "@derive(Default): invalid default expression for '{}': {err:?}",
                                field.name
                            ),
                        )
                    })?;
                    Ok((ts_ident!(field.name.as_str()), *value_expr))
                })
                .collect::<Result<_, MacroforgeError>>()?;

            // Generate the method body using parsed field data
            // Note: field_data is consumed by the body! macro below
            let _ = &field_data; // Explicitly mark as used to satisfy clippy
            let class_body = ts_template!(Within {
                static defaultValue(): @{class_ident.clone()} {
                    const instance = new @{class_expr.clone()}();
                    {#for (name_ident, value_expr) in field_data}
                        instance.@{name_ident} = @{value_expr};
                    {/for}
                    return instance;
                }
            });

            // Also generate standalone function for consistency
            // Using {$typescript} to compose TsStream objects
            let fn_name_ident = ts_ident!("{}DefaultValue", class_name.to_case(Case::Camel));
            Ok(ts_template! {
                {$typescript class_body}

                export function @{fn_name_ident}(): @{class_ident.clone()} {
                    return @{class_expr.clone()}.defaultValue();
                }
            })
        }
        Data::Enum(enum_data) => {
            let enum_name = input.name();
            let enum_ident = ts_ident!(enum_name);

            // Find variant with @default attribute (like Rust's #[default] on enums)
            let default_variant = enum_data.variants().iter().find(|v| {
                v.decorators
                    .iter()
                    .any(|d| d.name.eq_ignore_ascii_case("default"))
            });

            match default_variant {
                Some(variant) => {
                    let variant_name = &variant.name;
                    let fn_name_ident = ts_ident!("{}DefaultValue", enum_name.to_case(Case::Camel));
                    let enum_expr: Expr = ts_ident!(enum_name).into();
                    let variant_ident = ts_ident!(variant_name.as_str());
                    Ok(ts_template! {
                        export function @{fn_name_ident}(): @{enum_ident} {
                            return @{enum_expr}.@{variant_ident};
                        }
                    })
                }
                None => Err(MacroforgeError::new(
                    input.decorator_span(),
                    format!(
                        "@derive(Default) on enum requires exactly one variant with @default attribute. \
                        Add @default to one variant of {}",
                        enum_name
                    ),
                )),
            }
        }
        Data::Interface(interface) => {
            let interface_name = input.name();
            let interface_ident = ts_ident!(interface_name);

            // Validate fields against type registry (emit warnings for types missing Default)
            let fields_to_validate: Vec<(String, String)> = interface
                .fields()
                .iter()
                .filter(|f| {
                    !f.optional && !DefaultFieldOptions::from_decorators(&f.decorators).has_default
                })
                .map(|f| (f.name.clone(), f.ts_type.clone()))
                .collect();
            validate_default_fields(&fields_to_validate, interface_name, type_registry);

            // Check for required non-primitive fields missing @default (like Rust's derive(Default))
            let missing_defaults: Vec<&str> = interface
                .fields()
                .iter()
                .filter(|field| {
                    // Skip optional fields
                    if field.optional {
                        return false;
                    }
                    // Skip if has explicit @default
                    if DefaultFieldOptions::from_decorators(&field.decorators).has_default {
                        return false;
                    }
                    // Skip if type has known default (primitives, collections, nullable)
                    if has_known_default(&field.ts_type) {
                        return false;
                    }
                    // This field needs @default but doesn't have it
                    true
                })
                .map(|f| f.name.as_str())
                .collect();

            if !missing_defaults.is_empty() {
                return Err(MacroforgeError::new(
                    input.decorator_span(),
                    format!(
                        "@derive(Default) cannot determine default for non-primitive fields. Add @default(value) to: {}",
                        missing_defaults.join(", ")
                    ),
                ));
            }

            // Build defaults for ALL non-optional fields
            let default_fields: Vec<DefaultField> = interface
                .fields()
                .iter()
                .filter(|field| !field.optional)
                .map(|field| {
                    let opts = DefaultFieldOptions::from_decorators(&field.decorators);
                    DefaultField {
                        name: field.name.clone(),
                        value: opts
                            .value
                            .unwrap_or_else(|| get_type_default(&field.ts_type)),
                    }
                })
                .collect();

            let has_defaults = !default_fields.is_empty();

            let fn_name_ident = ts_ident!("{}DefaultValue", interface_name.to_case(Case::Camel));

            if has_defaults {
                let object_fields: Vec<(Ident, Expr)> = default_fields
                    .iter()
                    .map(|f| {
                        let value_expr = parse_ts_expr(&f.value).map_err(|err| {
                            MacroforgeError::new(
                                input.decorator_span(),
                                format!(
                                    "@derive(Default): invalid default expression for '{}': {err:?}",
                                    f.name
                                ),
                            )
                        })?;
                        Ok((ts_ident!(f.name.as_str()), *value_expr))
                    })
                    .collect::<Result<_, MacroforgeError>>()?;

                let mut props = String::new();
                for (name_ident, value_expr) in &object_fields {
                    let name = name_ident.sym.as_ref();
                    let value = emit_expr(value_expr);
                    props.push_str(&format!("{name}: {value},\n"));
                }

                let return_stmt = format!("return {{\n{props}}} as {interface_name};");
                let return_stmt_stream = TsStream::from_string(return_stmt);

                Ok(ts_template! {
                    export function @{fn_name_ident}(): @{interface_ident.clone()} {
                        {$typescript return_stmt_stream}
                    }
                })
            } else {
                let return_stmt = format!("return {{}} as {interface_name};");
                let return_stmt_stream = TsStream::from_string(return_stmt);

                Ok(ts_template! {
                    export function @{fn_name_ident}(): @{interface_ident.clone()} {
                        {$typescript return_stmt_stream}
                    }
                })
            }
        }
        Data::TypeAlias(type_alias) => {
            let type_name = input.name();

            // Build generic type signature if type has type params
            let type_params = type_alias.type_params();
            let (generic_decl, generic_args) = if type_params.is_empty() {
                (String::new(), String::new())
            } else {
                let params = type_params.join(", ");
                (format!("<{}>", params), format!("<{}>", params))
            };
            let full_type_name = format!("{}{}", type_name, generic_args);
            let full_type_ident = ts_ident!(full_type_name.as_str());
            let generic_decl_ident = ts_ident!(generic_decl.as_str());

            if type_alias.is_object() {
                let fields = type_alias.as_object().unwrap();

                // Validate fields against type registry (emit warnings for types missing Default)
                let fields_to_validate: Vec<(String, String)> = fields
                    .iter()
                    .filter(|f| {
                        !f.optional
                            && !DefaultFieldOptions::from_decorators(&f.decorators).has_default
                    })
                    .map(|f| (f.name.clone(), f.ts_type.clone()))
                    .collect();
                validate_default_fields(&fields_to_validate, type_name, type_registry);

                // Check for required non-primitive fields missing @default (like Rust's derive(Default))
                let missing_defaults: Vec<&str> = fields
                    .iter()
                    .filter(|field| {
                        // Skip optional fields
                        if field.optional {
                            return false;
                        }
                        // Skip if has explicit @default
                        if DefaultFieldOptions::from_decorators(&field.decorators).has_default {
                            return false;
                        }
                        // Skip if type has known default (primitives, collections, nullable)
                        if has_known_default(&field.ts_type) {
                            return false;
                        }
                        // This field needs @default but doesn't have it
                        true
                    })
                    .map(|f| f.name.as_str())
                    .collect();

                if !missing_defaults.is_empty() {
                    return Err(MacroforgeError::new(
                        input.decorator_span(),
                        format!(
                            "@derive(Default) cannot determine default for non-primitive fields. Add @default(value) to: {}",
                            missing_defaults.join(", ")
                        ),
                    ));
                }

                // Build defaults for ALL non-optional fields
                let default_fields: Vec<DefaultField> = fields
                    .iter()
                    .filter(|field| !field.optional)
                    .map(|field| {
                        let opts = DefaultFieldOptions::from_decorators(&field.decorators);
                        DefaultField {
                            name: field.name.clone(),
                            value: opts
                                .value
                                .unwrap_or_else(|| get_type_default(&field.ts_type)),
                        }
                    })
                    .collect();

                let has_defaults = !default_fields.is_empty();

                let fn_name_ident = ts_ident!("{}DefaultValue", type_name.to_case(Case::Camel));

                if has_defaults {
                    let object_fields: Vec<(Ident, Expr)> = default_fields
                        .iter()
                        .map(|f| {
                            let value_expr = parse_ts_expr(&f.value).map_err(|err| {
                                MacroforgeError::new(
                                    input.decorator_span(),
                                    format!(
                                        "@derive(Default): invalid default expression for '{}': {err:?}",
                                        f.name
                                    ),
                                )
                            })?;
                            Ok((ts_ident!(f.name.as_str()), *value_expr))
                        })
                        .collect::<Result<_, MacroforgeError>>()?;

                    let mut props = String::new();
                    for (name_ident, value_expr) in &object_fields {
                        let name = name_ident.sym.as_ref();
                        let value = emit_expr(value_expr);
                        props.push_str(&format!("{name}: {value},\n"));
                    }

                    let return_stmt = format!("return {{\n{props}}} as {full_type_name};");
                    let return_stmt_stream = TsStream::from_string(return_stmt);

                    Ok(ts_template! {
                        export function @{fn_name_ident}@{generic_decl_ident}(): @{full_type_ident.clone()} {
                            {$typescript return_stmt_stream}
                        }
                    })
                } else {
                    let return_stmt = format!("return {{}} as {full_type_name};");
                    let return_stmt_stream = TsStream::from_string(return_stmt);

                    Ok(ts_template! {
                        export function @{fn_name_ident}@{generic_decl_ident}(): @{full_type_ident.clone()} {
                            {$typescript return_stmt_stream}
                        }
                    })
                }
            } else if type_alias.is_union() {
                // Union type: check for @default on a variant OR @default(...) on the type
                let members = type_alias.as_union().unwrap();

                // Helper: build an object literal default from an inline object variant's fields
                fn build_object_default(fields: &[crate::ts_syn::InterfaceFieldIR]) -> String {
                    let props: Vec<String> = fields
                        .iter()
                        .map(|f| {
                            let opts = DefaultFieldOptions::from_decorators(&f.decorators);
                            let value = opts.value.unwrap_or_else(|| get_type_default(&f.ts_type));
                            format!("{}: {}", f.name, value)
                        })
                        .collect();
                    format!("({{ {} }})", props.join(", "))
                }

                // Check for parenthesized union members - can't place @default inside parens
                // e.g., `(string | Product) | (string | Service)` is not allowed
                let parenthesized: Vec<&str> = members
                    .iter()
                    .filter_map(|m| m.as_type_ref())
                    .filter(|t| t.trim().starts_with('('))
                    .collect();

                if !parenthesized.is_empty() {
                    return Err(MacroforgeError::new(
                        input.decorator_span(),
                        format!(
                            "@derive(Default): Parenthesized union expressions ({}) are not supported. \
                             Formatters cannot preserve doc comments inside parentheses. \
                             Create a named type alias for each variant instead \
                             (e.g., use `RecordLink<Product>` instead of `(string | Product)`).",
                            parenthesized.join(", ")
                        ),
                    ));
                }

                // First, look for a variant with @default decorator
                let default_variant_from_member = members.iter().find_map(|member| {
                    if member.has_decorator("default") {
                        // Named type (TypeRef or Literal) — use the type name
                        if let Some(name) = member.type_name() {
                            return Some(name.to_string());
                        }
                        // Object type (tagged union variant) — build an object literal
                        // with default values for each field
                        if let Some(fields) = member.as_object() {
                            return Some(build_object_default(fields));
                        }
                        None
                    } else {
                        None
                    }
                });

                // Fallback for tagged object unions where @default may not be
                // attached to the member: use the first object variant.
                let default_variant_from_member = default_variant_from_member.or_else(|| {
                    let all_objects = members.iter().all(|m| m.is_object());
                    if all_objects {
                        members
                            .first()
                            .and_then(|m| m.as_object())
                            .map(build_object_default)
                    } else {
                        None
                    }
                });

                // Fall back to @default(...) on the type alias itself
                let default_variant = default_variant_from_member.or_else(|| {
                    let default_opts = DefaultFieldOptions::from_decorators(
                        &input
                            .attrs
                            .iter()
                            .map(|a| a.inner.clone())
                            .collect::<Vec<_>>(),
                    );
                    default_opts.value
                });

                if let Some(variant) = default_variant {
                    if variant.is_empty() {
                        return Err(MacroforgeError::new(
                            input.decorator_span(),
                            format!(
                                "@derive(Default): resolved an empty default expression for union type '{}'. \
                                 Add @default on a variant or @default(expression) on the type.",
                                type_name
                            ),
                        ));
                    }
                    // Determine the default expression based on variant type
                    // Use as-is if it's already an expression, a literal, or a primitive value
                    let is_expression = variant.contains('.') || variant.contains('(');
                    let is_string_literal = variant.starts_with('"')
                        || variant.starts_with('\'')
                        || variant.starts_with('`');
                    let is_primitive_value = variant.parse::<f64>().is_ok()
                        || variant == "true"
                        || variant == "false"
                        || variant == "null";

                    let default_expr = if is_expression || is_string_literal || is_primitive_value {
                        variant // Use as-is
                    } else {
                        // Use get_type_default which properly handles all types:
                        // - Primitives (string, number, boolean, bigint)
                        // - Generic types (RecordLink<Service>)
                        // - Named types (CompanyName, PersonName - interfaces/classes)
                        get_type_default(&variant)
                    };

                    // Handle generic type aliases (e.g., type RecordLink<T> = ...)
                    let type_params = type_alias.type_params();
                    let has_generics = !type_params.is_empty();
                    let generic_params = if has_generics {
                        format!("<{}>", type_params.join(", "))
                    } else {
                        String::new()
                    };
                    let return_type = if has_generics {
                        format!("{}<{}>", type_name, type_params.join(", "))
                    } else {
                        type_name.to_string()
                    };
                    let return_type_ident = ts_ident!(return_type.as_str());
                    let generic_params_ident = ts_ident!(generic_params.as_str());

                    let fn_name_ident = ts_ident!("{}DefaultValue", type_name.to_case(Case::Camel));
                    let return_expr = parse_ts_expr(&default_expr).map_err(|err| {
                        MacroforgeError::new(
                            input.decorator_span(),
                            format!(
                                "@derive(Default): invalid default expression for '{}': {err:?}",
                                type_name
                            ),
                        )
                    })?;
                    Ok(ts_template! {
                        export function @{fn_name_ident}@{generic_params_ident}(): @{return_type_ident} {
                            return @{return_expr};
                        }
                    })
                } else {
                    Err(MacroforgeError::new(
                        input.decorator_span(),
                        format!(
                            "@derive(Default) on union type '{}' requires @default on one variant \
                            or @default(VariantName.defaultValue()) on the type.",
                            type_name
                        ),
                    ))
                }
            } else {
                // Tuple or simple alias: check for explicit @default(value)
                let default_opts = DefaultFieldOptions::from_decorators(
                    &input
                        .attrs
                        .iter()
                        .map(|a| a.inner.clone())
                        .collect::<Vec<_>>(),
                );

                if let Some(default_variant) = default_opts.value {
                    let fn_name_ident = ts_ident!("{}DefaultValue", type_name.to_case(Case::Camel));
                    let return_expr = parse_ts_expr(&default_variant).map_err(|err| {
                        MacroforgeError::new(
                            input.decorator_span(),
                            format!(
                                "@derive(Default): invalid default expression for '{}': {err:?}",
                                type_name
                            ),
                        )
                    })?;
                    Ok(ts_template! {
                        export function @{fn_name_ident}@{generic_decl_ident}(): @{full_type_ident.clone()} {
                            return @{return_expr};
                        }
                    })
                } else {
                    Err(MacroforgeError::new(
                        input.decorator_span(),
                        format!(
                            "@derive(Default) on type '{}' requires @default(value) to specify the default.",
                            type_name
                        ),
                    ))
                }
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_macro_output() {
        let class_name = "User";
        let class_ident = ts_ident!(class_name);

        let default_fields: Vec<DefaultField> = vec![
            DefaultField {
                name: "id".to_string(),
                value: "0".to_string(),
            },
            DefaultField {
                name: "name".to_string(),
                value: r#""""#.to_string(),
            },
        ];

        let output = ts_template!(Within {
            static defaultValue(): @{class_ident.clone()} {
                const instance = new @{class_ident.clone()}();
                {#if !default_fields.is_empty()}
                    {#for f in default_fields.iter()}
                        instance.@{ts_ident!(f.name.as_str())} = @{*parse_ts_expr(&f.value).expect("should parse")};
                    {/for}
                {/if}
                return instance;
            }
        });

        let source = output.source();
        let body_content = source
            .strip_prefix("/* @macroforge:body */")
            .unwrap_or(source);
        let wrapped = format!("class __Temp {{ {} }}", body_content);

        assert!(
            macroforge_ts_syn::parse_ts_stmt(&wrapped).is_ok(),
            "Generated Default macro output should parse as class members"
        );
        assert!(
            source.contains("defaultValue"),
            "Should contain defaultValue method"
        );
        assert!(source.contains("static"), "Should be a static method");
    }

    #[test]
    fn test_default_field_assignment() {
        let fields: Vec<DefaultField> = vec![
            DefaultField {
                name: "count".to_string(),
                value: "42".to_string(),
            },
            DefaultField {
                name: "items".to_string(),
                value: "[]".to_string(),
            },
        ];

        let assignments = fields
            .iter()
            .map(|f| format!("instance.{} = {};", f.name, f.value))
            .collect::<Vec<_>>()
            .join("\n");

        assert!(assignments.contains("instance.count = 42;"));
        assert!(assignments.contains("instance.items = [];"));
    }
}