nim-lang / Nim

Nim is a statically typed compiled systems programming language. It combines successful concepts from mature languages like Python, Ada and Modula. Its design focuses on efficiency, expressiveness, and elegance (in that order of priority).
https://nim-lang.org
Other
16.47k stars 1.47k forks source link

Generic sequence of proc type mismatch #23744

Closed nitely closed 3 months ago

nitely commented 3 months ago

Description

type Callback = proc(s: string): int

proc foobar(s: string): int =
  result = s.len

proc foo[B](b:B) =
  echo b("foo")

proc bar[B](a: seq[B]) =
  for x in items a:
    echo x("foo")

proc main() =
  foo[Callback](foobar)
  bar(@[foobar]) 
  bar[Callback](@[foobar])  # Error: type mismatch
main()

Nim Version

Nim Compiler Version 2.1.1 [Linux: amd64] Compiled at 2024-06-20 Copyright (c) 2006-2024 by Andreas Rumpf

git hash: 646bd99d461469f08e656f92ae278d6695b35778 active boot switches: -d:release

Current Output

bug.nim(16, 16) Error: type mismatch: got <seq[proc (s: string): int{.noSideEffect, gcsafe.}]>
but expected one of:
proc (a: seq[Callback])

Expected Output

3
3
3

Possible Solution

No response

Additional Information

I found it while trying to make a table of [string, proc] type with initial data.

nitely commented 3 months ago

workaround:

type Callback = proc(s: string): int

proc foobar(s: string): int =
  result = s.len

proc foo[B](b:B) =
  echo b("foo")

proc bar[B](a: seq[B]) =
  for x in items a:
    echo x("foo")

proc main() =
  foo[Callback](foobar)
  bar(@[foobar])
  bar[Callback](@[foobar.Callback])
main()
nitely commented 3 months ago

mmh pretty sure this is an inference limitation that won't get fixed.

beef331 commented 3 months ago

Not really inference as much as Callback gets noSideEffect the following is "more correct"

type Callback = proc(s: string): int {.nimcall.} # or {.closure.}`