Relax build-deps to allow upcoming `array-0.5.0.0`
[packages/haskell98.git] / IO.hs
1 {-# OPTIONS_GHC -fno-warn-deprecations #-}
2 #if __GLASGOW_HASKELL__ >= 701
3 {-# LANGUAGE Safe #-}
4 #endif
5
6 module IO (
7 Handle, HandlePosn,
8 IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),
9 BufferMode(NoBuffering,LineBuffering,BlockBuffering),
10 SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),
11 stdin, stdout, stderr,
12 openFile, hClose, hFileSize, hIsEOF, isEOF,
13 hSetBuffering, hGetBuffering, hFlush,
14 hGetPosn, hSetPosn, hSeek,
15 hWaitForInput, hReady, hGetChar, hGetLine, hLookAhead, hGetContents,
16 hPutChar, hPutStr, hPutStrLn, hPrint,
17 hIsOpen, hIsClosed, hIsReadable, hIsWritable, hIsSeekable,
18 isAlreadyExistsError, isDoesNotExistError, isAlreadyInUseError,
19 isFullError, isEOFError,
20 isIllegalOperation, isPermissionError, isUserError,
21 ioeGetErrorString, ioeGetHandle, ioeGetFileName,
22 try, bracket, bracket_,
23
24 -- ...and what the Prelude exports
25 IO, FilePath, IOError, ioError, userError, catch, interact,
26 putChar, putStr, putStrLn, print, getChar, getLine, getContents,
27 readFile, writeFile, appendFile, readIO, readLn
28 ) where
29
30 import System.IO
31 import System.IO.Error
32
33 -- | The 'bracket' function captures a common allocate, compute, deallocate
34 -- idiom in which the deallocation step must occur even in the case of an
35 -- error during computation. This is similar to try-catch-finally in Java.
36 --
37 -- This version handles only IO errors, as defined by Haskell 98.
38 -- The version of @bracket@ in "Control.Exception" handles all exceptions,
39 -- and should be used instead.
40
41 bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
42 bracket before after m = do
43 x <- before
44 rs <- try (m x)
45 _ <- after x
46 case rs of
47 Right r -> return r
48 Left e -> ioError e
49
50 -- | A variant of 'bracket' where the middle computation doesn't want @x@.
51 --
52 -- This version handles only IO errors, as defined by Haskell 98.
53 -- The version of @bracket_@ in "Control.Exception" handles all exceptions,
54 -- and should be used instead.
55
56 bracket_ :: IO a -> (a -> IO b) -> IO c -> IO c
57 bracket_ before after m = do
58 x <- before
59 rs <- try m
60 _ <- after x
61 case rs of
62 Right r -> return r
63 Left e -> ioError e
64
65 -- | The construct 'try' @comp@ exposes IO errors which occur within a
66 -- computation, and which are not fully handled.
67 --
68 -- Non-I\/O exceptions are not caught by this variant; to catch all
69 -- exceptions, use 'Control.Exception.try' from "Control.Exception".
70 try :: IO a -> IO (Either IOError a)
71 try f = catch (do r <- f
72 return (Right r))
73 (return . Left)
74