tsz-solver 0.1.8

TypeScript type solver for the tsz compiler
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
//! Concurrent type interning tests
//!
//! These tests verify that the `TypeInterner`'s lock-free `DashMap` architecture
//! enables true parallel type checking without lock contention or deadlocks.

use crate::{
    CallableShape, FunctionShape, ObjectFlags, ObjectShape, ParamInfo, PropertyInfo, TypeId,
    TypeInterner, TypeParamInfo, Visibility,
};
use rayon::prelude::*;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use tsz_common::interner::Atom;

#[test]
fn test_concurrent_string_interning_deduplication() {
    let interner = Arc::new(TypeInterner::new());

    // Have many threads intern the same strings
    let strings: Vec<String> = (0..1000).map(|i| format!("string_{}", i % 100)).collect();

    let results: Vec<Atom> = strings
        .par_iter()
        .map(|s| interner.intern_string(s))
        .collect();

    // Verify deduplication: same string should produce same atom
    for (i, s) in strings.iter().enumerate() {
        let atom1 = results[i];
        let atom2 = interner.intern_string(s);
        assert_eq!(atom1, atom2, "String should deduplicate: {s}");
    }

    // Verify we can resolve all atoms
    for atom in results.iter() {
        let resolved = interner.resolve_atom(*atom);
        assert!(!resolved.is_empty());
    }
}

#[test]
fn test_concurrent_type_interning() {
    let interner = Arc::new(TypeInterner::new());

    // Many threads intern different types concurrently
    let type_ids: Vec<TypeId> = (0..1000)
        .into_par_iter()
        .map(|i| match i % 4 {
            0 => interner.literal_number(i as f64),
            1 => interner.literal_string(&format!("str_{i}")),
            2 => interner.union(vec![TypeId::STRING, TypeId::NUMBER]),
            3 => interner.intersection(vec![TypeId::STRING, TypeId::NUMBER]),
            _ => panic!("internal error: unexpected concurrent partition index"),
        })
        .collect();

    // Verify all types are valid (not error)
    for &type_id in &type_ids {
        assert_ne!(type_id, TypeId::ERROR);
        assert!(interner.lookup(type_id).is_some());
    }
}

#[test]
fn test_concurrent_object_creation() {
    let interner = Arc::new(TypeInterner::new());

    // Many threads create objects concurrently
    let object_types: Vec<TypeId> = (0..100)
        .into_par_iter()
        .map(|i| {
            let props = vec![
                PropertyInfo::new(interner.intern_string("x"), TypeId::NUMBER),
                PropertyInfo {
                    name: interner.intern_string(&format!("prop_{i}")),
                    type_id: TypeId::STRING,
                    write_type: TypeId::STRING,
                    optional: false,
                    readonly: false,
                    is_method: false,
                    visibility: Visibility::Public,
                    parent_id: None,
                },
            ];
            interner.object(props)
        })
        .collect();

    // Verify all objects were created successfully
    assert_eq!(object_types.len(), 100);
    for &type_id in &object_types {
        assert_ne!(type_id, TypeId::ERROR);
        assert!(interner.lookup(type_id).is_some());
    }
}

#[test]
fn test_concurrent_function_creation() {
    let interner = Arc::new(TypeInterner::new());

    // Many threads create function types concurrently
    let function_types: Vec<TypeId> = (0..100)
        .into_par_iter()
        .map(|_| {
            let shape = FunctionShape {
                type_params: vec![TypeParamInfo {
                    name: interner.intern_string("T"),
                    constraint: None,
                    default: None,
                    is_const: false,
                }],
                params: vec![
                    ParamInfo {
                        name: Some(interner.intern_string("x")),
                        type_id: TypeId::NUMBER,
                        optional: false,
                        rest: false,
                    },
                    ParamInfo {
                        name: Some(interner.intern_string("y")),
                        type_id: TypeId::STRING,
                        optional: false,
                        rest: false,
                    },
                ],
                this_type: None,
                return_type: TypeId::BOOLEAN,
                type_predicate: None,
                is_constructor: false,
                is_method: false,
            };
            interner.function(shape)
        })
        .collect();

    // Verify all functions were created successfully
    assert_eq!(function_types.len(), 100);
    for &type_id in &function_types {
        assert_ne!(type_id, TypeId::ERROR);
        assert!(interner.lookup(type_id).is_some());
    }
}

#[test]
fn test_concurrent_union_creation() {
    let interner = Arc::new(TypeInterner::new());

    // Create many union types concurrently
    let union_types: Vec<TypeId> = (0..500)
        .into_par_iter()
        .map(|i| {
            interner.union(vec![
                TypeId::STRING,
                TypeId::NUMBER,
                interner.literal_number((i % 10) as f64),
            ])
        })
        .collect();

    // Verify all unions were created successfully
    assert_eq!(union_types.len(), 500);
    for &type_id in &union_types {
        assert_ne!(type_id, TypeId::ERROR);
        assert!(interner.lookup(type_id).is_some());
    }

    // Verify deduplication: same union should produce same TypeId
    let union1 = interner.union(vec![TypeId::STRING, TypeId::NUMBER]);
    let union2 = interner.union(vec![TypeId::NUMBER, TypeId::STRING]); // Order normalized
    assert_eq!(union1, union2, "Unions should normalize and deduplicate");
}

#[test]
fn test_concurrent_intersection_creation() {
    let interner = Arc::new(TypeInterner::new());

    // Create many intersection types concurrently
    let intersection_types: Vec<TypeId> = (0..500)
        .into_par_iter()
        .map(|_| interner.intersection(vec![TypeId::STRING, TypeId::NUMBER, TypeId::BOOLEAN]))
        .collect();

    // Verify all intersections were created successfully
    // Note: disjoint primitives = never, so some will be NEVER
    assert_eq!(intersection_types.len(), 500);
    for &type_id in &intersection_types {
        assert!(interner.lookup(type_id).is_some());
    }
}

#[test]
fn test_concurrent_property_map_building() {
    let interner = Arc::new(TypeInterner::new());

    // Create a large object (above cache threshold)
    let props: Vec<PropertyInfo> = (0..30)
        .map(|i| PropertyInfo {
            name: interner.intern_string(&format!("prop_{i}")),
            type_id: TypeId::STRING,
            write_type: TypeId::STRING,
            optional: false,
            readonly: false,
            is_method: false,
            visibility: Visibility::Public,
            parent_id: None,
        })
        .collect();

    let shape = ObjectShape {
        symbol: None,
        flags: ObjectFlags::empty(),
        properties: props,
        string_index: None,
        number_index: None,
    };
    let shape_id = interner.intern_object_shape(shape);

    // Concurrent property lookups should build the cache safely
    let lookups: Vec<_> = (0..100)
        .into_par_iter()
        .map(|i| {
            let prop_name = interner.intern_string(&format!("prop_{}", i % 30));
            interner.object_property_index(shape_id, prop_name)
        })
        .collect();

    // All lookups should succeed
    for lookup in &lookups {
        match lookup {
            PropertyLookup::Found(_) | PropertyLookup::Uncached => {}
            PropertyLookup::NotFound => panic!("Property should be found"),
        }
    }
}

#[test]
fn test_no_data_races_in_parallel_type_checking() {
    use rayon::ThreadPoolBuilder;

    let pool = ThreadPoolBuilder::new().num_threads(8).build().unwrap();

    pool.scope(|_s| {
        let interner = Arc::new(TypeInterner::new());
        let counter = Arc::new(AtomicUsize::new(0));

        // Spawn many tasks that all access the interner
        (0..100).for_each(|_| {
            let interner_clone = Arc::clone(&interner);
            let counter_clone = Arc::clone(&counter);

            rayon::spawn(move || {
                // Perform various type operations
                for i in 0..100 {
                    let _ = interner_clone.intern_string(&format!("key_{}", i % 10));
                    let _ = interner_clone.literal_number(i as f64);
                    let _ = interner_clone.union(vec![TypeId::STRING, TypeId::NUMBER]);
                    counter_clone.fetch_add(1, Ordering::Relaxed);
                }
            });
        });
    });

    // If we reach here without panicking, there were no data races
    // The lock-free DashMap architecture handled concurrent access correctly
}

#[test]
fn test_concurrent_callable_creation() {
    let interner = Arc::new(TypeInterner::new());

    // Create callable types with multiple signatures concurrently
    let callable_types: Vec<TypeId> = (0..50)
        .into_par_iter()
        .map(|_| {
            let shape = CallableShape {
                symbol: None,
                call_signatures: vec![],
                construct_signatures: vec![],
                properties: vec![PropertyInfo::readonly(
                    interner.intern_string("length"),
                    TypeId::NUMBER,
                )],
                number_index: None,
                string_index: None,
            };
            interner.callable(shape)
        })
        .collect();

    // Verify all callables were created successfully
    assert_eq!(callable_types.len(), 50);
    for &type_id in &callable_types {
        assert_ne!(type_id, TypeId::ERROR);
        assert!(interner.lookup(type_id).is_some());
    }
}

#[test]
fn test_shard_distribution() {
    let interner = Arc::new(TypeInterner::new());

    // Intern many different types to distribute across shards
    let _type_ids: Vec<TypeId> = (0..10000)
        .into_par_iter()
        .map(|i| {
            interner.union(vec![
                interner.literal_number(i as f64),
                interner.literal_string(&format!("str_{i}")),
            ])
        })
        .collect();

    // Verify the interner has many types (proving distribution)
    let total_types = interner.len();
    assert!(
        total_types > 1000,
        "Should have interned many types: {total_types}"
    );
}

#[test]
fn test_concurrent_array_creation() {
    let interner = Arc::new(TypeInterner::new());

    // Create many array types concurrently
    let array_types: Vec<TypeId> = (0..1000)
        .into_par_iter()
        .map(|i| {
            let element_type = match i % 4 {
                0 => TypeId::STRING,
                1 => TypeId::NUMBER,
                2 => TypeId::BOOLEAN,
                3 => interner.literal_number(i as f64),
                _ => panic!("internal error: unexpected concurrent array type selector"),
            };
            interner.array(element_type)
        })
        .collect();

    // Verify all arrays were created successfully
    assert_eq!(array_types.len(), 1000);
    for &type_id in &array_types {
        assert_ne!(type_id, TypeId::ERROR);
        assert!(interner.lookup(type_id).is_some());
    }
}

#[test]
fn test_concurrent_tuple_creation() {
    use crate::TupleElement;

    let interner = Arc::new(TypeInterner::new());

    // Create many tuple types concurrently
    let tuple_types: Vec<TypeId> = (0..100)
        .into_par_iter()
        .map(|_| {
            let elements = vec![
                TupleElement {
                    type_id: TypeId::STRING,
                    name: None,
                    optional: false,
                    rest: false,
                },
                TupleElement {
                    type_id: TypeId::NUMBER,
                    name: None,
                    optional: false,
                    rest: false,
                },
            ];
            interner.tuple(elements)
        })
        .collect();

    // Verify all tuples were created successfully
    assert_eq!(tuple_types.len(), 100);
    for &type_id in &tuple_types {
        assert_ne!(type_id, TypeId::ERROR);
        assert!(interner.lookup(type_id).is_some());
    }

    // Verify deduplication: same tuple should produce same TypeId
    let tuple1 = interner.tuple(vec![
        TupleElement {
            type_id: TypeId::STRING,
            name: None,
            optional: false,
            rest: false,
        },
        TupleElement {
            type_id: TypeId::NUMBER,
            name: None,
            optional: false,
            rest: false,
        },
    ]);
    let tuple2 = interner.tuple(vec![
        TupleElement {
            type_id: TypeId::STRING,
            name: None,
            optional: false,
            rest: false,
        },
        TupleElement {
            type_id: TypeId::NUMBER,
            name: None,
            optional: false,
            rest: false,
        },
    ]);
    assert_eq!(tuple1, tuple2, "Tuples should deduplicate");
}

#[test]
fn test_concurrent_template_literal_creation() {
    use crate::TemplateSpan;

    let interner = Arc::new(TypeInterner::new());

    // Create many template literal types concurrently
    let template_types: Vec<TypeId> = (0..100)
        .into_par_iter()
        .map(|i| {
            let spans = vec![
                TemplateSpan::Text(interner.intern_string("prefix_")),
                TemplateSpan::Type(interner.literal_string(&format!("literal_{i}"))),
            ];
            interner.template_literal(spans)
        })
        .collect();

    // Verify all template literals were created successfully
    assert_eq!(template_types.len(), 100);
    for &type_id in &template_types {
        assert_ne!(type_id, TypeId::ERROR);
        assert!(interner.lookup(type_id).is_some());
    }
}
use crate::types::PropertyLookup;