2 % (c) The AQUA Project, Glasgow University, 1994-1998
4 \section[IO]{Module @IO@}
6 Implementation of the standard Haskell IO interface, see
7 @http://haskell.org/onlinelibrary/io.html@ for the official
11 {-# OPTIONS -fno-implicit-prelude -#include "cbits/stgio.h" #-}
14 Handle, -- abstract, instance of: Eq, Show.
15 HandlePosn(..), -- abstract, instance of: Eq, Show.
17 IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),
18 BufferMode(NoBuffering,LineBuffering,BlockBuffering),
19 SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),
21 stdin, stdout, stderr, -- :: Handle
23 openFile, -- :: FilePath -> IOMode -> IO Handle
24 hClose, -- :: Handle -> IO ()
25 hFileSize, -- :: Handle -> IO Integer
26 hIsEOF, -- :: Handle -> IO Bool
29 hSetBuffering, -- :: Handle -> BufferMode -> IO ()
30 hGetBuffering, -- :: Handle -> IO BufferMode
31 hFlush, -- :: Handle -> IO ()
32 hGetPosn, -- :: Handle -> IO HandlePosn
33 hSetPosn, -- :: Handle -> HandlePosn -> IO ()
34 hSeek, -- :: Handle -> SeekMode -> Integer -> IO ()
35 hWaitForInput, -- :: Handle -> Int -> IO Bool
36 hReady, -- :: Handle -> IO Bool
37 hGetChar, -- :: Handle -> IO Char
38 hGetLine, -- :: Handle -> IO [Char]
39 hLookAhead, -- :: Handle -> IO Char
40 hGetContents, -- :: Handle -> IO [Char]
41 hPutChar, -- :: Handle -> Char -> IO ()
42 hPutStr, -- :: Handle -> [Char] -> IO ()
43 hPutStrLn, -- :: Handle -> [Char] -> IO ()
44 hPrint, -- :: Show a => Handle -> a -> IO ()
45 hIsOpen, hIsClosed, -- :: Handle -> IO Bool
46 hIsReadable, hIsWritable, -- :: Handle -> IO Bool
47 hIsSeekable, -- :: Handle -> IO Bool
49 isAlreadyExistsError, isDoesNotExistError, -- :: IOError -> Bool
50 isAlreadyInUseError, isFullError,
51 isEOFError, isIllegalOperation,
52 isPermissionError, isUserError,
54 ioeGetErrorString, -- :: IOError -> String
55 ioeGetHandle, -- :: IOError -> Maybe Handle
56 ioeGetFileName, -- :: IOError -> Maybe FilePath
58 try, -- :: IO a -> IO (Either IOError a)
59 bracket, -- :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
60 bracket_, -- :: IO a -> (a -> IO b) -> IO c -> IO c
72 import PrelHandle -- much of the real stuff is in here
74 import PrelRead ( readParen, Read(..), reads, lex )
75 import PrelNum ( toInteger )
76 import PrelBounded () -- Bounded Int instance.
77 import PrelEither ( Either(..) )
78 import PrelAddr ( Addr(..), nullAddr )
79 import PrelArr ( ByteArray )
80 import PrelPack ( unpackNBytesAccST )
82 #ifndef __PARALLEL_HASKELL__
83 import PrelForeign ( ForeignObj )
86 import Char ( ord, chr )
90 Standard instances for @Handle@:
93 instance Eq IOError where
94 (IOError h1 e1 loc1 str1) == (IOError h2 e2 loc2 str2) =
95 e1==e2 && str1==str2 && h1==h2 && loc1 == loc2
97 instance Eq Handle where
98 (Handle h1) == (Handle h2) = h1 == h2
100 --Type declared in IOHandle, instance here because it depends on Eq.Handle
101 instance Eq HandlePosn where
102 (HandlePosn h1 p1) == (HandlePosn h2 p2) = p1==p2 && h1==h2
104 -- Type declared in IOBase, instance here because it
105 -- depends on PrelRead.(Read Maybe) instance.
106 instance Read BufferMode where
109 (\r -> let lr = lex r
111 [(NoBuffering, rest) | ("NoBuffering", rest) <- lr] ++
112 [(LineBuffering,rest) | ("LineBuffering",rest) <- lr] ++
113 [(BlockBuffering mb,rest2) | ("BlockBuffering",rest1) <- lr,
114 (mb, rest2) <- reads rest1])
118 %*********************************************************
120 \subsection{Simple input operations}
122 %*********************************************************
124 Computation @hReady hdl@ indicates whether at least
125 one item is available for input from handle {\em hdl}.
127 @hWaitForInput@ is the generalisation, wait for \tr{n} milliseconds
128 before deciding whether the Handle has run dry or not.
130 If @hWaitForInput@ finds anything in the Handle's buffer, it immediately returns.
131 If not, it tries to read from the underlying OS handle. Notice that
132 for buffered Handles connected to terminals this means waiting until a complete
136 hReady :: Handle -> IO Bool
137 hReady h = hWaitForInput h 0
139 hWaitForInput :: Handle -> Int -> IO Bool
140 hWaitForInput handle msecs = do
141 handle_ <- wantReadableHandle "hWaitForInput" handle
142 rc <- _ccall_ inputReady (haFO__ handle_) (msecs::Int) -- ConcHask: SAFE, won't block
143 writeHandle handle handle_
147 _ -> constructErrorAndFail "hWaitForInput"
150 @hGetChar hdl@ reads the next character from handle @hdl@,
151 blocking until a character is available.
154 hGetChar :: Handle -> IO Char
156 handle_ <- wantReadableHandle "hGetChar" handle
157 let fo = haFO__ handle_
158 intc <- mayBlock fo (_ccall_ fileGetc fo) -- ConcHask: UNSAFE, may block
159 writeHandle handle handle_
161 then return (chr intc)
162 else constructErrorAndFail "hGetChar"
164 hGetLine :: Handle -> IO String
175 @hLookahead hdl@ returns the next character from handle @hdl@
176 without removing it from the input buffer, blocking until a
177 character is available.
180 hLookAhead :: Handle -> IO Char
181 hLookAhead handle = do
182 handle_ <- wantReadableHandle "hLookAhead" handle
183 let fo = haFO__ handle_
184 intc <- mayBlock fo (_ccall_ fileLookAhead fo) -- ConcHask: UNSAFE, may block
185 writeHandle handle handle_
187 then return (chr intc)
188 else constructErrorAndFail "hLookAhead"
193 %*********************************************************
195 \subsection{Getting the entire contents of a handle}
197 %*********************************************************
199 @hGetContents hdl@ returns the list of characters corresponding
200 to the unread portion of the channel or file managed by @hdl@,
201 which is made semi-closed.
204 hGetContents :: Handle -> IO String
205 hGetContents handle = do
206 handle_ <- wantReadableHandle "hGetContents" handle
208 To avoid introducing an extra layer of buffering here,
209 we provide three lazy read methods, based on character,
210 line, and block buffering.
212 writeHandle handle (handle_{ haType__ = SemiClosedHandle })
213 case (haBufferMode__ handle_) of
214 LineBuffering -> unsafeInterleaveIO (lazyReadLine handle (haFO__ handle_))
215 BlockBuffering _ -> unsafeInterleaveIO (lazyReadBlock handle (haFO__ handle_))
216 NoBuffering -> unsafeInterleaveIO (lazyReadChar handle (haFO__ handle_))
220 Note that someone may close the semi-closed handle (or change its buffering),
221 so each these lazy read functions are pulled on, they have to check whether
222 the handle has indeed been closed.
225 #ifndef __PARALLEL_HASKELL__
226 lazyReadBlock :: Handle -> ForeignObj -> IO String
227 lazyReadLine :: Handle -> ForeignObj -> IO String
228 lazyReadChar :: Handle -> ForeignObj -> IO String
230 lazyReadBlock :: Handle -> Addr -> IO String
231 lazyReadLine :: Handle -> Addr -> IO String
232 lazyReadChar :: Handle -> Addr -> IO String
235 lazyReadBlock handle fo = do
236 buf <- _ccall_ getBufStart fo (0::Int)
237 bytes <- mayBlock fo (_ccall_ readBlock fo) -- ConcHask: UNSAFE, may block.
239 -3 -> -- buffering has been turned off, use lazyReadChar instead
240 lazyReadChar handle fo
242 -1 -> do -- an error occurred, close the handle
243 handle_ <- readHandle handle
244 _ccall_ closeFile (haFO__ handle_) 0{-don't bother flushing-} -- ConcHask: SAFE, won't block.
245 writeHandle handle (handle_ { haType__ = ClosedHandle,
246 haFO__ = nullFile__ })
249 more <- unsafeInterleaveIO (lazyReadBlock handle fo)
250 stToIO (unpackNBytesAccST buf bytes more)
252 lazyReadLine handle fo = do
253 bytes <- mayBlock fo (_ccall_ readLine fo) -- ConcHask: UNSAFE, may block.
255 -3 -> -- buffering has been turned off, use lazyReadChar instead
256 lazyReadChar handle fo
257 -2 -> return "" -- handle closed by someone else, stop reading.
258 -1 -> do -- an error occurred, close the handle
259 handle_ <- readHandle handle
260 _ccall_ closeFile (haFO__ handle_) 0{- don't bother flushing-} -- ConcHask: SAFE, won't block
261 writeHandle handle (handle_ { haType__ = ClosedHandle,
262 haFO__ = nullFile__ })
265 more <- unsafeInterleaveIO (lazyReadLine handle fo)
266 buf <- _ccall_ getBufStart fo bytes -- ConcHask: won't block
267 stToIO (unpackNBytesAccST buf bytes more)
269 lazyReadChar handle fo = do
270 char <- mayBlock fo (_ccall_ readChar fo) -- ConcHask: UNSAFE, may block.
272 -4 -> -- buffering is now block-buffered, use lazyReadBlock instead
273 lazyReadBlock handle fo
275 -3 -> -- buffering is now line-buffered, use lazyReadLine instead
276 lazyReadLine handle fo
278 -1 -> do -- error, silently close handle.
279 handle_ <- readHandle handle
280 _ccall_ closeFile (haFO__ handle_) 0{-don't bother flusing-} -- ConcHask: SAFE, won't block
281 writeHandle handle (handle_{ haType__ = ClosedHandle,
282 haFO__ = nullFile__ })
285 more <- unsafeInterleaveIO (lazyReadChar handle fo)
286 return (chr char : more)
291 %*********************************************************
293 \subsection{Simple output functions}
295 %*********************************************************
297 @hPutChar hdl ch@ writes the character @ch@ to the file
298 or channel managed by @hdl@. Characters may be buffered if
299 buffering is enabled for @hdl@
302 hPutChar :: Handle -> Char -> IO ()
303 hPutChar handle c = do
304 handle_ <- wantWriteableHandle "hPutChar" handle
305 let fo = haFO__ handle_
306 rc <- mayBlock fo (_ccall_ filePutc fo (ord c)) -- ConcHask: UNSAFE, may block.
307 writeHandle handle handle_
310 else constructErrorAndFail "hPutChar"
314 @hPutStr hdl s@ writes the string @s@ to the file or
315 channel managed by @hdl@, buffering the output if needs be.
318 hPutStr :: Handle -> String -> IO ()
319 hPutStr handle str = do
320 handle_ <- wantWriteableHandle "hPutStr" handle
321 let fo = haFO__ handle_
322 case haBufferMode__ handle_ of
324 buf <- _ccall_ getWriteableBuf fo
325 pos <- _ccall_ getBufWPtr fo
326 bsz <- _ccall_ getBufSize fo
327 writeLines fo buf bsz pos str
328 BlockBuffering _ -> do
329 buf <- _ccall_ getWriteableBuf fo
330 pos <- _ccall_ getBufWPtr fo
331 bsz <- _ccall_ getBufSize fo
332 writeBlocks fo buf bsz pos str
335 writeHandle handle handle_
339 Going across the border between Haskell and C is relatively costly,
340 so for block writes we pack the character strings on the Haskell-side
341 before passing the external write routine a pointer to the buffer.
345 #ifndef __PARALLEL_HASKELL__
346 writeLines :: ForeignObj -> Addr -> Int -> Int -> String -> IO ()
348 writeLines :: Addr -> Addr -> Int -> Int -> String -> IO ()
350 writeLines obj buf bf@(I# bufLen) (I# initPos#) s =
352 write_char :: Addr -> Int# -> Char# -> IO ()
353 write_char (A# buf) n# c# =
355 case (writeCharOffAddr# buf n# c# s#) of s2# -> IOok s2# ()
357 shoveString :: Int# -> [Char] -> IO ()
362 _ccall_ setBufWPtr obj (0::Int)
365 At the end of a buffer write, update the buffer position
366 in the underlying file object, so that if the handle
367 is subsequently dropped by the program, the whole
368 buffer will be properly flushed.
370 There's one case where this delayed up-date of the buffer
371 position can go wrong: if a thread is killed, it might be
372 in the middle of filling up a buffer, with the result that
373 the partial buffer update is lost upon finalisation. Not
374 that killing of threads is supported at the moment.
377 _ccall_ setBufWPtr obj (I# n)
381 {- Flushing on buffer exhaustion or newlines (even if it isn't the last one) -}
382 if n ==# bufLen || x `eqChar#` '\n'#
384 rc <- mayBlock obj (_ccall_ writeFileObject obj (I# (n +# 1#))) -- ConcHask: UNSAFE, may block.
386 then shoveString 0# xs
387 else constructErrorAndFail "writeLines"
389 shoveString (n +# 1#) xs
391 shoveString initPos# s
393 #ifndef __PARALLEL_HASKELL__
394 writeBlocks :: ForeignObj -> Addr -> Int -> Int -> String -> IO ()
396 writeBlocks :: Addr -> Addr -> Int -> Int -> String -> IO ()
398 writeBlocks obj buf bf@(I# bufLen) (I# initPos#) s =
400 write_char :: Addr -> Int# -> Char# -> IO ()
401 write_char (A# buf) n# c# =
403 case (writeCharOffAddr# buf n# c# s#) of s2# -> IOok s2# ()
405 shoveString :: Int# -> [Char] -> IO ()
410 _ccall_ setBufWPtr obj (0::Int)
413 At the end of a buffer write, update the buffer position
414 in the underlying file object, so that if the handle
415 is subsequently dropped by the program, the whole
416 buffer will be properly flushed.
418 There's one case where this delayed up-date of the buffer
419 position can go wrong: if a thread is killed, it might be
420 in the middle of filling up a buffer, with the result that
421 the partial buffer update is lost upon finalisation. However,
422 by the time killThread is supported, Haskell finalisers are also
423 likely to be in, which means the 'IOFileObject' hack can go
427 _ccall_ setBufWPtr obj (I# n)
433 rc <- mayBlock obj (_ccall_ writeFileObject obj (I# (n +# 1#))) -- ConcHask: UNSAFE, may block.
435 then shoveString 0# xs
436 else constructErrorAndFail "writeChunks"
438 shoveString (n +# 1#) xs
440 shoveString initPos# s
442 #ifndef __PARALLEL_HASKELL__
443 writeChars :: ForeignObj -> String -> IO ()
445 writeChars :: Addr -> String -> IO ()
447 writeChars fo "" = return ()
448 writeChars fo (c:cs) = do
449 rc <- mayBlock fo (_ccall_ filePutc fo (ord c)) -- ConcHask: UNSAFE, may block.
451 then writeChars fo cs
452 else constructErrorAndFail "writeChars"
456 Computation @hPrint hdl t@ writes the string representation of {\em t}
457 given by the @shows@ function to the file or channel managed by {\em
460 [ Seem to have disappeared from the 1.4 interface - SOF 2/97 ]
463 hPrint :: Show a => Handle -> a -> IO ()
464 hPrint hdl = hPutStr hdl . show
467 Derived action @hPutStrLn hdl str@ writes the string \tr{str} to
468 the handle \tr{hdl}, adding a newline at the end.
471 hPutStrLn :: Handle -> String -> IO ()
472 hPutStrLn hndl str = do
479 %*********************************************************
481 \subsection{Try and bracket}
483 %*********************************************************
485 The construct $try comp$ exposes errors which occur within a
486 computation, and which are not fully handled. It always succeeds.
489 try :: IO a -> IO (Either IOError a)
490 try f = catch (do r <- f
494 bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
495 bracket before after m = do
503 -- variant of the above where middle computation doesn't want x
504 bracket_ :: IO a -> (a -> IO b) -> IO c -> IO c
505 bracket_ before after m = do