Skip to content

Commit

Permalink
fix #8519 T.distinctBase to reverse T = distinct A
Browse files Browse the repository at this point in the history
  • Loading branch information
timotheecour committed Aug 4, 2018
1 parent 96c6c82 commit 1663a21
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
3 changes: 2 additions & 1 deletion doc/manual.rst
Original file line number Diff line number Diff line change
Expand Up @@ -1673,7 +1673,8 @@ A ``distinct`` type is new type derived from a `base type`:idx: that is
incompatible with its base type. In particular, it is an essential property
of a distinct type that it **does not** imply a subtype relation between it
and its base type. Explicit type conversions from a distinct type to its
base type and vice versa are allowed.
base type and vice versa are allowed. See also ``distinctBase`` to get the
reverse operation.


Modelling currencies
Expand Down
31 changes: 31 additions & 0 deletions lib/pure/sugar.nim
Original file line number Diff line number Diff line change
Expand Up @@ -198,3 +198,34 @@ macro dump*(x: typed): untyped =
let r = quote do:
debugEcho `s`, " = ", `x`
return r

macro distinctBase*(T: typedesc, recursive: static[bool] = false): untyped =
## reverses ``type T = distinct A``
runnableExamples:
import typetraits
type T = distinct int
doAssert distinctBase(T) is int
doAssert: not compiles(distinctBase(int))
type T2 = distinct T
doAssert distinctBase(T2, recursive = false) is T
doAssert distinctBase(int, recursive = true) is int
doAssert distinctBase(T2, recursive = true) is int

let typeNode = getTypeImpl(T)
expectKind(typeNode, nnkBracketExpr)
if $typeNode[0] != "typeDesc":
error "expected typeDesc, got " & $typeNode[0]
var typeSym = typeNode[1]
if not recursive:
let impl = getTypeImpl(typeSym)
if $impl.typeKind != "ntyDistinct":
error "type is not distinct"
getTypeInst(impl[0])
else:
while true:
let impl = getTypeImpl(typeSym)
if $impl.typeKind != "ntyDistinct":
typeSym = impl
break
typeSym=getTypeInst(impl[0])
typeSym

0 comments on commit 1663a21

Please sign in to comment.