Nim
Nim copied to clipboard
Less constrained generic overload wins over more constrained one
Description
I expect the encode
of Base64Types
will be selected by the compiler, but it's not.
type
Base64* = object
## Type to use RFC4648 alphabet without padding
Base64Pad* = object
## Type to use RFC4648 alphabet with padding
Base64Url* = object
## Type to use RFC4648 URL alphabet without padding
Base64UrlPad* = object
## Type to use RFC4648 URL alphabet with padding
Base64Types* = Base64 | Base64Pad | Base64Url | Base64UrlPad
proc encode*(btype: type Base64Types, inbytes: openArray[byte]) =
debugEcho "OK"
proc encode*(Format: type, value: auto) =
{.error: "Wrong generic resolution".}
proc main() =
var data = @[1.byte, 2, 3]
Base64.encode(data)
main()
Nim Version
Nim Compiler Version 1.6.18 [Windows: amd64] Compiled at 2024-01-14 Copyright (c) 2006-2023 by Andreas Rumpf
git hash: a749a8b742bd0a4272c26a65517275db4720e58a active boot switches: -d:release
Nim Compiler Version 2.1.1 [Windows: amd64] Compiled at 2024-01-01 Copyright (c) 2006-2024 by Andreas Rumpf
git hash: b280100499fafe43657c860e3c79d9347be5b4b6 active boot switches: -d:release
Current Output
..../main.nim(21, 9) template/generic instantiation of `encode` from here
..../main.nim(17, 10) Error: Wrong generic resolution
Expected Output
OK
Possible Solution
No response
Additional Information
No response
auto
is a generic match but openArray[byte]
is a subtype/conversion match, which matches worse according to the manual.
That being said, I think the fact that this doesn't work is wrong:
proc foo[T: openArray[byte]](x: T) =
echo "yes"
proc foo[T](x: T) =
echo "no"
doAssert false
var data = @[1.byte, 2, 3]
foo(data) # no
since the constrained openArray
match should be additive. This seems to be the issue in #6407.
What about the first parameter. It looks incorrect to me.