Add hasDefaultValue type trait (#22636)

Needed for #21842.
This commit is contained in:
Amjad Ben Hedhili
2023-09-04 22:18:58 +01:00
committed by GitHub
parent 3fbb078a3c
commit 8f7aedb3d1
3 changed files with 21 additions and 1 deletions

View File

@@ -11,7 +11,8 @@
[//]: # "Additions:"
- Adds `newStringUninit` to system, which creates a new string of length `len` like `newString` but with uninitialized content.
- Added `newStringUninit` to system, which creates a new string of length `len` like `newString` but with uninitialized content.
- Added `hasDefaultValue` to `std/typetraits` to check if a type has a valid default value.
[//]: # "Deprecations:"

View File

@@ -197,6 +197,8 @@ proc evalTypeTrait(c: PContext; traitCall: PNode, operand: PType, context: PSym)
let complexObj = containsGarbageCollectedRef(t) or
hasDestructor(t)
result = newIntNodeT(toInt128(ord(not complexObj)), traitCall, c.idgen, c.graph)
of "hasDefaultValue":
result = newIntNodeT(toInt128(ord(not operand.requiresInit)), traitCall, c.idgen, c.graph)
of "isNamedTuple":
var operand = operand.skipTypes({tyGenericInst})
let cond = operand.kind == tyTuple and operand.n != nil

View File

@@ -96,6 +96,23 @@ proc supportsCopyMem*(t: typedesc): bool {.magic: "TypeTrait".}
##
## Other languages name a type like these `blob`:idx:.
proc hasDefaultValue*(t: typedesc): bool {.magic: "TypeTrait".} =
## Returns true if `t` has a valid default value.
runnableExamples:
{.experimental: "strictNotNil".}
type
NilableObject = ref object
a: int
Object = NilableObject not nil
RequiresInit[T] = object
a {.requiresInit.}: T
assert hasDefaultValue(NilableObject)
assert not hasDefaultValue(Object)
assert hasDefaultValue(string)
assert not hasDefaultValue(var string)
assert not hasDefaultValue(RequiresInit[int])
proc isNamedTuple*(T: typedesc): bool {.magic: "TypeTrait".} =
## Returns true for named tuples, false for any other type.
runnableExamples: