From 7e589bcbe4e2f299533795bac72ffa578b5310b0 Mon Sep 17 00:00:00 2001 From: metagn Date: Sat, 12 Apr 2025 09:37:36 +0300 Subject: [PATCH] add bit type overloads of `$` and `repr` (#24865) fixes #24864 (cherry picked from commit 97d819a25173840d6abdb249b73fe629578fd918) --- lib/system/dollars.nim | 25 ++++++++++++++++--------- lib/system/repr_v2.nim | 29 +++++++++++++++++------------ tests/system/treprconverter.nim | 5 +++++ 3 files changed, 38 insertions(+), 21 deletions(-) create mode 100644 tests/system/treprconverter.nim diff --git a/lib/system/dollars.nim b/lib/system/dollars.nim index 4ff3d0ae6c..bd4099ef5e 100644 --- a/lib/system/dollars.nim +++ b/lib/system/dollars.nim @@ -13,17 +13,24 @@ when not defined(nimPreviewSlimSystem): ## Outplace version of `addFloat`. result.addFloat(x) -proc `$`*(x: int): string {.raises: [].} = - ## Outplace version of `addInt`. - result.addInt(x) +template addIntAlias(T: typedesc) = + proc `$`*(x: T): string {.raises: [].} = + ## Outplace version of `addInt`. + result = "" + result.addInt(x) -proc `$`*(x: int64): string {.raises: [].} = - ## Outplace version of `addInt`. - result.addInt(x) +# need to declare for bit types as well to not clash with converters: +addIntAlias int +addIntAlias int8 +addIntAlias int16 +addIntAlias int32 +addIntAlias int64 -proc `$`*(x: uint64): string {.raises: [].} = - ## Outplace version of `addInt`. - addInt(result, x) +addIntAlias uint +addIntAlias uint8 +addIntAlias uint16 +addIntAlias uint32 +addIntAlias uint64 # same as old `ctfeWhitelist` behavior, whether or not this is a good idea. template gen(T) = diff --git a/lib/system/repr_v2.nim b/lib/system/repr_v2.nim index fd2dd4c695..fdff7083c3 100644 --- a/lib/system/repr_v2.nim +++ b/lib/system/repr_v2.nim @@ -14,21 +14,26 @@ proc rangeBase(T: typedesc): typedesc {.magic: "TypeTrait".} proc repr*(x: NimNode): string {.magic: "Repr", noSideEffect.} -proc repr*(x: int): string = - ## Same as $x - $x +template dollarAlias(T: typedesc) = + proc repr*(x: T): string {.noSideEffect.} = + ## Same as $x + $x -proc repr*(x: int64): string = - ## Same as $x - $x +# need to declare for bit types as well to not clash with converters: +dollarAlias int +dollarAlias int8 +dollarAlias int16 +dollarAlias int32 +dollarAlias int64 -proc repr*(x: uint64): string {.noSideEffect.} = - ## Same as $x - $x +dollarAlias uint +dollarAlias uint8 +dollarAlias uint16 +dollarAlias uint32 +dollarAlias uint64 -proc repr*(x: float): string = - ## Same as $x - $x +dollarAlias float +dollarAlias float32 proc repr*(x: bool): string {.magic: "BoolToStr", noSideEffect.} ## repr for a boolean argument. Returns `x` diff --git a/tests/system/treprconverter.nim b/tests/system/treprconverter.nim new file mode 100644 index 0000000000..545fa54bd7 --- /dev/null +++ b/tests/system/treprconverter.nim @@ -0,0 +1,5 @@ +# issue #24864 + +type S = distinct uint16 +converter d(field: uint8 | uint16): S = discard +discard (repr(0'u16), repr(0'u8))