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
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
//! # Shared Utilities for Derive Macros
//!
//! This module provides common functionality used by multiple derive macros,
//! including:
//!
//! - **Field options parsing**: `CompareFieldOptions`, `DefaultFieldOptions`
//! - **Type utilities**: Type checking and default value generation
//! - **Decorator parsing**: Flag extraction and named argument parsing
//!
//! ## Field Options
//!
//! Many macros support field-level customization through decorators:
//!
//! ```typescript
//! /** @derive(PartialEq, Hash, Default) */
//! class User {
//!     /** @partialEq({ skip: true }) @hash({ skip: true }) */
//!     cachedValue: number;
//!
//!     /** @default("guest") */
//!     name: string;
//! }
//! ```
//!
//! ## Type Defaults (Rust-like Philosophy)
//!
//! Like Rust's `Default` trait, this module assumes all types implement
//! default values:
//!
//! | Type | Default Value |
//! |------|---------------|
//! | `string` | `""` |
//! | `number` | `0` |
//! | `boolean` | `false` |
//! | `bigint` | `0n` |
//! | `T[]` | `[]` |
//! | `Map<K,V>` | `new Map()` |
//! | `Set<T>` | `new Set()` |
//! | `Date` | `new Date()` |
//! | `T \| null` | `null` |
//! | `CustomType` | `CustomType.defaultValue()` |

use convert_case::{Case, Casing};

use crate::builtin::serde::{TypeCategory, get_foreign_types, split_top_level_union};
use crate::ts_syn::abi::DecoratorIR;
use crate::ts_syn::abi::ir::type_registry::{
    ResolvedTypeRef, TypeDefinitionIR, TypeRegistry, TypeRegistryEntry,
};

/// Options parsed from field-level decorators for comparison macros
/// Supports @partialEq(skip), @hash(skip), @ord(skip)
#[derive(Default, Clone)]
pub struct CompareFieldOptions {
    pub skip: bool,
}

impl CompareFieldOptions {
    /// Parse field options from decorators for a specific attribute name
    pub fn from_decorators(decorators: &[DecoratorIR], attr_name: &str) -> Self {
        let mut opts = Self::default();
        for decorator in decorators {
            if !decorator.name.eq_ignore_ascii_case(attr_name) {
                continue;
            }
            let args = decorator.args_src.trim();
            if has_flag(args, "skip") {
                opts.skip = true;
            }
        }
        opts
    }
}

// ============================================================================
// Field Options for Default Macro
// ============================================================================

/// Options parsed from @default decorator on fields
#[derive(Default, Clone)]
pub struct DefaultFieldOptions {
    /// The default value expression (e.g., "0", "\"\"", "[]")
    pub value: Option<String>,
    /// Whether this field has a @default decorator
    pub has_default: bool,
}

impl DefaultFieldOptions {
    pub fn from_decorators(decorators: &[DecoratorIR]) -> Self {
        let mut opts = Self::default();
        for decorator in decorators {
            if !decorator.name.eq_ignore_ascii_case("default") {
                continue;
            }
            opts.has_default = true;
            let args = decorator.args_src.trim();

            // Check for @default("value") or @default({ value: "..." })
            if let Some(value) = extract_default_value(args) {
                opts.value = Some(value);
            } else if !args.is_empty() {
                // Treat the args directly as the value if not empty
                // This handles @default(0), @default([]), @default(false), etc.
                opts.value = Some(args.to_string());
            }
        }
        opts
    }
}

/// Extract default value from decorator arguments
fn extract_default_value(args: &str) -> Option<String> {
    // Try named form: { value: "..." }
    if let Some(value) = extract_named_string(args, "value") {
        return Some(value);
    }

    // Try direct string literal: "..."
    if let Some(value) = parse_string_literal(args) {
        return Some(format!("\"{}\"", value));
    }

    None
}

// ============================================================================
// Type Utilities
// ============================================================================

/// Check if a TypeScript type is a primitive type
pub fn is_primitive_type(ts_type: &str) -> bool {
    matches!(
        ts_type.trim(),
        "string" | "number" | "boolean" | "bigint" | "null" | "undefined"
    )
}

/// Check if a TypeScript type is numeric
pub fn is_numeric_type(ts_type: &str) -> bool {
    matches!(ts_type.trim(), "number" | "bigint")
}

/// Check if a TypeScript type is nullable (contains `| null` or `| undefined`)
/// Like Rust's Option<T>, these types default to null.
pub fn is_nullable_type(ts_type: &str) -> bool {
    let normalized = ts_type.replace(' ', "");
    normalized.contains("|null") || normalized.contains("|undefined")
}

/// Check if a type name contains generic parameters (e.g., "RecordLink<Service>")
/// This is used to detect generic type instantiations that need special handling.
pub fn is_generic_type(type_name: &str) -> bool {
    type_name.contains('<') && type_name.contains('>')
}

/// Extracts base type and type arguments from a generic type.
/// "RecordLink<Service>" -> Some(("RecordLink", "Service"))
/// "Map<string, number>" -> Some(("Map", "string, number"))
/// "User" -> None
pub fn parse_generic_type(type_name: &str) -> Option<(&str, &str)> {
    let open = type_name.find('<')?;
    let close = type_name.rfind('>')?;
    if open < close {
        let base = &type_name[..open];
        let args = &type_name[open + 1..close];
        Some((base.trim(), args.trim()))
    } else {
        None
    }
}

/// Returns whether a type can have a default value generated for it.
///
/// Always returns `true` because all types are assumed to implement Default:
/// primitives and collections have built-in defaults, and custom types are
/// assumed to provide a `{typeName}DefaultValue()` standalone function
/// (following Rust's `derive(Default)` philosophy). This function exists
/// as a named predicate for readability.
pub fn has_known_default(_ts_type: &str) -> bool {
    true
}

/// Get default value for a TypeScript type
pub fn get_type_default(ts_type: &str) -> String {
    let t = ts_type.trim();

    // Check for foreign type default first
    let foreign_types = get_foreign_types();
    let ft_match = TypeCategory::match_foreign_type(t, &foreign_types);
    // Note: Warnings from near-matches are handled by serialize/deserialize macros
    // which have access to diagnostics
    if let Some(ft) = ft_match.config
        && let Some(ref default_expr) = ft.default_expr
    {
        // Wrap the expression in an IIFE if it's a function
        // Foreign type defaults are expected to be functions: () => DateTime.now()
        // Rewrite namespace references to use generated aliases
        let rewritten = crate::builtin::serde::rewrite_expression_namespaces(default_expr);
        return format!("({})()", rewritten);
    }

    // Nullable first (like Rust's Option::default() -> None)
    if is_nullable_type(t) {
        return "null".to_string();
    }

    // Object literal types: { [key: string]: number }, { foo: string }, etc.
    // Must be checked before union splitting since braces can contain pipes.
    if t.starts_with('{') {
        return "{}".to_string();
    }

    // Handle union types (e.g., string | Account, "Estimate" | "Invoice")
    // Nullable unions (T | null, T | undefined) are already handled above.
    if let Some(parts) = split_top_level_union(t) {
        // 1. If any member is a primitive, use that primitive's default
        for part in &parts {
            if is_primitive_type(part) {
                return get_type_default(part);
            }
        }
        // 2. If any member is a literal, use the first literal
        for part in &parts {
            let p = part.trim();
            if (p.starts_with('"') && p.ends_with('"'))
                || (p.starts_with('\'') && p.ends_with('\''))
                || (p.starts_with('`') && p.ends_with('`'))
                || p.parse::<f64>().is_ok()
                || matches!(p, "true" | "false")
            {
                return get_type_default(p);
            }
        }
        // 3. Union of only custom types — default via first member
        return get_type_default(parts[0]);
    }

    match t {
        "string" => r#""""#.to_string(),
        "number" => "0".to_string(),
        "boolean" => "false".to_string(),
        "bigint" => "0n".to_string(),
        t if t.ends_with("[]") => "[]".to_string(),
        t if t.starts_with("Array<") => "[]".to_string(),
        t if t.starts_with("Map<") => "new Map()".to_string(),
        t if t.starts_with("Set<") => "new Set()".to_string(),
        "Date" => "new Date()".to_string(),
        // Generic type instantiations like RecordLink<Service>
        t if is_generic_type(t) => {
            if let Some((base, args)) = parse_generic_type(t) {
                format!("{}DefaultValue<{}>()", base.to_case(Case::Camel), args)
            } else {
                // Fallback: shouldn't happen if is_generic_type returned true
                format_default_call(t)
            }
        }
        // String literal types: "active", 'pending', `template`
        t if (t.starts_with('"') && t.ends_with('"'))
            || (t.starts_with('\'') && t.ends_with('\''))
            || (t.starts_with('`') && t.ends_with('`')) =>
        {
            t.to_string()
        }
        // Number literal types: 42, 3.14
        t if t.parse::<f64>().is_ok() => t.to_string(),
        // Boolean literal types
        "true" | "false" => t.to_string(),
        // Unknown types: assume they implement Default trait
        type_name => format_default_call(type_name),
    }
}

fn format_default_call(type_name: &str) -> String {
    format!("{}DefaultValue()", type_name.to_case(Case::Camel))
}

// ============================================================================
// Helper functions (shared with other modules)
// ============================================================================

/// Check if a decorator argument string contains the given flag.
///
/// Splits the argument string on non-alphanumeric characters and checks if
/// any token matches `flag` (case-insensitive). Returns `false` if the flag
/// is explicitly set to `false` (e.g., `skip: false` or `skip=false`).
pub fn has_flag(args: &str, flag: &str) -> bool {
    if flag_explicit_false(args, flag) {
        return false;
    }

    args.split(|c: char| !c.is_alphanumeric() && c != '_')
        .any(|token| token.eq_ignore_ascii_case(flag))
}

fn flag_explicit_false(args: &str, flag: &str) -> bool {
    let lower = args.to_ascii_lowercase();
    let condensed: String = lower.chars().filter(|c| !c.is_whitespace()).collect();
    condensed.contains(&format!("{flag}:false")) || condensed.contains(&format!("{flag}=false"))
}

/// Extract a named string value from a decorator argument string.
///
/// Looks for patterns like `name: "value"`, `name = "value"`, or `name("value")`
/// and returns the unquoted string. The name match is case-insensitive.
///
/// Returns `None` if the name is not found or the value is not a string literal.
pub fn extract_named_string(args: &str, name: &str) -> Option<String> {
    let lower = args.to_ascii_lowercase();
    let idx = lower.find(name)?;
    let remainder = &args[idx + name.len()..];
    let remainder = remainder.trim_start();

    if remainder.starts_with(':') || remainder.starts_with('=') {
        let value = remainder[1..].trim_start();
        return parse_string_literal(value);
    }

    if remainder.starts_with('(')
        && let Some(close) = remainder.rfind(')')
    {
        let inner = remainder[1..close].trim();
        return parse_string_literal(inner);
    }

    None
}

fn parse_string_literal(input: &str) -> Option<String> {
    let trimmed = input.trim();
    let mut chars = trimmed.chars();
    let quote = chars.next()?;
    if quote != '"' && quote != '\'' {
        return None;
    }

    let mut escaped = false;
    let mut buf = String::new();
    for c in chars {
        if escaped {
            buf.push(c);
            escaped = false;
            continue;
        }
        if c == '\\' {
            escaped = true;
            continue;
        }
        if c == quote {
            return Some(buf);
        }
        buf.push(c);
    }
    None
}

// ============================================================================
// Type Registry Helpers
// ============================================================================

/// Check if a type in the registry has `@derive(MacroName)` applied.
/// Works for classes, interfaces, enums, and type aliases.
/// Returns false if the type is not in the registry or has no such derive.
///
/// When a name is ambiguous (same type name in multiple files), checks ALL
/// qualified entries — returns true if ANY entry with that name has the derive.
pub fn type_has_derive(registry: &TypeRegistry, type_name: &str, derive_name: &str) -> bool {
    let has_derive = |entry: &TypeRegistryEntry| {
        let decorators = match &entry.definition {
            TypeDefinitionIR::Class(c) => &c.decorators,
            TypeDefinitionIR::Interface(i) => &i.decorators,
            TypeDefinitionIR::Enum(e) => &e.decorators,
            TypeDefinitionIR::TypeAlias(t) => &t.decorators,
        };
        decorators.iter().any(|d| {
            d.name.eq_ignore_ascii_case("derive")
                && d.args_src
                    .split(',')
                    .any(|arg| arg.trim().eq_ignore_ascii_case(derive_name))
        })
    };

    // Check primary entry first (fast path for unambiguous names)
    if let Some(entry) = registry.get(type_name)
        && has_derive(entry)
    {
        return true;
    }

    // If ambiguous, check all qualified entries with this name
    if registry.ambiguous_names.iter().any(|n| n == type_name) {
        return registry
            .qualified_types
            .values()
            .any(|entry| entry.name == type_name && has_derive(entry));
    }

    false
}

/// Check if a resolved field type (or its inner element type for collections)
/// has a specific derive. Handles arrays, generics, and direct types.
#[allow(dead_code)]
pub fn resolved_type_has_derive(
    registry: &TypeRegistry,
    resolved: &ResolvedTypeRef,
    derive_name: &str,
) -> bool {
    type_has_derive(registry, &resolved.base_type_name, derive_name)
}

/// Get the inner element [`ResolvedTypeRef`] for a collection type.
/// For `User[]` or `Array<User>`, returns the `User` ref.
/// For `Map<K, V>`, returns the `V` ref (value type).
/// For `Set<T>`, returns the `T` ref.
pub fn collection_element_type(resolved: &ResolvedTypeRef) -> Option<&ResolvedTypeRef> {
    if !resolved.is_collection || resolved.type_args.is_empty() {
        return None;
    }
    match resolved.base_type_name.as_str() {
        "Map" if resolved.type_args.len() >= 2 => Some(&resolved.type_args[1]),
        _ => Some(&resolved.type_args[0]), // Array, Set, etc.
    }
}

/// Get the Map key type for `Map<K, V>` collections.
#[allow(dead_code)]
pub fn map_key_type(resolved: &ResolvedTypeRef) -> Option<&ResolvedTypeRef> {
    if resolved.base_type_name == "Map" && resolved.type_args.len() >= 2 {
        Some(&resolved.type_args[0])
    } else {
        None
    }
}

/// Generate the standalone function name for a given type and derive macro.
/// E.g., `("User", "Clone")` → `"userClone"`, `("User", "HashCode")` → `"userHashCode"`.
pub fn standalone_fn_name(type_name: &str, suffix: &str) -> String {
    format!("{}{}", type_name.to_case(Case::Camel), suffix)
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::ts_syn::abi::SpanIR;

    fn span() -> SpanIR {
        SpanIR::new(0, 0)
    }

    fn make_decorator(name: &str, args: &str) -> DecoratorIR {
        DecoratorIR {
            name: name.into(),
            args_src: args.into(),
            span: span(),
            node: None,
        }
    }

    #[test]
    fn test_compare_field_skip() {
        let decorator = make_decorator("partialEq", "skip");
        let opts = CompareFieldOptions::from_decorators(&[decorator], "partialEq");
        assert!(opts.skip);
    }

    #[test]
    fn test_compare_field_no_skip() {
        let decorator = make_decorator("partialEq", "");
        let opts = CompareFieldOptions::from_decorators(&[decorator], "partialEq");
        assert!(!opts.skip);
    }

    #[test]
    fn test_compare_field_skip_false() {
        let decorator = make_decorator("hash", "skip: false");
        let opts = CompareFieldOptions::from_decorators(&[decorator], "hash");
        assert!(!opts.skip);
    }

    #[test]
    fn test_default_field_with_string_value() {
        let decorator = make_decorator("default", r#""hello""#);
        let opts = DefaultFieldOptions::from_decorators(&[decorator]);
        assert!(opts.has_default);
        assert_eq!(opts.value.as_deref(), Some(r#""hello""#));
    }

    #[test]
    fn test_default_field_with_number_value() {
        let decorator = make_decorator("default", "42");
        let opts = DefaultFieldOptions::from_decorators(&[decorator]);
        assert!(opts.has_default);
        assert_eq!(opts.value.as_deref(), Some("42"));
    }

    #[test]
    fn test_default_field_with_array_value() {
        let decorator = make_decorator("default", "[]");
        let opts = DefaultFieldOptions::from_decorators(&[decorator]);
        assert!(opts.has_default);
        assert_eq!(opts.value.as_deref(), Some("[]"));
    }

    #[test]
    fn test_default_field_with_named_value() {
        let decorator = make_decorator("default", r#"{ value: "test" }"#);
        let opts = DefaultFieldOptions::from_decorators(&[decorator]);
        assert!(opts.has_default);
        assert_eq!(opts.value.as_deref(), Some("test"));
    }

    #[test]
    fn test_is_primitive_type() {
        assert!(is_primitive_type("string"));
        assert!(is_primitive_type("number"));
        assert!(is_primitive_type("boolean"));
        assert!(is_primitive_type("bigint"));
        assert!(!is_primitive_type("Date"));
        assert!(!is_primitive_type("User"));
        assert!(!is_primitive_type("string[]"));
    }

    #[test]
    fn test_is_numeric_type() {
        assert!(is_numeric_type("number"));
        assert!(is_numeric_type("bigint"));
        assert!(!is_numeric_type("string"));
        assert!(!is_numeric_type("boolean"));
    }

    #[test]
    fn test_get_type_default() {
        assert_eq!(get_type_default("string"), r#""""#);
        assert_eq!(get_type_default("number"), "0");
        assert_eq!(get_type_default("boolean"), "false");
        assert_eq!(get_type_default("bigint"), "0n");
        assert_eq!(get_type_default("string[]"), "[]");
        assert_eq!(get_type_default("Array<number>"), "[]");
        assert_eq!(get_type_default("Map<string, number>"), "new Map()");
        assert_eq!(get_type_default("Set<string>"), "new Set()");
        assert_eq!(get_type_default("Date"), "new Date()");
        // Unknown types call their defaultValue() method (Prefix style)
        assert_eq!(get_type_default("User"), "userDefaultValue()");
        // Generic type instantiations use typeDefaultValue<Args>() syntax
        assert_eq!(
            get_type_default("RecordLink<Service>"),
            "recordLinkDefaultValue<Service>()"
        );
        assert_eq!(
            get_type_default("Result<User, Error>"),
            "resultDefaultValue<User, Error>()"
        );
        // Object literal types default to {}
        assert_eq!(get_type_default("{ [key: string]: number }"), "{}");
        assert_eq!(get_type_default("{ foo: string; bar: number }"), "{}");
        assert_eq!(get_type_default("{ [K in keyof T]: V }"), "{}");
    }

    #[test]
    fn test_get_type_default_object_literal_before_union_split() {
        // Object types containing pipes should not be split as unions
        assert_eq!(get_type_default("{ a: string | number }"), "{}");
        assert_eq!(
            get_type_default("{ status: \"active\" | \"inactive\" }"),
            "{}"
        );
    }

    #[test]
    fn test_get_type_default_union_with_primitive() {
        // string | CustomType → default of the primitive member
        assert_eq!(get_type_default("string | Account"), r#""""#);
        assert_eq!(get_type_default("string | Employee"), r#""""#);
        assert_eq!(get_type_default("string | Appointment"), r#""""#);
        assert_eq!(get_type_default("string | Site"), r#""""#);
        assert_eq!(get_type_default("number | Custom"), "0");
        assert_eq!(get_type_default("boolean | Foo"), "false");
        assert_eq!(get_type_default("bigint | Bar"), "0n");
        // Primitive not first in union
        assert_eq!(get_type_default("Account | string"), r#""""#);
    }

    #[test]
    fn test_get_type_default_union_with_literal() {
        // Literal unions → first literal value
        assert_eq!(
            get_type_default(r#""Estimate" | "Invoice""#),
            r#""Estimate""#
        );
        assert_eq!(
            get_type_default(r#""active" | "pending" | "completed""#),
            r#""active""#
        );
    }

    #[test]
    fn test_get_type_default_union_custom_types() {
        // Union of only custom types → default of the first member
        assert_eq!(
            get_type_default("Account | Employee"),
            "accountDefaultValue()"
        );
    }

    #[test]
    fn test_get_type_default_nullable_union() {
        // Nullable unions are still handled by is_nullable_type
        assert_eq!(get_type_default("string | null"), "null");
        assert_eq!(get_type_default("Account | undefined"), "null");
        assert_eq!(get_type_default("string | Account | null"), "null");
    }

    #[test]
    fn test_is_generic_type() {
        // Generic types
        assert!(is_generic_type("RecordLink<Service>"));
        assert!(is_generic_type("Map<string, number>"));
        assert!(is_generic_type("Array<User>"));
        assert!(is_generic_type("Result<T, E>"));

        // Non-generic types
        assert!(!is_generic_type("User"));
        assert!(!is_generic_type("string"));
        assert!(!is_generic_type("number[]")); // Array syntax, not generic
    }

    #[test]
    fn test_parse_generic_type() {
        // Simple generic
        assert_eq!(
            parse_generic_type("RecordLink<Service>"),
            Some(("RecordLink", "Service"))
        );

        // Multiple type parameters
        assert_eq!(
            parse_generic_type("Map<string, number>"),
            Some(("Map", "string, number"))
        );

        // Nested generics
        assert_eq!(
            parse_generic_type("Result<Array<User>, Error>"),
            Some(("Result", "Array<User>, Error"))
        );

        // Non-generic types return None
        assert_eq!(parse_generic_type("User"), None);
        assert_eq!(parse_generic_type("string"), None);

        // Malformed (no closing bracket)
        assert_eq!(parse_generic_type("Array<User"), None);
    }

    // ========================================================================
    // Type Registry Helper Tests
    // ========================================================================

    use crate::ts_syn::abi::ir::type_registry::{
        TypeDefinitionIR, TypeRegistry, TypeRegistryEntry,
    };
    use crate::ts_syn::abi::{ClassIR, InterfaceIR};

    fn zero_span() -> SpanIR {
        SpanIR::new(0, 0)
    }

    fn make_registry_with_derives() -> TypeRegistry {
        let mut registry = TypeRegistry::new();

        // User class with @derive(Clone, Hash, PartialEq, Debug, Default)
        let user_entry = TypeRegistryEntry {
            name: "User".to_string(),
            file_path: "/project/src/user.ts".to_string(),
            is_exported: true,
            definition: TypeDefinitionIR::Class(ClassIR {
                name: "User".to_string(),
                span: zero_span(),
                body_span: zero_span(),
                is_abstract: false,
                type_params: vec![],
                heritage: vec![],
                decorators: vec![make_decorator(
                    "derive",
                    "Clone, Hash, PartialEq, Debug, Default",
                )],
                decorators_ast: vec![],
                fields: vec![],
                methods: vec![],
                members: vec![],
            }),
            file_imports: vec![],
        };
        registry.insert(user_entry, "/project");

        // Order interface with @derive(Clone) only
        let order_entry = TypeRegistryEntry {
            name: "Order".to_string(),
            file_path: "/project/src/order.ts".to_string(),
            is_exported: true,
            definition: TypeDefinitionIR::Interface(InterfaceIR {
                name: "Order".to_string(),
                span: zero_span(),
                body_span: zero_span(),
                type_params: vec![],
                heritage: vec![],
                decorators: vec![make_decorator("derive", "Clone")],
                fields: vec![],
                methods: vec![],
            }),
            file_imports: vec![],
        };
        registry.insert(order_entry, "/project");

        // Product class with no derives
        let product_entry = TypeRegistryEntry {
            name: "Product".to_string(),
            file_path: "/project/src/product.ts".to_string(),
            is_exported: true,
            definition: TypeDefinitionIR::Class(ClassIR {
                name: "Product".to_string(),
                span: zero_span(),
                body_span: zero_span(),
                is_abstract: false,
                type_params: vec![],
                heritage: vec![],
                decorators: vec![],
                decorators_ast: vec![],
                fields: vec![],
                methods: vec![],
                members: vec![],
            }),
            file_imports: vec![],
        };
        registry.insert(product_entry, "/project");

        registry
    }

    #[test]
    fn test_type_has_derive() {
        let registry = make_registry_with_derives();

        // User has Clone, Hash, PartialEq, Debug, Default
        assert!(type_has_derive(&registry, "User", "Clone"));
        assert!(type_has_derive(&registry, "User", "Hash"));
        assert!(type_has_derive(&registry, "User", "PartialEq"));
        assert!(type_has_derive(&registry, "User", "Debug"));
        assert!(type_has_derive(&registry, "User", "Default"));

        // User does NOT have Ord
        assert!(!type_has_derive(&registry, "User", "Ord"));

        // Order only has Clone
        assert!(type_has_derive(&registry, "Order", "Clone"));
        assert!(!type_has_derive(&registry, "Order", "Hash"));

        // Product has no derives
        assert!(!type_has_derive(&registry, "Product", "Clone"));

        // Unknown type returns false
        assert!(!type_has_derive(&registry, "Unknown", "Clone"));
    }

    #[test]
    fn test_type_has_derive_ambiguous_name() {
        // Simulate a type that exists in both its own file and a barrel file
        let mut registry = TypeRegistry::new();

        let phone_entry = TypeRegistryEntry {
            name: "PhoneNumber".to_string(),
            file_path: "/project/src/types/phone-number.svelte.ts".to_string(),
            is_exported: true,
            definition: TypeDefinitionIR::Interface(InterfaceIR {
                name: "PhoneNumber".to_string(),
                span: zero_span(),
                body_span: zero_span(),
                type_params: vec![],
                heritage: vec![],
                decorators: vec![make_decorator(
                    "derive",
                    "Default, Serialize, Deserialize, Gigaform",
                )],
                fields: vec![],
                methods: vec![],
            }),
            file_imports: vec![],
        };
        registry.insert(phone_entry, "/project");

        // Same type in barrel file
        let barrel_entry = TypeRegistryEntry {
            name: "PhoneNumber".to_string(),
            file_path: "/project/src/types/all-types.svelte.ts".to_string(),
            is_exported: true,
            definition: TypeDefinitionIR::Interface(InterfaceIR {
                name: "PhoneNumber".to_string(),
                span: zero_span(),
                body_span: zero_span(),
                type_params: vec![],
                heritage: vec![],
                decorators: vec![make_decorator(
                    "derive",
                    "Default, Serialize, Deserialize, Gigaform",
                )],
                fields: vec![],
                methods: vec![],
            }),
            file_imports: vec![],
        };
        registry.insert(barrel_entry, "/project");

        // Must be marked ambiguous
        assert!(
            registry
                .ambiguous_names
                .contains(&"PhoneNumber".to_string())
        );

        // type_has_derive should still return true
        assert!(type_has_derive(&registry, "PhoneNumber", "Gigaform"));
        assert!(type_has_derive(&registry, "PhoneNumber", "Default"));
        assert!(type_has_derive(&registry, "PhoneNumber", "Serialize"));
        assert!(type_has_derive(&registry, "PhoneNumber", "Deserialize"));
    }

    #[test]
    fn test_type_has_derive_case_insensitive() {
        let registry = make_registry_with_derives();
        assert!(type_has_derive(&registry, "User", "clone"));
        assert!(type_has_derive(&registry, "User", "CLONE"));
    }

    #[test]
    fn test_resolved_type_has_derive() {
        let registry = make_registry_with_derives();

        let resolved = ResolvedTypeRef {
            raw_type: "User".to_string(),
            base_type_name: "User".to_string(),
            registry_key: Some("src/user.ts::User".to_string()),
            is_collection: false,
            is_optional: false,
            type_args: vec![],
        };

        assert!(resolved_type_has_derive(&registry, &resolved, "Clone"));
        assert!(!resolved_type_has_derive(&registry, &resolved, "Ord"));
    }

    #[test]
    fn test_collection_element_type() {
        // Array<User> → User
        let user_ref = ResolvedTypeRef {
            raw_type: "User".to_string(),
            base_type_name: "User".to_string(),
            registry_key: Some("src/user.ts::User".to_string()),
            is_collection: false,
            is_optional: false,
            type_args: vec![],
        };
        let array_ref = ResolvedTypeRef {
            raw_type: "User[]".to_string(),
            base_type_name: "User".to_string(),
            registry_key: Some("src/user.ts::User".to_string()),
            is_collection: true,
            is_optional: false,
            type_args: vec![user_ref.clone()],
        };
        let elem = collection_element_type(&array_ref);
        assert!(elem.is_some());
        assert_eq!(elem.unwrap().base_type_name, "User");

        // Map<string, User> → User (value type)
        let string_ref = ResolvedTypeRef {
            raw_type: "string".to_string(),
            base_type_name: "string".to_string(),
            registry_key: None,
            is_collection: false,
            is_optional: false,
            type_args: vec![],
        };
        let map_ref = ResolvedTypeRef {
            raw_type: "Map<string, User>".to_string(),
            base_type_name: "Map".to_string(),
            registry_key: None,
            is_collection: true,
            is_optional: false,
            type_args: vec![string_ref.clone(), user_ref.clone()],
        };
        let elem = collection_element_type(&map_ref);
        assert!(elem.is_some());
        assert_eq!(elem.unwrap().base_type_name, "User");

        // Non-collection returns None
        assert!(collection_element_type(&user_ref).is_none());
    }

    #[test]
    fn test_map_key_type() {
        let string_ref = ResolvedTypeRef {
            raw_type: "string".to_string(),
            base_type_name: "string".to_string(),
            registry_key: None,
            is_collection: false,
            is_optional: false,
            type_args: vec![],
        };
        let user_ref = ResolvedTypeRef {
            raw_type: "User".to_string(),
            base_type_name: "User".to_string(),
            registry_key: Some("src/user.ts::User".to_string()),
            is_collection: false,
            is_optional: false,
            type_args: vec![],
        };
        let map_ref = ResolvedTypeRef {
            raw_type: "Map<string, User>".to_string(),
            base_type_name: "Map".to_string(),
            registry_key: None,
            is_collection: true,
            is_optional: false,
            type_args: vec![string_ref.clone(), user_ref.clone()],
        };

        let key = map_key_type(&map_ref);
        assert!(key.is_some());
        assert_eq!(key.unwrap().base_type_name, "string");

        // Non-Map returns None
        assert!(map_key_type(&user_ref).is_none());
    }

    #[test]
    fn test_standalone_fn_name() {
        assert_eq!(standalone_fn_name("User", "Clone"), "userClone");
        assert_eq!(standalone_fn_name("User", "HashCode"), "userHashCode");
        assert_eq!(standalone_fn_name("User", "Equals"), "userEquals");
        assert_eq!(standalone_fn_name("Order", "ToString"), "orderToString");
        assert_eq!(
            standalone_fn_name("MyLongType", "PartialCompare"),
            "myLongTypePartialCompare"
        );
    }
}