JSAbrahams / mamba

🐍 The Mamba programming language, because we care about safety
MIT License
88 stars 4 forks source link

Type annotation cannot be unified with union types #427

Open JSAbrahams opened 1 year ago

JSAbrahams commented 1 year ago

Description of Bug

When we add certain type annotations, which are correct, the check stage complains. We know they are correct, however, in the current implementation because the output does actually have these unions.

How to Reproduce

Give as input:

class MyClass
    def __str__() -> String => "M"

def a := if True then 20 else MyClass()

print(a)

Which gives output

from typing import Union

class MyClass:
    def __str__() -> str:
        return "M"

a: Union[int, MyClass] = 20 if True else MyClass()

print(a)

However, if we give input

class MyClass
    def __str__() -> String => "M"

def a: Union[Int, MyClass] := if True then 20 else MyClass()

print(a)

We get the following:

Error: Expected an Union[Int, MyClass], was an Int
 ──→ assign_with_if_different_types.mamba:4:47
   4 | def a: Union[String, MyClass] := if True then 20 else MyClass()
                                                     ^^
     └─→ variable and expression: `if`
       4 | def a: Union[String, MyClass] := if True then 20 else MyClass()

Expected behavior

The check stage should pass. Perhaps this is a quick fix by flipping around the constraint in the variable definition generation stage/function.

Additional context

Putting in milestone 3.7.0 in case this is a non-trivial fix. It not a critical error, but if it is an easy fix would be nice to have for 3.6.0