Casting from function returning a tuple fails #4345

Closed
edubart opened this Issue Jun 16, 2016 · 3 comments

Projects

None yet

3 participants

@edubart
Contributor
edubart commented Jun 16, 2016 edited

The following sample file fails when compiling:

proc f(): tuple[a, b: uint8] = (1'u8, 2'u8)

let a, b = f()
let c = cast[int](b)

Compile error:

Error: execution of an external compiler program 'gcc -c -w -Os -I/opt/nim/lib -o /tmp/nim/nimcache/hello.o /tmp/nim/nimcache/hello.c' failed with exit code: 256
/tmp/nimcache/hello.c: In function ‘helloInit000’:
/tmp/nimcache/hello.c:77:2: error: aggregate value used where an integer was expected
c_94012_617288324 = ((NI) (b_94011_617288324));

Nim version:

Nim Compiler Version 0.14.2 (2016-06-11) [Linux: amd64]
Copyright (c) 2006-2016 by Andreas Rumpf
git hash: abf4e20
active boot switches: -d:release

@edubart edubart changed the title from Cast from function returning a tuple fails to Casting from function returning a tuple fails Jun 16, 2016
@edubart
Contributor
edubart commented Jun 16, 2016

I've just noted that the code was missing parenthesis to correctly unpack the tuple, anyway I think nim must show a syntax error before trying to compile in gcc.

@Parashurama
Contributor
Parashurama commented Jun 16, 2016 edited

The problem is that

let a, b = dummy()

is completely valid code. It means assign to a as well as b.
It can be surprising considering that dummy() is called for each variable a, b, c... instead of being shallow-copied as you might expect.

Also, don't use cast[int] here. It is unchecked by nim, so you are trying to cast a tuple of value to int.
Prefer using type conversion i.e.int(value).
cast[type] should really be reserved for casting pointer types, or doing low level bit twiddling.

@Araq
Member
Araq commented Jun 16, 2016

The compiler does check for 'cast' and the codegen emits a union. Apparently it's not covering every case yet. but the code is perfectly fine and should produce nice garbage at runtime.

@Araq Araq added a commit that closed this issue Jul 19, 2016
@Araq Araq fixes #4345 d455d58
@Araq Araq closed this in d455d58 Jul 19, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment