base parseEnum on a case statement, fixes #14030 (#14046)

* base `parseEnum` on a case statement, fixes #14030

* apply simplifactions / clean up, remove `norm` node, use strVal

* export `normalize` in json.nim

* cmp using nimIdentNormalize, error at CT if ambiguous enum found

`nimIdentNormalize` provided by @cooldome.

We track all names of the branches we have created so far and error if
a duplicate is found.

Dummy change to make github react...

* fix docstring of `nimIdentNormalize`

* make `typ` arg `typedesc`, add lineinfo, call norm. only once
This commit is contained in:
Vindaar
2020-04-22 10:41:56 +02:00
committed by GitHub
parent c3f4b93060
commit d42c5a575d
3 changed files with 171 additions and 11 deletions

View File

@@ -348,3 +348,90 @@ when true:
main()
#OUT ha/home/a1xyz/usr/bin
# `parseEnum`, ref issue #14030
# check enum defined at top level
type
Foo = enum
A
B = "bb"
C = (5, "ccc")
D = 15
E = "ee" # check that we count enum fields correctly
block:
let a = parseEnum[Foo]("A")
let b = parseEnum[Foo]("bb")
let c = parseEnum[Foo]("ccc")
let d = parseEnum[Foo]("D")
let e = parseEnum[Foo]("ee")
doAssert a == A
doAssert b == B
doAssert c == C
doAssert d == D
doAssert e == E
try:
let f = parseEnum[Foo]("Bar")
doAssert false
except ValueError:
discard
# finally using default
let g = parseEnum[Foo]("Bar", A)
doAssert g == A
block:
# check enum defined in block
type
Bar = enum
V
W = "ww"
X = (3, "xx")
Y = 10
Z = "zz" # check that we count enum fields correctly
let a = parseEnum[Bar]("V")
let b = parseEnum[Bar]("ww")
let c = parseEnum[Bar]("xx")
let d = parseEnum[Bar]("Y")
let e = parseEnum[Bar]("zz")
doAssert a == V
doAssert b == W
doAssert c == X
doAssert d == Y
doAssert e == Z
try:
let f = parseEnum[Bar]("Baz")
doAssert false
except ValueError:
discard
# finally using default
let g = parseEnum[Bar]("Baz", V)
doAssert g == V
block:
# check ambiguous enum fails to parse
type
Ambig = enum
f1 = "A"
f2 = "B"
f3 = "A"
doAssert not compiles((let a = parseEnum[Ambig]("A")))
block:
# check almost ambiguous enum
type
AlmostAmbig = enum
f1 = "someA"
f2 = "someB"
f3 = "SomeA"
let a = parseEnum[AlmostAmbig]("someA")
let b = parseEnum[AlmostAmbig]("someB")
let c = parseEnum[AlmostAmbig]("SomeA")
doAssert a == f1
doAssert b == f2
doAssert c == f3