Ph0enixKM / Amber

💎 Amber the programming language compiled to bash
https://amber-lang.com
GNU General Public License v3.0
3.54k stars 70 forks source link

✨ Type conditions should be lazy evaluated #125

Open jon4hz opened 1 month ago

jon4hz commented 1 month ago

Currently type condition's aren't lazy evaluated which causes the following code to fail:

fun choose(options, ref result): Bool {
    let res = $gum choose {options}$ failed {
        return false
    }
    if result is Text {
        result = res
    } else {
        result = parse(res) failed {
            return false
        }
    }
    return true
}

let fruits = ["apple", "banana", "cherry", "orange"]
let fav_fruit = "none"
echo "What's your favorite fruit?"
let success = choose(fruits, fav_fruit)
if {
    success: echo "Your favorite fruit is: {fav_fruit}"
    else: echo "More of a meat type?"
}

Error: Cannot assign value of type 'Num' to a variable of type 'Text'

b1ek commented 1 month ago

i am confused. why should this code work? result is clearly Text here.

you want an Any type, right? or something like OneOf<[Text, Int]>

jon4hz commented 1 month ago

i am confused. why should this code work? result is clearly Text here.

Yeah in this example result is Text but result could be also a Num, so this example shouldn't cause a compiler/transpiler error. I mean, that's the entire point of the type condition...

Ph0enixKM commented 1 month ago

It should work like so @b1ek:

fun foo(val: Text) {
  if val is Text: val = "hello"
  else: val = 12
}

foo("test")

The function should not throw error. Because the value will always be Text so the else clause will never run.

Right now it errors that val = 12 is incorrect as it's unable to assign Num to Text

Ph0enixKM commented 1 month ago

I think this issue should only cover type evaluations that can be known at compile time. We fallback to the regular behavior when some arithmetic comparison is detected.

b1ek commented 1 month ago

Do types even exist at runtime?

I mean, this code:

let var = "hi!";
if var is Text {
    echo var
}

compiles to this:

__0_var="hi!"
if [ 1 != 0 ]; then # the "if var is Text" part
    echo "${__0_var}"
fi

and 1 is obviously not 0

Ph0enixKM commented 1 month ago

@b1ek Types do not exist at runtime. All var is Type resolve at the compile time