From cfe4c6fc95435b54db0cb6f9d890773015fa502f Mon Sep 17 00:00:00 2001 From: Mark Spanbroek Date: Sat, 4 Dec 2021 17:26:08 +0100 Subject: [PATCH] =?UTF-8?q?Ensure=20that=20=3D=3F=20works=20with=20types?= =?UTF-8?q?=20that=20do=20not=20have=20a=20default=20value?= --- questionable/binding.nim | 10 +++++++--- testmodules/nim.cfg | 2 ++ testmodules/options/test.nim | 14 ++++++++++++++ 3 files changed, 23 insertions(+), 3 deletions(-) create mode 100644 testmodules/nim.cfg diff --git a/questionable/binding.nim b/questionable/binding.nim index a88ffa7..da01187 100644 --- a/questionable/binding.nim +++ b/questionable/binding.nim @@ -4,15 +4,19 @@ import std/macros proc option[T](option: Option[T]): Option[T] = option +proc placeholder(T: type): T = + discard + template bindLet(name, expression): bool = let option = expression.option - const default = typeof(option.unsafeGet()).default - let name {.used.} = if option.isSome: option.unsafeGet() else: default + type T = typeof(option.unsafeGet()) + let name {.used.} = if option.isSome: option.unsafeGet() else: placeholder(T) option.isSome template bindVar(name, expression): bool = let option = expression.option - var name {.used.} : typeof(option.unsafeGet()) + type T = typeof(option.unsafeGet()) + var name {.used.} : T = placeholder(T) if option.isSome: name = option.unsafeGet() option.isSome diff --git a/testmodules/nim.cfg b/testmodules/nim.cfg new file mode 100644 index 0000000..222cb3d --- /dev/null +++ b/testmodules/nim.cfg @@ -0,0 +1,2 @@ +--warningAsError[UnsafeDefault]:"on" +--warningAsError[ProveInit]:"on" diff --git a/testmodules/options/test.nim b/testmodules/options/test.nim index 3733169..ece94fe 100644 --- a/testmodules/options/test.nim +++ b/testmodules/options/test.nim @@ -162,6 +162,20 @@ suite "optionals": 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": proc test1 = without a =? 42.some: