Nim: varargs[string, `$`] parameter of template can't be passed to write with one string

Created on 20 Jan 2020  路  6Comments  路  Source: nim-lang/Nim

Example

template custom(args: varargs[string, `$`]) =
  stdout.writeLine "customized ", args

custom "echo"

Current Output

Hint: used config file '/playground/nim/config/nim.cfg' [Conf]
Hint: system [Processing]
Hint: widestrs [Processing]
Hint: io [Processing]
Hint: in [Processing]
/usercode/in.nim(4, 8) Error: cannot convert varargs[string] to varargs[Ty]

Expected Output

customized echo

Additional Information

Affects both playground and my system

Nim Compiler Version 1.1.1 [Linux: amd64]
Compiled at 2020-01-18
Copyright (c) 2006-2019 by Andreas Rumpf

git hash: bc14453f69b9bde449cb52655eb6ffe571d6a28b
active boot switches: -d:release -d:useLinenoise -d:nativeStackTrace

Most helpful comment

not sure what's your use case but lenVarargs may be useful, also

All 6 comments

I think code is wrong, Nim is right.

writeLine takes as arguments f: File ; x: varargs[Ty, $].
You are passing as arguments f: File ; string literal ; x: varargs[Ty, $],
being the argument values stdout, "customized ", args.

This works:

template custom(args: varargs[string, `$`]) =
  stdout.writeLine args

custom "echo"

On runtime, a string literal is a string, and the compiler shouldn't consider them different. And if you specify the type you want out:

template custom(args: varargs[string, `$`]) =
  stdout.writeLine[string] "customized ", args

custom "echo"

You'll get:

/usercode/in.nim(4, 8) template/generic instantiation of `custom` from here
/usercode/in.nim(2, 9) template/generic instantiation of `writeLine` from here
/playground/nim/lib/system/io.nim(444, 17) Error: cannot instantiate: 'Ty'

The walkaround for this is to make args untyped.

You need to use macros.unpackVarargs, I think.

not sure what's your use case but lenVarargs may be useful, also

This way you spot the error more easily:

writeLine( f: File = stdout,  "customized ",  x: varargs[string] = args )

I guess it's not a bug then, but the error message could be better.

Was this page helpful?
0 / 5 - 0 ratings