Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Haskell - Safe and Trustworthy extensions

Tags:

haskell

Looking at some code in hackage I stumbled upon the Safe and Trustworthy extensions.

What do they mean broadly (or also exactly...)? Is there a good rule of thumb on when to use them and when not?

like image 246
marcosh Avatar asked Mar 03 '23 11:03

marcosh


1 Answers

Safe Haskell is in essence a subset of the Haskell language. It aims to disable certain "tricks" that are often used, like for example unsafePerformIO :: IO a -> a, and furthermore it (aims to) guarantee that you do not somehow get access to private functions, data constructors, etc. of a module that aims to prevent access from these. In short safe Haskell guarantees three things:

  1. Referential transparency;
  2. Module boundary control; and
  3. Semantic consistency.

A safe module has to follow these limitations, and furthermore only work with safe modules. A safe module of course does not mean that the code it works with is correct, or that an IO action for example can not be malicious. But it has some guarantees since if a function has a type that has no IO, then normally the module should not be able to perform IO in an unsafe way.

Certain extensions like TemplateHaskell and specifying {-# RULES … #-} pragma's are not allowed in safe Haskell. Other extensions, like DeriveDataTypeable are allowed, but only if one makes use of the deriving clause to generate an instance, and thus not generates a custom one.

Some modules however, need to make use of extensions in order to work properly. In that case, the author can mark the module as Trustworthy. That means that the author claims that the module exposes a safe API, but that it internally need to work with some unsafe extensions, pragmas, etc. The compiler thus can not guarantee safety.

These extensions are documented in the documentation:

The Safe Haskell extension introduces the following three language flags:

  • XSafe — Enables the safe language dialect, asking GHC to guarantee trust. The safe language dialect requires that all imports be trusted or a compilation error will occur.
  • XTrustworthy — Means that while this module may invoke unsafe functions internally, the module's author claims that it exports an API that can't be used in an unsafe way. This doesn't enable the safe language or place any restrictions on the allowed Haskell code. The trust guarantee is provided by the module author, not GHC. An import statement with the safe keyword results in a compilation error if the imported module is not trusted. An import statement without the keyword behaves as usual and can import any module whether trusted or not.
  • XUnsafe — Marks the module being compiled as unsafe so that modules compiled using -XSafe can't import it.
like image 116
Willem Van Onsem Avatar answered Mar 11 '23 08:03

Willem Van Onsem