mimium-lang 4.0.0-alpha

mimium(minimal-musical-medium) an infrastructural programming language for sound and music.
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
721
722
723
724
725
726
727
728
729
730
731
732
733
use crate::utils::metadata::Span;
use std::collections::HashSet;

use super::*;

/// Represents the relationship between two types after unification.
#[derive(PartialEq, Eq, Debug, Clone, Copy)]
pub(crate) enum Relation {
    /// t1 is subtype of t2 (e.g., int is subtype of float | int)
    Subtype,
    /// t1 and t2 are identical types
    Identical,
    /// t1 is supertype of t2
    Supertype,
}
#[derive(PartialEq, Eq, Debug)]
pub(crate) enum Error {
    TypeMismatch {
        left: (TypeNodeId, Span),
        right: (TypeNodeId, Span),
    },
    LengthMismatch {
        left: (Vec<TypeNodeId>, Span),
        right: (Vec<TypeNodeId>, Span),
    },
    CircularType {
        left: Span,
        right: Span,
    },
    ImcompatibleRecords {
        left: (Vec<(Symbol, TypeNodeId)>, Span),
        right: (Vec<(Symbol, TypeNodeId)>, Span),
    },
}

fn is_dummy_span(span: &Span) -> bool {
    span.start == 0 && span.end == 0
}

fn span_from_type_tree(t: TypeNodeId) -> Option<Span> {
    let mut stack = vec![t];
    let mut visited = HashSet::new();

    while let Some(current) = stack.pop() {
        if !visited.insert(current) {
            continue;
        }

        let span = current.to_span();
        if !is_dummy_span(&span) {
            return Some(span);
        }

        match current.to_type() {
            Type::Array(elem) | Type::Ref(elem) | Type::Code(elem) | Type::Boxed(elem) => {
                stack.push(elem);
            }
            Type::Tuple(items) | Type::Union(items) => {
                stack.extend(items.iter().copied());
            }
            Type::Record(fields) => {
                stack.extend(fields.iter().map(|RecordTypeField { ty, .. }| *ty));
            }
            Type::Function { arg, ret } => {
                stack.push(arg);
                stack.push(ret);
            }
            Type::Intermediate(cell) => {
                if let Some(parent) = cell.read().ok().and_then(|tv| tv.parent) {
                    stack.push(parent);
                }
            }
            Type::UserSum { variants, .. } => {
                stack.extend(variants.iter().filter_map(|(_, payload)| *payload));
            }
            Type::Primitive(_)
            | Type::TypeScheme(_)
            | Type::TypeAlias(_)
            | Type::Any
            | Type::Failure
            | Type::Unknown => {}
        }
    }

    None
}

fn best_span(primary: TypeNodeId, secondary: TypeNodeId) -> Span {
    span_from_type_tree(primary)
        .or_else(|| span_from_type_tree(secondary))
        .unwrap_or_else(|| primary.to_span())
}

// return true when the circular loop of intermediate variable exists.
fn occur_check(id1: IntermediateId, t2: TypeNodeId) -> bool {
    let cls = |t2dash: TypeNodeId| -> bool { occur_check(id1, t2dash) };

    let vec_cls = |t: &[_]| -> bool { t.iter().any(|a| cls(*a)) };

    match &t2.to_type() {
        Type::Intermediate(cell) => cell
            .read()
            .map(|tv2| match tv2.parent {
                Some(tid2) => id1 == tv2.var || occur_check(id1, tid2),
                None => id1 == tv2.var,
            })
            .unwrap_or(true),
        Type::Array(a) => cls(*a),
        Type::Tuple(t) => vec_cls(t),
        Type::Function { arg, ret } => cls(*arg) && cls(*ret),
        Type::Record(s) => vec_cls(
            s.iter()
                .map(|RecordTypeField { ty, .. }| *ty)
                .collect::<Vec<_>>()
                .as_slice(),
        ),
        Type::Union(types) => vec_cls(types),
        Type::Boxed(b) => cls(*b),
        _ => false,
    }
}

// fn covariant(rel: Relation) -> Relation {
//     match rel {
//         Relation::Subtype => Relation::Subtype,
//         Relation::Identical => Relation::Subtype,
//         Relation::Supertype => Relation::Supertype,
//     }
// }
// fn contravariant(rel: Relation) -> Relation {
//     match rel {
//         Relation::Subtype => Relation::Supertype,
//         Relation::Supertype => Relation::Subtype,
//         Relation::Identical => Relation::Sub,
//     }
// }

//todo
fn unify_vec(a1: &[TypeNodeId], a2: &[TypeNodeId]) -> Result<Relation, Vec<Error>> {
    assert_eq!(a1.len(), a2.len());
    let (res, errs): (Vec<_>, Vec<_>) = a1
        .iter()
        .zip(a2)
        .map(|(a1, a2)| unify_types(*a1, *a2))
        .partition_result();
    let errs: Vec<_> = errs.into_iter().flatten().collect();

    let res_relation = if res.iter().all(|r| *r != Relation::Subtype) {
        Relation::Supertype
    } else if res.iter().all(|r| *r != Relation::Supertype) {
        Relation::Subtype
    } else {
        //TODO more specific error report, if the tuple contains both subtype and supertype
        return Err(errs);
    };
    Ok(res_relation)
}
fn unify_types_args(t1: TypeNodeId, t2: TypeNodeId) -> Result<Relation, Vec<Error>> {
    log::trace!("unify_args {} and {}", t1.to_type(), t2.to_type());
    let loc1 = best_span(t1, t2);
    let loc2 = best_span(t2, t1);
    let t1r = t1.get_root();
    let t2r = t2.get_root();
    let res = match &(t1r.to_type(), t2r.to_type()) {
        (Type::Record(_), Type::Record(_)) | (Type::Tuple(_), Type::Tuple(_)) => {
            unify_types(t1, t2)?
        }
        (Type::Record(v), _t) if v.len() == 1 => unify_types_args(v.first().unwrap().ty, t2)?,
        (_t, Type::Record(v)) if v.len() == 1 && !v.first().unwrap().has_default => {
            unify_types_args(t1, v.first().unwrap().ty)?
        }
        (_t, Type::Tuple(v)) if v.len() == 1 => unify_types_args(t1, *v.first().unwrap())?,
        (Type::Tuple(v), _t) if v.len() == 1 => unify_types_args(*v.first().unwrap(), t2)?,

        (Type::Intermediate(i1), Type::Intermediate(i2)) => {
            // Read all necessary values first, then release read locks
            let (tv1_eq, var1, level1, parent1) = {
                let guard = i1.read().unwrap();
                (guard.clone(), guard.var, guard.level, guard.parent)
            };
            let (tv2_eq, var2, level2, parent2) = {
                let guard = i2.read().unwrap();
                (guard.clone(), guard.var, guard.level, guard.parent)
            };

            if tv1_eq == tv2_eq {
                return Ok(Relation::Identical);
            }
            if occur_check(var1, t2) {
                return Err(vec![Error::CircularType {
                    left: loc1,
                    right: loc2,
                }]);
            }

            // Now acquire write locks only when needed
            if level2 > level1 {
                i2.write().unwrap().level = level1;
            }

            match (parent1, parent2) {
                (None, None) => {
                    if var1 > var2 {
                        i2.write().unwrap().parent = Some(t1r);
                    } else {
                        i1.write().unwrap().parent = Some(t2r);
                    };
                }
                (_, Some(p2)) => {
                    i1.write().unwrap().parent = Some(p2);
                }
                (Some(p1), _) => {
                    i2.write().unwrap().parent = Some(p1);
                }
            };
            Relation::Identical
        }
        (Type::Intermediate(i1), _) => {
            let var1 = i1.read().unwrap().var;
            if occur_check(var1, t2r) {
                return Err(vec![Error::CircularType {
                    left: loc1,
                    right: loc2,
                }]);
            }
            let mut tv1 = i1.write().unwrap();
            tv1.parent = Some(t2r);
            tv1.bound.upper = t2r;
            drop(tv1); // Explicitly release lock

            Relation::Identical
        }
        (_, Type::Intermediate(i2)) => {
            let var2 = i2.read().unwrap().var;
            if occur_check(var2, t1r) {
                return Err(vec![Error::CircularType {
                    left: loc1,
                    right: loc2,
                }]);
            }
            let mut tv2 = i2.write().unwrap();
            tv2.parent = Some(t1r);
            tv2.bound.upper = t1r;
            drop(tv2); // Explicitly release lock
            Relation::Identical
        }
        (Type::Record(kvs), Type::Tuple(_)) => {
            let recordvec = kvs
                .iter()
                .map(|RecordTypeField { ty, .. }| *ty)
                .collect::<Vec<_>>();
            let loc_record = t1.to_loc();
            let new_tup = Type::Tuple(recordvec).into_id_with_location(loc_record);
            unify_types_args(new_tup, t2)?
        }
        (Type::Tuple(_), Type::Record(_)) => unify_types_args(t2, t1)?,
        // Union type in argument position: check if actual type can be part of the union
        (Type::Union(union_types), _t) => {
            // Expected type is a union, actual type should match one of the union members
            for union_member in union_types {
                if unify_types_args(*union_member, t2r).is_ok() {
                    // Treat as identical when the actual type matches a union member
                    return Ok(Relation::Identical);
                }
            }
            return Err(vec![Error::TypeMismatch {
                left: (t1, loc1.clone()),
                right: (t2, loc2.clone()),
            }]);
        }
        (_, _) => unify_types(t1, t2)?,
    };
    Ok(res)
}

/// Solve type constraints. Though the function arguments are immutable, it modified the content of Intermediate Type.
/// If the result is `Relation::Subtype`, it means "t1 is subtype of t2".
pub(crate) fn unify_types(t1: TypeNodeId, t2: TypeNodeId) -> Result<Relation, Vec<Error>> {
    let loc1 = best_span(t1, t2);
    let loc2 = best_span(t2, t1);

    let t1r = t1.get_root();
    let t2r = t2.get_root();
    let res = match &(t1r.to_type(), t2r.to_type()) {
        (Type::Intermediate(i1), Type::Intermediate(i2)) => {
            // Read all necessary values first, then release read locks
            let (tv1_eq, var1, level1, parent1) = {
                let guard = i1.read().unwrap();
                (guard.clone(), guard.var, guard.level, guard.parent)
            };
            let (tv2_eq, var2, level2, parent2) = {
                let guard = i2.read().unwrap();
                (guard.clone(), guard.var, guard.level, guard.parent)
            };

            if tv1_eq == tv2_eq {
                return Ok(Relation::Identical);
            }
            if occur_check(var1, t2) {
                return Err(vec![Error::CircularType {
                    left: loc1,
                    right: loc2,
                }]);
            }

            // Now acquire write locks only when needed
            if level1 < level2 {
                i1.write().unwrap().level = level2;
            }

            match (parent1, parent2) {
                (None, None) => {
                    if var1 > var2 {
                        i2.write().unwrap().parent = Some(t1r);
                    } else {
                        i1.write().unwrap().parent = Some(t2r);
                    };
                }
                (_, Some(p2)) => {
                    i1.write().unwrap().parent = Some(p2);
                }
                (Some(p1), _) => {
                    i2.write().unwrap().parent = Some(p1);
                }
            };
            Relation::Identical
        }
        (Type::Intermediate(i1), _) => {
            let var1 = i1.read().unwrap().var;
            if occur_check(var1, t2r) {
                return Err(vec![Error::CircularType {
                    left: loc1,
                    right: loc2,
                }]);
            }
            let mut tv1 = i1.write().unwrap();
            tv1.parent = Some(t2r);
            tv1.bound.lower = t2r;
            drop(tv1); // Explicitly release lock

            Relation::Identical
        }
        (_, Type::Intermediate(i2)) => {
            let var2 = i2.read().unwrap().var;
            if occur_check(var2, t1r) {
                return Err(vec![Error::CircularType {
                    left: loc1,
                    right: loc2,
                }]);
            }
            let mut tv2 = i2.write().unwrap();
            tv2.parent = Some(t1r);
            tv2.bound.lower = t1r;
            drop(tv2); // Explicitly release lock
            Relation::Identical
        }
        (Type::Array(a1), Type::Array(a2)) => {
            //theoriticaly, the array type can be covariant but it makes implementation complex and might be not intuitive for beginners.
            let res = unify_types(*a1, *a2)?;
            match res {
                Relation::Identical => Relation::Identical,
                _ => {
                    return Err(vec![Error::TypeMismatch {
                        left: (*a1, loc1.clone()),
                        right: (*a2, loc2.clone()),
                    }]);
                }
            }
        }
        (Type::Ref(x1), Type::Ref(x2)) => unify_types(*x1, *x2)?,
        (Type::Tuple(a1), Type::Tuple(a2)) => {
            // if a1 have nth elements, a2 must have at least n, or more elements.
            // but for simplicity, currently the tuple length must be identical.
            use std::cmp::Ordering;
            match a1.len().cmp(&a2.len()) {
                Ordering::Equal => {
                    let _ = unify_vec(a1, a2)?;
                    //todo covariance
                    Relation::Identical
                }
                // Ordering::Less => {
                //     let _ = unify_vec(a1, &a2[0..a1.len()])?;
                //     Relation::Subtype
                // }
                // Ordering::Greater => {
                //     let _ = unify_vec(&a1[0..a2.len()], a2)?;
                //     Relation::Supertype
                // }
                _ => {
                    return Err(vec![Error::LengthMismatch {
                        left: (a1.to_vec(), loc1),
                        right: (a2.to_vec(), loc2),
                    }]);
                }
            }
        }
        // a and b are identical:
        // a: {key1:A, key2:_, key3:C}
        // b: {key1:_, key2:B, key3:C}
        // - a is subtype of b
        // a: {key1:A,       , key3:C,       , key5:E}
        // b: {key1:A, key2:_, key3:C, key4:D, key5:E}
        // - a is supertype of b
        // a: {key1:A, key2:_, key3:C, key4:D, key5:E}
        // b: {key1:A,       , key3:C,       , key5:E}
        // - a and b are imcompatible
        // a: {key1:A, key2:_,       , key4:D, key5:E}
        // b: {key1:A,       , key3:C,       , key5:E}
        (Type::Record(a1), Type::Record(a2)) => {
            // the algotithm used here may not be efficient but we prioritize the clarity of logic.
            // it will not matter because the code rarely contains huge entries of record

            //list up all keys. expect that the records are sorted by the alphabetical order.

            let keys_a = a1.iter().sorted_by(move |a, b| {
                let keya = a.key;
                let keyb = b.key;
                keya.as_str().cmp(keyb.as_str())
            });
            let keys_b = a2.iter().sorted_by(move |a, b| {
                let keya = a.key;
                let keyb = b.key;
                keya.as_str().cmp(keyb.as_str())
            });
            let allkeys = keys_a
                .clone()
                .chain(keys_b.clone())
                .unique_by(|RecordTypeField { key, .. }| key.as_str());
            let sparse_fields1 = allkeys.clone().map(|parent| {
                a1.iter()
                    .find(|RecordTypeField { key, .. }| parent.key == *key)
                    .or(parent.has_default.then_some(parent))
            });
            let sparse_fields2 = allkeys.map(|parent| {
                a2.iter()
                    .find(|RecordTypeField { key, .. }| parent.key == *key)
                    .or(parent.has_default.then_some(parent))
            });
            #[derive(PartialEq, Eq, Debug)]
            enum SearchRes {
                Both,
                A,
                B,
            }
            let searchresults = sparse_fields1.zip(sparse_fields2).map(|pair| match pair {
                (Some(s1), Some(s2)) => unify_types(s1.ty, s2.ty).map(|_| SearchRes::Both),
                (Some(_), None) => Ok(SearchRes::A),
                (None, Some(_)) => Ok(SearchRes::B),
                (None, None) => unreachable!(),
            });
            log::trace!(
                "unify_records {} and {}: {:?}",
                t1,
                t2,
                searchresults.clone().collect_vec()
            );
            let all_both = searchresults
                .clone()
                .all(|r| r.is_ok_and(|r| r == SearchRes::Both));
            let collected_errs = searchresults
                .clone()
                .filter_map(|r| r.err())
                .flatten()
                .collect::<Vec<_>>();
            let mut all_errs = vec![];
            let contains_err = !collected_errs.is_empty();
            if contains_err {
                all_errs = collected_errs;
            }
            let contains_a = searchresults
                .clone()
                .any(|r| r.is_ok_and(|r| r == SearchRes::A));
            let contains_b = searchresults
                .clone()
                .any(|r| r.is_ok_and(|r| r == SearchRes::B));
            if all_both {
                Relation::Identical
            } else if !contains_err && contains_a && !contains_b {
                //a has more fields than b, that means A is
                Relation::Supertype
            } else if !contains_err && contains_b && !contains_a {
                Relation::Subtype
            } else if contains_b && contains_a {
                let keys_a = a1
                    .iter()
                    .map(|RecordTypeField { key, ty, .. }| (*key, *ty))
                    .collect::<Vec<_>>();
                let keys_b = a2
                    .iter()
                    .map(|RecordTypeField { key, ty, .. }| (*key, *ty))
                    .collect::<Vec<_>>();
                all_errs.push(Error::ImcompatibleRecords {
                    left: (keys_a, loc1.clone()),
                    right: (keys_b, loc2.clone()),
                });
                return Err(all_errs);
            } else {
                return Err(all_errs);
            }
        }
        (
            Type::Function {
                arg: arg1,
                ret: ret1,
            },
            Type::Function {
                arg: arg2,
                ret: ret2,
            },
        ) => {
            let arg_res = unify_types_args(*arg1, *arg2);
            let ret_res = unify_types(*ret1, *ret2);
            match (arg_res, ret_res) {
                (Ok(Relation::Subtype), Ok(_)) | (Ok(_), Ok(Relation::Supertype)) => {
                    return Err(vec![Error::TypeMismatch {
                        left: (t1, loc1.clone()),
                        right: (t2, loc2.clone()),
                    }]);
                }
                (Ok(Relation::Identical), Ok(Relation::Identical)) => Relation::Identical,
                (Ok(_), Err(errs)) | (Err(errs), Ok(_)) => {
                    return Err(errs);
                }
                (Err(mut e1), Err(mut e2)) => {
                    e1.append(&mut e2);
                    return Err(e1);
                }
                _ => Relation::Subtype,
            }
        }
        (Type::Primitive(p1), Type::Primitive(p2)) if p1 == p2 => Relation::Identical,
        (Type::TypeScheme(s1), Type::TypeScheme(s2)) if s1 == s2 => Relation::Identical,
        (Type::TypeScheme(_), _) | (_, Type::TypeScheme(_)) => {
            return Err(vec![Error::TypeMismatch {
                left: (t1, loc1.clone()),
                right: (t2, loc2.clone()),
            }]);
        }
        (Type::Primitive(PType::Unit), Type::Tuple(v))
        | (Type::Tuple(v), Type::Primitive(PType::Unit))
            if v.is_empty() =>
        {
            Relation::Identical
        }
        (_t, Type::Tuple(v)) if v.len() == 1 => unify_types(t1, *v.first().unwrap())?,
        (Type::Tuple(v), _t) if v.len() == 1 => unify_types(*v.first().unwrap(), t2)?,
        (Type::Primitive(PType::Unit), Type::Record(v))
        | (Type::Record(v), Type::Primitive(PType::Unit))
            if v.is_empty() =>
        {
            Relation::Identical
        }
        // Keep single-field records as records in general unification.
        // Collapsing `{k:T}` to `T` here loses structural information and can
        // incorrectly narrow chained accesses like `e.arc.start` into `{arc:{end:_}}`.
        (Type::Failure, _t) | (_t, Type::Any) => Relation::Identical,
        (Type::Any, _t) | (_t, Type::Failure) => Relation::Identical,

        (Type::Code(p1), Type::Code(p2)) => unify_types(*p1, *p2)?,
        // Union type support: check if two union types are identical
        (Type::Union(union_types1), Type::Union(union_types2)) => {
            // Two unions are identical if they have the same members (in any order)
            if union_types1.len() != union_types2.len() {
                return Err(vec![Error::TypeMismatch {
                    left: (t1, loc1.clone()),
                    right: (t2, loc2.clone()),
                }]);
            }
            // Check that each member of union1 matches exactly one member of union2
            let all_match = union_types1.iter().all(|m1| {
                union_types2
                    .iter()
                    .any(|m2| unify_types(*m1, *m2).is_ok_and(|r| r == Relation::Identical))
            });
            if all_match {
                Relation::Identical
            } else {
                return Err(vec![Error::TypeMismatch {
                    left: (t1, loc1.clone()),
                    right: (t2, loc2.clone()),
                }]);
            }
        }
        // Union type support: T is a subtype of T | U if T can unify with one of the union members
        (_t, Type::Union(union_types)) => {
            // Check if t can unify with any type in the union
            for union_member in union_types {
                if unify_types(t1r, *union_member).is_ok() {
                    return Ok(Relation::Subtype);
                }
            }
            return Err(vec![Error::TypeMismatch {
                left: (t1, loc1.clone()),
                right: (t2, loc2.clone()),
            }]);
        }
        (Type::Union(union_types), _t) => {
            // Check if all types in the union can unify with t
            // Union is subtype of t only if all members are subtypes
            let all_match = union_types
                .iter()
                .all(|union_member| unify_types(*union_member, t2r).is_ok());
            if all_match {
                return Ok(Relation::Supertype);
            }
            return Err(vec![Error::TypeMismatch {
                left: (t1, loc1.clone()),
                right: (t2, loc2.clone()),
            }]);
        }
        // UserSum type support: nominal typing — same name means identical type
        (Type::UserSum { name: n1, .. }, Type::UserSum { name: n2, .. }) => {
            if n1 == n2 {
                Relation::Identical
            } else {
                return Err(vec![Error::TypeMismatch {
                    left: (t1, loc1.clone()),
                    right: (t2, loc2.clone()),
                }]);
            }
        }
        // Boxed type support: unify inner types
        (Type::Boxed(b1), Type::Boxed(b2)) => unify_types(*b1, *b2)?,
        // Implicit boxing coercion: T can be treated as Boxed(T)
        // Boxing is a transparent coercion — T and Boxed(T) are considered identical
        // because the compiler automatically inserts box/unbox operations.
        (Type::Boxed(inner), _t2) => {
            let inner_res = unify_types(*inner, t2r);
            match inner_res {
                Ok(_) => Relation::Identical,
                Err(_) => {
                    return Err(vec![Error::TypeMismatch {
                        left: (t1, loc1.clone()),
                        right: (t2, loc2.clone()),
                    }]);
                }
            }
        }
        (_t1, Type::Boxed(inner)) => {
            let inner_res = unify_types(t1r, *inner);
            match inner_res {
                Ok(_) => Relation::Identical,
                Err(_) => {
                    return Err(vec![Error::TypeMismatch {
                        left: (t1, loc1.clone()),
                        right: (t2, loc2.clone()),
                    }]);
                }
            }
        }
        (_p1, _p2) => {
            return Err(vec![Error::TypeMismatch {
                left: (t1, loc1),
                right: (t2, loc2),
            }]);
        }
    };
    log::trace!("unified {} and {}:{:?}", t1.to_type(), t2.to_type(), res);

    Ok(res)
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::{Error, unify_types};
    use crate::{
        types::{PType, Type},
        utils::metadata::Location,
    };

    #[test]
    fn length_mismatch_keeps_both_spans() {
        let left_span = 10..20;
        let right_span = 30..40;

        let left_elem = Type::Primitive(PType::Numeric)
            .into_id_with_location(Location::new(left_span.clone(), PathBuf::from("left.mmm")));
        let right_elem = Type::Primitive(PType::Numeric).into_id_with_location(Location::new(
            right_span.clone(),
            PathBuf::from("right.mmm"),
        ));

        let left = Type::Tuple(vec![left_elem])
            .into_id_with_location(Location::new(left_span.clone(), PathBuf::from("left.mmm")));
        let right = Type::Tuple(vec![right_elem, right_elem]).into_id_with_location(Location::new(
            right_span.clone(),
            PathBuf::from("right.mmm"),
        ));

        let err = unify_types(left, right).expect_err("expected tuple length mismatch");
        let Some(Error::LengthMismatch {
            left: (_, lspan),
            right: (_, rspan),
        }) = err.first()
        else {
            panic!("unexpected error variant");
        };

        assert_eq!(lspan, &left_span);
        assert_eq!(rspan, &right_span);
    }

    #[test]
    fn length_mismatch_avoids_dummy_span_when_one_side_has_location() {
        let right_span = 30..40;

        let left_elem = Type::Primitive(PType::Numeric).into_id();
        let right_elem = Type::Primitive(PType::Numeric).into_id_with_location(Location::new(
            right_span.clone(),
            PathBuf::from("right.mmm"),
        ));

        let left = Type::Tuple(vec![left_elem]).into_id();
        let right = Type::Tuple(vec![right_elem, right_elem]).into_id_with_location(Location::new(
            right_span.clone(),
            PathBuf::from("right.mmm"),
        ));

        let err = unify_types(left, right).expect_err("expected tuple length mismatch");
        let Some(Error::LengthMismatch {
            left: (_, lspan),
            right: (_, rspan),
        }) = err.first()
        else {
            panic!("unexpected error variant");
        };

        assert_eq!(lspan, &right_span);
        assert_eq!(rspan, &right_span);
    }
}