diff options
author | ringabout <43030857+ringabout@users.noreply.github.com> | 2024-09-03 22:35:04 +0800 |
---|---|---|
committer | GitHub <noreply@github.com> | 2024-09-03 16:35:04 +0200 |
commit | c948ab9b8511ef2db31bf7b7a366f1e5eff3b0a2 (patch) | |
tree | 2e39c039fd75e90a0f2f7527bf173342865629d9 | |
parent | 4bf323d6c44b329fe1955f210580a73952c081d0 (diff) | |
download | Nim-c948ab9b8511ef2db31bf7b7a366f1e5eff3b0a2.tar.gz |
fixes symbolName for range enums (#24052)
-rw-r--r-- | lib/std/enumutils.nim | 8 | ||||
-rw-r--r-- | tests/stdlib/tenumutils.nim | 10 |
2 files changed, 17 insertions, 1 deletions
diff --git a/lib/std/enumutils.nim b/lib/std/enumutils.nim index bcfb2d5d7..9c338817d 100644 --- a/lib/std/enumutils.nim +++ b/lib/std/enumutils.nim @@ -174,6 +174,9 @@ template symbolRank*[T: enum](a: T): int = when T is Ordinal: ord(a) - T.low.ord.static else: symbolRankImpl(a) +proc rangeBase(T: typedesc): typedesc {.magic: "TypeTrait".} + # skip one level of range; return the base type of a range type + func symbolName*[T: enum](a: T): string = ## Returns the symbol name of an enum. ## @@ -192,5 +195,8 @@ func symbolName*[T: enum](a: T): string = c1 = 4 c2 = 20 assert c1.symbolName == "c1" - const names = enumNames(T) + when T is range: + const names = enumNames(rangeBase T) + else: + const names = enumNames(T) names[a.symbolRank] diff --git a/tests/stdlib/tenumutils.nim b/tests/stdlib/tenumutils.nim index 67b98efe1..2662a660d 100644 --- a/tests/stdlib/tenumutils.nim +++ b/tests/stdlib/tenumutils.nim @@ -35,5 +35,15 @@ template main = doAssert $b == "kb0" static: doAssert B.high.symbolName == "b2" + block: + type + Color = enum + Red = "red", Yellow = "yellow", Blue = "blue" + + var s = Red + doAssert symbolName(s) == "Red" + var x: range[Red..Blue] = Yellow + doAssert symbolName(x) == "Yellow" + static: main() main() |