Nim: Compiler should forbid duplicate enum string values

Created on 30 Oct 2018  路  7Comments  路  Source: nim-lang/Nim

Currently the string values for enum entries dont need to be unique like in the following code

from strutils import parseEnum

type X = enum x1 = "x.2", x2 = "x.2"

echo x1 # x.2
echo x2 # x.2

var e = "x.2"
var x = parseEnum[X](e)
doAssert x == x1

I think it would be good to have a pragma for enums to check unique string values at compile time if the developer wants this. This can prevent errors like it prevents it in a case by checking duplicates.

Low Priority Semcheck

Most helpful comment

shouldnt it always give an error? ie error instead of warning, and not require a pragma (which reduces utility of this check)

All 7 comments

I misunderstood you on IRC. Why is that problem, how hard is it to get the string literals right once in a lifetime...

well I guess it is valid to emit a warning when string values of enums are duplicated. This is most likely an accident, and if not it is probably bad anyway.

shouldnt it always give an error? ie error instead of warning, and not require a pragma (which reduces utility of this check)

Okay so i just read the manual https://nim-lang.org/docs/manual.html#types-enumeration-types and I found that the string value is just a representation for printing purposes (kind of a shorthand to creating $ proc).

The enum members are still assigned a unique ord value.

So why should the string value be unique if it is just a string representation for printing?

A very bad example but -

import strutils

type
    X = enum
        a = "ord value $1"
        b = "ord value $1"

echo $a % $(ord(a))
echo $b % $(ord(b))

gives -

ord value 0
ord value 1

Here the string representation is same but it is modified during printing.

@nc-x yes that is why I suggest to emit a warning. This is like you said "A very bad example" and I guess whoever programs like that doesn't care about warnings. But for people who care about warnings, the strings should be distinct.

There is no issue here, Nim requires you to get your string literals right. If that's so hard, use fewer of them. String literals are not checked anywhere else either.

well in this cane the string literals are part of the enum type declaration, so they are pretty easy to check.

Was this page helpful?
0 / 5 - 0 ratings