distinctBase type trait for distinct types (#13031)
This commit is contained in:
parent
8bcc7e8b9e
commit
871d5e79b1
7 changed files with 91 additions and 70 deletions
|
|
@ -13,6 +13,7 @@
|
|||
include system/inclrtl
|
||||
|
||||
import macros
|
||||
import typetraits
|
||||
|
||||
proc createProcType(p, b: NimNode): NimNode {.compileTime.} =
|
||||
#echo treeRepr(p)
|
||||
|
|
@ -160,27 +161,9 @@ proc freshIdentNodes(ast: NimNode): NimNode =
|
|||
result.add inspect(child)
|
||||
result = inspect(ast)
|
||||
|
||||
macro distinctBase*(T: typedesc): untyped =
|
||||
template distinctBase*(T: typedesc): typedesc {.deprecated: "use distinctBase from typetraits instead".} =
|
||||
## reverses ``type T = distinct A``; works recursively.
|
||||
runnableExamples:
|
||||
type T = distinct int
|
||||
doAssert distinctBase(T) is int
|
||||
doAssert: not compiles(distinctBase(int))
|
||||
type T2 = distinct T
|
||||
doAssert distinctBase(T2) is int
|
||||
|
||||
let typeNode = getTypeImpl(T)
|
||||
expectKind(typeNode, nnkBracketExpr)
|
||||
if typeNode[0].typeKind != ntyTypeDesc:
|
||||
error "expected typeDesc, got " & $typeNode[0]
|
||||
var typeSym = typeNode[1]
|
||||
typeSym = getTypeImpl(typeSym)
|
||||
if typeSym.typeKind != ntyDistinct:
|
||||
error "type is not distinct"
|
||||
typeSym = typeSym[0]
|
||||
while typeSym.typeKind == ntyDistinct:
|
||||
typeSym = getTypeImpl(typeSym)[0]
|
||||
typeSym.freshIdentNodes
|
||||
typetraits.distinctBase(T)
|
||||
|
||||
macro capture*(locals: openArray[typed], body: untyped): untyped {.since: (1, 1).} =
|
||||
## Useful when creating a closure in a loop to capture some local loop variables
|
||||
|
|
|
|||
|
|
@ -63,19 +63,12 @@ proc supportsCopyMem*(t: typedesc): bool {.magic: "TypeTrait".}
|
|||
##
|
||||
## Other languages name a type like these `blob`:idx:.
|
||||
|
||||
proc isNamedTuple*(T: typedesc): bool =
|
||||
proc isNamedTuple*(T: typedesc): bool {.magic: "TypeTrait".}
|
||||
## Return true for named tuples, false for any other type.
|
||||
when T isnot tuple: result = false
|
||||
else:
|
||||
var t: T
|
||||
for name, _ in t.fieldPairs:
|
||||
when name == "Field0":
|
||||
return compiles(t.Field0)
|
||||
else:
|
||||
return true
|
||||
# empty tuple should be un-named,
|
||||
# see https://github.com/nim-lang/Nim/issues/8861#issue-356631191
|
||||
return false
|
||||
|
||||
proc distinctBase*(T: typedesc): typedesc {.magic: "TypeTrait".}
|
||||
## Returns base type for distinct types, works only for distinct types.
|
||||
## compile time error otherwise
|
||||
|
||||
|
||||
when isMainModule:
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue