Skip to content

Commit 291397b

Browse files
alexisthedevtheosotr
authored andcommitted
Add type unification support for union types
1 parent 3e06d6f commit 291397b

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

src/ir/type_utils.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1040,6 +1040,9 @@ def unify_types(t1: tp.Type, t2: tp.Type, factory,
10401040
class A<T>
10411041
class B : A<String>()
10421042
"""
1043+
if t1.is_combound() and not t1.is_parameterized():
1044+
return t1.unify_types(t2, factory, same_type)
1045+
10431046
if same_type and type(t1) != type(t2):
10441047
return {}
10451048

src/ir/typescript_types.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -491,6 +491,42 @@ def to_type_variable_free(self, factory):
491491
else t)
492492
return UnionType(new_types)
493493

494+
def unify_types(self, other, factory, same_type=True):
495+
"""
496+
This is used in src.ir.type_utils in the function
497+
unify_types.
498+
499+
We delegate work here when the first of the two
500+
types that are passed to that function is a union type.
501+
502+
For more information on the function see the detailed
503+
explanation at the unify_types function definition.
504+
505+
The only way a union type type-unification can be
506+
achieved is when the first of the two types
507+
(here: self) is a union type and the second
508+
is either a type variable or another union type
509+
with similar union structure and has at least one
510+
type variable in its union.
511+
512+
"""
513+
type_var_map = {}
514+
if (isinstance(other, UnionType)
515+
and len(self.types) == len(other.types)
516+
and other.has_type_variables()):
517+
for i, t in enumerate(self.types):
518+
t1 = t
519+
t2 = other.types[i]
520+
is_type_var = t2.is_type_var()
521+
if not is_type_var:
522+
if not t2.is_subtype(t1):
523+
return {}
524+
else:
525+
type_var_map[t2] = t1
526+
elif other.is_type_var():
527+
type_var_map[other] = self
528+
return type_var_map
529+
494530
def get_name(self):
495531
return self.name
496532

0 commit comments

Comments
 (0)