问题描述
我的理解是,没有字段的类型的构造函数是静态分配的,而GHC ,并且像 False
和 Nothing
这样的值是非常安全的(没有错误的否定或肯定),因为它们只能被表示为指向该构造函数的单个实例。
我的推理是否正确?是否有任何潜在的疑难杂症,或者有理由怀疑这可能会在GHC的近期版本中变得不安全? 获得 reallyUnsafePtrEquality
来做错事。
这里是我的最小代码示例
{ - #LANGUAGE MagicHash# - }
导入GHC.Prim
- 很好地包装它
ptrCmp :: a - > a - > Bool
ptrCmp a b = case(reallyUnsafePtrEquality#a b)of
0# - >假
1# - > True
$ b $ main = do
b< - readLn
let a = if b then Nothing else Just()
a'= Nothing
print $ a == a' - Normal
print $ ptrCmp a a' - Evil
以及做一些像
$ ghc --version
Glorious Glasgow Haskell编译系统,版本7.8.2
$ ghc unsafe.hs
$ ./unsafe
True
True
False
所以...是的, reallyUnsafePtrEquality
仍然是邪恶的。
It's my understanding that the constructors of a type which have no fields are "statically allocated" and GHC shares these between all uses, and that the GC will not move these.
If that's correct then I would expect uses of reallyUnsafePtrEquality#
on values like False
and Nothing
to be very safe (no false negatives or positives), because they can only be represented as identical pointers to the single instance of that constructor.
Is my reasoning correct? Are there any potential gotchas, or reasons to suspect that this could become unsafe in near future versions of GHC?
I actually managed to get reallyUnsafePtrEquality
to do the wrong thing.
Here's my minimal code example
{-# LANGUAGE MagicHash #-}
import GHC.Prim
-- Package it up nicely
ptrCmp :: a -> a -> Bool
ptrCmp a b = case (reallyUnsafePtrEquality# a b) of
0# -> False
1# -> True
main = do
b <- readLn
let a = if b then Nothing else Just ()
a' = Nothing
print $ a == a' -- Normal
print $ ptrCmp a a' -- Evil
And doing something like
$ ghc --version
The Glorious Glasgow Haskell Compilation System, version 7.8.2
$ ghc unsafe.hs
$ ./unsafe
True
True
False
So... yes, reallyUnsafePtrEquality
is still evil.
这篇关于reallyUnsafePtrEquality#对于没有字段的构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!