WurstScript icon indicating copy to clipboard operation
WurstScript copied to clipboard

Enums Implicitly Converts to Int when Compared to Null

Open frederikaalund opened this issue 5 years ago • 2 comments

Let's use the following enum as an example:

public enum AreaType
	WOODLAND
	SNOWY

The compiler will associate 0 with WOODLAND and 1 with SNOWY.

The compiler complains if we try to compare an enum with an integer. This is a good thing. Take for instance:

let isWoodland = AreaType.WOODLAND == 0

The above gives the error Cannot compare types AreaType with integer-literal. Exactly what we want.

Unfortunately, comparison between enum and null works. This produces unexpected results:

let isWoodland = AreaType.WOODLAND == null

isWoodland will be assigned true since null is coalesced into 0 (which coincides with the integer representation of WOODLAND). This leads to subtle bugs. Note that you can also do meaningless stuff like AreaType areaType = null.

I think comparison between enum and null should give a compiler error instead.

frederikaalund avatar Jun 09 '19 14:06 frederikaalund

I'm not sure if AreaType areaType = null is meaningless, but the better variant would probably to define a "null" member of the enum to use instead.

Frotty avatar Jun 20 '19 10:06 Frotty

I'm not sure if AreaType areaType = null is meaningless, ...

The semantics could be sound. The current implementation, however, is not sound. The current implementation does not properly handle the comparison against null, which leads to bad code gen (it's a bug).

I suggest, that we either:

  1. Issue a compile-time error if comparing an enum to null.
  2. Implicitly add a hidden null member to all enums that is used for comparisons against null.

Personally, I favor the first approach but I'd be happy with either solution.

...but the better variant would probably to define a "null" member of the enum to use instead.

This is normally what I do when I need a none/null/undefined/unassigned value for the enum in Wurst and other languages.

frederikaalund avatar Jun 20 '19 11:06 frederikaalund