macroforge_ts 0.1.80

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
#![cfg(feature = "swc")]

// Integration tests for ts_template! macro and derive macros
// Migrated from tooling/playground/tests/rust-tests

#[path = "template/ir_declarations.rs"]
mod ir_declarations;
#[path = "template/ir_expressions.rs"]
mod ir_expressions;
#[path = "template/ir_patterns.rs"]
mod ir_patterns;
#[path = "template/ir_statements.rs"]
mod ir_statements;
#[path = "template/ir_types.rs"]
mod ir_types;
#[path = "template/test_single.rs"]
mod test_single;

use macroforge_ts::macros::ts_template;
use macroforge_ts::swc_core::common::{FileName, GLOBALS, Globals, SourceMap, sync::Lrc};
use macroforge_ts::swc_core::ecma::parser::{Parser, StringInput, Syntax, TsSyntax, lexer::Lexer};
use macroforge_ts::ts_syn::abi::{MacroContextIR, SpanIR};
use macroforge_ts::ts_syn::{
    Data, DeriveInput, ParseTs, TsStream, lower_classes, lower_interfaces,
};

fn capitalize(s: &str) -> String {
    let mut chars = s.chars();
    match chars.next() {
        Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
        None => String::new(),
    }
}

// Helper to create a TsStream with valid context for testing derive macros
fn create_test_stream(source: &str) -> TsStream {
    GLOBALS.set(&Globals::new(), || {
        let cm: Lrc<SourceMap> = Default::default();
        let fm = cm.new_source_file(
            FileName::Custom("test.ts".into()).into(),
            source.to_string(),
        );

        let lexer = Lexer::new(
            Syntax::Typescript(TsSyntax {
                tsx: false,
                decorators: true,
                ..Default::default()
            }),
            Default::default(),
            StringInput::from(&*fm),
            None,
        );

        let mut parser = Parser::new_from(lexer);
        let module = parser.parse_module().expect("Failed to parse test source");

        let classes = lower_classes(&module, source, None).expect("Failed to lower classes");
        let class = classes
            .first()
            .expect("Expected at least one class in test source")
            .clone();

        let ctx = MacroContextIR::new_derive_class(
            "TestMacro".to_string(),
            "test-macro".to_string(),
            SpanIR::new(0, 0), // Dummy spans
            class.span,
            "test.ts".to_string(),
            class,
            source.to_string(),
        );

        TsStream::with_context(source, "test.ts", ctx).unwrap()
    })
}

// Helper to create a TsStream with valid context for testing derive macros on interfaces
fn create_test_stream_interface(source: &str) -> TsStream {
    GLOBALS.set(&Globals::new(), || {
        let cm: Lrc<SourceMap> = Default::default();
        let fm = cm.new_source_file(
            FileName::Custom("test.ts".into()).into(),
            source.to_string(),
        );

        let lexer = Lexer::new(
            Syntax::Typescript(TsSyntax {
                tsx: false,
                decorators: true,
                ..Default::default()
            }),
            Default::default(),
            StringInput::from(&*fm),
            None,
        );

        let mut parser = Parser::new_from(lexer);
        let module = parser.parse_module().expect("Failed to parse test source");

        let interfaces =
            lower_interfaces(&module, source, None).expect("Failed to lower interfaces");
        let interface = interfaces
            .first()
            .expect("Expected at least one interface in test source")
            .clone();

        let ctx = MacroContextIR::new_derive_interface(
            "TestMacro".to_string(),
            "test-macro".to_string(),
            SpanIR::new(0, 0), // Dummy spans
            interface.span,
            "test.ts".to_string(),
            interface,
            source.to_string(),
        );

        TsStream::with_context(source, "test.ts", ctx).unwrap()
    })
}

#[test]
pub fn derive_json_macro() {
    let raw = include_str!("./fixtures/macro-user.ts");
    let mut stream = create_test_stream(raw);

    let input = DeriveInput::parse(&mut stream).unwrap();

    match &input.data {
        Data::Class(class) => {
            // Use Rust-style templating for clean code generation!
            let stream = ts_template! {
                toJSON(): Record<string, unknown> {

                    const result: Record<string, unknown> = {};

                    {#for field in class.field_names()}
                        result.@{field} = this.@{field};
                    {/for}

                    return result;
                }
            };

            let source = stream.source();
            println!("Generated JSON Source:\n{}", source);

            // Assertions - expect clean formatting now!
            assert!(source.contains("toJSON(): Record<string, unknown>"));
            assert!(source.contains("result.id = this.id"));
            assert!(source.contains("result.name = this.name"));
            assert!(source.contains("result.role = this.role"));
        }
        _ => panic!("Expected class data in macro-user.ts"),
    }
}

#[test]
pub fn field_controller_macro() {
    let raw = include_str!("./fixtures/field-controller.fixture.ts");
    let mut stream = create_test_stream_interface(raw);

    let input = DeriveInput::parse(&mut stream).unwrap();

    match &input.data {
        Data::Interface(interface) => {
            // Collect decorated fields
            let decorated_fields: Vec<_> = interface
                .fields()
                .iter()
                .filter(|field| {
                    field
                        .decorators
                        .iter()
                        .any(|d| d.name == "fieldController" || d.name == "textAreaController")
                })
                .collect();

            let class_name = input.name();
            let base_props_method = format!("make{}BaseProps", class_name);

            // Prepare field data for template
            let field_data: Vec<_> = decorated_fields
                .iter()
                .map(|field| {
                    let field_name = &field.name;
                    (
                        format!("\"{}\"", capitalize(field_name)), // label_text
                        format!("\"{}\"", field_name),             // field_path_literal
                        format!("{}FieldPath", field_name),        // field_path_prop
                        format!("{}FieldController", field_name),  // field_controller_prop
                        &field.ts_type,
                    )
                })
                .collect();

            // ===== Generate All Runtime Code in Single Template =====

            let stream = ts_template! {
                make@{class_name}BaseProps<D extends number, const P extends DeepPath<@{class_name}, D>, V = DeepValue<@{class_name}, P, never, D>>(
                    superForm: SuperForm<@{class_name}>,
                    path: P,
                    overrides?: BasePropsOverrides<@{class_name}, V, D>
                 ): BaseFieldProps<@{class_name}, V, D> {
                    const proxy = formFieldProxy(superForm, path);
                    const baseProps = {
                        fieldPath: path,
                        ...(overrides ?? {}),
                        value: proxy.value,
                        errors: proxy.errors,
                        superForm
                    };
                    return baseProps;
                };

                {#for (label_text, field_path_literal, field_path_prop, field_controller_prop, field_type) in field_data}
                    {$let controller_type = format!("{}FieldController", label_text.replace("\"", ""))}

                    static {
                        this.prototype.@{field_path_prop} = [@{field_path_literal}];
                    }

                    @{field_controller_prop}(superForm: SuperForm<@{class_name}>): @{controller_type}<@{class_name}, @{field_type}, 1> {
                        const fieldPath = this.@{field_path_prop};

                        return {
                            fieldPath,
                            baseProps: this.@{base_props_method}(
                                superForm,
                                fieldPath,
                                {
                                    labelText: @{label_text}
                                }
                            )
                        };
                    };
                {/for}
            };

            let source = stream.source();
            println!("Generated FieldController Source:\n{}", source);

            // Assertions - matching SWC default formatting
            assert!(source.contains("makeFormModelBaseProps"));
            // SWC adds spaces around colons but NOT before generics
            assert!(source.contains("memoFieldController(superForm: SuperForm<FormModel>"));
            assert!(source.contains("descriptionFieldController(superForm: SuperForm<FormModel>"));
            // Check correct type generation
            assert!(source.contains("MemoFieldController<FormModel, string | null, 1>"));
            // Check static block generation
            assert!(source.contains("this.prototype.memoFieldPath = ["));
            assert!(source.contains("\"memo\""));
        }
        _ => panic!("Expected interface data in field-controller.fixture.ts"),
    }
}

#[test]
fn test_json_macro_pattern() {
    let field_name_str = "id";
    let field_name = field_name_str.to_string();
    let fields = vec![field_name];

    let stream: TsStream = ts_template! {
        toJSON(): Record<string, unknown> {

            const result: Record<string, unknown> = {};

            {#for field in fields}
                result.@{field} = this.@{field};
            {/for}

            return result;
        }
    };

    let s = stream.source();
    println!("Generated JSON Source:\n{}", s);

    // Verify that result.id = this.id; is generated correctly with CLEAN formatting
    assert!(
        s.contains(&format!("result.{} =", field_name_str)),
        "Expected result.field to be concatenated. Found: {}",
        s
    );

    assert!(
        s.contains(&format!("this.{};", field_name_str)),
        "Expected this.field to be concatenated. Found: {}",
        s
    );
}

#[test]
fn test_field_controller_template_spacing() {
    let class_name_str = "FormModel";
    let class_name = class_name_str.to_string();

    let field_name_str = "memo";
    let field_type = "string | null";

    let field_data_tuple = (
        format!("\"{}\"", capitalize(field_name_str)),
        format!("\"{}\"", field_name_str),
        format!("{}FieldPath", field_name_str),
        format!("{}FieldController", field_name_str),
        field_type,
    );
    let field_data: Vec<(_, _, _, _, _)> = vec![field_data_tuple];

    let base_props_method = format!("make{}BaseProps", class_name_str);

    let stream: TsStream = ts_template! {
        make@{class_name}BaseProps<D extends number, const P extends DeepPath<@{class_name}, D>, V = DeepValue<@{class_name}, P, never, D>>(
            superForm: SuperForm<@{class_name}>,
            path: P,
            overrides?: BasePropsOverrides<@{class_name}, V, D>
         ): BaseFieldProps<@{class_name}, V, D> {
            const proxy = formFieldProxy(superForm, path);
            const baseProps = {
                fieldPath: path,
                ...(overrides ?? {}),
                value: proxy.value,
                errors: proxy.errors,
                superForm
            };
            return baseProps;
        };

        {#for (label_text, field_path_literal, field_path_prop, field_controller_prop, field_type) in field_data}
            {$let controller_type_ident = label_text.replace("\"", "") + "FieldController"}

            static {
                this.prototype.@{field_path_prop} = [@{field_path_literal}];
            }

            @{field_controller_prop}(superForm: SuperForm<@{class_name}>): @{controller_type_ident}<@{class_name}, @{field_type}, 1> {
                const fieldPath = this.@{field_path_prop};

                return {
                    fieldPath,
                    baseProps: this.@{base_props_method}(
                        superForm,
                        fieldPath,
                        {
                            labelText: @{label_text}
                        }
                    )
                };
            };
        {/for}
    };

    let s = stream.source();
    println!("Generated Source:\n{}", s);

    // Assert that 'make' and 'FormModelBaseProps' are concatenated
    assert!(
        s.contains(&format!("make{}BaseProps<", class_name_str)),
        "Expected 'make' and class name to be concatenated, but found: {}",
        s
    );

    // Assert that 'return' has a space
    assert!(
        s.contains("return baseProps"),
        "Expected 'return' to have a space before 'baseProps', but found: {}",
        s
    );

    // Assert that 'this.prototype.' and 'field_path_prop' are concatenated
    assert!(
        s.contains(&format!("this.prototype.{}FieldPath", field_name_str)),
        "Expected 'this.prototype.' and field_path_prop to be concatenated, but found: {}",
        s
    );

    // Assert that 'this.' and 'base_props_method' are concatenated
    assert!(
        s.contains(&format!("this.{}(", base_props_method)),
        "Expected 'this.' and base_props_method to be concatenated, but found: {}",
        s
    );
}

// ========== Ident Block   Integration Tests ==========

#[test]
fn test_ident_block_basic_concatenation() {
    // Test that   concatenates content without spaces
    let suffix = "Status";

    let stream: TsStream = ts_template! {
        const namespace@{suffix} = "value";
    };

    let s = stream.source();
    println!("Generated Source:\n{}", s);

    // Should produce "namespaceStatus" as a single identifier
    assert!(
        s.contains("namespaceStatus"),
        "Expected 'namespace' and 'Status' to be concatenated without space, but found: {}",
        s
    );
}

#[test]
fn test_ident_block_function_name() {
    // Test real-world use case: generating function names
    let type_name = "User";

    let stream: TsStream = ts_template! {
        function get@{type_name}(): @{type_name} {
            return {} as @{type_name};
        }
    };

    let s = stream.source();
    println!("Generated Source:\n{}", s);

    // Function name should be concatenated
    assert!(
        s.contains("getUser()"),
        "Expected 'get' and 'User' to form 'getUser()', but found: {}",
        s
    );

    // Return type should have space before it
    assert!(
        s.contains("getUser(): User"),
        "Expected proper spacing around return type, but found: {}",
        s
    );
}

#[test]
fn test_ident_block_multiple_interpolations() {
    // Test multiple @{} inside a single ident block
    let prefix = "get";
    let middle = "User";
    let suffix = "ById";

    let stream: TsStream = ts_template! {
        function @{prefix}@{middle}@{suffix}(id: string) { }
    };

    let s = stream.source();
    println!("Generated Source:\n{}", s);

    // All three parts should be concatenated
    assert!(
        s.contains("getUserById("),
        "Expected all parts to be concatenated into 'getUserById', but found: {}",
        s
    );
}

#[test]
fn test_ident_block_preserves_external_spacing() {
    // Test that space before   is preserved
    let name = "Handler";

    let stream: TsStream = ts_template! {
        export class Event@{name} { }
    };

    let s = stream.source();
    println!("Generated Source:\n{}", s);

    // Should have space between "class" and "EventHandler"
    assert!(
        s.contains("class EventHandler"),
        "Expected 'class EventHandler' with space, but found: {}",
        s
    );
}

#[test]
fn test_ident_block_vs_regular_interpolation() {
    // Compare ident block to regular interpolation
    let type_name = "User";

    // With ident block - explicit no space
    let with_block: TsStream = ts_template! {
        create@{type_name}
    };

    // Regular interpolation - relies on heuristics
    let regular: TsStream = ts_template! {
        create@{type_name}
    };

    let block_s = with_block.source();
    let regular_s = regular.source();

    println!("With block: {}", block_s);
    println!("Regular: {}", regular_s);

    // Ident block should always produce concatenated result
    assert!(
        block_s.contains("createUser"),
        "Ident block should produce 'createUser', but found: {}",
        block_s
    );
}

#[test]
fn test_ident_block_in_method_chain() {
    // Test ident blocks in method/property access patterns
    let prop = "Status";

    let stream: TsStream = ts_template! {
        const value = obj.get@{prop}();
    };

    let s = stream.source();
    println!("Generated Source:\n{}", s);

    // Should produce "obj.getStatus()"
    assert!(
        s.contains("obj.getStatus()"),
        "Expected 'obj.getStatus()', but found: {}",
        s
    );
}

#[test]
fn test_ident_block_empty() {
    // Test empty ident block produces empty string
    let stream: TsStream = ts_template! {
        const prefixsuffix = 1;
    };

    let s = stream.source();
    println!("Generated Source:\n{}", s);

    // Should have prefix and suffix (empty block produces nothing)
    assert!(
        s.contains("prefix") && s.contains("suffix"),
        "Expected prefix and suffix in output, but found: {}",
        s
    );
}

#[test]
fn test_ident_block_with_underscore_separator() {
    // Test ident blocks with underscores (snake_case generation)
    // All parts that need concatenation should be inside
    let entity = "user";
    let action = "create";

    let stream: TsStream = ts_template! {
        function @{entity}_@{action}() { }
    };

    let s = stream.source();
    println!("Generated Source:\n{}", s);

    // Should produce "user_create"
    assert!(
        s.contains("user_create()"),
        "Expected 'user_create()', but found: {}",
        s
    );
}

// ========== Union Type For Loop Tests ==========

#[test]
fn test_union_type_for_loop_basic() {
    // Test basic for loop with Vec<String> - simulating union type refs
    let type_refs: Vec<String> = vec!["User".to_string(), "Admin".to_string(), "Guest".to_string()];

    let stream: TsStream = ts_template! {
        function dispatch(value: any) {
            {#for type_ref in type_refs}
                if (value.__type === "@{type_ref}") {
                    return @{type_ref}.deserializeWithContext(value);
                }
            {/for}
        }
    };

    let s = stream.source();
    println!("Generated Source:\n{}", s);

    assert!(
        s.contains("User.deserializeWithContext"),
        "Expected User.deserializeWithContext, found: {}",
        s
    );
    assert!(
        s.contains("Admin.deserializeWithContext"),
        "Expected Admin.deserializeWithContext, found: {}",
        s
    );
    assert!(
        s.contains("Guest.deserializeWithContext"),
        "Expected Guest.deserializeWithContext, found: {}",
        s
    );
}

#[test]
fn test_union_type_for_loop_with_conditionals() {
    // Test for loop inside conditionals - like the union type pattern
    let type_refs: Vec<String> = vec!["Success".to_string(), "Failure".to_string()];
    let literals: Vec<String> = vec!["\"pending\"".to_string(), "\"active\"".to_string()];

    let is_literal_only = false;
    let is_type_ref_only = true;

    let stream: TsStream = ts_template! {
        function deserializeWithContext(value: any) {
            {#if is_literal_only}
                const allowedValues = [{#for lit in literals}@{lit}, {/for}] as const;
                return value;
            {:else if is_type_ref_only}
                const typeName = value.__type;
                {#for type_ref in type_refs}
                    if (typeName === "@{type_ref}") {
                        return @{type_ref}.deserializeWithContext(value);
                    }
                {/for}
                throw new Error("Unknown type");
            {:else}
                return value;
            {/if}
        }
    };

    let s = stream.source();
    println!("Generated Source:\n{}", s);

    assert!(
        s.contains("Success.deserializeWithContext"),
        "Expected Success.deserializeWithContext, found: {}",
        s
    );
    assert!(
        s.contains("Failure.deserializeWithContext"),
        "Expected Failure.deserializeWithContext, found: {}",
        s
    );
}

#[test]
fn test_union_type_for_loop_reuse() {
    // Test using the same Vec in multiple for loops - need to clone
    let type_refs: Vec<String> = vec!["TypeA".to_string(), "TypeB".to_string()];

    let stream: TsStream = ts_template! {
        function dispatch(value: any) {
            // First use
            {#for type_ref in type_refs.clone()}
                console.log("@{type_ref}");
            {/for}

            // Second use
            {#for type_ref in type_refs}
                return @{type_ref};
            {/for}
        }
    };

    let s = stream.source();
    println!("Generated Source:\n{}", s);

    // Count occurrences - should appear twice each
    assert!(
        s.matches("TypeA").count() >= 2,
        "Expected TypeA to appear at least twice, found: {}",
        s
    );
    assert!(
        s.matches("TypeB").count() >= 2,
        "Expected TypeB to appear at least twice, found: {}",
        s
    );
}

#[test]
fn test_union_type_nested_if_for() {
    // Test nested if with for loop - matching the actual union type pattern
    let type_refs: Vec<String> = vec!["Option1".to_string(), "Option2".to_string()];
    let has_type_refs = !type_refs.is_empty();

    let stream: TsStream = ts_template! {
        function deserializeWithContext(value: any) {
            {#if has_type_refs}
                if (typeof value === "object" && value !== null) {
                    const __typeName = value.__type;
                    if (typeof __typeName === "string") {
                        {#for type_ref in type_refs}
                            if (__typeName === "@{type_ref}") {
                                return @{type_ref}.deserializeWithContext(value);
                            }
                        {/for}
                    }
                }
            {/if}
            return value;
        }
    };

    let s = stream.source();
    println!("Generated Source:\n{}", s);

    assert!(
        s.contains("Option1.deserializeWithContext"),
        "Expected Option1.deserializeWithContext, found: {}",
        s
    );
    assert!(
        s.contains("Option2.deserializeWithContext"),
        "Expected Option2.deserializeWithContext, found: {}",
        s
    );
}