proc exec(message: (proc: void) | string): void =
discard
exec(proc = echo 1)
Error:
Hint: used config file '/playground/nim/config/nim.cfg' [Conf]
Hint: used config file '/playground/nim/config/config.nims' [Conf]
....
/usercode/in.nim(4, 5) Error: type mismatch: got <proc (){.gcsafe, locks: 0.}>
but expected one of:
proc exec(message: (proc (): void) | string): void
first type mismatch at position: 1
required type for message: proc (){.closure.} or string
but expression 'proc () = echo ["1"]' is of type: proc (){.gcsafe, locks: 0.}
expression: exec(proc () = echo ["1"])
Hmm, the bug itself is not related, but the use case related, this also won't work, seems because of the void, if changed to string it would work
import sugar
proc exec*(message: proc (log: string): void): void =
discard
exec(proc (log: auto) = discard)
exec((log) => discard)
You can annotate it with {.nimcall.} which will let the first example compile, chaning the calling convention since:
Closure is the default calling convention for a procedural type that lacks any pragma annotations. It indicates that the procedure has a hidden implicit parameter (an environment). Proc vars that have the calling convention closure take up two machine words: One for the proc pointer and another one for the pointer to implicitly passed environment.
import sugar
type VoidProc = proc: void {.nimcall.}
proc exec*(message: VoidProc | string) =
message()
exec (proc() = echo 1)
here's how to get the sugar example to compile. a) turn discard statement into an expression by parenthesizing. b)explicitly specify log's type
import sugar
proc exec*(message: proc (log: string): void): void =
discard
exec((log:string) => (discard))
Thanks for suggestions, I eventually refactored the code to avoid need for such cases.
For the first example the {.nimcall.} compiles but it doesn't capture the scope variables. And for the second example the explicitly specifying type for proc feels too verbose.
Would it be worth to add those examples to backlog? It looks to me like a pretty reasonable code that should work.