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

Dot operators with type mismatch, shows assertion instead of compiler error #17779

Open jtiai opened 3 years ago

jtiai commented 3 years ago

The following code doesn't compile and causes unhandled exception:

Example

{.experimental: "dotOperators".}

type
    Flag = enum
        A

    Flags = set[Flag]

template `.=`*(flags: Flags, key: Flag, val: bool) =
    if val: flags.incl key else: flags.excl key

var flags: Flags

flags.A = 123

Current Output

....fatal.nim(53)            sysFatal
Error: unhandled exception: semcall.nim(233, 18) `nArg != nil`  [AssertionDefect]

Expected Output

Compiler provides meanful error message or compiles.

Possible Solution

If flags.A = 123 is written as flags.A = bool(123) code compiles as expected.

$ nim -v
Nim Compiler Version 1.4.6 [Linux: amd64]
# make sure to include the git hash if not using a tagged release
beef331 commented 3 years ago

As I mentioned in the realtime chat this is not due to the bool, it seems to be a dot operators with type mismatch bug. This code shouldnt compile either, since you're passing an int as a bool and Nim doesnt implictly convert. You can do the following and it'll work fine for you.

{.experimental: "dotOperators".}

type
    Flag = enum
        A

    Flags = set[Flag]

template `.=`*(flags: Flags, key: Flag, val: int | bool) =
    if val.bool: flags.incl key else: flags.excl key

var flags: Flags

flags.A = 123