Skip to content

Commit 1663a21

Browse files
committed
fix #8519 T.distinctBase to reverse T = distinct A
1 parent 96c6c82 commit 1663a21

File tree

2 files changed

+33
-1
lines changed

2 files changed

+33
-1
lines changed

doc/manual.rst

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1673,7 +1673,8 @@ A ``distinct`` type is new type derived from a `base type`:idx: that is
16731673
incompatible with its base type. In particular, it is an essential property
16741674
of a distinct type that it **does not** imply a subtype relation between it
16751675
and its base type. Explicit type conversions from a distinct type to its
1676-
base type and vice versa are allowed.
1676+
base type and vice versa are allowed. See also ``distinctBase`` to get the
1677+
reverse operation.
16771678

16781679

16791680
Modelling currencies

lib/pure/sugar.nim

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -198,3 +198,34 @@ macro dump*(x: typed): untyped =
198198
let r = quote do:
199199
debugEcho `s`, " = ", `x`
200200
return r
201+
202+
macro distinctBase*(T: typedesc, recursive: static[bool] = false): untyped =
203+
## reverses ``type T = distinct A``
204+
runnableExamples:
205+
import typetraits
206+
type T = distinct int
207+
doAssert distinctBase(T) is int
208+
doAssert: not compiles(distinctBase(int))
209+
type T2 = distinct T
210+
doAssert distinctBase(T2, recursive = false) is T
211+
doAssert distinctBase(int, recursive = true) is int
212+
doAssert distinctBase(T2, recursive = true) is int
213+
214+
let typeNode = getTypeImpl(T)
215+
expectKind(typeNode, nnkBracketExpr)
216+
if $typeNode[0] != "typeDesc":
217+
error "expected typeDesc, got " & $typeNode[0]
218+
var typeSym = typeNode[1]
219+
if not recursive:
220+
let impl = getTypeImpl(typeSym)
221+
if $impl.typeKind != "ntyDistinct":
222+
error "type is not distinct"
223+
getTypeInst(impl[0])
224+
else:
225+
while true:
226+
let impl = getTypeImpl(typeSym)
227+
if $impl.typeKind != "ntyDistinct":
228+
typeSym = impl
229+
break
230+
typeSym=getTypeInst(impl[0])
231+
typeSym

0 commit comments

Comments
 (0)