Ensure that =? works with types that do not have a default value

This commit is contained in:
Mark Spanbroek 2021-12-04 17:26:08 +01:00
parent d7a757a8cb
commit cfe4c6fc95
3 changed files with 23 additions and 3 deletions

View File

@ -4,15 +4,19 @@ import std/macros
proc option[T](option: Option[T]): Option[T] = proc option[T](option: Option[T]): Option[T] =
option option
proc placeholder(T: type): T =
discard
template bindLet(name, expression): bool = template bindLet(name, expression): bool =
let option = expression.option let option = expression.option
const default = typeof(option.unsafeGet()).default type T = typeof(option.unsafeGet())
let name {.used.} = if option.isSome: option.unsafeGet() else: default let name {.used.} = if option.isSome: option.unsafeGet() else: placeholder(T)
option.isSome option.isSome
template bindVar(name, expression): bool = template bindVar(name, expression): bool =
let option = expression.option let option = expression.option
var name {.used.} : typeof(option.unsafeGet()) type T = typeof(option.unsafeGet())
var name {.used.} : T = placeholder(T)
if option.isSome: if option.isSome:
name = option.unsafeGet() name = option.unsafeGet()
option.isSome option.isSome

2
testmodules/nim.cfg Normal file
View File

@ -0,0 +1,2 @@
--warningAsError[UnsafeDefault]:"on"
--warningAsError[ProveInit]:"on"

View File

@ -162,6 +162,20 @@ suite "optionals":
check called check called
test "=? works with types that do not have a default value":
type NoDefault {.requiresInit.} = distinct int
proc `==`(a,b: NoDefault): bool {.borrow.}
if a =? some NoDefault(42):
check a == NoDefault(42)
else:
fail()
if var a =? some NoDefault(42):
check a == NoDefault(42)
else:
fail()
test "without statement can be used for early returns": test "without statement can be used for early returns":
proc test1 = proc test1 =
without a =? 42.some: without a =? 42.some: