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.5k stars 2.15k forks source link

cgen error for generic function over maps and arrays #21700

Closed spytheman closed 6 days ago

spytheman commented 1 week ago

V doctor:

V full version: V 0.4.6 c689f80.d7cc5c8
OS: linux, Ubuntu 20.04.6 LTS
Processor: 4 cpus, 64bit, little endian, Intel(R) Core(TM) i3-3225 CPU @ 3.30GHz

getwd: /space/v/oo
vexe: /space/v/oo/v
vexe mtime: 2024-06-19 10:14:30

vroot: OK, value: /space/v/oo
VMODULES: OK, value: /home/delian/.vmodules
VTMP: OK, value: /tmp/v_1000

Git version: git version 2.43.2
Git vroot status: weekly.2024.24-25-gd7cc5c88
.git/config present: true

CC version: cc (Ubuntu 10.5.0-1ubuntu1~20.04) 10.5.0
thirdparty/tcc status: thirdparty-linux-amd64 40e5cbb5

What did you do? v -g -o vdbg cmd/v && vdbg a.v

fn mkey[K,V](m map[K]V) K { return K{} }
fn mvalue[K,V](m map[K]V) V { return V{} }
fn aelem[E](a []E) E { return E{} }

fn g[T](x T) {
    $if T is $map {
        dk := mkey(x)
        dv := mvalue(x)
        eprintln('default k: `${dk}` | typeof dk: ${typeof(dk).name}')
        eprintln('default v: `${dv}` | typeof dv: ${typeof(dv).name}')
        for k, v in x {
            eprintln('> k: $k | v: $v')
        }
    }
    $if T is $array {
        de := aelem(x)
        eprintln('default e: `${de}` | typeof de: ${typeof(de).name}')
        for idx, e in x {
            eprintln('> idx: $idx | e: $e')
        }
    }
}

g({'abc': 123, 'def': 456})
g([1,2,3])

// Uncommenting one of the lines below leads to a cgen error:
//g({123: 'ggg', 456: 'hhh'})
g(['xyz', 'zzz'])

What did you expect to see?

a compiled program

What did you see instead?

==================
/tmp/v_1000/a.01J0QZVMWFPXR5MVQ2HEV9TGDX.tmp.c:13203: error: '{' expected (got ";")
...
==================
(Use `v -cg` to print the entire error message)

[!NOTE] You can use the 👍 reaction to increase the issue's priority for developers.

Please note that only the 👍 reaction to the issue itself counts as a vote. Other reactions and those to comments will not be taken into account.

spytheman commented 1 week ago

Note: when the last 2 lines are commented, the program correctly prints:

default k: `` | typeof dk: string
default v: `0` | typeof dv: int
> k: abc | v: 123
> k: def | v: 456
default e: `0` | typeof de: int
> idx: 0 | e: 1
> idx: 1 | e: 2
> idx: 2 | e: 3