amber-lang / amber

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

[BUG] Variable passed by reference uses global scope #526

Open hdwalters opened 1 month ago

hdwalters commented 1 month ago

Describe the bug If a function declares a variable by reference, but an identically named variable exists in another scope, the value is not returned correctly.

To Reproduce Run the following script to reproduce:

$ cat ref.ab
#!/usr/bin/env amber

fun set_ref(ref numbers: [Num]): Null {
    echo "In fun before set: {numbers}"
    numbers = [4, 5, 6]
    echo "In fun after set: {numbers}"
}

main {
    let numbers = [1, 2, 3]
    echo "In main before call: {numbers}"
    set_ref(numbers)
    echo "In main after call: {numbers}"
}
$ ./ref.ab
In main before call: 1 2 3
In fun before set: numbers // <======== Expected "1 2 3"
In fun after set: 4 5 6
In main after call: 1 2 3 // <========= Expected "4 5 6"

Expected behavior The script above should behave as it does if a different variable name is used:

$ cat ref.ab
#!/usr/bin/env amber

fun set_ref(ref byref: [Num]): Null {
    echo "In fun before set: {byref}"
    byref = [4, 5, 6]
    echo "In fun after set: {byref}"
}

main {
    let numbers = [1, 2, 3]
    echo "In main before call: {numbers}"
    set_ref(numbers)
    echo "In main after call: {numbers}"
}
$ ./ref.ab
In main before call: 1 2 3
In fun before set: 1 2 3
In fun after set: 4 5 6
In main after call: 4 5 6

Additional context N/A

hdwalters commented 4 weeks ago

The solution to this may fall out of @Ph0enixKM's proposed translation layer, if it can generate temporary Bash variable names.

mks-h commented 1 week ago

Just stumbled upon this one. With the shorthand add operator, it simply fails to append.

let verification = "eeded"

fun test(ref the_bug: Text): Null {
    the_bug += verification
}

main {
    let the_bug = "Succ"
    test(the_bug)
    echo the_bug // Outputs "Succ"
}
hdwalters commented 1 week ago

Yep, that would do it; the_bug is the same in both function and main block. I don't think it's worth trying to fix anything until @Ph0enixKM has done his translation layer thingy though.