Skip to content

Commit

Permalink
fix nim-lang/RFCs#294 ; disallow enum <=> enum conversion
Browse files Browse the repository at this point in the history
  • Loading branch information
timotheecour committed Dec 5, 2020
1 parent 8178388 commit 2e3589d
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 2 deletions.
7 changes: 7 additions & 0 deletions changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,13 @@

- nil dereference is not allowed at compile time. `cast[ptr int](nil)[]` is rejected at compile time.

- An enum now can't be converted to another enum directly, you must use `ord`:
```
type A = enum a1, a2
type B = enum b1, b2
doAssert not compiles(a1.B)
doAssert compiles(a1.ord.B)
```

## Compiler changes

Expand Down
4 changes: 3 additions & 1 deletion compiler/semexprs.nim
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,9 @@ proc checkConvertible(c: PContext, targetTyp: PType, src: PNode): TConvStatus =
result = checkConversionBetweenObjects(d.skipTypes(abstractInst), s.skipTypes(abstractInst), pointers)
elif (targetBaseTyp.kind in IntegralTypes) and
(srcBaseTyp.kind in IntegralTypes):
if targetTyp.kind == tyBool:
if targetTyp.kind == tyEnum and srcBaseTyp.kind == tyEnum:
result = convNotLegal
elif targetTyp.kind == tyBool:
discard "convOk"
elif targetTyp.isOrdinalType:
if src.kind in nkCharLit..nkUInt64Lit and
Expand Down
17 changes: 16 additions & 1 deletion tests/misc/tconv.nim
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
template reject(x) =
static: assert(not compiles(x))
static: doAssert(not compiles(x))
template accept(x) =
static: doAssert(compiles(x))

reject:
const x = int8(300)
Expand Down Expand Up @@ -55,3 +57,16 @@ block: # issue 3766
proc r(x: static[R]) =
echo x
r 3.R


block: # https://github.com/nim-lang/RFCs/issues/294
type Koo = enum k1, k2
type Goo = enum g1, g2

reject: Goo(k2)
reject: k2.Goo
reject: k2.string

accept: Koo(k2)
accept: k2.Koo
accept: k2.int.Goo

0 comments on commit 2e3589d

Please sign in to comment.