Skip to content

Commit

Permalink
Fix: without should work when $ has side effects
Browse files Browse the repository at this point in the history
It's ok to use unsafeError in bindFailed, because we've
already checked that the result contains an error.
  • Loading branch information
markspanbroek committed Mar 10, 2024
1 parent 47692e0 commit 4c03fbe
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 5 deletions.
10 changes: 5 additions & 5 deletions questionable/private/binderror.nim
Original file line number Diff line number Diff line change
Expand Up @@ -21,16 +21,16 @@ macro captureBindError*(error: var ref CatchableError, expression): auto =
# return the evaluated result
evaluated

func error[T](_: Option[T]): ref CatchableError =
func unsafeError[T](_: Option[T]): ref CatchableError =
newException(ValueError, "Option is set to `none`")

func error[T](_: ref T): ref CatchableError =
func unsafeError[T](_: ref T): ref CatchableError =
newException(ValueError, "ref is nil")

func error[T](_: ptr T): ref CatchableError =
func unsafeError[T](_: ptr T): ref CatchableError =
newException(ValueError, "ptr is nil")

func error[Proc: proc | iterator](_: Proc): ref CatchableError =
func unsafeError[Proc: proc | iterator](_: Proc): ref CatchableError =
newException(ValueError, "proc or iterator is nil")

macro bindFailed*(expression: typed) =
Expand All @@ -49,4 +49,4 @@ macro bindFailed*(expression: typed) =
# check that the error variable is in scope
when compiles(`errorVariable`):
# assign bind error to error variable
`errorVariable` = `expression`.error
`errorVariable` = `expression`.unsafeError
13 changes: 13 additions & 0 deletions testmodules/results/test.nim
Original file line number Diff line number Diff line change
Expand Up @@ -643,6 +643,19 @@ suite "result":
someProc(42.success)
someProc(int.failure "some error")

type TypeWithSideEffect = object
proc `$`*(value: TypeWithSideEffect): string {.sideEffect.} =
discard

suite "result side effects":

test "without statement with error works when `$` has side effects":
proc foo =
without x =? TypeWithSideEffect.failure("error"), error:
discard error
return
fail()
foo()

import pkg/questionable/resultsbase

Expand Down

0 comments on commit 4c03fbe

Please sign in to comment.