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
//! Patch-based code modification types.
//!
//! This module provides the types used by macros to express code modifications.
//! Instead of returning complete transformed source code, macros return a list
//! of [`Patch`] operations that describe insertions, replacements, and deletions.
//!
//! ## Why Patches?
//!
//! The patch-based approach has several advantages:
//!
//! 1. **Composable**: Multiple macros can contribute patches to the same file
//! 2. **Precise**: Each patch targets a specific span, preserving surrounding code
//! 3. **Traceable**: Patches can track which macro generated them
//! 4. **Efficient**: Only changed regions need to be processed
//!
//! ## Patch Types
//!
//! | Variant | Description |
//! |---------|-------------|
//! | [`Patch::Insert`] | Insert code at a position (zero-width span) |
//! | [`Patch::Replace`] | Replace code in a span with new code |
//! | [`Patch::Delete`] | Remove code in a span |
//! | [`Patch::InsertRaw`] | Insert raw text with optional context |
//! | [`Patch::ReplaceRaw`] | Replace with raw text and context |
//!
//! ## Example
//!
//! ```rust,no_run
//! use macroforge_ts_syn::{Patch, PatchCode, SpanIR, MacroResult};
//!
//! fn add_method_to_class(body_span: SpanIR) -> MacroResult {
//!     // Insert a method just before the closing brace
//!     let insert_point = SpanIR::new(body_span.end - 1, body_span.end - 1);
//!
//!     let patch = Patch::Insert {
//!         at: insert_point,
//!         code: "toString() { return 'MyClass'; }".into(),
//!         source_macro: Some("Debug".to_string()),
//!     };
//!
//!     MacroResult {
//!         runtime_patches: vec![patch],
//!         ..Default::default()
//!     }
//! }
//! ```

use serde::{Deserialize, Serialize};

use crate::abi::{SpanIR, swc_ast};

/// Specifies where generated code should be inserted relative to the target.
///
/// This enum provides structured control over code placement, replacing
/// the string-based marker system (`/* @macroforge:body */`, etc.).
///
/// # Positions
///
/// ```text
/// // ─── Top ─────────────────────────
/// import { foo } from "./runtime";
///
/// // ─── Above ───────────────────────
/// /** @derive(Debug) */
/// class User {
///     // ─── Within ──────────────────
///     name: string;
///     debug() { ... }  // <-- inserted here
/// }
/// // ─── Below ───────────────────────
/// User.prototype.toJSON = ...;
///
/// // ─── Bottom ──────────────────────
/// export { User };
/// ```
///
/// # Example
///
/// ```rust
/// use macroforge_ts_syn::InsertPos;
///
/// // Generated imports go at the top
/// let import_pos = InsertPos::Top;
///
/// // Generated methods go inside the class
/// let method_pos = InsertPos::Within;
///
/// // Prototype extensions go after the class
/// let proto_pos = InsertPos::Below;
/// ```
#[derive(Serialize, Deserialize, Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum InsertPos {
    /// Insert at the top of the file (before all other code).
    /// Use for imports and module-level setup.
    Top,

    /// Insert immediately before the target declaration.
    /// Use for helper functions or type declarations that the target depends on.
    Above,

    /// Insert inside the target's body (class body, interface body, etc.).
    /// Use for generated methods, properties, or members.
    Within,

    /// Insert immediately after the target declaration.
    /// Use for prototype extensions, companion functions, or related code.
    #[default]
    Below,

    /// Insert at the bottom of the file (after all other code).
    /// Use for exports or cleanup code.
    Bottom,
}
#[cfg(feature = "swc")]
use swc_core::common::{DUMMY_SP, SyntaxContext};

/// A code modification operation returned by macros.
///
/// Patches describe how to transform the original source code. They are
/// applied in order by the macro host to produce the final output.
///
/// # Source Macro Tracking
///
/// Patches can optionally track which macro generated them via the
/// `source_macro` field. This is useful for:
/// - Debugging macro output
/// - Source mapping in generated code
/// - Error attribution
///
/// Use [`with_source_macro()`](Self::with_source_macro) to set this field.
///
/// # Example
///
/// ```rust,no_run
/// use macroforge_ts_syn::{Patch, SpanIR};
///
/// // Insert new code
/// let insert = Patch::Insert {
///     at: SpanIR::new(100, 100),  // Zero-width span = insertion point
///     code: "// generated code".into(),
///     source_macro: Some("MyMacro".to_string()),
/// };
///
/// // Replace existing code
/// let replace = Patch::Replace {
///     span: SpanIR::new(50, 75),  // The span to replace
///     code: "newCode()".into(),
///     source_macro: None,
/// };
///
/// // Delete code
/// let delete = Patch::Delete {
///     span: SpanIR::new(200, 250),
/// };
/// ```
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub enum Patch {
    /// Insert code at a specific position.
    ///
    /// The `at` span should typically be zero-width (`start == end`)
    /// to mark an insertion point. The code is inserted at that position.
    Insert {
        /// The position to insert at (use zero-width span for pure insertion).
        at: SpanIR,
        /// The code to insert.
        code: PatchCode,
        /// Which macro generated this patch (e.g., "Debug", "Clone").
        #[serde(default)]
        source_macro: Option<String>,
    },

    /// Replace code in a span with new code.
    ///
    /// The original code in `span` is removed and replaced with `code`.
    Replace {
        /// The span of code to replace.
        span: SpanIR,
        /// The replacement code.
        code: PatchCode,
        /// Which macro generated this patch.
        #[serde(default)]
        source_macro: Option<String>,
    },

    /// Delete code in a span.
    ///
    /// The code in `span` is removed entirely.
    Delete {
        /// The span of code to delete.
        span: SpanIR,
    },

    /// Insert raw text with optional context.
    ///
    /// Similar to `Insert`, but takes a raw string and optional context
    /// for more control over formatting.
    InsertRaw {
        /// The position to insert at.
        at: SpanIR,
        /// The raw code string to insert.
        code: String,
        /// Optional context hint (e.g., "class_body", "module_level").
        context: Option<String>,
        /// Which macro generated this patch.
        #[serde(default)]
        source_macro: Option<String>,
    },

    /// Replace code with raw text and optional context.
    ///
    /// Similar to `Replace`, but takes a raw string and optional context.
    ReplaceRaw {
        /// The span of code to replace.
        span: SpanIR,
        /// The raw replacement code string.
        code: String,
        /// Optional context hint for formatting.
        context: Option<String>,
        /// Which macro generated this patch.
        #[serde(default)]
        source_macro: Option<String>,
    },
}

impl Patch {
    /// Get the source macro name for this patch, if set
    pub fn source_macro(&self) -> Option<&str> {
        match self {
            Patch::Insert { source_macro, .. } => source_macro.as_deref(),
            Patch::Replace { source_macro, .. } => source_macro.as_deref(),
            Patch::Delete { .. } => None,
            Patch::InsertRaw { source_macro, .. } => source_macro.as_deref(),
            Patch::ReplaceRaw { source_macro, .. } => source_macro.as_deref(),
        }
    }

    /// Set the source macro name for this patch
    pub fn with_source_macro(self, macro_name: &str) -> Self {
        match self {
            Patch::Insert { at, code, .. } => Patch::Insert {
                at,
                code,
                source_macro: Some(macro_name.to_string()),
            },
            Patch::Replace { span, code, .. } => Patch::Replace {
                span,
                code,
                source_macro: Some(macro_name.to_string()),
            },
            Patch::Delete { span } => Patch::Delete { span },
            Patch::InsertRaw {
                at, code, context, ..
            } => Patch::InsertRaw {
                at,
                code,
                context,
                source_macro: Some(macro_name.to_string()),
            },
            Patch::ReplaceRaw {
                span,
                code,
                context,
                ..
            } => Patch::ReplaceRaw {
                span,
                code,
                context,
                source_macro: Some(macro_name.to_string()),
            },
        }
    }
}

/// The code content of a patch, supporting both text and AST representations.
///
/// `PatchCode` can hold code in different forms:
///
/// - **Text**: Raw source code strings (serializable)
/// - **AST nodes**: SWC AST types for programmatic construction (not serializable)
///
/// When serialized, AST variants are converted to placeholder text since
/// SWC AST nodes are not directly serializable.
///
/// # Example
///
/// ```rust
/// use macroforge_ts_syn::PatchCode;
///
/// // From a string
/// let _text_code: PatchCode = "myMethod() {}".into();
///
/// // From a String
/// let method_code = "toString() { return 'MyClass'; }".to_string();
/// let _code: PatchCode = method_code.into();
/// ```
#[derive(Clone, Debug, PartialEq)]
pub enum PatchCode {
    /// Raw source code as text.
    ///
    /// This is the most portable form, as it can be serialized
    /// and processed by any consumer.
    Text(String),

    /// An SWC class member AST node.
    ///
    /// Use this when constructing class members programmatically
    /// using SWC's AST types or the `quote!` macro.
    ClassMember(swc_ast::ClassMember),

    /// An SWC statement AST node.
    ///
    /// Use for standalone statements or function/method bodies.
    Stmt(swc_ast::Stmt),

    /// An SWC module item AST node.
    ///
    /// Use for top-level declarations like imports, exports,
    /// or function/class declarations.
    ModuleItem(swc_ast::ModuleItem),
}

// Custom serde for PatchCode - only serialize Text variant, skip AST variants
impl serde::Serialize for PatchCode {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            PatchCode::Text(s) => serializer.serialize_str(s),
            _ => serializer.serialize_str("/* AST node - cannot serialize */"),
        }
    }
}

impl<'de> serde::Deserialize<'de> for PatchCode {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Ok(PatchCode::Text(s))
    }
}

impl From<String> for PatchCode {
    fn from(value: String) -> Self {
        PatchCode::Text(value)
    }
}

impl From<&str> for PatchCode {
    fn from(value: &str) -> Self {
        PatchCode::Text(value.to_string())
    }
}

impl From<swc_ast::ClassMember> for PatchCode {
    fn from(member: swc_ast::ClassMember) -> Self {
        PatchCode::ClassMember(member)
    }
}

impl From<swc_ast::Stmt> for PatchCode {
    fn from(stmt: swc_ast::Stmt) -> Self {
        PatchCode::Stmt(stmt)
    }
}

impl From<swc_ast::ModuleItem> for PatchCode {
    fn from(item: swc_ast::ModuleItem) -> Self {
        PatchCode::ModuleItem(item)
    }
}

impl From<Vec<swc_ast::Stmt>> for PatchCode {
    fn from(stmts: Vec<swc_ast::Stmt>) -> Self {
        // For Vec<Stmt>, wrap in a block and convert to a single Stmt
        if stmts.len() == 1 {
            PatchCode::Stmt(stmts.into_iter().next().unwrap())
        } else {
            PatchCode::Stmt(swc_ast::Stmt::Block(swc_ast::BlockStmt {
                span: DUMMY_SP,
                ctxt: SyntaxContext::empty(),
                stmts,
            }))
        }
    }
}

impl From<Vec<swc_ast::ModuleItem>> for PatchCode {
    fn from(items: Vec<swc_ast::ModuleItem>) -> Self {
        // For Vec<ModuleItem>, take the first if there's only one
        if items.len() == 1 {
            PatchCode::ModuleItem(items.into_iter().next().unwrap())
        } else {
            // Multiple items - convert to a string representation
            // This is a limitation since PatchCode doesn't have a Vec variant
            let code = items
                .iter()
                .map(|_| "/* generated code */")
                .collect::<Vec<_>>()
                .join("\n");
            PatchCode::Text(code)
        }
    }
}

/// The result returned by a macro function.
///
/// `MacroResult` is the standard return type for all macro functions.
/// It contains patches to apply to the code, diagnostic messages,
/// and optional debug information.
///
/// # Patch Separation
///
/// Patches are separated into two categories:
///
/// - `runtime_patches`: Applied to the `.js`/`.ts` runtime code
/// - `type_patches`: Applied to `.d.ts` type declaration files
///
/// This separation allows macros to generate different code for
/// runtime and type-checking contexts.
///
/// # Example
///
/// ```rust,no_run
/// use macroforge_ts_syn::{MacroResult, Patch, Diagnostic, DiagnosticLevel, InsertPos};
///
/// fn my_macro() -> MacroResult {
///     // Success with patches
///     MacroResult {
///         runtime_patches: vec![/* ... */],
///         type_patches: vec![],
///         diagnostics: vec![],
///         tokens: None,
///         insert_pos: InsertPos::Below,
///         debug: Some("Generated 2 methods".to_string()),
///         ..Default::default()
///     }
/// }
///
/// fn my_macro_error() -> MacroResult {
///     // Error result
///     MacroResult {
///         diagnostics: vec![Diagnostic {
///             level: DiagnosticLevel::Error,
///             message: "Invalid input".to_string(),
///             span: None,
///             notes: vec![],
///             help: Some("Try using @derive(Debug) instead".to_string()),
///         }],
///         ..Default::default()
///     }
/// }
/// ```
#[derive(Serialize, Deserialize, Clone, Debug, Default)]
pub struct MacroResult {
    /// Patches to apply to the runtime JS/TS code.
    pub runtime_patches: Vec<Patch>,

    /// Patches to apply to the `.d.ts` type declarations.
    pub type_patches: Vec<Patch>,

    /// Diagnostic messages (errors, warnings, info).
    /// If any error diagnostics are present, the macro expansion is considered failed.
    pub diagnostics: Vec<Diagnostic>,

    /// Optional raw token stream (source code) returned by the macro.
    /// Used for macros that generate complete output rather than patches.
    pub tokens: Option<String>,

    /// Where to insert the tokens relative to the target.
    /// Defaults to `Below` (after the target declaration).
    /// This is used when `tokens` is set and no string markers are present.
    #[serde(default)]
    pub insert_pos: InsertPos,

    /// Optional debug information for development.
    /// Can be displayed in verbose mode or logged for debugging.
    pub debug: Option<String>,

    /// Cross-module function suffixes registered by external macros for auto-import resolution.
    /// The framework combines these with its built-in suffixes when resolving cross-module
    /// references following the `{camelCaseTypeName}{Suffix}` naming convention.
    #[serde(default)]
    pub cross_module_suffixes: Vec<String>,

    /// Cross-module type suffixes for auto-import resolution of PascalCase type references.
    /// Unlike `cross_module_suffixes` (which resolve `{camelCase}{Suffix}` function calls),
    /// these resolve `{PascalCase}{Suffix}` type references and generate `import type` statements.
    /// Used for types like `ColorsErrors`, `ColorsTainted`, `ColorsFieldControllers`.
    #[serde(default)]
    pub cross_module_type_suffixes: Vec<String>,

    /// Imports requested by the macro via `TsStream::add_import()` and related methods.
    /// These are captured from the thread-local `ImportRegistry` when `into_result()` is called,
    /// so they survive serialization across process boundaries (important for external macros
    /// that run in a child Node.js process).
    #[serde(default)]
    pub imports: Vec<crate::import_registry::GeneratedImport>,
}

/// A diagnostic message from macro expansion.
///
/// Diagnostics provide feedback about the macro expansion process,
/// including errors, warnings, and informational messages. Each
/// diagnostic can include a source span, additional notes, and
/// help text.
///
/// # Example
///
/// ```rust,no_run
/// use macroforge_ts_syn::{Diagnostic, DiagnosticLevel, SpanIR};
///
/// let error = Diagnostic {
///     level: DiagnosticLevel::Error,
///     message: "Field 'password' cannot be serialized".to_string(),
///     span: Some(SpanIR::new(100, 115)),
///     notes: vec!["Sensitive fields should use @serde(skip)".to_string()],
///     help: Some("Add @serde(skip) decorator to this field".to_string()),
/// };
/// ```
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq)]
pub struct Diagnostic {
    /// The severity level of the diagnostic.
    pub level: DiagnosticLevel,

    /// The main diagnostic message.
    pub message: String,

    /// Optional source span where the issue occurred.
    /// If `None`, the diagnostic applies to the whole macro invocation.
    pub span: Option<SpanIR>,

    /// Additional notes providing context.
    pub notes: Vec<String>,

    /// Optional help text suggesting how to fix the issue.
    pub help: Option<String>,
}

/// The severity level of a diagnostic message.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub enum DiagnosticLevel {
    /// An error that prevents successful macro expansion.
    /// Any error diagnostic causes the macro result to be considered failed.
    Error,

    /// A warning that doesn't prevent expansion but indicates potential issues.
    Warning,

    /// Informational message for debugging or user guidance.
    Info,
}

/// A builder for collecting diagnostics during macro expansion.
///
/// `DiagnosticCollector` provides a convenient way to accumulate
/// multiple diagnostics and then convert them to a `Vec<Diagnostic>`
/// for inclusion in a `MacroResult`.
///
/// # Example
///
/// ```rust
/// use macroforge_ts_syn::{DiagnosticCollector, SpanIR};
///
/// let mut collector = DiagnosticCollector::new();
///
/// // Add diagnostics as you encounter issues
/// collector.warning(SpanIR::new(10, 20), "Avoid using 'any' type");
/// collector.warning(SpanIR::new(30, 40), "Consider using strict mode");
///
/// // Convert to a vector for MacroResult
/// let diagnostics = collector.into_vec();
/// assert_eq!(diagnostics.len(), 2);
/// ```
#[derive(Default, Clone, Debug)]
pub struct DiagnosticCollector {
    diagnostics: Vec<Diagnostic>,
}

impl DiagnosticCollector {
    /// Create a new empty collector
    pub fn new() -> Self {
        Self::default()
    }

    /// Add a diagnostic to the collection
    pub fn push(&mut self, diagnostic: Diagnostic) {
        self.diagnostics.push(diagnostic);
    }

    /// Add an error diagnostic with span
    pub fn error(&mut self, span: SpanIR, message: impl Into<String>) {
        self.push(Diagnostic {
            level: DiagnosticLevel::Error,
            message: message.into(),
            span: Some(span),
            notes: vec![],
            help: None,
        });
    }

    /// Add an error diagnostic with span and help text
    pub fn error_with_help(
        &mut self,
        span: SpanIR,
        message: impl Into<String>,
        help: impl Into<String>,
    ) {
        self.push(Diagnostic {
            level: DiagnosticLevel::Error,
            message: message.into(),
            span: Some(span),
            notes: vec![],
            help: Some(help.into()),
        });
    }

    /// Add a warning diagnostic with span
    pub fn warning(&mut self, span: SpanIR, message: impl Into<String>) {
        self.push(Diagnostic {
            level: DiagnosticLevel::Warning,
            message: message.into(),
            span: Some(span),
            notes: vec![],
            help: None,
        });
    }

    /// Merge diagnostics from another collector
    pub fn extend(&mut self, other: DiagnosticCollector) {
        self.diagnostics.extend(other.diagnostics);
    }

    /// Check if there are any errors in the collection
    pub fn has_errors(&self) -> bool {
        self.diagnostics
            .iter()
            .any(|d| d.level == DiagnosticLevel::Error)
    }

    /// Check if the collection is empty
    pub fn is_empty(&self) -> bool {
        self.diagnostics.is_empty()
    }

    /// Get the number of diagnostics
    pub fn len(&self) -> usize {
        self.diagnostics.len()
    }

    /// Convert to a Vec of Diagnostics
    pub fn into_vec(self) -> Vec<Diagnostic> {
        self.diagnostics
    }

    /// Get a reference to the diagnostics
    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diagnostics
    }
}