Skip to content

A random converter is being used in ambiguous generic scenarios. #23170

Open
@IgorGRBR

Description

@IgorGRBR

Description

Implicitly converting a value to one of the matching generic types doesn't produce an error when multiple types can be matched.

Nim Version

Nim Compiler Version 2.0.2 [Linux: amd64]
Compiled at 2023-12-15
Copyright (c) 2006-2023 by Andreas Rumpf

git hash: c4c44d10df8a14204a75c34e499def200589cb7c
active boot switches: -d:release

Example

type Baz = object
  num*: int
  str*: string

converter asInt(x: Baz): int = x.num
converter asStr(x: Baz): string = x.str

proc printme(n: int) = echo "Here's a num: " & $n
proc printme(s: string) = echo "Here's a string: " & s

proc printAThing(t: int | string) = printme(t)

when isMainModule:
  var b = Baz()
  b.num = 37
  b.str = "a string"
  # printme(b) # Properly produces a compiler error (Good)
  printAThing(b) # Lets the compiler decide which converter to use (Bad)

Current Output

Here's a num: 37

Expected Output

A compiler error, similarly to how it behaves with static dispatch.

Possible Solution

Check if multiple converters match the generic and refuse to compile if they do, forcing the user to call the correct converter explicitly.

Additional Information

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions