Difference between revisions of "Unsafe functions"

From HaskellWiki
Jump to navigation Jump to search
m (Typo)
m
 
(8 intermediate revisions by 3 users not shown)
Line 1: Line 1:
  +
<div style="border-left:1px solid lightgray; padding: 1em" alt="blockquote">
  +
A colleague [...] asked me today whether I know how to use <code>unsafePerformIO</code> safely. And I realized I have no idea. [...]
  +
  +
<small>[https://discourse.haskell.org/t/using-unsafeperformio-safely/4146 Richard Eisenberg.]</small>
  +
</div>
  +
  +
<sub> </sub>
 
There are a number of '''unsafe functions''' in the libraries.
 
There are a number of '''unsafe functions''' in the libraries.
   
Line 6: Line 13:
 
* <hask>unsafeIOToST :: IO a -> ST s a</hask>
 
* <hask>unsafeIOToST :: IO a -> ST s a</hask>
 
* <hask>unsafeIOToSTM :: IO a -> STM a</hask>
 
* <hask>unsafeIOToSTM :: IO a -> STM a</hask>
* <hask>unsafeFreeze, unsafeThaw</hask>
+
* <hask>unsafeFreeze</hask>, <hask>unsafeThaw</hask>
 
* <hask>unsafeCoerce# :: a -> b</hask>
 
* <hask>unsafeCoerce# :: a -> b</hask>
 
* <hask>seq :: a -> b -> b</hask>
 
* <hask>seq :: a -> b -> b</hask>
   
Unsafe functions can break type safety (unsafeCoerce#, unsafePerformIO),
+
Unsafe functions can break:
  +
interfere with lazy IO (unsafeInterleaveIO), or break paramatericity (seq).
 
  +
* type safety (<code>unsafeCoerce#</code>, <code>unsafePerformIO</code>),
Their use (except in the case of <hask>seq</hask>) would require some
 
  +
  +
* [https://okmij.org/ftp/Haskell/index.html#lazyIO-not-True equational reasoning] (<code>unsafeInterleaveIO</code>),
  +
  +
* or [http://en.wikipedia.org/wiki/Parametricity parametricity] (<code>seq</code>).
  +
 
Their use (except in the case of <code>seq</code>) would require some
 
kind of assurance on the part of the programmer that what they're doing
 
kind of assurance on the part of the programmer that what they're doing
 
is safe.
 
is safe.
  +
  +
<code>unsafe</code> is also a keyword which can be used in a [http://haskell.org/haskellwiki/Performance/FFI foreign import declaration].
  +
   
 
{{stub}}
 
{{stub}}

Latest revision as of 12:27, 8 June 2023

A colleague [...] asked me today whether I know how to use unsafePerformIO safely. And I realized I have no idea. [...]

Richard Eisenberg.

There are a number of unsafe functions in the libraries.

  • unsafePerformIO :: IO a -> a
  • unsafeInterleaveIO :: IO a -> IO a
  • unsafeInterleaveST :: ST s a -> ST s a
  • unsafeIOToST :: IO a -> ST s a
  • unsafeIOToSTM :: IO a -> STM a
  • unsafeFreeze, unsafeThaw
  • unsafeCoerce# :: a -> b
  • seq :: a -> b -> b

Unsafe functions can break:

  • type safety (unsafeCoerce#, unsafePerformIO),

Their use (except in the case of seq) would require some kind of assurance on the part of the programmer that what they're doing is safe.

unsafe is also a keyword which can be used in a foreign import declaration.


This article is a stub. You can help by expanding it.