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
//! # Debug Macro Implementation
//!
//! The `Debug` macro generates a human-readable `toString()` method for
//! TypeScript classes, interfaces, enums, and type aliases.
//!
//! ## Generated Output
//!
//! **Classes**: Generates a standalone function `{className}ToString(value)` and a static wrapper
//! method `static toString(value)` returning a string like `"ClassName { field1: value1, field2: value2 }"`.
//!
//! **Enums**: Generates a standalone function `{enumName}ToString(value)` that performs
//! reverse lookup on numeric enums.
//!
//! **Interfaces**: Generates a standalone function `{ifaceName}ToString(value)`.
//!
//! **Type Aliases**: Generates a standalone function using JSON.stringify for
//! complex types, or field enumeration for object types.
//!
//! Names use **camelCase** conversion (e.g., `User` → `userToString`).
//!
//!
//! ## Field-Level Options
//!
//! The `@debug` decorator supports:
//!
//! - `skip` - Exclude the field from debug output
//! - `rename = "label"` - Use a custom label instead of the field name
//!
//! ## Example
//!
//! ```typescript
//! /** @derive(Debug) */
//! class User {
//!     /** @debug({ rename: "id" }) */
//!     userId: number;
//!
//!     /** @debug({ skip: true }) */
//!     password: string;
//!
//!     email: string;
//! }
//! ```
//!
//! Generated output:
//!
//! ```typescript
//! class User {
//!     userId: number;
//!
//!     password: string;
//!
//!     email: string;
//!
//!     static toString(value: User): string {
//!         return userToString(value);
//!     }
//! }
//!
//! export function userToString(value: User): string {
//!     const parts: string[] = [];
//!     parts.push('id: ' + value.userId);
//!     parts.push('email: ' + value.email);
//!     return 'User { ' + parts.join(', ') + ' }';
//! }
//! ```

use convert_case::{Case, Casing};

use crate::builtin::derive_common::{collection_element_type, standalone_fn_name, type_has_derive};
use crate::macros::{ts_macro_derive, ts_template};
use crate::swc_ecma_ast::Expr;
use crate::ts_syn::abi::ir::type_registry::{ResolvedTypeRef, TypeRegistry};
use crate::ts_syn::ts_ident;
use crate::ts_syn::{Data, DeriveInput, MacroforgeError, TsStream, parse_ts_macro_input};

/// Options parsed from @Debug decorator on fields
#[derive(Default)]
struct DebugFieldOptions {
    skip: bool,
    rename: Option<String>,
}

impl DebugFieldOptions {
    fn from_decorators(decorators: &[crate::ts_syn::abi::DecoratorIR]) -> Self {
        let mut opts = DebugFieldOptions::default();
        for decorator in decorators {
            if !decorator.name.eq_ignore_ascii_case("debug") {
                continue;
            }

            let args = decorator.args_src.trim();
            if args.is_empty() {
                continue;
            }

            if has_flag(args, "skip") {
                opts.skip = true;
            }

            if let Some(rename) = extract_named_string(args, "rename") {
                opts.rename = Some(rename);
            }
        }
        opts
    }
}

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"))
}

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
}

/// Debug field info: (label, field_name, ts_type)
type DebugField = (String, String, String);

/// Generate a debug value expression for a field.
/// When the field type has @derive(Debug), calls the standalone toString function.
fn debug_value_expr(
    field_name: &str,
    _ts_type: &str,
    var: &str,
    resolved: Option<&ResolvedTypeRef>,
    registry: Option<&TypeRegistry>,
) -> String {
    let access = format!("{var}.{field_name}");

    if let (Some(resolved), Some(registry)) = (resolved, registry) {
        // Direct known Debug type → call standalone toString function
        if !resolved.is_collection
            && resolved.registry_key.is_some()
            && type_has_derive(registry, &resolved.base_type_name, "Debug")
        {
            let fn_name = standalone_fn_name(&resolved.base_type_name, "ToString");
            return format!("{fn_name}({access})");
        }

        // Array of known Debug type → map toString
        if resolved.is_collection
            && let Some(elem) = collection_element_type(resolved)
            && elem.registry_key.is_some()
            && type_has_derive(registry, &elem.base_type_name, "Debug")
        {
            let elem_fn = standalone_fn_name(&elem.base_type_name, "ToString");
            return format!("'[' + {access}.map(v => {elem_fn}(v)).join(', ') + ']'");
        }
    }

    // Fallback: string concatenation (original behavior)
    access
}

#[ts_macro_derive(
    Debug,
    description = "Generates a toString() method for debugging",
    attributes((debug, "Configure debug output for this field. Options: skip (exclude from output), rename (custom label)"))
)]
pub fn derive_debug_macro(mut input: TsStream) -> Result<TsStream, MacroforgeError> {
    let input = parse_ts_macro_input!(input as DeriveInput);
    let resolved_fields = input.context.resolved_fields.as_ref();
    let type_registry = input.context.type_registry.as_ref();

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

            // Collect fields that should be included in debug output
            let debug_fields: Vec<DebugField> = class
                .fields()
                .iter()
                .filter_map(|field| {
                    let opts = DebugFieldOptions::from_decorators(&field.decorators);
                    if opts.skip {
                        return None;
                    }
                    let label = opts.rename.unwrap_or_else(|| field.name.clone());
                    Some((label, field.name.clone(), field.ts_type.clone()))
                })
                .collect();

            // Generate function name (always prefix style)
            let fn_name_ident = ts_ident!("{}ToString", class_name.to_case(Case::Camel));
            let fn_name_expr: Expr = fn_name_ident.clone().into();

            // Build push statements with type-aware value expressions
            let mut push_stmts = String::new();
            for (label, name, ts_type) in &debug_fields {
                let resolved = resolved_fields.and_then(|rf| rf.get(name));
                let val_expr = debug_value_expr(name, ts_type, "value", resolved, type_registry);
                push_stmts.push_str(&format!("parts.push(\"{label}: \" + {val_expr});\n"));
            }

            // Generate standalone function with value parameter
            let standalone = if debug_fields.is_empty() {
                ts_template! {
                    export function @{fn_name_ident}(value: @{class_ident.clone()}): string {
                        return "@{class_name} {}";
                    }
                }
            } else {
                ts_template! {
                    export function @{fn_name_ident}(value: @{class_ident.clone()}): string {
                        const parts: string[] = [];
                        {$typescript TsStream::from_string(push_stmts)}
                        return "@{class_name} { " + parts.join(", ") + " }";
                    }
                }
            };

            // Generate static wrapper method that delegates to standalone function
            let class_body = ts_template!(Within {
                static toString(value: @{class_ident.clone()}): string {
                    return @{fn_name_expr}(value);
                }
            });

            // Combine standalone function with class body using {$typescript}
            // The standalone output (no marker) must come FIRST so it defaults to "below" (after class)
            // The body! output has /* @macroforge:body */ marker for class body insertion
            Ok(ts_template! {
                {$typescript standalone}
                {$typescript class_body}
            })
        }
        Data::Enum(enum_data) => {
            let enum_name = input.name();
            let enum_ident = ts_ident!(enum_name);
            let _variants: Vec<String> = enum_data
                .variants()
                .iter()
                .map(|v| v.name.clone())
                .collect();

            let fn_name_ident = ts_ident!("{}ToString", enum_name.to_case(Case::Camel));
            // Convert ident to expression for array access
            let enum_expr: Expr = enum_ident.clone().into();
            Ok(ts_template! {
                export function @{fn_name_ident}(value: @{enum_ident.clone()}): string {
                    {#if !_variants.is_empty()}
                        const key = @{enum_expr.clone()}[value as unknown as keyof typeof @{enum_ident.clone()}];
                        if (key !== undefined) {
                            return "@{enum_name}." + key;
                        }
                        return "@{enum_name}(" + String(value) + ")";
                    {:else}
                        return "@{enum_name}(" + String(value) + ")";
                    {/if}
                }
            })
        }
        Data::Interface(interface) => {
            let interface_name = input.name();
            let interface_ident = ts_ident!(interface_name);

            // Collect fields that should be included in debug output
            let debug_fields: Vec<DebugField> = interface
                .fields()
                .iter()
                .filter_map(|field| {
                    let opts = DebugFieldOptions::from_decorators(&field.decorators);
                    if opts.skip {
                        return None;
                    }
                    let label = opts.rename.unwrap_or_else(|| field.name.clone());
                    Some((label, field.name.clone(), field.ts_type.clone()))
                })
                .collect();

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

            if debug_fields.is_empty() {
                Ok(ts_template! {
                    export function @{fn_name_ident}(value: @{interface_ident.clone()}): string {
                        return "@{interface_name} {}";
                    }
                })
            } else {
                let mut push_stmts = String::new();
                for (label, name, ts_type) in &debug_fields {
                    let resolved = resolved_fields.and_then(|rf| rf.get(name));
                    let val_expr =
                        debug_value_expr(name, ts_type, "value", resolved, type_registry);
                    push_stmts.push_str(&format!("parts.push(\"{label}: \" + {val_expr});\n"));
                }

                Ok(ts_template! {
                    export function @{fn_name_ident}(value: @{interface_ident.clone()}): string {
                        const parts: string[] = [];
                        {$typescript TsStream::from_string(push_stmts)}
                        return "@{interface_name} { " + parts.join(", ") + " }";
                    }
                })
            }
        }
        Data::TypeAlias(type_alias) => {
            let type_name = input.name();
            let type_ident = ts_ident!(type_name);

            // Generate different output based on type body
            if type_alias.is_object() {
                // Object type: show fields
                let debug_fields: Vec<DebugField> = type_alias
                    .as_object()
                    .unwrap()
                    .iter()
                    .filter_map(|field| {
                        let opts = DebugFieldOptions::from_decorators(&field.decorators);
                        if opts.skip {
                            return None;
                        }
                        let label = opts.rename.unwrap_or_else(|| field.name.clone());
                        Some((label, field.name.clone(), field.ts_type.clone()))
                    })
                    .collect();

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

                if debug_fields.is_empty() {
                    Ok(ts_template! {
                        export function @{fn_name_ident}(value: @{type_ident.clone()}): string {
                            return "@{type_name} {}";
                        }
                    })
                } else {
                    let mut push_stmts = String::new();
                    for (label, name, ts_type) in &debug_fields {
                        let resolved = resolved_fields.and_then(|rf| rf.get(name));
                        let val_expr =
                            debug_value_expr(name, ts_type, "value", resolved, type_registry);
                        push_stmts.push_str(&format!("parts.push(\"{label}: \" + {val_expr});\n"));
                    }

                    Ok(ts_template! {
                        export function @{fn_name_ident}(value: @{type_ident.clone()}): string {
                            const parts: string[] = [];
                            {$typescript TsStream::from_string(push_stmts)}
                            return "@{type_name} { " + parts.join(", ") + " }";
                        }
                    })
                }
            } else {
                // Union, intersection, tuple, or simple alias: use JSON.stringify
                let fn_name_ident = ts_ident!("{}ToString", type_name.to_case(Case::Camel));

                Ok(ts_template! {
                    export function @{fn_name_ident}(value: @{type_ident.clone()}): string {
                        return "@{type_name}(" + JSON.stringify(value) + ")";
                    }
                })
            }
        }
    }
}

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

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

    #[test]
    fn test_skip_flag() {
        let decorator = DecoratorIR {
            name: "Debug".into(),
            args_src: "skip".into(),
            span: span(),
            node: None,
        };

        let opts = DebugFieldOptions::from_decorators(&[decorator]);
        assert!(opts.skip, "skip flag should be true");
    }

    #[test]
    fn test_skip_false_keeps_field() {
        let decorator = DecoratorIR {
            name: "Debug".into(),
            args_src: r#"{ skip: false }"#.into(),
            span: span(),
            node: None,
        };

        let opts = DebugFieldOptions::from_decorators(&[decorator]);
        assert!(!opts.skip, "skip: false should not skip the field");
    }

    #[test]
    fn test_rename_option() {
        let decorator = DecoratorIR {
            name: "Debug".into(),
            args_src: r#"{ rename: "identifier" }"#.into(),
            span: span(),
            node: None,
        };

        let opts = DebugFieldOptions::from_decorators(&[decorator]);
        assert_eq!(opts.rename.as_deref(), Some("identifier"));
    }
}