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
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
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
//! Binary operation type evaluation.
//!
//! This module handles type evaluation for binary operations like:
//! - Arithmetic: +, -, *, /, %, **
//! - Comparison: ==, !=, <, >, <=, >=
//! - Logical: &&, ||, !
//! - Bitwise: &, |, ^, ~, <<, >>, >>>
//!
//! ## Architecture
//!
//! The `BinaryOpEvaluator` evaluates the result type of binary operations
//! and validates that operands are compatible with the operator.
//!
//! All functions take `TypeId` as input and return structured results,
//! making them pure logic that can be unit tested independently.

use crate::types::TypeListId;
use crate::visitor::TypeVisitor;
use crate::{IntrinsicKind, LiteralValue, QueryDatabase, TypeData, TypeDatabase, TypeId};

/// Result of a binary operation.
#[derive(Clone, Debug, PartialEq)]
pub enum BinaryOpResult {
    /// Operation succeeded, returns the result type
    Success(TypeId),

    /// Operand type error
    TypeError {
        left: TypeId,
        right: TypeId,
        op: &'static str,
    },
}

/// Primitive type classes for overlap detection.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PrimitiveClass {
    String,
    Number,
    Boolean,
    Bigint,
    Symbol,
    Null,
    Undefined,
}

// =============================================================================
// Visitor Pattern Implementations
// =============================================================================

/// Generate a `TypeVisitor` that checks whether a type belongs to a specific
/// primitive class (number-like, string-like, etc.).
///
/// ## Arguments
/// - `$name`: Visitor struct name
/// - `$ik`: The `IntrinsicKind` to match
/// - `$lit_pat`: Pattern to match `LiteralValue` against (use `_` for always-false)
/// - `$lit_result`: Value to return when the pattern matches
/// - Optional feature flags:
///   - `check_union_all` — `visit_union` returns true when ALL members match
///   - `check_constraint` — `visit_type_parameter/visit_infer` recurse into constraint
///   - `recurse_enum`    — `visit_enum` recurses into the member type
///   - `ref_conservative`— `visit_ref` returns true (conservative for unresolved enums)
///   - `match_template_literal` — `visit_template_literal` returns true
///   - `match_unique_symbol`    — `visit_unique_symbol` returns true
///   - `check_intersection_any` — `visit_intersection` returns true when ANY member matches
macro_rules! primitive_visitor {
    ($name:ident, $ik:expr, $lit_pat:pat => $lit_result:expr $(, $feat:ident)*) => {
        struct $name<'a> { _db: &'a dyn TypeDatabase }
        impl<'a> TypeVisitor for $name<'a> {
            type Output = bool;
            fn visit_intrinsic(&mut self, kind: IntrinsicKind) -> bool { kind == $ik }
            fn visit_literal(&mut self, value: &LiteralValue) -> bool {
                match value { $lit_pat => $lit_result, _ => false }
            }
            $(primitive_visitor!(@method $feat);)*
            fn default_output() -> bool { false }
        }
    };
    (@method check_union_all) => {
        fn visit_union(&mut self, list_id: u32) -> bool {
            let members = self._db.type_list(TypeListId(list_id));
            !members.is_empty() && members.iter().all(|&m| self.visit_type(self._db, m))
        }
    };
    (@method check_constraint) => {
        fn visit_type_parameter(&mut self, info: &crate::types::TypeParamInfo) -> bool {
            info.constraint.map(|c| self.visit_type(self._db, c)).unwrap_or(false)
        }
        fn visit_infer(&mut self, info: &crate::types::TypeParamInfo) -> bool {
            info.constraint.map(|c| self.visit_type(self._db, c)).unwrap_or(false)
        }
    };
    (@method recurse_enum) => {
        fn visit_enum(&mut self, _def_id: u32, member_type: TypeId) -> bool {
            self.visit_type(self._db, member_type)
        }
    };
    (@method ref_conservative) => {
        fn visit_ref(&mut self, _symbol_ref: u32) -> bool { true }
    };
    (@method match_template_literal) => {
        fn visit_template_literal(&mut self, _template_id: u32) -> bool { true }
    };
    (@method match_unique_symbol) => {
        fn visit_unique_symbol(&mut self, _symbol_ref: u32) -> bool { true }
    };
    (@method check_intersection_any) => {
        fn visit_intersection(&mut self, list_id: u32) -> bool {
            let members = self._db.type_list(TypeListId(list_id));
            members.iter().any(|&m| self.visit_type(self._db, m))
        }
    };
}

primitive_visitor!(NumberLikeVisitor, IntrinsicKind::Number,
    LiteralValue::Number(_) => true,
    check_union_all, check_constraint, recurse_enum, check_intersection_any);

primitive_visitor!(StringLikeVisitor, IntrinsicKind::String,
    LiteralValue::String(_) => true,
    check_union_all, check_constraint, recurse_enum, match_template_literal, check_intersection_any);

primitive_visitor!(BigIntLikeVisitor, IntrinsicKind::Bigint,
    LiteralValue::BigInt(_) => true,
    check_union_all, check_constraint, recurse_enum, check_intersection_any);

primitive_visitor!(BooleanLikeVisitor, IntrinsicKind::Boolean,
    LiteralValue::Boolean(_) => true);

struct InstanceofLeftOperandVisitor<'a> {
    _db: &'a dyn TypeDatabase,
}

impl<'a> TypeVisitor for InstanceofLeftOperandVisitor<'a> {
    type Output = bool;

    fn visit_intrinsic(&mut self, kind: IntrinsicKind) -> bool {
        matches!(
            kind,
            IntrinsicKind::Any | IntrinsicKind::Unknown | IntrinsicKind::Object
        )
    }

    fn visit_literal(&mut self, _value: &LiteralValue) -> bool {
        false
    }

    fn visit_type_parameter(&mut self, _info: &crate::types::TypeParamInfo) -> bool {
        true
    }

    fn visit_object(&mut self, _shape_id: u32) -> bool {
        true
    }
    fn visit_object_with_index(&mut self, _shape_id: u32) -> bool {
        true
    }
    fn visit_array(&mut self, _element_type: TypeId) -> bool {
        true
    }
    fn visit_tuple(&mut self, _list_id: u32) -> bool {
        true
    }
    fn visit_function(&mut self, _shape_id: u32) -> bool {
        true
    }
    fn visit_callable(&mut self, _shape_id: u32) -> bool {
        true
    }
    fn visit_application(&mut self, _app_id: u32) -> bool {
        true
    }
    fn visit_readonly_type(&mut self, _type_id: TypeId) -> bool {
        true
    }

    fn visit_union(&mut self, list_id: u32) -> bool {
        let members = self._db.type_list(crate::types::TypeListId(list_id));
        let mut any_valid = false;
        for &m in members.iter() {
            if self.visit_type(self._db, m) {
                any_valid = true;
                break;
            }
        }
        any_valid
    }

    fn visit_intersection(&mut self, list_id: u32) -> bool {
        let members = self._db.type_list(crate::types::TypeListId(list_id));
        let mut any_valid = false;
        for &m in members.iter() {
            if self.visit_type(self._db, m) {
                any_valid = true;
                break;
            }
        }
        any_valid
    }

    fn default_output() -> bool {
        false
    }
}

struct SymbolLikeVisitor<'a> {
    _db: &'a dyn TypeDatabase,
}

impl<'a> TypeVisitor for SymbolLikeVisitor<'a> {
    type Output = bool;

    fn visit_intrinsic(&mut self, kind: IntrinsicKind) -> bool {
        kind == IntrinsicKind::Symbol
    }

    fn visit_literal(&mut self, value: &LiteralValue) -> bool {
        let _ = value;
        false
    }

    fn visit_ref(&mut self, _symbol_ref: u32) -> bool {
        true
    }

    fn visit_unique_symbol(&mut self, _symbol_ref: u32) -> bool {
        true
    }

    fn default_output() -> bool {
        false
    }
}

/// Visitor that checks if all union members are orderable (string/number/bigint-like).
/// Used for relational operator validation on mixed unions.
struct OrderableVisitor<'a> {
    _db: &'a dyn TypeDatabase,
}

impl<'a> TypeVisitor for OrderableVisitor<'a> {
    type Output = bool;

    fn visit_intrinsic(&mut self, kind: IntrinsicKind) -> bool {
        matches!(
            kind,
            IntrinsicKind::String | IntrinsicKind::Number | IntrinsicKind::Bigint
        )
    }

    fn visit_literal(&mut self, value: &LiteralValue) -> bool {
        matches!(
            value,
            LiteralValue::String(_) | LiteralValue::Number(_) | LiteralValue::BigInt(_)
        )
    }

    fn visit_union(&mut self, list_id: u32) -> bool {
        let members = self._db.type_list(TypeListId(list_id));
        !members.is_empty() && members.iter().all(|&m| self.visit_type(self._db, m))
    }

    fn visit_enum(&mut self, _def_id: u32, member_type: TypeId) -> bool {
        self.visit_type(self._db, member_type)
    }

    fn visit_template_literal(&mut self, _template_id: u32) -> bool {
        true // Template literals are string-like
    }

    fn visit_intersection(&mut self, list_id: u32) -> bool {
        let members = self._db.type_list(TypeListId(list_id));
        members.iter().any(|&m| self.visit_type(self._db, m))
    }

    fn visit_type_parameter(&mut self, info: &crate::types::TypeParamInfo) -> bool {
        info.constraint
            .map(|c| self.visit_type(self._db, c))
            .unwrap_or(false)
    }

    fn default_output() -> bool {
        false
    }
}

/// Visitor to extract primitive class from a type.
struct PrimitiveClassVisitor;

impl TypeVisitor for PrimitiveClassVisitor {
    type Output = Option<PrimitiveClass>;

    fn visit_intrinsic(&mut self, kind: IntrinsicKind) -> Self::Output {
        match kind {
            IntrinsicKind::String => Some(PrimitiveClass::String),
            IntrinsicKind::Number => Some(PrimitiveClass::Number),
            IntrinsicKind::Boolean => Some(PrimitiveClass::Boolean),
            IntrinsicKind::Bigint => Some(PrimitiveClass::Bigint),
            IntrinsicKind::Symbol => Some(PrimitiveClass::Symbol),
            IntrinsicKind::Null => Some(PrimitiveClass::Null),
            IntrinsicKind::Undefined | IntrinsicKind::Void => Some(PrimitiveClass::Undefined),
            _ => None,
        }
    }

    fn visit_literal(&mut self, value: &LiteralValue) -> Self::Output {
        match value {
            LiteralValue::String(_) => Some(PrimitiveClass::String),
            LiteralValue::Number(_) => Some(PrimitiveClass::Number),
            LiteralValue::Boolean(_) => Some(PrimitiveClass::Boolean),
            LiteralValue::BigInt(_) => Some(PrimitiveClass::Bigint),
        }
    }

    fn visit_template_literal(&mut self, _template_id: u32) -> Self::Output {
        Some(PrimitiveClass::String)
    }

    fn visit_unique_symbol(&mut self, _symbol_ref: u32) -> Self::Output {
        Some(PrimitiveClass::Symbol)
    }

    fn default_output() -> Self::Output {
        None
    }
}

/// Check if an intrinsic primitive type overlaps with a literal value.
/// e.g., `string` overlaps with `"foo"`, `number` overlaps with `42`.
const fn intrinsic_overlaps_literal(kind: IntrinsicKind, value: &LiteralValue) -> bool {
    matches!(
        (kind, value),
        (IntrinsicKind::String, LiteralValue::String(_))
            | (IntrinsicKind::Number, LiteralValue::Number(_))
            | (IntrinsicKind::Boolean, LiteralValue::Boolean(_))
            | (IntrinsicKind::Bigint, LiteralValue::BigInt(_))
    )
}

/// Visitor to check type overlap for comparison operations.
struct OverlapChecker<'a> {
    db: &'a dyn TypeDatabase,
    left: TypeId,
}

impl<'a> OverlapChecker<'a> {
    fn new(db: &'a dyn TypeDatabase, left: TypeId) -> Self {
        Self { db, left }
    }

    fn check(&mut self, right: TypeId) -> bool {
        // Fast path: same type
        if self.left == right {
            return true;
        }

        // Fast path: top/bottom types
        if matches!(
            (self.left, right),
            (TypeId::ANY | TypeId::UNKNOWN | TypeId::ERROR, _)
                | (_, TypeId::ANY | TypeId::UNKNOWN | TypeId::ERROR)
        ) {
            return true;
        }

        if self.left == TypeId::NEVER || right == TypeId::NEVER {
            return false;
        }

        // Check intersection first before visitor
        if self.db.intersection2(self.left, right) == TypeId::NEVER {
            return false;
        }

        // Use visitor to check overlap
        self.visit_type(self.db, right)
    }
}

impl<'a> TypeVisitor for OverlapChecker<'a> {
    type Output = bool;

    fn visit_intrinsic(&mut self, _kind: IntrinsicKind) -> Self::Output {
        // Intrinsics can overlap with many things, check intersection above
        true
    }

    fn visit_union(&mut self, list_id: u32) -> Self::Output {
        let members = self.db.type_list(TypeListId(list_id));
        members.iter().any(|&member| self.check(member))
    }

    fn visit_type_parameter(&mut self, info: &crate::types::TypeParamInfo) -> Self::Output {
        // Unconstrained type parameters are handled in has_overlap before visitor
        match info.constraint {
            Some(constraint) => self.check(constraint),
            None => panic!("TypeParameter without constraint should not reach visitor"),
        }
    }

    fn visit_infer(&mut self, info: &crate::types::TypeParamInfo) -> Self::Output {
        // Unconstrained type parameters are handled in has_overlap before visitor
        match info.constraint {
            Some(constraint) => self.check(constraint),
            None => panic!("Infer without constraint should not reach visitor"),
        }
    }

    fn visit_literal(&mut self, value: &LiteralValue) -> Self::Output {
        // Check if left is a literal with same value, or a supertype of the literal
        match self.db.lookup(self.left) {
            Some(TypeData::Literal(left_lit)) => left_lit == *value,
            Some(TypeData::Union(members)) => {
                // Check if left's union contains this literal or a supertype
                let members = self.db.type_list(members);
                members.iter().any(|&m| match self.db.lookup(m) {
                    Some(TypeData::Literal(lit)) => lit == *value,
                    Some(TypeData::Intrinsic(kind)) => intrinsic_overlaps_literal(kind, value),
                    _ => false,
                })
            }
            // An intrinsic primitive type overlaps with its corresponding literal type
            // e.g., `string` overlaps with `"foo"`, `number` overlaps with `42`
            Some(TypeData::Intrinsic(kind)) => intrinsic_overlaps_literal(kind, value),
            // Intersection types: if ANY member overlaps with the literal, the
            // intersection overlaps. e.g., `string & { $Brand: any }` overlaps with `""`.
            Some(TypeData::Intersection(members)) => {
                let members = self.db.type_list(members);
                members.iter().any(|&m| match self.db.lookup(m) {
                    Some(TypeData::Literal(lit)) => lit == *value,
                    Some(TypeData::Intrinsic(kind)) => intrinsic_overlaps_literal(kind, value),
                    _ => false,
                })
            }
            _ => false,
        }
    }

    fn default_output() -> Self::Output {
        // Default: check for disjoint primitive classes
        // We conservatively return true unless we can prove they're disjoint
        // This matches the original behavior where most types are considered to overlap
        true
    }
}

/// Evaluates binary operations on types.
pub struct BinaryOpEvaluator<'a> {
    interner: &'a dyn QueryDatabase,
}

impl<'a> BinaryOpEvaluator<'a> {
    /// Create a new binary operation evaluator.
    pub fn new(interner: &'a dyn QueryDatabase) -> Self {
        Self { interner }
    }

    /// Check if a type is valid for the left side of an `instanceof` expression.
    /// TS2358: "The left-hand side of an 'instanceof' expression must be of type 'any', an object type or a type parameter."
    pub fn is_valid_instanceof_left_operand(&self, type_id: TypeId) -> bool {
        if type_id == TypeId::ERROR || type_id == TypeId::ANY || type_id == TypeId::UNKNOWN {
            return true;
        }
        let mut visitor = InstanceofLeftOperandVisitor { _db: self.interner };
        visitor.visit_type(self.interner, type_id)
    }

    /// Check if a type is valid for the right side of an `instanceof` expression.
    /// TS2359: "The right-hand side of an 'instanceof' expression must be either of type 'any', a class, function, or other type assignable to the 'Function' interface type..."
    pub fn is_valid_instanceof_right_operand<F>(
        &self,
        type_id: TypeId,
        func_ty: TypeId,
        assignable_check: &mut F,
    ) -> bool
    where
        F: FnMut(TypeId, TypeId) -> bool,
    {
        if type_id == TypeId::ANY
            || type_id == TypeId::UNKNOWN
            || type_id == TypeId::ERROR
            || type_id == TypeId::FUNCTION
        {
            return true;
        }

        if let Some(crate::TypeData::Union(list_id)) = self.interner.lookup(type_id) {
            let members = self.interner.type_list(list_id);
            let mut all_valid = true;
            for &m in members.iter() {
                if !self.is_valid_instanceof_right_operand(m, func_ty, assignable_check) {
                    all_valid = false;
                    break;
                }
            }
            return all_valid && !members.is_empty();
        }

        if let Some(crate::TypeData::Intersection(list_id)) = self.interner.lookup(type_id) {
            let members = self.interner.type_list(list_id);
            let mut any_valid = false;
            for &m in members.iter() {
                if self.is_valid_instanceof_right_operand(m, func_ty, assignable_check) {
                    any_valid = true;
                    break;
                }
            }
            return any_valid;
        }

        assignable_check(type_id, func_ty) || assignable_check(type_id, TypeId::FUNCTION)
    }

    /// Check if a type is valid for arithmetic operations (number, bigint, enum, or any).
    /// This is used for TS2362/TS2363 error checking.
    ///
    /// Also returns true for ERROR and UNKNOWN types to prevent cascading errors.
    /// If a type couldn't be resolved (TS2304, etc.), we don't want to add noise
    /// with arithmetic errors - the primary error is more useful.
    pub fn is_arithmetic_operand(&self, type_id: TypeId) -> bool {
        // Don't emit arithmetic errors for error/unknown/never types - prevents cascading errors.
        // NEVER (bottom type) is assignable to all types, so it's valid everywhere.
        if type_id == TypeId::ANY
            || type_id == TypeId::ERROR
            || type_id == TypeId::UNKNOWN
            || type_id == TypeId::NEVER
        {
            return true;
        }
        self.is_number_like(type_id) || self.is_bigint_like(type_id)
    }

    /// Evaluate a binary operation on two types.
    pub fn evaluate(&self, left: TypeId, right: TypeId, op: &'static str) -> BinaryOpResult {
        match op {
            "+" => self.evaluate_plus(left, right),
            "-" | "*" | "/" | "%" | "**" | "&" | "|" | "^" | "<<" | ">>" | ">>>" => {
                self.evaluate_arithmetic(left, right, op)
            }
            "==" | "!=" | "===" | "!==" => {
                if self.has_overlap(left, right) {
                    BinaryOpResult::Success(TypeId::BOOLEAN)
                } else {
                    BinaryOpResult::TypeError { left, right, op }
                }
            }
            "<" | ">" | "<=" | ">=" => self.evaluate_comparison(left, right),
            "&&" | "||" | "??" => self.evaluate_logical(left, right, op),
            _ => BinaryOpResult::TypeError { left, right, op },
        }
    }

    /// Evaluate the + operator (can be string concatenation or addition).
    fn evaluate_plus(&self, left: TypeId, right: TypeId) -> BinaryOpResult {
        // Don't emit errors for unknown types - prevents cascading errors
        if left == TypeId::UNKNOWN || right == TypeId::UNKNOWN {
            return BinaryOpResult::Success(TypeId::UNKNOWN);
        }

        // Error types act like `any` in tsc - prevents cascading errors
        // while still inferring the correct result type (e.g., string + error = string)
        let left = if left == TypeId::ERROR {
            TypeId::ANY
        } else {
            left
        };
        let right = if right == TypeId::ERROR {
            TypeId::ANY
        } else {
            right
        };

        // TS2469: Symbol cannot be used in arithmetic
        if self.is_symbol_like(left) || self.is_symbol_like(right) {
            return BinaryOpResult::TypeError {
                left,
                right,
                op: "+",
            };
        }

        // any + anything = any (and vice versa)
        if left == TypeId::ANY || right == TypeId::ANY {
            return BinaryOpResult::Success(TypeId::ANY);
        }

        // String concatenation: string + primitive = string
        if self.is_string_like(left) || self.is_string_like(right) {
            // Check if the non-string side is a valid operand (primitive)
            let valid_left = self.is_string_like(left) || self.is_valid_string_concat_operand(left);
            let valid_right =
                self.is_string_like(right) || self.is_valid_string_concat_operand(right);

            if valid_left && valid_right {
                return BinaryOpResult::Success(TypeId::STRING);
            }
            // TS2365: Operator '+' cannot be applied to types 'string' and 'object'
            return BinaryOpResult::TypeError {
                left,
                right,
                op: "+",
            };
        }

        // number-like + number-like = number
        if self.is_number_like(left) && self.is_number_like(right) {
            return BinaryOpResult::Success(TypeId::NUMBER);
        }

        // bigint-like + bigint-like = bigint
        if self.is_bigint_like(left) && self.is_bigint_like(right) {
            return BinaryOpResult::Success(TypeId::BIGINT);
        }

        BinaryOpResult::TypeError {
            left,
            right,
            op: "+",
        }
    }

    /// Evaluate arithmetic operators (-, *, /, %, **).
    fn evaluate_arithmetic(&self, left: TypeId, right: TypeId, op: &'static str) -> BinaryOpResult {
        // Don't emit errors for unknown types - prevents cascading errors
        if left == TypeId::UNKNOWN || right == TypeId::UNKNOWN {
            return BinaryOpResult::Success(TypeId::UNKNOWN);
        }

        // Error types act like `any` in tsc - prevents cascading errors
        let left = if left == TypeId::ERROR {
            TypeId::ANY
        } else {
            left
        };
        let right = if right == TypeId::ERROR {
            TypeId::ANY
        } else {
            right
        };

        // TS2469: Symbol cannot be used in arithmetic
        if self.is_symbol_like(left) || self.is_symbol_like(right) {
            return BinaryOpResult::TypeError { left, right, op };
        }

        // any allows all operations
        if left == TypeId::ANY || right == TypeId::ANY {
            return BinaryOpResult::Success(TypeId::NUMBER);
        }

        // number-like * number-like = number
        if self.is_number_like(left) && self.is_number_like(right) {
            return BinaryOpResult::Success(TypeId::NUMBER);
        }

        // bigint-like * bigint-like = bigint
        if self.is_bigint_like(left) && self.is_bigint_like(right) {
            return BinaryOpResult::Success(TypeId::BIGINT);
        }

        BinaryOpResult::TypeError { left, right, op }
    }

    /// Evaluate comparison operators (<, >, <=, >=).
    fn evaluate_comparison(&self, left: TypeId, right: TypeId) -> BinaryOpResult {
        // Don't emit errors for unknown types - prevents cascading errors
        if left == TypeId::UNKNOWN || right == TypeId::UNKNOWN {
            return BinaryOpResult::Success(TypeId::BOOLEAN);
        }

        // Error types act like `any` in tsc - prevents cascading errors
        let left = if left == TypeId::ERROR {
            TypeId::ANY
        } else {
            left
        };
        let right = if right == TypeId::ERROR {
            TypeId::ANY
        } else {
            right
        };

        // TS2469: Symbol cannot be used in comparison operators
        if self.is_symbol_like(left) || self.is_symbol_like(right) {
            return BinaryOpResult::TypeError {
                left,
                right,
                op: "<",
            };
        }

        // Any allows comparison
        if left == TypeId::ANY || right == TypeId::ANY {
            return BinaryOpResult::Success(TypeId::BOOLEAN);
        }

        // Numbers (and Enums) can be compared
        if self.is_number_like(left) && self.is_number_like(right) {
            return BinaryOpResult::Success(TypeId::BOOLEAN);
        }

        // Strings can be compared
        if self.is_string_like(left) && self.is_string_like(right) {
            return BinaryOpResult::Success(TypeId::BOOLEAN);
        }

        // BigInts can be compared
        if self.is_bigint_like(left) && self.is_bigint_like(right) {
            return BinaryOpResult::Success(TypeId::BOOLEAN);
        }

        // Booleans can be compared (valid in JS/TS)
        if self.is_boolean_like(left) && self.is_boolean_like(right) {
            return BinaryOpResult::Success(TypeId::BOOLEAN);
        }

        // Mixed orderable unions: unions of string/number/bigint are valid for
        // relational operators. e.g., ("ABC" | number) < ("XYZ" | number) is valid
        // because each member is individually orderable.
        if self.is_orderable(left) && self.is_orderable(right) {
            return BinaryOpResult::Success(TypeId::BOOLEAN);
        }

        // Mismatch - emit TS2365
        BinaryOpResult::TypeError {
            left,
            right,
            op: "<",
        }
    }

    /// Evaluate logical operators (&&, ||).
    fn evaluate_logical(&self, left: TypeId, right: TypeId, op: &'static str) -> BinaryOpResult {
        let ctx = crate::narrowing::NarrowingContext::new(self.interner);

        let result = if op == "&&" {
            // left && right
            let falsy_left = ctx.narrow_to_falsy(left);
            let truthy_left = ctx.narrow_by_truthiness(left);

            if truthy_left == TypeId::NEVER {
                left
            } else if falsy_left == TypeId::NEVER {
                right
            } else {
                self.interner.union2(falsy_left, right)
            }
        } else if op == "||" {
            // left || right
            let truthy_left = ctx.narrow_by_truthiness(left);
            let falsy_left = ctx.narrow_to_falsy(left);

            if falsy_left == TypeId::NEVER {
                left
            } else if truthy_left == TypeId::NEVER {
                right
            } else {
                self.interner.union2(truthy_left, right)
            }
        } else {
            // left ?? right
            let non_nullish_left = ctx.narrow_by_nullishness(left, false);
            let nullish_left = ctx.narrow_by_nullishness(left, true);

            if nullish_left == TypeId::NEVER {
                left
            } else if non_nullish_left == TypeId::NEVER {
                right
            } else {
                self.interner.union2(non_nullish_left, right)
            }
        };

        BinaryOpResult::Success(result)
    }

    /// Check if a type is number-like (number, number literal, numeric enum, or any).
    fn is_number_like(&self, type_id: TypeId) -> bool {
        if type_id == TypeId::NUMBER || type_id == TypeId::ANY {
            return true;
        }
        let mut visitor = NumberLikeVisitor { _db: self.interner };
        visitor.visit_type(self.interner, type_id)
    }

    /// Check if a type is string-like (string, string literal, template literal, or any).
    fn is_string_like(&self, type_id: TypeId) -> bool {
        if type_id == TypeId::STRING || type_id == TypeId::ANY {
            return true;
        }
        let mut visitor = StringLikeVisitor { _db: self.interner };
        visitor.visit_type(self.interner, type_id)
    }

    /// Check if a type is bigint-like (bigint, bigint literal, bigint enum, or any).
    fn is_bigint_like(&self, type_id: TypeId) -> bool {
        if type_id == TypeId::BIGINT || type_id == TypeId::ANY {
            return true;
        }
        let mut visitor = BigIntLikeVisitor { _db: self.interner };
        visitor.visit_type(self.interner, type_id)
    }

    /// Check if a type is orderable for relational operators (<, >, <=, >=).
    /// A type is orderable if all its union members are string-like, number-like,
    /// or bigint-like. This allows mixed unions like `string | number` to be compared.
    fn is_orderable(&self, type_id: TypeId) -> bool {
        if type_id == TypeId::ANY
            || type_id == TypeId::NUMBER
            || type_id == TypeId::STRING
            || type_id == TypeId::BIGINT
        {
            return true;
        }
        let mut visitor = OrderableVisitor { _db: self.interner };
        visitor.visit_type(self.interner, type_id)
    }

    /// Check if two types have any overlap (can be compared).
    pub fn has_overlap(&self, left: TypeId, right: TypeId) -> bool {
        if left == right {
            return true;
        }
        if left == TypeId::ANY
            || right == TypeId::ANY
            || left == TypeId::UNKNOWN
            || right == TypeId::UNKNOWN
            || left == TypeId::ERROR
            || right == TypeId::ERROR
        {
            return true;
        }
        if left == TypeId::NEVER || right == TypeId::NEVER {
            return false;
        }

        // Special handling for TypeParameter and Infer before visitor pattern
        if let Some(TypeData::TypeParameter(info) | TypeData::Infer(info)) =
            self.interner.lookup(left)
        {
            if let Some(constraint) = info.constraint {
                return self.has_overlap(constraint, right);
            }
            return true;
        }

        if let Some(TypeData::TypeParameter(info) | TypeData::Infer(info)) =
            self.interner.lookup(right)
        {
            if let Some(constraint) = info.constraint {
                return self.has_overlap(left, constraint);
            }
            return true;
        }

        // Handle Union types explicitly (recursively check members)
        if let Some(TypeData::Union(members)) = self.interner.lookup(left) {
            let members = self.interner.type_list(members);
            return members
                .iter()
                .any(|member| self.has_overlap(*member, right));
        }

        if let Some(TypeData::Union(members)) = self.interner.lookup(right) {
            let members = self.interner.type_list(members);
            return members.iter().any(|member| self.has_overlap(left, *member));
        }

        // Check primitive class disjointness before intersection
        if self.primitive_classes_disjoint(left, right) {
            return false;
        }

        // Check intersection before visitor pattern
        if self.interner.intersection2(left, right) == TypeId::NEVER {
            return false;
        }

        // Use visitor for remaining type checks
        let mut checker = OverlapChecker::new(self.interner, left);
        checker.check(right)
    }

    /// Check if two types belong to disjoint primitive classes.
    fn primitive_classes_disjoint(&self, left: TypeId, right: TypeId) -> bool {
        match (self.primitive_class(left), self.primitive_class(right)) {
            (Some(left_class), Some(right_class)) => left_class != right_class,
            _ => false,
        }
    }

    /// Get the primitive class of a type (if applicable).
    fn primitive_class(&self, type_id: TypeId) -> Option<PrimitiveClass> {
        let mut visitor = PrimitiveClassVisitor;
        visitor.visit_type(self.interner, type_id)
    }

    /// Check if a type is symbol-like (symbol or unique symbol).
    pub fn is_symbol_like(&self, type_id: TypeId) -> bool {
        if type_id == TypeId::SYMBOL {
            return true;
        }
        let mut visitor = SymbolLikeVisitor { _db: self.interner };
        visitor.visit_type(self.interner, type_id)
    }

    /// Check if a type is a valid computed property name type (TS2464).
    ///
    /// Valid types: string, number, symbol, any (including literals, enums,
    /// template literals, unique symbols). For unions, ALL members must be valid.
    /// This check is independent of strictNullChecks.
    pub fn is_valid_computed_property_name_type(&self, type_id: TypeId) -> bool {
        if type_id == TypeId::ANY || type_id == TypeId::NEVER || type_id == TypeId::ERROR {
            return true;
        }
        // For union types, each member must individually be valid
        if let Some(TypeData::Union(list_id)) = self.interner.lookup(type_id) {
            let members = self.interner.type_list(list_id);
            return !members.is_empty()
                && members
                    .iter()
                    .all(|&m| self.is_valid_computed_property_name_type(m));
        }
        self.is_string_like(type_id) || self.is_number_like(type_id) || self.is_symbol_like(type_id)
    }

    /// Check if a type is boolean-like (boolean or boolean literal).
    pub fn is_boolean_like(&self, type_id: TypeId) -> bool {
        if type_id == TypeId::BOOLEAN || type_id == TypeId::ANY {
            return true;
        }
        let mut visitor = BooleanLikeVisitor { _db: self.interner };
        visitor.visit_type(self.interner, type_id)
    }

    /// Check if a type is a valid operand for string concatenation.
    /// Valid operands are: string, number, boolean, bigint, null, undefined, void, any.
    fn is_valid_string_concat_operand(&self, type_id: TypeId) -> bool {
        if type_id == TypeId::ANY || type_id == TypeId::ERROR || type_id == TypeId::NEVER {
            return true;
        }
        if type_id == TypeId::UNKNOWN {
            return false;
        }
        if let Some(TypeData::Union(list_id)) = self.interner.lookup(type_id) {
            let members = self.interner.type_list(list_id);
            return !members.is_empty()
                && members
                    .iter()
                    .all(|&member| self.is_valid_string_concat_operand(member));
        }
        if self.is_symbol_like(type_id) {
            return false;
        }
        // Primitives are valid
        if self.is_number_like(type_id)
            || self.is_boolean_like(type_id)
            || self.is_bigint_like(type_id)
            || type_id == TypeId::NULL
            || type_id == TypeId::UNDEFINED
            || type_id == TypeId::VOID
        {
            return true;
        }

        // Non-nullish non-symbol object/function-like types are string-concat-compatible.
        true
    }
}