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
635
636
637
638
639
640
641
//! # Hash Macro Implementation
//!
//! The `Hash` macro generates a `hashCode()` method for computing numeric hash codes.
//! This is analogous to Rust's `Hash` trait and Java's `hashCode()` method, enabling
//! objects to be used as keys in hash-based collections.
//!
//! ## Generated Output
//!
//! | Type | Generated Code | Description |
//! |------|----------------|-------------|
//! | Class | `classNameHashCode(value)` + `static hashCode(value)` | Standalone function + static wrapper method |
//! | Enum | `enumNameHashCode(value: EnumName): number` | Standalone function hashing by enum value |
//! | Interface | `interfaceNameHashCode(value: InterfaceName): number` | Standalone function computing hash |
//! | Type Alias | `typeNameHashCode(value: TypeName): number` | Standalone function computing hash |
//!
//!
//! ## Hash Algorithm
//!
//! Uses the standard polynomial rolling hash algorithm:
//!
//! ```text
//! hash = 17  // Initial seed
//! for each field:
//!     hash = (hash * 31 + fieldHash) | 0
//! ```
//!
//! The `| 0` (bitwise OR with zero) at the end of each step coerces the result
//! to a 32-bit signed integer, preventing floating-point drift from repeated
//! multiplication. This is equivalent to casting to `i32` in Rust and consistent
//! with Java's `Objects.hash()` implementation.
//!
//! ## Type-Specific Hashing
//!
//! | Type | Hash Strategy |
//! |------|---------------|
//! | `number` | Integer: direct value; Float: string hash of decimal |
//! | `bigint` | String hash of decimal representation |
//! | `string` | Character-by-character polynomial hash |
//! | `boolean` | 1231 for true, 1237 for false (Java convention) |
//! | `Date` | `getTime()` timestamp |
//! | Arrays | Element-by-element hash combination |
//! | `Map` | Entry-by-entry key+value hash |
//! | `Set` | Element-by-element hash |
//! | Objects | Calls `hashCode()` if available, else JSON string hash |
//!
//! ## Field-Level Options
//!
//! The `@hash` decorator supports:
//!
//! - `skip` - Exclude the field from hash calculation
//!
//! ## Example
//!
//! ```typescript
//! /** @derive(Hash) */
//! class User {
//!     id: number;
//!     name: string;
//!
//!     /** @hash({ skip: true }) */
//!     cachedScore: number;
//! }
//! ```
//!
//! Generated output:
//!
//! ```typescript
//! class User {
//!     id: number;
//!     name: string;
//!
//!     cachedScore: number;
//!
//!     static hashCode(value: User): number {
//!         return userHashCode(value);
//!     }
//! }
//!
//! export function userHashCode(value: User): number {
//!     let hash = 17;
//!     hash =
//!         (hash * 31 +
//!             (Number.isInteger(value.id)
//!                 ? value.id | 0
//!                 : value.id
//!                       .toString()
//!                       .split('')
//!                       .reduce((h, c) => (h * 31 + c.charCodeAt(0)) | 0, 0))) |
//!         0;
//!     hash =
//!         (hash * 31 +
//!             (value.name ?? '').split('').reduce((h, c) => (h * 31 + c.charCodeAt(0)) | 0, 0)) |
//!         0;
//!     return hash;
//! }
//! ```
//!
//! ## Hash Contract
//!
//! Objects that are equal (`PartialEq`) should produce the same hash code.
//! When using `@hash(skip)`, ensure the same fields are skipped in both
//! `Hash` and `PartialEq` to maintain this contract.

use convert_case::{Case, Casing};

use crate::builtin::derive_common::{
    CompareFieldOptions, collection_element_type, is_primitive_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::{
    Data, DeriveInput, MacroforgeError, TsStream, parse_ts_expr, parse_ts_macro_input, ts_ident,
};

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

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

/// Generates JavaScript code that computes a hash contribution for a single field.
///
/// This function produces an expression that evaluates to an integer hash value.
/// The generated code handles different TypeScript types with appropriate
/// hashing strategies.
///
/// # Arguments
///
/// * `field` - The field to generate hash code for
/// * `var` - The variable name to use for field access (e.g., "self", "value")
///
/// # Returns
///
/// A string containing a JavaScript expression that evaluates to an integer hash value.
/// Field access uses the provided variable name: `var.fieldName`.
///
/// # Type-Specific Strategies
///
/// - **number**: Integer values used directly; floats hashed as strings
/// - **bigint**: String hash of decimal representation
/// - **string**: Character-by-character polynomial hash
/// - **boolean**: 1231 for true, 1237 for false (Java convention)
/// - **Date**: `getTime()` timestamp
/// - **Arrays**: Element-by-element hash combination
/// - **Map**: Entry-by-entry key+value hash
/// - **Set**: Element-by-element hash
/// - **Objects**: Calls `hashCode()` if available, else JSON string hash
///
/// # Example
///
/// ```rust
/// use macroforge_ts::builtin::derive_hash::{HashField, generate_field_hash_for_interface};
///
/// let field = HashField { name: "name".to_string(), ts_type: "string".to_string() };
/// let code = generate_field_hash_for_interface(&field, "self", None, None);
/// assert!(code.contains("self.name"));
/// assert!(code.contains("reduce"));
/// ```
pub fn generate_field_hash_for_interface(
    field: &HashField,
    var: &str,
    resolved: Option<&ResolvedTypeRef>,
    registry: Option<&TypeRegistry>,
) -> String {
    let field_name = &field.name;
    let ts_type = &field.ts_type;

    // Type-aware path: check if the field type has @derive(Hash)
    if let (Some(resolved), Some(registry)) = (resolved, registry) {
        // Direct known Hash type → call standalone function
        if !resolved.is_collection
            && resolved.registry_key.is_some()
            && type_has_derive(registry, &resolved.base_type_name, "Hash")
        {
            let fn_name = standalone_fn_name(&resolved.base_type_name, "HashCode");
            return format!("{fn_name}({var}.{field_name})");
        }

        // Array of known Hash type → direct element calls
        if resolved.is_collection
            && let Some(elem) = collection_element_type(resolved)
            && elem.registry_key.is_some()
            && type_has_derive(registry, &elem.base_type_name, "Hash")
        {
            let elem_fn = standalone_fn_name(&elem.base_type_name, "HashCode");
            let base = resolved.base_type_name.as_str();
            match base {
                "Map" => {
                    return format!(
                        "({var}.{field_name} instanceof Map \
                                    ? Array.from({var}.{field_name}.entries()).reduce((h, [k, v]) => \
                                        (h * 31 + String(k).split('').reduce((hh, c) => (hh * 31 + c.charCodeAt(0)) | 0, 0) + \
                                        {elem_fn}(v)) | 0, 0) \
                                    : 0)"
                    );
                }
                "Set" => {
                    return format!(
                        "({var}.{field_name} instanceof Set \
                                    ? Array.from({var}.{field_name}).reduce((h, v) => \
                                        (h * 31 + {elem_fn}(v)) | 0, 0) \
                                    : 0)"
                    );
                }
                _ => {
                    // Array types
                    return format!(
                        "(Array.isArray({var}.{field_name}) \
                                    ? {var}.{field_name}.reduce((h, v) => \
                                        (h * 31 + {elem_fn}(v)) | 0, 0) \
                                    : 0)"
                    );
                }
            }
        }
    }

    // Fallback: original duck-typing behavior
    if is_primitive_type(ts_type) {
        match ts_type.as_str() {
            "number" => {
                format!(
                    "(Number.isInteger({var}.{field_name}) \
                        ? {var}.{field_name} | 0 \
                        : {var}.{field_name}.toString().split('').reduce((h, c) => (h * 31 + c.charCodeAt(0)) | 0, 0))"
                )
            }
            "bigint" => {
                format!(
                    "{var}.{field_name}.toString().split('').reduce((h, c) => (h * 31 + c.charCodeAt(0)) | 0, 0)"
                )
            }
            "string" => {
                format!(
                    "({var}.{field_name} ?? '').split('').reduce((h, c) => (h * 31 + c.charCodeAt(0)) | 0, 0)"
                )
            }
            "boolean" => {
                format!("({var}.{field_name} ? 1231 : 1237)")
            }
            _ => {
                format!("({var}.{field_name} != null ? 1 : 0)")
            }
        }
    } else if ts_type.ends_with("[]") || ts_type.starts_with("Array<") {
        format!(
            "(Array.isArray({var}.{field_name}) \
                ? {var}.{field_name}.reduce((h, v) => \
                    (h * 31 + (typeof (v as any)?.hashCode === 'function' \
                        ? (v as any).hashCode() \
                        : (v != null ? String(v).split('').reduce((hh, c) => (hh * 31 + c.charCodeAt(0)) | 0, 0) : 0))) | 0, 0) \
                : 0)"
        )
    } else if ts_type == "Date" {
        format!("({var}.{field_name} instanceof Date ? {var}.{field_name}.getTime() | 0 : 0)")
    } else if ts_type.starts_with("Map<") {
        format!(
            "({var}.{field_name} instanceof Map \
                ? Array.from({var}.{field_name}.entries()).reduce((h, [k, v]) => \
                    (h * 31 + String(k).split('').reduce((hh, c) => (hh * 31 + c.charCodeAt(0)) | 0, 0) + \
                    (typeof (v as any)?.hashCode === 'function' ? (v as any).hashCode() : 0)) | 0, 0) \
                : 0)"
        )
    } else if ts_type.starts_with("Set<") {
        format!(
            "({var}.{field_name} instanceof Set \
                ? Array.from({var}.{field_name}).reduce((h, v) => \
                    (h * 31 + (typeof (v as any)?.hashCode === 'function' \
                        ? (v as any).hashCode() \
                        : (v != null ? String(v).split('').reduce((hh, c) => (hh * 31 + c.charCodeAt(0)) | 0, 0) : 0))) | 0, 0) \
                : 0)"
        )
    } else {
        format!(
            "(typeof ({var}.{field_name} as any)?.hashCode === 'function' \
                ? ({var}.{field_name} as any).hashCode() \
                : ({var}.{field_name} != null \
                    ? JSON.stringify({var}.{field_name}).split('').reduce((h, c) => (h * 31 + c.charCodeAt(0)) | 0, 0) \
                    : 0))"
        )
    }
}

#[ts_macro_derive(
    Hash,
    description = "Generates a hashCode() method for hashing",
    attributes(hash)
)]
pub fn derive_hash_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 hash
            let hash_fields: Vec<HashField> = class
                .fields()
                .iter()
                .filter_map(|field| {
                    let opts = CompareFieldOptions::from_decorators(&field.decorators, "hash");
                    if opts.skip {
                        return None;
                    }
                    Some(HashField {
                        name: field.name.clone(),
                        ts_type: field.ts_type.clone(),
                    })
                })
                .collect();

            // Note: Rust's linter doesn't understand template macro variable capture
            let _has_fields = !hash_fields.is_empty();

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

            // Generate hash expressions for each field
            // Note: Rust's linter doesn't understand template macro variable capture
            let _hash_exprs: Vec<Expr> = hash_fields
                .iter()
                .map(|f| {
                    let resolved = resolved_fields.and_then(|rf| rf.get(&f.name));
                    let expr_src =
                        generate_field_hash_for_interface(f, "value", resolved, type_registry);
                    let expr = parse_ts_expr(&expr_src).map_err(|err| {
                        MacroforgeError::new(
                            input.decorator_span(),
                            format!(
                                "@derive(Hash): invalid hash expression for '{}': {err:?}",
                                f.name
                            ),
                        )
                    })?;
                    Ok(*expr)
                })
                .collect::<Result<_, MacroforgeError>>()?;

            // Generate standalone function with value parameter
            let standalone = ts_template! {
                export function @{fn_name_ident}(value: @{class_ident.clone()}): number {
                    let hash = 17;
                    {#if _has_fields}
                        {#for hash_expr in _hash_exprs}
                            hash = (hash * 31 + @{hash_expr}) | 0;
                        {/for}
                    {/if}
                    return hash;
                }
            };

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

            // Combine standalone function with class body using {$typescript} for proper composition
            // The standalone output (no marker) must come FIRST so it defaults to "below" (after class)
            Ok(ts_template! {
                {$typescript standalone}
                {$typescript class_body}
            })
        }
        Data::Enum(enum_data) => {
            let enum_name = input.name();
            let fn_name_ident = ts_ident!("{}HashCode", enum_name.to_case(Case::Camel));

            // Check if all variants are string values
            let is_string_enum = enum_data.variants().iter().all(|v| v.value.is_string());

            if is_string_enum {
                // String enum: hash the string value
                Ok(ts_template! {
                    export function @{fn_name_ident}(value: @{ts_ident!(enum_name)}): number {
                        let hash = 0;
                        for (let i = 0; i < value.length; i++) {
                            hash = (hash * 31 + value.charCodeAt(i)) | 0;
                        }
                        return hash;
                    }
                })
            } else {
                // Numeric enum: use the number value directly
                Ok(ts_template! {
                    export function @{fn_name_ident}(value: @{ts_ident!(enum_name)}): number {
                        return value as number;
                    }
                })
            }
        }
        Data::Interface(interface) => {
            let interface_name = input.name();

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

            // Note: Rust's linter doesn't understand template macro variable capture
            let _has_fields = !hash_fields.is_empty();

            // Generate hash expressions for each field
            // Note: Rust's linter doesn't understand template macro variable capture
            let _hash_exprs: Vec<Expr> = hash_fields
                .iter()
                .map(|f| {
                    let resolved = resolved_fields.and_then(|rf| rf.get(&f.name));
                    let expr_src =
                        generate_field_hash_for_interface(f, "value", resolved, type_registry);
                    let expr = parse_ts_expr(&expr_src).map_err(|err| {
                        MacroforgeError::new(
                            input.decorator_span(),
                            format!(
                                "@derive(Hash): invalid hash expression for '{}': {err:?}",
                                f.name
                            ),
                        )
                    })?;
                    Ok(*expr)
                })
                .collect::<Result<_, MacroforgeError>>()?;

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

            Ok(ts_template! {
                export function @{fn_name_ident}(value: @{ts_ident!(interface_name)}): number {
                    let hash = 17;
                    {#if _has_fields}
                        {#for hash_expr in _hash_exprs}
                            hash = (hash * 31 + @{hash_expr}) | 0;
                        {/for}
                    {/if}
                    return hash;
                }
            })
        }
        Data::TypeAlias(type_alias) => {
            let type_name = input.name();

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

                // Note: Rust's linter doesn't understand template macro variable capture
                let _has_fields = !hash_fields.is_empty();

                // Generate hash expressions for each field
                // Note: Rust's linter doesn't understand template macro variable capture
                let _hash_exprs: Vec<Expr> = hash_fields
                    .iter()
                    .map(|f| {
                        let resolved = resolved_fields.and_then(|rf| rf.get(&f.name));
                        let expr_src =
                            generate_field_hash_for_interface(f, "value", resolved, type_registry);
                        let expr = parse_ts_expr(&expr_src).map_err(|err| {
                            MacroforgeError::new(
                                input.decorator_span(),
                                format!(
                                    "@derive(Hash): invalid hash expression for '{}': {err:?}",
                                    f.name
                                ),
                            )
                        })?;
                        Ok(*expr)
                    })
                    .collect::<Result<_, MacroforgeError>>()?;

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

                Ok(ts_template! {
                    export function @{fn_name_ident}(value: @{ts_ident!(type_name)}): number {
                        let hash = 17;
                        {#if _has_fields}
                            {#for hash_expr in _hash_exprs}
                                hash = (hash * 31 + @{hash_expr}) | 0;
                            {/for}
                        {/if}
                        return hash;
                    }
                })
            } else {
                // Union, tuple, or simple alias: use JSON hash
                let fn_name_ident = ts_ident!("{}HashCode", type_name.to_case(Case::Camel));

                Ok(ts_template! {
                    export function @{fn_name_ident}(value: @{ts_ident!(type_name)}): number {
                        const str = JSON.stringify(value);
                        let hash = 0;
                        for (let i = 0; i < str.length; i++) {
                            hash = (hash * 31 + str.charCodeAt(i)) | 0;
                        }
                        return hash;
                    }
                })
            }
        }
    }
}

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

    #[test]
    fn test_hash_macro_output() {
        let hash_fields: Vec<HashField> = vec![HashField {
            name: "id".to_string(),
            ts_type: "number".to_string(),
        }];
        let _has_fields = !hash_fields.is_empty();

        let _hash_exprs: Vec<Expr> = hash_fields
            .iter()
            .map(|f| {
                let expr_src = generate_field_hash_for_interface(f, "value", None, None);
                *parse_ts_expr(&expr_src).expect("hash expr should parse")
            })
            .collect();

        let output = ts_template!(Within {
            hashCode(): number {
                let hash = 17;
                {#if _has_fields}
                    {#for hash_expr in _hash_exprs}
                        hash = (hash * 31 + @{hash_expr}) | 0;
                    {/for}
                {/if}
                return hash;
            }
        });

        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 Hash macro output should parse as class members"
        );
        assert!(
            source.contains("hashCode"),
            "Should contain hashCode method"
        );
    }

    #[test]
    fn test_field_hash_number() {
        let field = HashField {
            name: "id".to_string(),
            ts_type: "number".to_string(),
        };
        let result = generate_field_hash_for_interface(&field, "value", None, None);
        assert!(result.contains("Number.isInteger"));
    }

    #[test]
    fn test_field_hash_string() {
        let field = HashField {
            name: "name".to_string(),
            ts_type: "string".to_string(),
        };
        let result = generate_field_hash_for_interface(&field, "value", None, None);
        assert!(result.contains("split"));
        assert!(result.contains("charCodeAt"));
    }

    #[test]
    fn test_field_hash_boolean() {
        let field = HashField {
            name: "active".to_string(),
            ts_type: "boolean".to_string(),
        };
        let result = generate_field_hash_for_interface(&field, "value", None, None);
        assert!(result.contains("1231")); // Java's Boolean.hashCode() constants
        assert!(result.contains("1237"));
    }

    #[test]
    fn test_field_hash_date() {
        let field = HashField {
            name: "createdAt".to_string(),
            ts_type: "Date".to_string(),
        };
        let result = generate_field_hash_for_interface(&field, "value", None, None);
        assert!(result.contains("getTime"));
    }

    #[test]
    fn test_field_hash_object() {
        let field = HashField {
            name: "user".to_string(),
            ts_type: "User".to_string(),
        };
        // Without registry — duck-typing fallback
        let result = generate_field_hash_for_interface(&field, "value", None, None);
        assert!(result.contains("hashCode"));
    }
}