vlang / v

Simple, fast, safe, compiled language for developing maintainable software. Compiles itself in <1s with zero library dependencies. Supports automatic C => V translation. https://vlang.io
MIT License
35.66k stars 2.15k forks source link

anonymous function in comptime wrong behaviour #12657

Open mvenditto opened 2 years ago

mvenditto commented 2 years ago

V version: V 0.2.4 1b691e7.5ab91dd OS: linux, Ubuntu 21.10 (VM)

maybe an edge case, but comptime calls seems to behave wrong if nested inside anon funcs.

What did you do?

struct Foo {}

fn (f Foo) foo() {
    println('foo')
}

fn (f Foo) bar() {
    println('bar')
}

fn main() {
    f := Foo {}
    $for method in Foo.methods {
        x := fn [f]() {
            f.$method()
        }
        x()
    }
}

What did you expect to see?

foo
bar

What did you see instead?

foo
foo
felipensp commented 1 year ago

This is because the anon func is being generated using the same name on parser phase.

struct Foo {}

fn (f Foo) foo() {
    println('foo')
}

fn (f Foo) bar() {
    println('bar')
}

fn main() {
    f := Foo {}
    $for method in Foo.methods {
        $if method.name == 'foo' {
            x := fn [method, f]() {
                f.$method()
            }
            x()
        }
        $if method.name == 'bar' {
            x := fn [method, f]() {
                f.$method()
            }
            x()
        }
    }
}

Make it works.