macroforge_ts_syn 0.1.79

TypeScript syntax types for compile-time macro code generation
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
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
//! `syn`-like derive input types for TypeScript macros.
//!
//! This module provides a [`DeriveInput`] type analogous to `syn::DeriveInput`,
//! making it easy to write derive macros with a familiar API. If you've written
//! proc macros in Rust using `syn`, this API will feel very natural.
//!
//! ## Overview
//!
//! The derive input system provides:
//!
//! - [`DeriveInput`] - The main entry point, containing the type name, attributes, and data
//! - [`Data`] - An enum distinguishing classes, enums, interfaces, and type aliases
//! - [`DataClass`], [`DataEnum`], [`DataInterface`], [`DataTypeAlias`] - Type-specific data
//! - [`Ident`] - A simple identifier type with span information
//! - [`Attribute`] - Decorator/attribute representation
//!
//! ## Comparison with syn
//!
//! | syn | macroforge_ts_syn | Notes |
//! |-----|-------------------|-------|
//! | `syn::DeriveInput` | [`DeriveInput`] | Same purpose |
//! | `syn::Ident` | [`Ident`] | Same purpose |
//! | `syn::Data` | [`Data`] | Includes more variants (Interface, TypeAlias) |
//! | `syn::DataStruct` | [`DataClass`] | TypeScript classes ≈ Rust structs |
//! | `syn::DataEnum` | [`DataEnum`] | Same purpose |
//! | `syn::Attribute` | [`Attribute`] | Wraps JSDoc/TS decorators |
//!
//! ## Example: Basic Derive Macro
//!
//! ```rust,ignore
//! use macroforge_ts_syn::{parse_ts_macro_input, DeriveInput, Data, MacroResult, TsStream};
//!
//! // This function signature shows how derive macros receive input
//! pub fn my_macro(mut input: TsStream) -> MacroResult {
//!     let input = parse_ts_macro_input!(input as DeriveInput);
//!
//!     // Get the type name
//!     let _name = input.name();
//!
//!     match &input.data {
//!         Data::Class(class) => {
//!             // Access class fields and methods
//!             for field in class.fields() {
//!                 println!("Field: {} ({})", field.name, field.ts_type);
//!             }
//!         }
//!         Data::Enum(enum_) => {
//!             // Access enum variants
//!             for variant in enum_.variants() {
//!                 println!("Variant: {}", variant.name);
//!             }
//!         }
//!         Data::Interface(iface) => {
//!             // Access interface fields and methods
//!             for field in iface.fields() {
//!                 println!("Property: {}", field.name);
//!             }
//!         }
//!         Data::TypeAlias(alias) => {
//!             // Handle union types, object types, etc.
//!             if let Some(members) = alias.as_union() {
//!                 println!("Union with {} variants", members.len());
//!             }
//!         }
//!     }
//!
//!     MacroResult::default()
//! }
//! ```
//!
//! ## Example: Accessing Decorators
//!
//! ```rust,ignore
//! use macroforge_ts_syn::{parse_ts_macro_input, DeriveInput, MacroResult, TsStream};
//!
//! // This function signature shows how derive macros receive input
//! pub fn my_macro(mut input: TsStream) -> MacroResult {
//!     let input = parse_ts_macro_input!(input as DeriveInput);
//!
//!     // Check for a specific decorator
//!     for attr in &input.attrs {
//!         if attr.name() == "serde" {
//!             let _args = attr.args(); // e.g., "rename = \"user\""
//!             // Parse and handle decorator arguments
//!         }
//!     }
//!
//!     // Or check field-level decorators
//!     if let Some(class) = input.as_class() {
//!         for field in class.fields() {
//!             for dec in &field.decorators {
//!                 if dec.name == "serde" {
//!                     // Handle field-level serde options
//!                 }
//!             }
//!         }
//!     }
//!
//!     MacroResult::default()
//! }
//! ```
//!
//! ## Span Information
//!
//! [`DeriveInput`] provides several useful spans for code generation:
//!
//! - [`DeriveInput::decorator_span()`] - The span of the `@derive(...)` decorator
//! - [`DeriveInput::target_span()`] - The span of the entire type definition
//! - [`DeriveInput::body_span()`] - The span inside `{ }` for inserting members
//! - [`DeriveInput::error_span()`] - Best span for error reporting

use crate::abi::{
    ClassIR, DecoratorIR, EnumIR, EnumVariantIR, FieldIR, InterfaceFieldIR, InterfaceIR,
    InterfaceMethodIR, MacroContextIR, MethodSigIR, SpanIR, TargetIR, TypeAliasIR, TypeBody,
    TypeMember,
};

use crate::TsSynError;

#[cfg(feature = "swc")]
use crate::TsStream;

/// The input to a derive macro, analogous to `syn::DeriveInput`.
///
/// This is the primary entry point for derive macros. It provides a unified
/// representation of all TypeScript types that can have derive macros applied:
/// classes, enums, interfaces, and type aliases.
///
/// # Creating a DeriveInput
///
/// Use the `parse_ts_macro_input!` macro to parse a [`TsStream`] into
/// a `DeriveInput`:
///
/// ```rust,ignore
/// use macroforge_ts_syn::{parse_ts_macro_input, DeriveInput, TsStream};
///
/// // This requires a TsStream with macro context
/// fn example(mut stream: TsStream) {
///     let _input = parse_ts_macro_input!(stream as DeriveInput);
/// }
/// ```
///
/// Or create one directly from a [`MacroContextIR`]:
///
/// ```rust,no_run
/// use macroforge_ts_syn::{DeriveInput, MacroContextIR, TsSynError};
///
/// fn example(ctx: MacroContextIR) -> Result<(), TsSynError> {
///     let _input = DeriveInput::from_context(ctx)?;
///     Ok(())
/// }
/// ```
///
/// # Accessing Type Data
///
/// Use the `data` field or convenience methods to access type-specific information:
///
/// ```rust,no_run
/// use macroforge_ts_syn::{DeriveInput, Data};
///
/// fn example(input: DeriveInput) {
///     // Using pattern matching
///     match &input.data {
///         Data::Class(_class) => { /* ... */ }
///         Data::Enum(_enum_) => { /* ... */ }
///         Data::Interface(_iface) => { /* ... */ }
///         Data::TypeAlias(_alias) => { /* ... */ }
///     }
///
///     // Using convenience methods
///     if let Some(class) = input.as_class() {
///         for _field in class.fields() {
///             // ...
///         }
///     }
/// }
/// ```
///
/// # Fields
///
/// - `ident` - The name of the type as an [`Ident`]
/// - `span` - The source span of the entire type definition
/// - `attrs` - Decorators on the type (excluding `@derive`)
/// - `data` - The type-specific data (class fields, enum variants, etc.)
/// - `context` - The full macro context with additional metadata
#[derive(Debug, Clone)]
pub struct DeriveInput {
    /// The name of the type (class or enum name)
    pub ident: Ident,

    /// The span of the entire type definition
    pub span: SpanIR,

    /// Decorators on this type (excluding the derive decorator itself)
    pub attrs: Vec<Attribute>,

    /// The data within the type (class fields/methods or enum variants)
    pub data: Data,

    /// The macro context, providing spans and other metadata
    pub context: MacroContextIR,
}

/// A simple identifier with span information, analogous to `syn::Ident`.
///
/// Represents a TypeScript identifier (type name, field name, etc.) along
/// with its source location. The identifier preserves the exact text from
/// the source code.
///
/// # Example
///
/// ```rust
/// use macroforge_ts_syn::{Ident, SpanIR};
///
/// let ident = Ident::new("MyClass", SpanIR::new(0, 7));
/// assert_eq!(ident.as_str(), "MyClass");
/// assert_eq!(format!("{}", ident), "MyClass");
/// ```
///
/// # Converting to String
///
/// `Ident` implements `Display`, `AsRef<str>`, and provides `as_str()`:
///
/// ```rust
/// use macroforge_ts_syn::{Ident, SpanIR};
///
/// let ident = Ident::new("MyClass", SpanIR::new(0, 7));
/// let name: &str = ident.as_str();
/// let name2: &str = ident.as_ref();
/// let name3: String = ident.to_string();
/// assert_eq!(name, "MyClass");
/// assert_eq!(name2, "MyClass");
/// assert_eq!(name3, "MyClass");
/// ```
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Ident {
    name: String,
    span: SpanIR,
}

impl Ident {
    /// Create a new identifier
    pub fn new(name: impl Into<String>, span: SpanIR) -> Self {
        Self {
            name: name.into(),
            span,
        }
    }

    /// Get the identifier as a string slice
    pub fn as_str(&self) -> &str {
        &self.name
    }

    /// Get the span of this identifier
    pub fn span(&self) -> SpanIR {
        self.span
    }
}

impl std::fmt::Display for Ident {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.name)
    }
}

impl AsRef<str> for Ident {
    fn as_ref(&self) -> &str {
        &self.name
    }
}

/// An attribute (decorator), analogous to `syn::Attribute`.
///
/// Wraps a [`DecoratorIR`] and provides convenient access to decorator
/// information. Attributes can come from either TypeScript decorators
/// (`@Decorator()`) or JSDoc comments (`/** @decorator(...) */`).
///
/// # Example
///
/// ```rust,no_run
/// use macroforge_ts_syn::DeriveInput;
///
/// fn example(input: DeriveInput) {
///     for attr in &input.attrs {
///         match attr.name() {
///             "serde" => {
///                 // Parse serde options from attr.args()
///                 let _args = attr.args(); // e.g., "rename = \"user_id\""
///             }
///             "validate" => {
///                 // Handle validation decorator
///             }
///             _ => {}
///         }
///     }
/// }
/// ```
///
/// # Note
///
/// The `@derive(...)` decorator itself is automatically filtered out from
/// the `attrs` list in [`DeriveInput`], since the macro is already being
/// invoked as a result of that decorator.
#[derive(Debug, Clone)]
pub struct Attribute {
    /// The underlying decorator IR with full details.
    pub inner: DecoratorIR,
}

impl Attribute {
    /// Get the attribute/decorator name
    pub fn name(&self) -> &str {
        &self.inner.name
    }

    /// Get the raw arguments string
    pub fn args(&self) -> &str {
        &self.inner.args_src
    }

    /// Get the span
    pub fn span(&self) -> SpanIR {
        self.inner.span
    }
}

/// The data within a derive input, analogous to `syn::Data`.
///
/// This enum distinguishes between the different kinds of TypeScript types
/// that can have derive macros applied. Each variant contains the type-specific
/// information needed for code generation.
///
/// # Variants
///
/// - [`Data::Class`] - A TypeScript class with fields, methods, and modifiers
/// - [`Data::Enum`] - A TypeScript enum with variants and values
/// - [`Data::Interface`] - A TypeScript interface with properties and method signatures
/// - [`Data::TypeAlias`] - A type alias (union, intersection, object, tuple, or simple)
///
/// # Example
///
/// ```rust
/// use macroforge_ts_syn::{DeriveInput, Data};
///
/// fn process_input(input: &DeriveInput) {
///     match &input.data {
///         Data::Class(class) => {
///             // Generate methods for a class
///             let _body_span = class.body_span();
///             for field in class.fields() {
///                 // Access field.name, field.ts_type, field.optional, etc.
///                 let _ = &field.name;
///             }
///         }
///         Data::Enum(enum_) => {
///             // Generate match arms or utility functions
///             for variant in enum_.variants() {
///                 // Access variant.name, variant.value
///                 let _ = &variant.name;
///             }
///         }
///         Data::Interface(iface) => {
///             // Generate class implementing the interface
///             for field in iface.fields() {
///                 // Access field.name, field.ts_type, field.optional
///                 let _ = &field.name;
///             }
///         }
///         Data::TypeAlias(alias) => {
///             // Handle different alias structures
///             if let Some(_union) = alias.as_union() {
///                 // Handle union type
///             } else if let Some(_fields) = alias.as_object() {
///                 // Handle object type
///             }
///         }
///     }
/// }
/// ```
#[derive(Debug, Clone)]
pub enum Data {
    /// A TypeScript class with fields, methods, and optional modifiers.
    Class(DataClass),
    /// A TypeScript enum with named variants.
    Enum(DataEnum),
    /// A TypeScript interface with property and method signatures.
    Interface(DataInterface),
    /// A TypeScript type alias (union, intersection, object, etc.).
    TypeAlias(DataTypeAlias),
}

/// Data for a TypeScript class, analogous to `syn::DataStruct`.
///
/// Provides access to class fields, methods, and metadata. The underlying
/// [`ClassIR`] contains the full parsed information including AST nodes
/// for advanced use cases.
///
/// # Example
///
/// ```rust
/// use macroforge_ts_syn::{DeriveInput, Data};
///
/// fn process_class(input: &DeriveInput) {
///     if let Data::Class(class) = &input.data {
///         // Iterate over fields
///         for field in class.fields() {
///             println!("Field: {} ({})", field.name, field.ts_type);
///             if field.optional {
///                 println!("  (optional)");
///             }
///         }
///
///         // Check for specific fields
///         if let Some(_id_field) = class.field("id") {
///             // Handle id field specifically
///         }
///
///         // Access methods
///         for method in class.methods() {
///             println!("Method: {}({})", method.name, method.params_src);
///         }
///
///         // Get the body span for inserting generated code
///         let _body = class.body_span();
///     }
/// }
/// ```
#[derive(Debug, Clone)]
pub struct DataClass {
    /// The underlying class IR with full details.
    pub inner: ClassIR,
}

impl DataClass {
    /// Get the fields of the class
    pub fn fields(&self) -> &[FieldIR] {
        &self.inner.fields
    }

    /// Get the methods of the class
    pub fn methods(&self) -> &[MethodSigIR] {
        &self.inner.methods
    }

    /// Get the class body span (for inserting code)
    pub fn body_span(&self) -> SpanIR {
        self.inner.body_span
    }

    /// Check if the class is abstract
    pub fn is_abstract(&self) -> bool {
        self.inner.is_abstract
    }

    /// Get type parameters
    pub fn type_params(&self) -> &[String] {
        &self.inner.type_params
    }

    /// Get heritage clauses (extends/implements)
    pub fn heritage(&self) -> &[String] {
        &self.inner.heritage
    }

    /// Iterate over field names
    pub fn field_names(&self) -> impl Iterator<Item = &str> {
        self.inner.fields.iter().map(|f| f.name.as_str())
    }

    /// Get a field by name
    pub fn field(&self, name: &str) -> Option<&FieldIR> {
        self.inner.fields.iter().find(|f| f.name == name)
    }

    /// Get a method by name
    pub fn method(&self, name: &str) -> Option<&MethodSigIR> {
        self.inner.methods.iter().find(|m| m.name == name)
    }
}

/// Data for a TypeScript enum, analogous to `syn::DataEnum`.
///
/// Provides access to enum variants and their values. TypeScript enums
/// support string, numeric, auto-incremented, and expression values.
///
/// # Example
///
/// ```rust
/// use macroforge_ts_syn::{DeriveInput, Data, EnumValue};
///
/// fn process_enum(input: &DeriveInput) {
///     if let Data::Enum(enum_) = &input.data {
///         // Iterate over variants
///         for variant in enum_.variants() {
///             println!("Variant: {}", variant.name);
///             match &variant.value {
///                 EnumValue::String(s) => println!("  = \"{}\"", s),
///                 EnumValue::Number(n) => println!("  = {}", n),
///                 EnumValue::Auto => println!("  (auto)"),
///                 EnumValue::Expr(e) => println!("  = {}", e),
///             }
///         }
///
///         // Get specific variant
///         if let Some(_active) = enum_.variant("Active") {
///             // Handle Active variant
///         }
///
///         // Get all variant names
///         let _names: Vec<_> = enum_.variant_names().collect();
///     }
/// }
/// ```
#[derive(Debug, Clone)]
pub struct DataEnum {
    /// The underlying enum IR with full details.
    pub inner: EnumIR,
}

impl DataEnum {
    /// Get the variants of the enum
    pub fn variants(&self) -> &[EnumVariantIR] {
        &self.inner.variants
    }

    /// Iterate over variant names
    pub fn variant_names(&self) -> impl Iterator<Item = &str> {
        self.inner.variants.iter().map(|v| v.name.as_str())
    }

    /// Get a variant by name
    pub fn variant(&self, name: &str) -> Option<&EnumVariantIR> {
        self.inner.variants.iter().find(|v| v.name == name)
    }
}

/// Data for a TypeScript interface.
///
/// Provides access to interface properties and method signatures. Interfaces
/// are similar to classes but define only the shape of data without
/// implementation details.
///
/// # Example
///
/// ```rust
/// use macroforge_ts_syn::{DeriveInput, Data};
///
/// fn process_interface(input: &DeriveInput) {
///     if let Data::Interface(iface) = &input.data {
///         // Iterate over properties
///         for field in iface.fields() {
///             let opt = if field.optional { "?" } else { "" };
///             let ro = if field.readonly { "readonly " } else { "" };
///             println!("{}{}{}: {}", ro, field.name, opt, field.ts_type);
///         }
///
///         // Access method signatures
///         for method in iface.methods() {
///             println!("{}({}): {}", method.name, method.params_src, method.return_type_src);
///         }
///
///         // Get body span for inserting code (useful for generating companion class)
///         let _body = iface.body_span();
///     }
/// }
/// ```
///
/// # Note
///
/// Unlike classes, interfaces cannot contain method implementations. Macros
/// targeting interfaces typically generate companion classes or utility
/// functions rather than modifying the interface directly.
#[derive(Debug, Clone)]
pub struct DataInterface {
    /// The underlying interface IR with full details.
    pub inner: InterfaceIR,
}

impl DataInterface {
    /// Get the fields of the interface
    pub fn fields(&self) -> &[InterfaceFieldIR] {
        &self.inner.fields
    }

    /// Get the methods of the interface
    pub fn methods(&self) -> &[InterfaceMethodIR] {
        &self.inner.methods
    }

    /// Get the interface body span (for inserting code)
    pub fn body_span(&self) -> SpanIR {
        self.inner.body_span
    }

    /// Get type parameters
    pub fn type_params(&self) -> &[String] {
        &self.inner.type_params
    }

    /// Get heritage clauses (extends)
    pub fn heritage(&self) -> &[String] {
        &self.inner.heritage
    }

    /// Iterate over field names
    pub fn field_names(&self) -> impl Iterator<Item = &str> {
        self.inner.fields.iter().map(|f| f.name.as_str())
    }

    /// Get a field by name
    pub fn field(&self, name: &str) -> Option<&InterfaceFieldIR> {
        self.inner.fields.iter().find(|f| f.name == name)
    }

    /// Get a method by name
    pub fn method(&self, name: &str) -> Option<&InterfaceMethodIR> {
        self.inner.methods.iter().find(|m| m.name == name)
    }
}

/// Data for a TypeScript type alias.
///
/// Type aliases can represent various type structures:
/// - Union types: `type Status = "active" | "inactive"`
/// - Intersection types: `type Combined = A & B`
/// - Object types: `type Point = { x: number; y: number }`
/// - Tuple types: `type Pair = [string, number]`
/// - Simple aliases: `type ID = string`
///
/// # Example
///
/// ```rust
/// use macroforge_ts_syn::{DeriveInput, Data};
///
/// fn process_type_alias(input: &DeriveInput) {
///     if let Data::TypeAlias(alias) = &input.data {
///         // Check the type structure
///         if let Some(union) = alias.as_union() {
///             println!("Union with {} members", union.len());
///             for member in union {
///                 // Each member may have decorators like @default
///                 if member.has_decorator("default") {
///                     println!("  Default: {:?}", member.kind);
///                 }
///             }
///         } else if let Some(fields) = alias.as_object() {
///             println!("Object type with {} fields", fields.len());
///             for field in fields {
///                 println!("  {}: {}", field.name, field.ts_type);
///             }
///         } else if alias.is_tuple() {
///             let elements = alias.as_tuple().unwrap();
///             println!("Tuple: [{}]", elements.join(", "));
///         } else if let Some(aliased) = alias.as_alias() {
///             println!("Simple alias to: {}", aliased);
///         }
///
///         // Access type parameters
///         let params = alias.type_params();
///         if !params.is_empty() {
///             println!("Generic: <{}>", params.join(", "));
///         }
///     }
/// }
/// ```
#[derive(Debug, Clone)]
pub struct DataTypeAlias {
    /// The underlying type alias IR with full details.
    pub inner: TypeAliasIR,
}

impl DataTypeAlias {
    /// Get the type body
    pub fn body(&self) -> &TypeBody {
        &self.inner.body
    }

    /// Get type parameters
    pub fn type_params(&self) -> &[String] {
        &self.inner.type_params
    }

    /// Check if this is a union type
    pub fn is_union(&self) -> bool {
        self.inner.body.is_union()
    }

    /// Check if this is an intersection type
    pub fn is_intersection(&self) -> bool {
        self.inner.body.is_intersection()
    }

    /// Check if this is an object type
    pub fn is_object(&self) -> bool {
        self.inner.body.is_object()
    }

    /// Check if this is a tuple type
    pub fn is_tuple(&self) -> bool {
        self.inner.body.is_tuple()
    }

    /// Check if this is a simple alias
    pub fn is_alias(&self) -> bool {
        self.inner.body.is_alias()
    }

    /// Get union members if this is a union type
    pub fn as_union(&self) -> Option<&[TypeMember]> {
        self.inner.body.as_union()
    }

    /// Get intersection members if this is an intersection type
    pub fn as_intersection(&self) -> Option<&[TypeMember]> {
        self.inner.body.as_intersection()
    }

    /// Get object fields if this is an object type
    pub fn as_object(&self) -> Option<&[InterfaceFieldIR]> {
        self.inner.body.as_object()
    }

    /// Get tuple elements if this is a tuple type
    pub fn as_tuple(&self) -> Option<&[String]> {
        self.inner.body.as_tuple()
    }

    /// Get aliased type if this is a simple alias
    pub fn as_alias(&self) -> Option<&str> {
        self.inner.body.as_alias()
    }
}

impl DeriveInput {
    /// Create a DeriveInput from a MacroContextIR
    pub fn from_context(ctx: MacroContextIR) -> Result<Self, TsSynError> {
        let (ident, span, attrs, data) = match &ctx.target {
            TargetIR::Class(class) => {
                let ident = Ident::new(&class.name, class.span);
                let attrs = class
                    .decorators
                    .iter()
                    .filter(|d| d.name != "Derive") // Filter out the derive decorator itself
                    .cloned()
                    .map(|d| Attribute { inner: d })
                    .collect();
                let data = Data::Class(DataClass {
                    inner: class.clone(),
                });
                (ident, class.span, attrs, data)
            }
            TargetIR::Enum(enum_) => {
                let ident = Ident::new(&enum_.name, enum_.span);
                let attrs = enum_
                    .decorators
                    .iter()
                    .filter(|d| d.name != "Derive")
                    .cloned()
                    .map(|d| Attribute { inner: d })
                    .collect();
                let data = Data::Enum(DataEnum {
                    inner: enum_.clone(),
                });
                (ident, enum_.span, attrs, data)
            }
            TargetIR::Interface(interface) => {
                let ident = Ident::new(&interface.name, interface.span);
                let attrs = interface
                    .decorators
                    .iter()
                    .filter(|d| d.name != "Derive")
                    .cloned()
                    .map(|d| Attribute { inner: d })
                    .collect();
                let data = Data::Interface(DataInterface {
                    inner: interface.clone(),
                });
                (ident, interface.span, attrs, data)
            }
            TargetIR::TypeAlias(type_alias) => {
                let ident = Ident::new(&type_alias.name, type_alias.span);
                let attrs = type_alias
                    .decorators
                    .iter()
                    .filter(|d| d.name != "Derive")
                    .cloned()
                    .map(|d| Attribute { inner: d })
                    .collect();
                let data = Data::TypeAlias(DataTypeAlias {
                    inner: type_alias.clone(),
                });
                (ident, type_alias.span, attrs, data)
            }
            TargetIR::Function => {
                return Err(TsSynError::Unsupported(
                    "Function derive macros not yet supported".into(),
                ));
            }
            TargetIR::Other => {
                return Err(TsSynError::Unsupported(
                    "Unknown target type for derive macro".into(),
                ));
            }
        };

        Ok(Self {
            ident,
            span,
            attrs,
            data,
            context: ctx,
        })
    }

    /// Get the name of the type as a string
    pub fn name(&self) -> &str {
        self.ident.as_str()
    }

    /// Get the class data, if this is a class
    pub fn as_class(&self) -> Option<&DataClass> {
        match &self.data {
            Data::Class(c) => Some(c),
            _ => None,
        }
    }

    /// Get the enum data, if this is an enum
    pub fn as_enum(&self) -> Option<&DataEnum> {
        match &self.data {
            Data::Enum(e) => Some(e),
            _ => None,
        }
    }

    /// Get the interface data, if this is an interface
    pub fn as_interface(&self) -> Option<&DataInterface> {
        match &self.data {
            Data::Interface(i) => Some(i),
            _ => None,
        }
    }

    /// Get the type alias data, if this is a type alias
    pub fn as_type_alias(&self) -> Option<&DataTypeAlias> {
        match &self.data {
            Data::TypeAlias(t) => Some(t),
            _ => None,
        }
    }

    /// Get the decorator span (for deletion/replacement)
    pub fn decorator_span(&self) -> SpanIR {
        self.context.decorator_span
    }

    /// Get the macro name span (just the macro name within the decorator)
    /// Returns None if not available
    pub fn macro_name_span(&self) -> Option<SpanIR> {
        self.context.macro_name_span
    }

    /// Get the best span for error reporting - prefers macro_name_span if available,
    /// falls back to decorator_span
    pub fn error_span(&self) -> SpanIR {
        self.context.error_span()
    }

    /// Get the target span (for inserting after)
    pub fn target_span(&self) -> SpanIR {
        self.context.target_span
    }

    /// Get the class or interface body span for inserting type signatures
    /// Returns None if this is an enum or type alias
    pub fn body_span(&self) -> Option<SpanIR> {
        match &self.data {
            Data::Class(c) => Some(c.body_span()),
            Data::Interface(i) => Some(i.body_span()),
            Data::Enum(_) => None,
            Data::TypeAlias(_) => None,
        }
    }
}

#[cfg(feature = "swc")]
impl crate::ParseTs for DeriveInput {
    fn parse(input: &mut TsStream) -> Result<Self, TsSynError> {
        let ctx = input
            .context()
            .ok_or_else(|| TsSynError::Parse("No macro context available".into()))?
            .clone();

        Self::from_context(ctx)
    }
}

/// Parse a `TsStream` into a `DeriveInput`, returning early with an error `MacroResult` on failure.
///
/// This macro is analogous to `syn::parse_macro_input!` and provides ergonomic error handling
/// for derive macros.
///
/// # Example
/// ```ignore
/// use ts_syn::{parse_ts_macro_input, DeriveInput};
/// use ts_syn::MacroResult;
///
/// #[ts_macro_derive(MyMacro)]
/// pub fn my_macro(mut input: TsStream) -> MacroResult {
///     let input = parse_ts_macro_input!(input as DeriveInput);
///
///     // input is now a DeriveInput
///     let name = input.name();
///     // ...
/// }
/// ```
///
/// # Variants
/// - `parse_ts_macro_input!(stream as DeriveInput)` - Parse as DeriveInput
/// - `parse_ts_macro_input!(stream)` - Same as above (DeriveInput is the default)
#[macro_export]
macro_rules! parse_ts_macro_input {
    ($input:ident as $ty:ty) => {
        match <$ty as $crate::ParseTs>::parse(&mut $input) {
            Ok(parsed) => parsed,
            Err(e) => {
                return Err($crate::MacroforgeError::new_global(format!(
                    "Failed to parse input: {}",
                    e
                )));
            }
        }
    };
    ($input:ident) => {
        $crate::parse_ts_macro_input!($input as $crate::DeriveInput)
    };
}

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

    fn make_test_class_context() -> MacroContextIR {
        MacroContextIR {
            abi_version: 1,
            macro_kind: MacroKind::Derive,
            macro_name: "Debug".into(),
            module_path: "@test/macro".into(),
            decorator_span: SpanIR::new(0, 10),
            macro_name_span: None,
            target_span: SpanIR::new(11, 100),
            file_name: "test.ts".into(),
            target: TargetIR::Class(ClassIR {
                name: "User".into(),
                span: SpanIR::new(11, 100),
                body_span: SpanIR::new(20, 99),
                is_abstract: false,
                type_params: vec![],
                heritage: vec![],
                decorators: vec![],
                fields: vec![
                    FieldIR {
                        name: "id".into(),
                        span: SpanIR::new(25, 35),
                        ts_type: "number".into(),
                        type_ann: None,
                        optional: false,
                        readonly: false,
                        visibility: crate::abi::Visibility::Public,
                        decorators: vec![],
                        prop_ast: None,
                    },
                    FieldIR {
                        name: "name".into(),
                        span: SpanIR::new(40, 55),
                        ts_type: "string".into(),
                        type_ann: None,
                        optional: false,
                        readonly: false,
                        visibility: crate::abi::Visibility::Public,
                        decorators: vec![],
                        prop_ast: None,
                    },
                ],
                methods: vec![],
                decorators_ast: vec![],
                members: vec![],
            }),
            target_source: "class User { id: number; name: string; }".into(),
            import_registry: crate::import_registry::ImportRegistry::new(),
            config: None,
            type_registry: None,
            resolved_fields: None,
        }
    }

    #[test]
    fn test_derive_input_from_class_context() {
        let ctx = make_test_class_context();
        let input = DeriveInput::from_context(ctx).expect("should parse");

        assert_eq!(input.name(), "User");
        assert!(input.as_class().is_some());
        assert!(input.as_enum().is_none());

        let class = input.as_class().unwrap();
        assert_eq!(class.fields().len(), 2);
        assert!(class.field("id").is_some());
        assert!(class.field("name").is_some());
        assert!(class.field("nonexistent").is_none());

        let field_names: Vec<_> = class.field_names().collect();
        assert_eq!(field_names, vec!["id", "name"]);
    }

    #[test]
    fn test_derive_input_from_enum_context() {
        let ctx = MacroContextIR {
            abi_version: 1,
            macro_kind: MacroKind::Derive,
            macro_name: "Debug".into(),
            module_path: "@test/macro".into(),
            decorator_span: SpanIR::new(0, 10),
            macro_name_span: None,
            target_span: SpanIR::new(11, 100),
            file_name: "test.ts".into(),
            target: TargetIR::Enum(EnumIR {
                name: "Status".into(),
                span: SpanIR::new(11, 100),
                body_span: SpanIR::new(18, 99),
                decorators: vec![],
                variants: vec![
                    EnumVariantIR {
                        name: "Active".into(),
                        span: SpanIR::new(20, 30),
                        value: crate::abi::EnumValue::Auto,
                        decorators: vec![],
                    },
                    EnumVariantIR {
                        name: "Inactive".into(),
                        span: SpanIR::new(35, 45),
                        value: crate::abi::EnumValue::Auto,
                        decorators: vec![],
                    },
                ],
                is_const: false,
            }),
            target_source: "enum Status { Active, Inactive }".into(),
            import_registry: crate::import_registry::ImportRegistry::new(),
            config: None,
            type_registry: None,
            resolved_fields: None,
        };

        let input = DeriveInput::from_context(ctx).expect("should parse");

        assert_eq!(input.name(), "Status");
        assert!(input.as_enum().is_some());
        assert!(input.as_class().is_none());

        let enum_ = input.as_enum().unwrap();
        assert_eq!(enum_.variants().len(), 2);
        assert!(enum_.variant("Active").is_some());
        assert!(enum_.variant("Inactive").is_some());

        let variant_names: Vec<_> = enum_.variant_names().collect();
        assert_eq!(variant_names, vec!["Active", "Inactive"]);
    }

    #[test]
    fn test_ident_display() {
        let ident = Ident::new("MyClass", SpanIR::new(0, 7));
        assert_eq!(format!("{}", ident), "MyClass");
        assert_eq!(ident.as_str(), "MyClass");
        assert_eq!(ident.as_ref(), "MyClass");
    }
}