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.61k stars 1.47k forks source link

Object types as generic constraints are treated as uninstantiated when passing subtypes #24447

Open metagn opened 5 days ago

metagn commented 5 days ago

Originally mentioned in this comment: https://github.com/nim-lang/Nim/issues/7713#issuecomment-821814214

Encountered in:

type
  Foo = object of RootObj
  Bar = object of Foo
  Baz[T:Foo] = object of RootObj
    val:T
let x = Baz[Bar]()#Error object constructor needs an object type
type
  Qux = object
    val:Baz[Bar]
let y = Qux() #Error: invalid type: 'Baz[Baz.T]' in this context: 'Qux' for let

concepts work:

type
  Foo = object of RootObj
  IsFoo = concept type t
    t is Foo
  Bar = object of Foo
  Baz[T:IsFoo] = object of RootObj
    val:T
  Qux = object
    val:Baz[Bar]
let x = Baz[Bar]()#fine
let y = Qux() #fine

another workaround:

func init[T:Foo](b: type Baz; c: typedesc[T]):Baz[T] = discard
let x = Baz.init(Bar)

Works if passing just Foo instead of Bar