2 % (c) The AQUA Project, Glasgow University, 1994-1996
5 \section[IO]{Module @IO@}
8 {-# OPTIONS -fno-implicit-prelude -#include "cbits/stgio.h" #-}
13 IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),
14 BufferMode(NoBuffering,LineBuffering,BlockBuffering),
15 SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),
17 stdin, stdout, stderr,
20 hFileSize, hIsEOF, isEOF,
21 hSetBuffering, hGetBuffering, hFlush,
22 hGetPosn, hSetPosn, hSeek,
23 hWaitForInput, hReady, hGetChar, hGetLine, hLookAhead, hGetContents,
24 hPutChar, hPutStr, hPutStrLn, hPrint,
25 hIsOpen, hIsClosed, hIsReadable, hIsWritable, hIsSeekable,
27 isAlreadyExistsError, isDoesNotExistError, isAlreadyInUseError,
28 isFullError, isEOFError,
29 isIllegalOperation, isPermissionError, isUserError,
31 ioeGetHandle, ioeGetFileName,
32 try, bracket, bracket_
37 import Unsafe ( unsafePerformIO, unsafeInterleaveIO )
39 import ArrBase ( MutableByteArray(..), newCharArray )
40 import IOHandle -- much of the real stuff is in here
41 import PackBase ( unpackNBytesST )
46 #ifndef __PARALLEL_HASKELL__
47 import Foreign ( ForeignObj, makeForeignObj, writeForeignObj )
50 import Char ( ord, chr )
53 %*********************************************************
55 \subsection{Signatures}
57 %*********************************************************
60 --IOHandle:hClose :: Handle -> IO ()
61 --IOHandle:hFileSize :: Handle -> IO Integer
62 --IOHandle:hFlush :: Handle -> IO ()
63 --IOHandle:hGetBuffering :: Handle -> IO BufferMode
64 hGetChar :: Handle -> IO Char
65 hGetContents :: Handle -> IO String
66 --IOHandle:hGetPosn :: Handle -> IO HandlePosn
67 --IOHandle:hIsClosed :: Handle -> IO Bool
68 --IOHandle:hIsEOF :: Handle -> IO Bool
69 --IOHandle:hIsOpen :: Handle -> IO Bool
70 --IOHandle:hIsReadable :: Handle -> IO Bool
71 --IOHandle:hIsSeekable :: Handle -> IO Bool
72 --IOHandle:hIsWritable :: Handle -> IO Bool
73 hLookAhead :: Handle -> IO Char
74 hPrint :: Show a => Handle -> a -> IO ()
75 hPutChar :: Handle -> Char -> IO ()
76 hPutStr :: Handle -> String -> IO ()
77 hPutStrLn :: Handle -> String -> IO ()
78 hReady :: Handle -> IO Bool
79 hWaitForInput :: Handle -> Int -> IO Bool
81 --IOHandle:hSeek :: Handle -> SeekMode -> Integer -> IO ()
82 --IOHandle:hSetBuffering :: Handle -> BufferMode -> IO ()
83 --IOHandle:hSetPosn :: HandlePosn -> IO ()
84 -- ioeGetFileName :: IOError -> Maybe FilePath
85 -- ioeGetErrorString :: IOError -> Maybe String
86 -- ioeGetHandle :: IOError -> Maybe Handle
87 -- isAlreadyExistsError :: IOError -> Bool
88 -- isAlreadyInUseError :: IOError -> Bool
89 --IOHandle:isEOF :: IO Bool
90 -- isEOFError :: IOError -> Bool
91 -- isFullError :: IOError -> Bool
92 -- isIllegalOperation :: IOError -> Bool
93 -- isPermissionError :: IOError -> Bool
94 -- isUserError :: IOError -> Maybe String
95 --IOHandle:openFile :: FilePath -> IOMode -> IO Handle
96 --IOHandle:stdin, stdout, stderr :: Handle
99 Standard instances for @Handle@:
102 instance Eq IOError where
103 (IOError h1 e1 str1) == (IOError h2 e2 str2) =
104 e1==e2 && str1==str2 && h1==h2
106 instance Eq Handle where
115 (ErrorHandle (IOError h1 _ _), ErrorHandle (IOError h2 _ _)) -> h1 == h2
116 (ClosedHandle, ClosedHandle) -> True
117 (SemiClosedHandle v1 _, SemiClosedHandle v2 _) -> v1 == v2
118 (ReadHandle v1 _ _ , ReadHandle v2 _ _) -> v1 == v2
119 (WriteHandle v1 _ _ , WriteHandle v2 _ _) -> v1 == v2
120 (AppendHandle v1 _ _ , AppendHandle v2 _ _) -> v1 == v2
121 (ReadWriteHandle v1 _ _ , ReadWriteHandle v2 _ _) -> v1 == v2
124 instance Show Handle where {showsPrec p h = showString "<<Handle>>"}
126 --Type declared in IOHandle, instance here because it depends on Eq.Handle
127 instance Eq HandlePosn where
128 (HandlePosn h1 p1) == (HandlePosn h2 p2) = p1==p2 && h1==h2
132 %*********************************************************
134 \subsection{Simple input operations}
136 %*********************************************************
138 Computation @hReady hdl@ indicates whether at least
139 one item is available for input from handle {\em hdl}.
141 @hWaitForInput@ is the generalisation, wait for \tr{n} seconds
142 before deciding whether the Handle has run dry or not.
145 --hReady :: Handle -> IO Bool
146 hReady h = hWaitForInput h 0
148 --hWaitForInput :: Handle -> Int -> IO Bool
149 hWaitForInput handle nsecs = do
150 htype <- readHandle handle
152 ErrorHandle ioError -> do
153 writeHandle handle htype
156 writeHandle handle htype
157 ioe_closedHandle handle
158 SemiClosedHandle _ _ -> do
159 writeHandle handle htype
160 ioe_closedHandle handle
161 AppendHandle _ _ _ -> do
162 writeHandle handle htype
163 fail (IOError (Just handle) IllegalOperation
164 "handle is not open for reading")
165 WriteHandle _ _ _ -> do
166 writeHandle handle htype
167 fail (IOError (Just handle) IllegalOperation
168 "handle is not open for reading")
170 rc <- _ccall_ inputReady (filePtr other) nsecs
171 writeHandle handle (markHandle htype)
175 _ -> constructErrorAndFail "hWaitForInput"
178 Computation $hGetChar hdl$ reads the next character from handle
179 {\em hdl}, blocking until a character is available.
182 --hGetChar :: Handle -> IO Char
185 htype <- readHandle handle
187 ErrorHandle ioError ->
188 writeHandle handle htype >>
191 writeHandle handle htype >>
192 ioe_closedHandle handle
193 SemiClosedHandle _ _ ->
194 writeHandle handle htype >>
195 ioe_closedHandle handle
196 AppendHandle _ _ _ ->
197 writeHandle handle htype >>
198 fail (IOError (Just handle) IllegalOperation "handle is not open for reading")
200 writeHandle handle htype >>
201 fail (IOError (Just handle) IllegalOperation "handle is not open for reading")
203 intc <- _ccall_ fileGetc (filePtr other)
204 writeHandle handle (markHandle htype)
205 if intc /= ``EOF'' then
208 constructErrorAndFail "hGetChar"
210 hGetLine :: Handle -> IO String
212 hGetChar h >>= \ c ->
216 hGetLine h >>= \ s -> return (c:s)
219 Computation $hLookahead hdl$ returns the next character from handle
220 {\em hdl} without removing it from the input buffer, blocking until a
221 character is available.
224 --hLookAhead :: Handle -> IO Char
227 readHandle handle >>= \ htype ->
229 ErrorHandle ioError ->
230 writeHandle handle htype >>
233 writeHandle handle htype >>
234 ioe_closedHandle handle
235 SemiClosedHandle _ _ ->
236 writeHandle handle htype >>
237 ioe_closedHandle handle
238 AppendHandle _ _ _ ->
239 writeHandle handle htype >>
240 fail (IOError (Just handle) IllegalOperation "handle is not open for reading")
242 writeHandle handle htype >>
243 fail (IOError (Just handle) IllegalOperation "handle is not open for reading")
245 intc <- _ccall_ fileLookAhead (filePtr other)
246 writeHandle handle (markHandle htype)
247 if intc /= ``EOF'' then
250 constructErrorAndFail "hLookAhead"
254 %*********************************************************
256 \subsection{Getting the entire contents of a handle}
258 %*********************************************************
260 Computation $hGetContents hdl$ returns the list of characters
261 corresponding to the unread portion of the channel or file managed by
262 {\em hdl}, which is made semi-closed.
265 --hGetContents :: Handle -> IO String
267 hGetContents handle =
268 readHandle handle >>= \ htype ->
270 ErrorHandle ioError ->
271 writeHandle handle htype >>
274 writeHandle handle htype >>
275 ioe_closedHandle handle
276 SemiClosedHandle _ _ ->
277 writeHandle handle htype >>
278 ioe_closedHandle handle
279 AppendHandle _ _ _ ->
280 writeHandle handle htype >>
281 fail (IOError (Just handle) IllegalOperation "handle is not open for reading")
283 writeHandle handle htype >>
284 fail (IOError (Just handle) IllegalOperation "handle is not open for reading")
287 To avoid introducing an extra layer of buffering here,
288 we provide three lazy read methods, based on character,
289 line, and block buffering.
291 getBufferMode other >>= \ other ->
292 case (bufferMode other) of
293 Just LineBuffering ->
294 allocBuf Nothing >>= \ buf_info ->
295 writeHandle handle (SemiClosedHandle (filePtr other) buf_info)
297 unsafeInterleaveIO (lazyReadLine handle)
301 Just (BlockBuffering size) ->
302 allocBuf size >>= \ buf_info ->
303 writeHandle handle (SemiClosedHandle (filePtr other) buf_info)
305 unsafeInterleaveIO (lazyReadBlock handle)
308 _ -> -- Nothing is treated pessimistically as NoBuffering
309 writeHandle handle (SemiClosedHandle (filePtr other) (``NULL'', 0))
311 unsafeInterleaveIO (lazyReadChar handle) >>= \ contents ->
314 allocBuf :: Maybe Int -> IO (Addr, Int)
316 _ccall_ malloc size >>= \ buf ->
317 if buf /= ``NULL'' then
320 fail (IOError Nothing ResourceExhausted "not enough virtual memory")
325 Nothing -> ``BUFSIZ''
328 Note that someone may yank our handle out from under us, and then re-use
329 the same FILE * for something else. Therefore, we have to re-examine the
330 handle every time through.
333 lazyReadBlock :: Handle -> IO String
334 lazyReadLine :: Handle -> IO String
335 lazyReadChar :: Handle -> IO String
337 lazyReadBlock handle =
338 readHandle handle >>= \ htype ->
340 -- There cannae be an ErrorHandle here
342 writeHandle handle htype >>
344 SemiClosedHandle fp (buf, size) ->
345 _ccall_ readBlock buf fp size >>= \ bytes ->
348 else stToIO (unpackNBytesST buf bytes)) >>= \ some ->
350 _ccall_ free buf >>= \ () ->
351 _ccall_ closeFile fp >>
352 #ifndef __PARALLEL_HASKELL__
353 writeForeignObj fp ``NULL'' >>
354 writeHandle handle (SemiClosedHandle fp (``NULL'', 0)) >>
356 writeHandle handle (SemiClosedHandle ``NULL'' (``NULL'', 0)) >>
360 writeHandle handle htype >>
361 unsafeInterleaveIO (lazyReadBlock handle) >>= \ more ->
362 return (some ++ more)
364 lazyReadLine handle =
365 readHandle handle >>= \ htype ->
367 -- There cannae be an ErrorHandle here
369 writeHandle handle htype >>
371 SemiClosedHandle fp (buf, size) ->
372 _ccall_ readLine buf fp size >>= \ bytes ->
375 else stToIO (unpackNBytesST buf bytes)) >>= \ some ->
377 _ccall_ free buf >>= \ () ->
378 _ccall_ closeFile fp >>
379 #ifndef __PARALLEL_HASKELL__
380 writeForeignObj fp ``NULL'' >>
381 writeHandle handle (SemiClosedHandle fp (``NULL'', 0)) >>
383 writeHandle handle (SemiClosedHandle ``NULL'' (``NULL'', 0)) >>
387 writeHandle handle htype >>
388 unsafeInterleaveIO (lazyReadLine handle)
390 return (some ++ more)
392 lazyReadChar handle =
393 readHandle handle >>= \ htype ->
395 -- There cannae be an ErrorHandle here
397 writeHandle handle htype >>
399 SemiClosedHandle fp buf_info ->
400 _ccall_ readChar fp >>= \ char ->
401 if char == ``EOF'' then
402 _ccall_ closeFile fp >>
403 #ifndef __PARALLEL_HASKELL__
404 writeForeignObj fp ``NULL'' >>
405 writeHandle handle (SemiClosedHandle fp (``NULL'', 0)) >>
407 writeHandle handle (SemiClosedHandle ``NULL'' (``NULL'', 0)) >>
411 writeHandle handle htype >>
412 unsafeInterleaveIO (lazyReadChar handle) >>= \ more ->
413 return (chr char : more)
418 %*********************************************************
420 \subsection{Simple output functions}
422 %*********************************************************
424 Computation $hPutChar hdl c$ writes the character {\em c} to the file
425 or channel managed by {\em hdl}. Characters may be buffered if
426 buffering is enabled for {\em hdl}.
429 --hPutChar :: Handle -> Char -> IO ()
432 readHandle handle >>= \ htype ->
434 ErrorHandle ioError ->
435 writeHandle handle htype >>
438 writeHandle handle htype >>
439 ioe_closedHandle handle
440 SemiClosedHandle _ _ ->
441 writeHandle handle htype >>
442 ioe_closedHandle handle
444 writeHandle handle htype >>
445 fail (IOError (Just handle) IllegalOperation "handle is not open for writing")
447 _ccall_ filePutc (filePtr other) (ord c) >>= \ rc ->
448 writeHandle handle (markHandle htype) >>
452 constructErrorAndFail "hPutChar"
455 Computation $hPutStr hdl s$ writes the string {\em s} to the file or
456 channel managed by {\em hdl}.
459 --hPutStr :: Handle -> String -> IO ()
462 readHandle handle >>= \ htype ->
464 ErrorHandle ioError ->
465 writeHandle handle htype >>
468 writeHandle handle htype >>
469 ioe_closedHandle handle
470 SemiClosedHandle _ _ ->
471 writeHandle handle htype >>
472 ioe_closedHandle handle
474 writeHandle handle htype >>
475 fail (IOError (Just handle) IllegalOperation "handle is not open for writing")
478 The code below is not correct for line-buffered terminal streams,
479 as the output stream is not flushed when terminal input is requested
480 again, just upon seeing a newline character. A temporary fix for the
481 most common line-buffered output stream, stdout, is to assume the
482 buffering it was given when created (no buffering). This is not
483 as bad as it looks, since stdio buffering sits underneath this.
487 getBufferMode other >>= \ other ->
488 (case bufferMode other of
489 Just LineBuffering ->
490 writeChars (filePtr other) str
491 --writeLines (filePtr other) str
492 Just (BlockBuffering (Just size)) ->
493 writeBlocks (filePtr other) size str
494 Just (BlockBuffering Nothing) ->
495 writeBlocks (filePtr other) ``BUFSIZ'' str
496 _ -> -- Nothing is treated pessimistically as NoBuffering
497 writeChars (filePtr other) str
499 writeHandle handle (markHandle other) >>
503 constructErrorAndFail "hPutStr"
505 #ifndef __PARALLEL_HASKELL__
506 writeLines :: ForeignObj -> String -> IO Bool
508 writeLines :: Addr -> String -> IO Bool
510 writeLines = writeChunks ``BUFSIZ'' True
512 #ifndef __PARALLEL_HASKELL__
513 writeBlocks :: ForeignObj -> Int -> String -> IO Bool
515 writeBlocks :: Addr -> Int -> String -> IO Bool
517 writeBlocks fp size s = writeChunks size False fp s
520 The breaking up of output into lines along \n boundaries
521 works fine as long as there are newlines to split by.
522 Avoid the splitting up into lines alltogether (doesn't work
523 for overly long lines like the stuff that showsPrec instances
524 normally return). Instead, we split them up into fixed size
525 chunks before blasting them off to the Real World.
527 Hacked to avoid multiple passes over the strings - unsightly, but
528 a whole lot quicker. -- SOF 3/96
531 #ifndef __PARALLEL_HASKELL__
532 writeChunks :: Int -> Bool -> ForeignObj -> String -> IO Bool
534 writeChunks :: Int -> Bool -> Addr -> String -> IO Bool
536 writeChunks (I# bufLen) chopOnNewLine fp s =
537 stToIO (newCharArray (0,I# bufLen)) >>= \ arr@(MutableByteArray _ arr#) ->
539 write_char :: MutableByteArray# RealWorld -> Int# -> Char# -> IO ()
540 write_char arr# n x = IO $ \ s# ->
541 case (writeCharArray# arr# n x s#) of { s1# ->
544 shoveString :: Int# -> [Char] -> IO Bool
551 _ccall_ writeFile arr fp (I# n) >>= \rc ->
555 write_char arr# n x >>
557 {- Flushing lines - should we bother? Yes, for line-buffered output. -}
558 if n ==# bufLen || (chopOnNewLine && (x `eqChar#` '\n'#)) then
559 _ccall_ writeFile arr fp (I# (n +# 1#)) >>= \ rc ->
565 shoveString (n +# 1#) xs
569 #ifndef __PARALLEL_HASKELL__
570 writeChars :: ForeignObj -> String -> IO Bool
572 writeChars :: Addr -> String -> IO Bool
574 writeChars fp "" = return True
575 writeChars fp (c:cs) =
576 _ccall_ filePutc fp (ord c) >>= \ rc ->
583 Computation $hPrint hdl t$ writes the string representation of {\em t}
584 given by the $shows$ function to the file or channel managed by {\em
587 SOF 2/97: Seem to have disappeared in 1.4 libs.
590 --hPrint :: Show a => Handle -> a -> IO ()
591 hPrint hdl = hPutStr hdl . show
594 Derived action @hPutStrLn hdl str@ writes the string \tr{str} to
595 the handle \tr{hdl}, adding a newline at the end.
598 --hPutStrLn :: Handle -> String -> IO ()
599 hPutStrLn hndl str = do
606 %*********************************************************
608 \subsection{Try and bracket}
610 %*********************************************************
612 The construct $try comp$ exposes errors which occur within a
613 computation, and which are not fully handled. It always succeeds.
616 try :: IO a -> IO (Either IOError a)
617 try f = catch (do r <- f
621 bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
622 bracket before after m = do
630 -- variant of the above where middle computation doesn't want x
631 bracket_ :: IO a -> (a -> IO b) -> IO c -> IO c
632 bracket_ before after m = do