优化、严格性和不精确的异常可能有点棘手。
重现上述问题的最简单方法是使用NOINLINE
on throwIfNegative
(该函数也没有跨模块边界内联):
import Control.Exception
import Test.HUnit
throwIfNegative :: Int -> String
throwIfNegative n | n < 0 = error "negative"
| otherwise = "no worries"
{-# NOINLINE throwIfNegative #-}
case_negative =
handleJust errorCalls (const $ return ()) $ do
evaluate $ throwIfNegative (-1)
assertFailure "must throw when given a negative number"
where errorCalls (ErrorCall _) = Just ()
main = runTestTT $ TestCase case_negative
阅读核心,优化,GHCevaluate
正确内联(?):
catch#
@ ()
@ SomeException
(\ _ ->
case throwIfNegative (I# (-1)) of _ -> ...
然后throwIfError
在案件审查员之外发出对 的调用:
lvl_sJb :: String
lvl_sJb = throwIfNegative lvl_sJc
lvl_sJc = I# (-1)
throwIfNegative =
\ (n_adO :: Int) ->
case n_adO of _ { I# x_aBb ->
case <# x_aBb 0 of _ {
False -> lvl_sCw; True -> error lvl_sCy
奇怪的是,此时,没有其他代码调用lvl_sJb
,所以整个测试变成了死代码,被剥离了——GHC 已经确定它没有被使用!
使用seq
而不是evaluate
很高兴:
case_negative =
handleJust errorCalls (const $ return ()) $ do
throwIfNegative (-1) `seq` assertFailure "must throw when given a negative number"
where errorCalls (ErrorCall _) = Just ()
或爆炸模式:
case_negative =
handleJust errorCalls (const $ return ()) $ do
let !x = throwIfNegative (-1)
assertFailure "must throw when given a negative number"
where errorCalls (ErrorCall _) = Just ()
所以我认为我们应该看看语义evaluate
:
-- | Forces its argument to be evaluated to weak head normal form when
-- the resultant 'IO' action is executed. It can be used to order
-- evaluation with respect to other 'IO' operations; its semantics are
-- given by
--
-- > evaluate x `seq` y ==> y
-- > evaluate x `catch` f ==> (return $! x) `catch` f
-- > evaluate x >>= f ==> (return $! x) >>= f
--
-- /Note:/ the first equation implies that @(evaluate x)@ is /not/ the
-- same as @(return $! x)@. A correct definition is
--
-- > evaluate x = (return $! x) >>= return
--
evaluate :: a -> IO a
evaluate a = IO $ \s -> let !va = a in (# s, va #) -- NB. see #2273
#2273 错误读起来很有趣。
我认为 GHC 在这里做了一些可疑的事情,建议不要使用evalaute
(而是seq
直接使用)。这需要更多地思考GHC在严格性方面做了什么。
我已经提交了一份错误报告,以帮助获得 GHC 总部的决定。