Skip to content

Commit

Permalink
Add hasDefaultValue type trait (#22636)
Browse files Browse the repository at this point in the history
Needed for #21842.
  • Loading branch information
AmjadHD committed Sep 4, 2023
1 parent 3fbb078 commit 8f7aedb
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 1 deletion.
3 changes: 2 additions & 1 deletion changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -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:"

Expand Down
2 changes: 2 additions & 0 deletions compiler/semmagic.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions lib/pure/typetraits.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down

0 comments on commit 8f7aedb

Please sign in to comment.