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
use super::*;

// ============================================================================
// Interface Derive Macro Tests
// ============================================================================

#[test]
fn test_derive_debug_on_interface_generates_namespace() {
    // Debug macro now works on interfaces, generating a namespace with toString function
    let source = r#"
/** @derive(Debug) */
interface Status {
    active: boolean;
}
"#;

    {
        let result = expand_test(source);

        // Should have no error diagnostics
        let error_count = result
            .diagnostics
            .iter()
            .filter(|d| d.level == DiagnosticLevel::Error)
            .count();
        assert_eq!(error_count, 0, "Should have no errors, got {}", error_count);

        // Output should contain prefix-style toString function (default naming style)
        assert!(
            result.code.contains("statusToString"),
            "Should generate prefix-style statusToString function. Got:\n{}",
            result.code
        );
    }
}

#[test]
fn test_derive_clone_on_interface_generates_functions() {
    let source = r#"
/** @derive(Clone) */
interface UserData {
    name: string;
    age: number;
}
"#;

    {
        let result = expand_test(source);

        // Should have no error diagnostics
        let error_count = result
            .diagnostics
            .iter()
            .filter(|d| d.level == DiagnosticLevel::Error)
            .count();
        assert_eq!(error_count, 0, "Should have no errors, got {}", error_count);

        // Output should contain prefix-style clone function (default naming style)
        assert!(
            result.code.contains("userDataClone"),
            "Should generate prefix-style userDataClone function"
        );
    }
}

#[test]
fn test_derive_partial_eq_hash_on_interface_generates_functions() {
    let source = r#"
/** @derive(PartialEq, Hash) */
interface Point {
    x: number;
    y: number;
}
"#;

    {
        let result = expand_test(source);

        // Should have no error diagnostics
        let error_count = result
            .diagnostics
            .iter()
            .filter(|d| d.level == DiagnosticLevel::Error)
            .count();
        assert_eq!(error_count, 0, "Should have no errors, got {}", error_count);

        // Output should contain prefix-style equals and hashCode functions (default naming style)
        assert!(
            result.code.contains("pointEquals"),
            "Should generate prefix-style pointEquals function"
        );
        assert!(
            result.code.contains("pointHashCode"),
            "Should generate prefix-style pointHashCode function"
        );
    }
}

#[test]
fn test_derive_debug_on_interface_generates_correct_output() {
    // Test that the generated Debug output is correct for interfaces
    let source = r#"
/** @derive(Debug) */
interface Status {
    active: boolean;
}
"#;

    {
        let result = expand_test(source);

        // Should have no errors
        let error_count = result
            .diagnostics
            .iter()
            .filter(|d| d.level == DiagnosticLevel::Error)
            .count();
        assert_eq!(error_count, 0, "Should succeed without errors");

        // Verify the output contains expected patterns (suffix-style uses value parameter)
        eprintln!("[DEBUG] result.code = {:?}", result.code);
        assert!(
            result.code.contains("value.active"),
            "Should reference value.active"
        );
    }
}

#[test]
fn test_multiple_derives_on_interface_all_succeed() {
    // When multiple derives are used on interface, all should succeed
    let source = r#"
/** @derive(Debug, Clone, PartialEq, Hash) */
interface Status {
    active: boolean;
}
"#;

    {
        let result = expand_test(source);

        // Should have no error diagnostics
        let error_count = result
            .diagnostics
            .iter()
            .filter(|d| d.level == DiagnosticLevel::Error)
            .count();
        assert_eq!(
            error_count, 0,
            "Should have no errors for derives on interface, got {} errors",
            error_count
        );

        // Should have all prefix-style functions generated
        assert!(
            result.code.contains("statusToString"),
            "Should have Debug's statusToString"
        );
        assert!(
            result.code.contains("statusClone"),
            "Should have Clone's statusClone"
        );
        assert!(
            result.code.contains("statusEquals"),
            "Should have PartialEq's statusEquals"
        );
        assert!(
            result.code.contains("statusHashCode"),
            "Should have Hash's statusHashCode"
        );
    }
}

#[test]
fn test_unknown_derive_macro_produces_error() {
    // A derive macro that doesn't exist should produce an error
    let source = r#"
/** @derive(NonExistentMacro) */
class User {
    name: string;
}
"#;

    {
        let result = expand_test(source);

        // Should have a diagnostic for unknown macro
        let unknown_error = result.diagnostics.iter().find(|d| {
            d.message.contains("NonExistentMacro")
                || d.message.contains("unknown")
                || d.message.contains("not found")
        });

        assert!(
            unknown_error.is_some(),
            "Should produce an error for unknown derive macro. Diagnostics: {:?}",
            result.diagnostics
        );
    }
}

#[test]
fn test_unknown_derive_macro_on_interface_produces_error() {
    // A derive macro that doesn't exist should produce an error for interfaces too
    let source = r#"
/** @derive(Serializable) */
interface Config {
    host: string;
    port: number;
}
"#;

    {
        let result = expand_test(source);

        // Should have a diagnostic for unknown macro
        let unknown_error = result.diagnostics.iter().find(|d| {
            d.message.contains("Serializable")
                || d.message.contains("unknown")
                || d.message.contains("not found")
        });

        assert!(
            unknown_error.is_some(),
            "Should produce an error for unknown derive macro on interface. Diagnostics: {:?}",
            result.diagnostics
        );
    }
}

#[test]
fn test_error_span_covers_macro_name_not_entire_decorator() {
    // Verify the error span is reasonably sized (not covering the entire file)
    // Use an unknown macro to trigger an error
    let source = r#"
/** @derive(NonExistent) */
interface Data {
    value: string;
}
"#;

    {
        let result = expand_test(source);

        let error_diag = result
            .diagnostics
            .iter()
            .find(|d| d.level == DiagnosticLevel::Error)
            .expect("Should have an error-level diagnostic");

        let span = error_diag.span.as_ref().expect("Error should have a span");
        let span_len = span.end - span.start;

        // The span should be reasonably sized - not the entire source
        // A macro name like "NonExistent" would be around 5-20 characters with context
        assert!(
            span_len < 100,
            "Error span should be focused, not cover entire source. Span length: {}",
            span_len
        );
    }
}

#[test]
fn test_derive_serialize_on_interface_generates_functions() {
    let source = r#"
/** @derive(Serialize) */
interface Point {
    x: number;
    y: number;
}
"#;

    {
        let result = expand_test(source);

        // Should have no error diagnostics
        let error_count = result
            .diagnostics
            .iter()
            .filter(|d| d.level == DiagnosticLevel::Error)
            .count();
        assert_eq!(error_count, 0, "Should have no errors, got {}", error_count);

        // Output should contain prefix-style serialize functions (default naming style)
        assert!(
            result.code.contains("pointSerialize"),
            "Should generate prefix-style pointSerialize function"
        );
        assert!(
            result.code.contains("pointSerializeWithContext"),
            "Should generate prefix-style pointSerializeWithContext function"
        );

        // Verify no syntax context markers in output (would indicate Ident emission bug)
        assert!(
            !result.code.contains("#0"),
            "Output should not contain SWC syntax context markers like #0. Got:\n{}",
            result.code
        );
    }
}

#[test]
fn test_derive_deserialize_on_interface_generates_functions() {
    let source = r#"
/** @derive(Deserialize) */
interface Point {
    x: number;
    y: number;
}
"#;

    {
        let result = expand_test(source);

        // Should have no error diagnostics
        let error_count = result
            .diagnostics
            .iter()
            .filter(|d| d.level == DiagnosticLevel::Error)
            .count();
        assert_eq!(error_count, 0, "Should have no errors, got {}", error_count);

        // Output should contain prefix-style deserialize functions (default naming style)
        assert!(
            result.code.contains("pointDeserialize"),
            "Should generate prefix-style pointDeserialize function"
        );
        assert!(
            result.code.contains("pointDeserializeWithContext"),
            "Should generate prefix-style pointDeserializeWithContextfunction"
        );
    }
}

#[test]
fn test_interface_derive_macros_default_to_prefix_functions() {
    let source = r#"
/** @derive(Debug, Clone, PartialEq, Hash, PartialOrd, Ord, Default, Serialize, Deserialize) */
export interface Point {
    x: number;
    y: number;
}
"#;

    {
        let result = expand_test(source);

        assert!(
            !result.code.contains("export namespace Point"),
            "Default naming style should not emit namespaces"
        );

        for expected in [
            "export function pointToString",
            "export function pointClone",
            "export function pointEquals",
            "export function pointHashCode",
            "export function pointPartialCompare",
            "export function pointCompare",
            "export function pointDefaultValue",
            "export function pointSerializeWithContext",
            "export function pointDeserializeWithContext",
        ] {
            assert!(
                result.code.contains(expected),
                "Expected prefix-style function: {expected}"
            );
        }
    }
}

#[test]
fn test_external_type_function_imports_for_prefix_style() {
    let source = r#"
import { Metadata } from "./metadata.svelte";

/** @derive(Default, Serialize, Deserialize) */
export interface User {
    metadata: Metadata;
}
"#;

    {
        let result = expand_test(source);

        // The expansion should call into the imported type's generated functions
        assert!(
            result.code.contains("metadataSerializeWithContext"),
            "Expected User serialization to reference metadataSerializeWithContext"
        );
        assert!(
            result.code.contains("metadataDeserializeWithContext"),
            "Expected User deserialization to reference metadataDeserializeWithContext"
        );
        assert!(
            result.code.contains("metadataDefaultValue"),
            "Expected User defaultValue to reference metadataDefaultValue"
        );

        // ...and it should add corresponding imports from the original module specifier.
        assert!(
            result
                .code
                .contains("import { metadataSerializeWithContext } from \"./metadata.svelte\";"),
            "Expected metadataSerializeWithContext import to be added"
        );
        assert!(
            result
                .code
                .contains("import { metadataDeserializeWithContext } from \"./metadata.svelte\";"),
            "Expected metadataDeserializeWithContext import to be added"
        );
        assert!(
            result
                .code
                .contains("import { metadataDefaultValue } from \"./metadata.svelte\";"),
            "Expected metadataDefaultValue import to be added"
        );
    }
}

#[test]
fn test_derive_default_on_interface_with_object_literal_field() {
    // Regression: interfaces with fields typed as object literals (e.g. index signatures)
    // must not silently fail to generate their defaultValue function.
    let source = r#"
/** @derive(Default) */
export interface Assignment {
    name: string;
    scores: { [key: string]: number };
    active: boolean;
}
"#;

    {
        let result = expand_test(source);

        let error_count = result
            .diagnostics
            .iter()
            .filter(|d| d.level == DiagnosticLevel::Error)
            .count();
        assert_eq!(
            error_count, 0,
            "Should have no errors for interface with object literal field. Got: {:?}",
            result.diagnostics
        );

        assert!(
            result.code.contains("assignmentDefaultValue"),
            "Should generate assignmentDefaultValue function. Got:\n{}",
            result.code
        );
        // The object literal field should default to {}
        assert!(
            result.code.contains("scores: {}") || result.code.contains("scores: ({})"),
            "Object literal field should default to {{}}. Got:\n{}",
            result.code
        );
    }
}