Nim: Cannot discard result of staticExec

Created on 8 Mar 2020  路  5Comments  路  Source: nim-lang/Nim

I cannot discard the result of staticExec.

Example

discard staticExec(r"echo ""hello""")

Current Output

test.nim(1, 19) Error: 'staticExec' can only be used in compile-time context

Expected Output

Successful compilation

Possible Solution

It works if i write:

const s = staticExec(r"echo ""hello""")

Additional Information

I'm just trying to learn the language and find this behavior unexpected.
Why would the program stop compiling if i discard the return value?

$ nim -v
Nim Compiler Version 1.0.6 [Linux: amd64]

Most helpful comment

Hmm, I think its because discard does not try to evaluate its arguments in a static context implicitly.
I'm not sure if its intended, so I will leave this open.

All 5 comments

static: discard staticExec(r"echo ""hello""")
should work.

Oh, it does. Thanks! Could you please explain why it behaves like this?

Hmm, I think its because discard does not try to evaluate its arguments in a static context implicitly.
I'm not sure if its intended, so I will leave this open.

If you the following in system.nim

proc gorge*(command: string, input = "", cache = ""): string {.
  magic: "StaticExec".} = discard

proc staticExec*(command: string, input = "", cache = ""): string {.
  magic: "StaticExec".} = discard

with:

proc staticExecImpl(command,input,cache: string): string {.
  magic: "StaticExec".} = discard

proc gorge*(command: string, input = "", cache = ""): string {.compileTime.} =
  staticExecImpl(command,input,cache)

proc staticExec*(command: string, input = "", cache = ""): string {.compileTime.} =
  staticExecImpl(command,input,cache)

Your code will work (comments omitted). The magic is in the compileTime pragma. Sure this can also be fixed by fixing the staticExec magic.

This fix does not work since gorge() now runs in $nim/lib since that's where system.nim is. Any calls to gorge() that use relative path break as the PR did.

Was this page helpful?
0 / 5 - 0 ratings