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
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
//! # PartialOrd Macro Implementation
//!
//! The `PartialOrd` macro generates a `compareTo()` method for **partial ordering**
//! comparison. This is analogous to Rust's `PartialOrd` trait, enabling comparison
//! between values where some pairs may be incomparable.
//!
//! ## Generated Output
//!
//! | Type | Generated Code | Description |
//! |------|----------------|-------------|
//! | Class | `{className}PartialCompare(a, b)` + `static compareTo(a, b)` | Standalone function + static wrapper method |
//! | Enum | `{enumName}PartialCompare(a, b): number \| null` | Standalone function returning `number \| null` |
//! | Interface | `{ifaceName}PartialCompare(a, b): number \| null` | Standalone function returning `number \| null` |
//! | Type Alias | `{typeName}PartialCompare(a, b): number \| null` | Standalone function returning `number \| null` |
//!
//! Names use **camelCase** conversion (e.g., `Temperature` → `temperaturePartialCompare`).
//!
//! ## Return Values
//!
//! Unlike `Ord`, `PartialOrd` returns `number | null` to handle incomparable values:
//!
//! - **-1**: `a` is less than `b`
//! - **0**: `a` is equal to `b`
//! - **1**: `a` is greater than `b`
//! - **null**: Values are incomparable
//!
//! ## When to Use PartialOrd vs Ord
//!
//! - **PartialOrd**: When some values may not be comparable
//!   - Example: Floating-point NaN values
//!   - Example: Mixed-type unions
//!   - Example: Type mismatches between objects
//!
//! - **Ord**: When all values are guaranteed comparable (total ordering)
//!
//! ## Comparison Strategy
//!
//! Fields are compared **lexicographically** in declaration order:
//!
//! 1. Compare first field
//! 2. If incomparable, return `null`
//! 3. If not equal, return that result
//! 4. Otherwise, compare next field
//! 5. Continue until a difference is found or all fields are equal
//!
//! ## Type-Specific Comparisons
//!
//! | Type | Comparison Method |
//! |------|-------------------|
//! | `number`/`bigint` | Direct subtraction (`a - b`) |
//! | `string` | `localeCompare()` |
//! | `boolean` | `false < true` (cast to number) |
//! | null/undefined | Returns `null` for mismatched nullability |
//! | Arrays | Lexicographic, propagates `null` on incomparable elements |
//! | `Date` | Timestamp comparison, `null` if invalid |
//! | Objects | Delegates to `compareTo()` if available |
//!
//! ## Field-Level Options
//!
//! The `@ord` decorator supports:
//!
//! - `skip` - Exclude the field from ordering comparison
//!
//! ## Example
//!
//! ```typescript
//! /** @derive(PartialOrd) */
//! class Temperature {
//!     value: number | null;
//!     unit: string;
//! }
//! ```
//!
//! Generated output:
//!
//! ```typescript
//! class Temperature {
//!     value: number | null;
//!     unit: string;
//!
//!     static compareTo(a: Temperature, b: Temperature): number | null {
//!         return temperaturePartialCompare(a, b);
//!     }
//! }
//!
//! export function temperaturePartialCompare(a: Temperature, b: Temperature): number | null {
//!     if (a === b) return 0;
//!     const cmp0 = (() => {
//!         if (typeof (a.value as any)?.compareTo === 'function') {
//!             const optResult = (a.value as any).compareTo(b.value);
//!             return optResult === null ? null : optResult;
//!         }
//!         return a.value === b.value ? 0 : null;
//!     })();
//!     if (cmp0 === null) return null;
//!     if (cmp0 !== 0) return cmp0;
//!     const cmp1 = a.unit.localeCompare(b.unit);
//!     if (cmp1 === null) return null;
//!     if (cmp1 !== 0) return cmp1;
//!     return 0;
//! }
//! ```
//!
//! ## Return Type
//!
//! The generated functions return `number | null` where `null` indicates incomparable values.

use convert_case::{Case, Casing};

use crate::builtin::derive_common::{
    CompareFieldOptions, is_numeric_type, is_primitive_type, standalone_fn_name, type_has_derive,
};
use crate::builtin::return_types::{is_none_check, partial_ord_return_type, unwrap_option_or_null};
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};

/// Contains field information needed for partial ordering comparison generation.
///
/// Each field that participates in ordering is represented by this struct,
/// which captures both the field name (for access) and its TypeScript type
/// (to select the appropriate comparison strategy).
struct OrdField {
    /// The field name as it appears in the source TypeScript class.
    /// Used to generate property access expressions like `this.name`.
    name: String,

    /// The TypeScript type annotation for this field.
    /// Used to determine which comparison strategy to apply
    /// (e.g., numeric comparison, string localeCompare, recursive compareTo).
    ts_type: String,
}

/// Generates JavaScript code that compares fields for partial ordering.
///
/// This function produces an expression that evaluates to -1, 0, 1, or `null`.
/// The `null` value indicates incomparable values (the caller wraps results in `Option`).
///
/// # Arguments
///
/// * `field` - The field to generate comparison code for
/// * `self_var` - Variable name for the first object (e.g., "self", "a")
/// * `other_var` - Variable name for the second object (e.g., "other", "b")
/// * `allow_null` - Whether to return `null` for incomparable values (true for
///   PartialOrd, false for Ord which uses 0 instead)
///
/// # Returns
///
/// A string containing a JavaScript expression that evaluates to -1, 0, 1, or null.
/// Field access uses the provided variable names: `self_var.field` vs `other_var.field`.
///
/// # Type-Specific Strategies
///
/// - **number/bigint**: Direct comparison, never null
/// - **string**: `localeCompare()`, never null
/// - **boolean**: false < true, never null
/// - **null/undefined**: Returns `null_return` if values differ
/// - **Arrays**: Returns null if element comparison returns null
/// - **Date**: Returns null if either value is not a valid Date
/// - **Objects**: Unwraps `Option` from nested `compareTo()` calls
fn generate_field_compare_for_interface(
    field: &OrdField,
    self_var: &str,
    other_var: &str,
    allow_null: bool,
    resolved: Option<&ResolvedTypeRef>,
    registry: Option<&TypeRegistry>,
) -> String {
    let field_name = &field.name;
    let ts_type = &field.ts_type;
    let null_return = if allow_null { "null" } else { "0" };

    // Type-aware path: direct compare call when type has @derive(PartialOrd)
    if let (Some(resolved), Some(registry)) = (resolved, registry)
        && !resolved.is_collection
        && resolved.registry_key.is_some()
        && type_has_derive(registry, &resolved.base_type_name, "PartialOrd")
    {
        let fn_name = standalone_fn_name(&resolved.base_type_name, "PartialCompare");
        return format!("{fn_name}({self_var}.{field_name}, {other_var}.{field_name})");
    }

    if is_numeric_type(ts_type) {
        format!(
            "({self_var}.{field_name} < {other_var}.{field_name} ? -1 : \
             {self_var}.{field_name} > {other_var}.{field_name} ? 1 : 0)"
        )
    } else if ts_type == "string" {
        format!("{self_var}.{field_name}.localeCompare({other_var}.{field_name})")
    } else if ts_type == "boolean" {
        format!(
            "({self_var}.{field_name} === {other_var}.{field_name} ? 0 : \
             {self_var}.{field_name} ? 1 : -1)"
        )
    } else if is_primitive_type(ts_type) {
        format!("({self_var}.{field_name} === {other_var}.{field_name} ? 0 : {null_return})")
    } else if ts_type.ends_with("[]") || ts_type.starts_with("Array<") {
        // Handle nested compareTo calls that return Option<number> or number | null
        let unwrap_opt = unwrap_option_or_null("optResult");
        format!(
            "(() => {{ \
                const a = {self_var}.{field_name}; \
                const b = {other_var}.{field_name}; \
                if (!Array.isArray(a) || !Array.isArray(b)) return {null_return}; \
                const minLen = Math.min(a.length, b.length); \
                for (let i = 0; i < minLen; i++) {{ \
                    let cmp: number | null; \
                    if (typeof (a[i] as any)?.compareTo === 'function') {{ \
                        const optResult = (a[i] as any).compareTo(b[i]); \
                        cmp = {unwrap_opt}; \
                    }} else {{ \
                        cmp = a[i] < b[i] ? -1 : a[i] > b[i] ? 1 : 0; \
                    }} \
                    if (cmp === null) return {null_return}; \
                    if (cmp !== 0) return cmp; \
                }} \
                return a.length < b.length ? -1 : a.length > b.length ? 1 : 0; \
            }})()"
        )
    } else if ts_type == "Date" {
        format!(
            "(() => {{ \
                const a = {self_var}.{field_name}; \
                const b = {other_var}.{field_name}; \
                if (!(a instanceof Date) || !(b instanceof Date)) return {null_return}; \
                const ta = a.getTime(); \
                const tb = b.getTime(); \
                return ta < tb ? -1 : ta > tb ? 1 : 0; \
            }})()"
        )
    } else {
        // For objects, check for compareTo method that returns Option<number> or number | null
        let unwrap_opt = unwrap_option_or_null("optResult");
        let is_none = is_none_check("optResult");
        format!(
            "(() => {{ \
                if (typeof ({self_var}.{field_name} as any)?.compareTo === 'function') {{ \
                    const optResult = ({self_var}.{field_name} as any).compareTo({other_var}.{field_name}); \
                    return {is_none} ? {null_return} : {unwrap_opt}; \
                }} \
                return {self_var}.{field_name} === {other_var}.{field_name} ? 0 : {null_return}; \
            }})()"
        )
    }
}

#[ts_macro_derive(
    PartialOrd,
    description = "Generates a compareTo() method for partial ordering (returns number | null: -1, 0, 1, or null)",
    attributes(ord)
)]
pub fn derive_partial_ord_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 for comparison
            let ord_fields: Vec<OrdField> = class
                .fields()
                .iter()
                .filter_map(|field| {
                    let opts = CompareFieldOptions::from_decorators(&field.decorators, "ord");
                    if opts.skip {
                        return None;
                    }
                    Some(OrdField {
                        name: field.name.clone(),
                        ts_type: field.ts_type.clone(),
                    })
                })
                .collect();

            let has_fields = !ord_fields.is_empty();

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

            // Get return type
            let return_type = partial_ord_return_type();
            let return_type_ident = ts_ident!(return_type);

            // Generate standalone function with two parameters
            let standalone = if has_fields {
                // Build comparison steps for each field
                let mut compare_body = String::new();
                for (i, f) in ord_fields.iter().enumerate() {
                    let cmp_var = format!("cmp{}", i);
                    let resolved = resolved_fields.and_then(|rf| rf.get(&f.name));
                    let expr_src = generate_field_compare_for_interface(
                        f,
                        "a",
                        "b",
                        true,
                        resolved,
                        type_registry,
                    );
                    compare_body.push_str(&format!(
                        "const {} = {};\nif ({} === null) return null;\nif ({} !== 0) return {};\n",
                        cmp_var, expr_src, cmp_var, cmp_var, cmp_var
                    ));
                }

                ts_template! {
                    export function @{fn_name_ident}(a: @{class_ident}, b: @{class_ident}): @{return_type_ident} {
                        if (a === b) return 0;
                        {$typescript TsStream::from_string(compare_body)}
                        return 0;
                    }
                }
            } else {
                ts_template! {
                    export function @{fn_name_ident}(a: @{class_ident}, b: @{class_ident}): @{return_type_ident} {
                        if (a === b) return 0;
                        return 0;
                    }
                }
            };

            // Generate static wrapper method that delegates to standalone function
            let class_body = ts_template!(Within {
                static compareTo(a: @{class_ident}, b: @{class_ident}): @{return_type_ident} {
                    return @{fn_name_expr}(a, b);
                }
            });

            // Combine standalone function with class body
            // The standalone output (no marker) must come FIRST so it defaults to "below" (after class)
            Ok(standalone.merge(class_body))
        }
        Data::Enum(_) => {
            let enum_name = input.name();
            let fn_name_ident = ts_ident!("{}PartialCompare", enum_name.to_case(Case::Camel));

            // Get return type
            let return_type = partial_ord_return_type();
            let return_type_ident = ts_ident!(return_type);

            let result = ts_template! {
                export function @{fn_name_ident}(a: @{ts_ident!(enum_name)}, b: @{ts_ident!(enum_name)}): @{return_type_ident} {
                    // For enums, compare by value (numeric enums) or string
                    if (typeof a === "number" && typeof b === "number") {
                        return a < b ? -1 : a > b ? 1 : 0;
                    }
                    if (typeof a === "string" && typeof b === "string") {
                        return a.localeCompare(b);
                    }
                    return a === b ? 0 : null;
                }
            };

            Ok(result)
        }
        Data::Interface(interface) => {
            let interface_name = input.name();
            let interface_ident = ts_ident!(interface_name);

            let ord_fields: Vec<OrdField> = interface
                .fields()
                .iter()
                .filter_map(|field| {
                    let opts = CompareFieldOptions::from_decorators(&field.decorators, "ord");
                    if opts.skip {
                        return None;
                    }
                    Some(OrdField {
                        name: field.name.clone(),
                        ts_type: field.ts_type.clone(),
                    })
                })
                .collect();

            let has_fields = !ord_fields.is_empty();

            // Get return type
            let return_type = partial_ord_return_type();
            let return_type_ident = ts_ident!(return_type);

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

            let result = if has_fields {
                // Build comparison steps for each field
                let mut compare_body = String::new();
                for (i, f) in ord_fields.iter().enumerate() {
                    let cmp_var = format!("cmp{}", i);
                    let resolved = resolved_fields.and_then(|rf| rf.get(&f.name));
                    let expr_src = generate_field_compare_for_interface(
                        f,
                        "a",
                        "b",
                        true,
                        resolved,
                        type_registry,
                    );
                    compare_body.push_str(&format!(
                        "const {} = {};\nif ({} === null) return null;\nif ({} !== 0) return {};\n",
                        cmp_var, expr_src, cmp_var, cmp_var, cmp_var
                    ));
                }

                ts_template! {
                    export function @{fn_name_ident}(a: @{interface_ident}, b: @{interface_ident}): @{return_type_ident} {
                        if (a === b) return 0;
                        {$typescript TsStream::from_string(compare_body)}
                        return 0;
                    }
                }
            } else {
                ts_template! {
                    export function @{fn_name_ident}(a: @{interface_ident}, b: @{interface_ident}): @{return_type_ident} {
                        if (a === b) return 0;
                        return 0;
                    }
                }
            };

            Ok(result)
        }
        Data::TypeAlias(type_alias) => {
            let type_name = input.name();
            let type_ident = ts_ident!(type_name);

            // Get return type
            let return_type = partial_ord_return_type();
            let return_type_ident = ts_ident!(return_type);

            if type_alias.is_object() {
                let ord_fields: Vec<OrdField> = type_alias
                    .as_object()
                    .unwrap()
                    .iter()
                    .filter_map(|field| {
                        let opts = CompareFieldOptions::from_decorators(&field.decorators, "ord");
                        if opts.skip {
                            return None;
                        }
                        Some(OrdField {
                            name: field.name.clone(),
                            ts_type: field.ts_type.clone(),
                        })
                    })
                    .collect();

                let has_fields = !ord_fields.is_empty();

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

                let result = if has_fields {
                    // Build comparison steps for each field
                    let mut compare_body = String::new();
                    for (i, f) in ord_fields.iter().enumerate() {
                        let cmp_var = format!("cmp{}", i);
                        let resolved = resolved_fields.and_then(|rf| rf.get(&f.name));
                        let expr_src = generate_field_compare_for_interface(
                            f,
                            "a",
                            "b",
                            true,
                            resolved,
                            type_registry,
                        );
                        compare_body.push_str(&format!(
                            "const {} = {};\nif ({} === null) return null;\nif ({} !== 0) return {};\n",
                            cmp_var, expr_src, cmp_var, cmp_var, cmp_var
                        ));
                    }

                    ts_template! {
                        export function @{fn_name_ident}(a: @{type_ident}, b: @{type_ident}): @{return_type_ident} {
                            if (a === b) return 0;
                            {$typescript TsStream::from_string(compare_body)}
                            return 0;
                        }
                    }
                } else {
                    ts_template! {
                        export function @{fn_name_ident}(a: @{type_ident}, b: @{type_ident}): @{return_type_ident} {
                            if (a === b) return 0;
                            return 0;
                        }
                    }
                };

                Ok(result)
            } else {
                // Union, tuple, or simple alias: limited comparison
                let fn_name_ident = ts_ident!("{}PartialCompare", type_name.to_case(Case::Camel));

                let result = ts_template! {
                    export function @{fn_name_ident}(a: @{type_ident}, b: @{type_ident}): @{return_type_ident} {
                        if (a === b) return 0;
                        // For unions/tuples, try primitive comparison
                        if (typeof a === "number" && typeof b === "number") {
                            return a < b ? -1 : a > b ? 1 : 0;
                        }
                        if (typeof a === "string" && typeof b === "string") {
                            return a.localeCompare(b);
                        }
                        return null;
                    }
                };

                Ok(result)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_partial_ord_macro_output_vanilla() {
        let ord_fields: Vec<OrdField> = vec![OrdField {
            name: "id".to_string(),
            ts_type: "number".to_string(),
        }];

        // Build comparison steps for each field
        let mut compare_body_str = String::new();
        for (i, f) in ord_fields.iter().enumerate() {
            let cmp_var = format!("cmp{}", i);
            let expr_src = generate_field_compare_for_interface(f, "a", "b", true, None, None);
            compare_body_str.push_str(&format!(
                "const {} = {};\nif ({} === null) return null;\nif ({} !== 0) return {};\n",
                cmp_var, expr_src, cmp_var, cmp_var, cmp_var
            ));
        }

        let return_type = partial_ord_return_type();
        let _return_type_ident = ts_ident!(return_type);
        let output = ts_template!(Within {
            compareTo(other: unknown): @{_return_type_ident} {
                if (a === b) return 0;
                {$typescript TsStream::from_string(compare_body_str)}
                return 0;
            }
        });

        let source = output.source();
        let body_content = source
            .strip_prefix("/* @macroforge:body */")
            .unwrap_or(source);
        let wrapped = format!("class __Temp {{ {} }}", body_content);

        assert!(
            macroforge_ts_syn::parse_ts_stmt(&wrapped).is_ok(),
            "Generated PartialOrd macro output should parse as class members"
        );
        assert!(
            source.contains("compareTo"),
            "Should contain compareTo method"
        );
        // Return type is "number | null"
        assert!(
            source.contains("number | null"),
            "Should have number | null return type"
        );
    }

    #[test]
    fn test_field_compare_number() {
        let field = OrdField {
            name: "id".to_string(),
            ts_type: "number".to_string(),
        };
        let result = generate_field_compare_for_interface(&field, "a", "b", true, None, None);
        assert!(result.contains("a.id < b.id"));
        assert!(result.contains("a.id > b.id"));
    }

    #[test]
    fn test_field_compare_string() {
        let field = OrdField {
            name: "name".to_string(),
            ts_type: "string".to_string(),
        };
        let result = generate_field_compare_for_interface(&field, "a", "b", true, None, None);
        assert!(result.contains("localeCompare"));
    }

    #[test]
    fn test_field_compare_boolean() {
        let field = OrdField {
            name: "active".to_string(),
            ts_type: "boolean".to_string(),
        };
        let result = generate_field_compare_for_interface(&field, "a", "b", true, None, None);
        // false < true: false returns -1, true returns 1
        assert!(result.contains("-1"));
        assert!(result.contains("1"));
    }

    #[test]
    fn test_field_compare_date() {
        let field = OrdField {
            name: "createdAt".to_string(),
            ts_type: "Date".to_string(),
        };
        let result = generate_field_compare_for_interface(&field, "a", "b", true, None, None);
        assert!(result.contains("getTime"));
    }

    #[test]
    fn test_field_compare_object_vanilla() {
        let field = OrdField {
            name: "user".to_string(),
            ts_type: "User".to_string(),
        };
        let result = generate_field_compare_for_interface(&field, "a", "b", true, None, None);
        assert!(result.contains("compareTo"));
        // We check for null directly
        assert!(result.contains("=== null"));
    }

    #[test]
    fn test_field_compare_array_vanilla() {
        let field = OrdField {
            name: "items".to_string(),
            ts_type: "Item[]".to_string(),
        };
        let result = generate_field_compare_for_interface(&field, "a", "b", true, None, None);
        // optResult is already the value
        assert!(result.contains("cmp = optResult"));
    }
}