gpt4 book ai didi

haskell - 我应该让我的 Haskell 模块默认安全吗?

转载 作者:行者123 更新时间:2023-12-04 05:34:28 24 4
gpt4 key购买 nike

标记模块有什么缺点Safe ?它应该是假定的默认值吗?

最佳答案

正如您在 GHC user manual 中所读到的那样, 如果你标记你的模块 Safe ,你被限制在 Haskell 语言的某个“安全”子集中。

  • 您只能导入同样标记为 Safe 的模块(排除了 unsafeCoerceunsafePerformIO 之类的功能)。
  • 您不能使用模板 Haskell。
  • 您不能在 IO 之外使用 FFI .
  • 您不能使用 GeneralisedNewtypeDeriving .
  • 您不能手动实现 Generic您在模块中定义的类型的类型类。

  • 作为交换,模块的用户获得了一堆保证(引自手册):

    • Referential transparency — The types can be trusted. Any pure function, is guaranteed to be pure. Evaluating them is deterministic and won’t cause any side effects. Functions in the IO monad are still allowed and behave as usual. So, for example, the unsafePerformIO ::
      IO a -> a
      function is disallowed in the safe language to enforce this property.
    • Module boundary control — Only symbols that are publicly available through other module export lists can be accessed in the safe language. Values using data constructors not exported by the defining module, cannot be examined or created. As such, if a module M establishes some invariants through careful use of its export list, then code written in the safe language that imports M is guaranteed to respect those invariants.
    • Semantic consistency — For any module that imports a module written in the safe language, expressions that compile both with and without the safe import have the same meaning in both cases. That is, importing a module written in the safe language cannot change the meaning of existing code that isn’t dependent on that module. So, for example, there are some restrictions placed on the use of OverlappingInstances, as these can violate this property.
    • Strict subset — The safe language is strictly a subset of Haskell as implemented by GHC. Any expression that compiles in the safe language has the same meaning as it does when compiled in normal Haskell.


    请注意,安全性是推断出来的。如果您的模块没有标记任何 Safe , Trustworthy , 或 Unsafe , GHC 将模块的安全性推断为 SafeUnsafe .当您设置 Safe标志,那么如果 GHC 确定模块实际上不安全,它将发出错误。您也可以设置 -Wunsafe ,如果模块被推断为不安全,则会发出警告。如果你让它被推断出来,即使你的依赖项的安全状态发生变化,你的模块也会继续编译。如果你把它写出来,你就向你的用户保证安全状态是稳定可靠的。

    手册中描述的一个用例是指运行“不受信任”的代码。如果您在产品中提供任何类型的扩展点,并且您希望确保这些功能不会被用来攻击您的产品,您可以要求将扩展点的代码标记为 Safe .

    您可以标记您的模块 Trustworthy这不会在实现您的模块时以任何方式限制您。您的模块可能从 Safe 开始使用代码然后你有责任不违反保证,这应该由 Safe 给出代码。所以这是一个 promise ,你说模块的作者,给。您可以使用标志 -fpackage-trust在编译标记为 Trustworthy 的模块时启用额外检查描述 here .

    因此,如果您编写普通库并且没有充分的理由关心 Safe Haskell,那么您可能不应该关心。如果您的模块是安全的,那很好并且可以推断。如果不是,那么这可能是有原因的,例如因为您使用了 unsafePerformIO ,这也很好。如果您知道您的模块将以需要在 -XSafe 下编译的方式使用(例如插件,如上所述),你应该这样做。在所有其他情况下,不要打扰。

    关于haskell - 我应该让我的 Haskell 模块默认安全吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52633292/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com