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 PrelArr ( MutableByteArray(..), newCharArray )
38 import PrelHandle -- much of the real stuff is in here
39 import PrelPack ( unpackNBytesST )
41 import PrelRead ( readParen, Read(..), reads, lex )
47 #ifndef __PARALLEL_HASKELL__
48 import PrelForeign ( ForeignObj, makeForeignObj, writeForeignObj )
52 import Char ( ord, chr )
55 %*********************************************************
57 \subsection{Signatures}
59 %*********************************************************
62 --IOHandle:hClose :: Handle -> IO ()
63 --IOHandle:hFileSize :: Handle -> IO Integer
64 --IOHandle:hFlush :: Handle -> IO ()
65 --IOHandle:hGetBuffering :: Handle -> IO BufferMode
66 hGetChar :: Handle -> IO Char
67 hGetContents :: Handle -> IO String
68 --IOHandle:hGetPosn :: Handle -> IO HandlePosn
69 --IOHandle:hIsClosed :: Handle -> IO Bool
70 --IOHandle:hIsEOF :: Handle -> IO Bool
71 --IOHandle:hIsOpen :: Handle -> IO Bool
72 --IOHandle:hIsReadable :: Handle -> IO Bool
73 --IOHandle:hIsSeekable :: Handle -> IO Bool
74 --IOHandle:hIsWritable :: Handle -> IO Bool
75 hLookAhead :: Handle -> IO Char
76 hPrint :: Show a => Handle -> a -> IO ()
77 hPutChar :: Handle -> Char -> IO ()
78 hPutStr :: Handle -> String -> IO ()
79 hPutStrLn :: Handle -> String -> IO ()
80 hReady :: Handle -> IO Bool
81 hWaitForInput :: Handle -> Int -> IO Bool
83 --IOHandle:hSeek :: Handle -> SeekMode -> Integer -> IO ()
84 --IOHandle:hSetBuffering :: Handle -> BufferMode -> IO ()
85 --IOHandle:hSetPosn :: HandlePosn -> IO ()
86 -- ioeGetFileName :: IOError -> Maybe FilePath
87 -- ioeGetErrorString :: IOError -> Maybe String
88 -- ioeGetHandle :: IOError -> Maybe Handle
89 -- isAlreadyExistsError :: IOError -> Bool
90 -- isAlreadyInUseError :: IOError -> Bool
91 --IOHandle:isEOF :: IO Bool
92 -- isEOFError :: IOError -> Bool
93 -- isFullError :: IOError -> Bool
94 -- isIllegalOperation :: IOError -> Bool
95 -- isPermissionError :: IOError -> Bool
96 -- isUserError :: IOError -> Bool
97 --IOHandle:openFile :: FilePath -> IOMode -> IO Handle
98 --IOHandle:stdin, stdout, stderr :: Handle
101 Standard instances for @Handle@:
104 instance Eq IOError where
105 (IOError h1 e1 str1) == (IOError h2 e2 str2) =
106 e1==e2 && str1==str2 && h1==h2
108 #ifndef __CONCURRENT_HASKELL__
110 instance Eq Handle where
111 (Handle h1) == (Handle h2) = h1 == h2
115 {- OLD equality instance. The simpler one above
116 seems more accurate! This one is still used for concurrent haskell,
117 since there's no equality instance over MVars.
120 instance Eq Handle where
129 (ErrorHandle (IOError h1 _ _), ErrorHandle (IOError h2 _ _)) -> h1 == h2
130 (ClosedHandle, ClosedHandle) -> True
131 (SemiClosedHandle v1 _, SemiClosedHandle v2 _) -> v1 == v2
132 (ReadHandle v1 _ _ , ReadHandle v2 _ _) -> v1 == v2
133 (WriteHandle v1 _ _ , WriteHandle v2 _ _) -> v1 == v2
134 (AppendHandle v1 _ _ , AppendHandle v2 _ _) -> v1 == v2
135 (ReadWriteHandle v1 _ _ , ReadWriteHandle v2 _ _) -> v1 == v2
140 instance Show Handle where {showsPrec p h = showString "<<Handle>>"}
142 --Type declared in IOHandle, instance here because it depends on Eq.Handle
143 instance Eq HandlePosn where
144 (HandlePosn h1 p1) == (HandlePosn h2 p2) = p1==p2 && h1==h2
146 -- Type declared in IOBase, instance here because it
147 -- depends on PrelRead.(Read Maybe) instance.
148 instance Read BufferMode where
151 (\r -> let lr = lex r
153 [(NoBuffering, rest) | ("NoBuffering", rest) <- lr] ++
154 [(LineBuffering,rest) | ("LineBuffering",rest) <- lr] ++
155 [(BlockBuffering mb,rest2) | ("BlockBuffering",rest1) <- lr,
156 (mb, rest2) <- reads rest1])
160 %*********************************************************
162 \subsection{Simple input operations}
164 %*********************************************************
166 Computation @hReady hdl@ indicates whether at least
167 one item is available for input from handle {\em hdl}.
169 @hWaitForInput@ is the generalisation, wait for \tr{n} seconds
170 before deciding whether the Handle has run dry or not.
173 --hReady :: Handle -> IO Bool
174 hReady h = hWaitForInput h 0
176 --hWaitForInput :: Handle -> Int -> IO Bool
177 hWaitForInput handle nsecs = do
178 hdl <- wantReadableHandle handle
179 rc <- _ccall_ inputReady (filePtr hdl) nsecs
180 writeHandle handle (markHandle hdl)
184 _ -> constructErrorAndFail "hWaitForInput"
187 Computation $hGetChar hdl$ reads the next character from handle
188 {\em hdl}, blocking until a character is available.
191 --hGetChar :: Handle -> IO Char
194 hdl <- wantReadableHandle handle
195 intc <- _ccall_ fileGetc (filePtr hdl)
196 writeHandle handle (markHandle hdl)
198 then return (chr intc)
199 else constructErrorAndFail "hGetChar"
201 hGetLine :: Handle -> IO String
212 Computation $hLookahead hdl$ returns the next character from handle
213 {\em hdl} without removing it from the input buffer, blocking until a
214 character is available.
217 --hLookAhead :: Handle -> IO Char
219 hLookAhead handle = do
220 hdl <- wantReadableHandle handle
221 intc <- _ccall_ fileLookAhead (filePtr hdl)
222 writeHandle handle (markHandle hdl)
224 then return (chr intc)
225 else constructErrorAndFail "hLookAhead"
230 %*********************************************************
232 \subsection{Getting the entire contents of a handle}
234 %*********************************************************
236 Computation $hGetContents hdl$ returns the list of characters
237 corresponding to the unread portion of the channel or file managed by
238 {\em hdl}, which is made semi-closed.
241 --hGetContents :: Handle -> IO String
243 hGetContents handle = do
244 hdl_ <- wantReadableHandle handle
246 To avoid introducing an extra layer of buffering here,
247 we provide three lazy read methods, based on character,
248 line, and block buffering.
250 hdl_ <- getBufferMode hdl_
251 case (bufferMode hdl_) of
252 Just LineBuffering -> do
253 buf_info <- allocBuf Nothing
254 writeHandle handle (SemiClosedHandle (filePtr hdl_) buf_info)
255 unsafeInterleaveIO (lazyReadLine handle)
256 Just (BlockBuffering size) -> do
257 buf_info <- allocBuf size
258 writeHandle handle (SemiClosedHandle (filePtr hdl_) buf_info)
259 unsafeInterleaveIO (lazyReadBlock handle)
260 _ -> do -- Nothing is treated pessimistically as NoBuffering
261 writeHandle handle (SemiClosedHandle (filePtr hdl_) (``NULL'', 0))
262 unsafeInterleaveIO (lazyReadChar handle)
264 allocBuf :: Maybe Int -> IO (Addr, Int)
266 buf <- _ccall_ malloc size
268 then return (buf, size)
269 else fail (IOError Nothing ResourceExhausted "not enough virtual memory")
274 Nothing -> ``BUFSIZ''
277 Note that someone may yank our handle out from under us, and then re-use
278 the same FILE * for something else. Therefore, we have to re-examine the
279 handle every time through.
282 lazyReadBlock :: Handle -> IO String
283 lazyReadLine :: Handle -> IO String
284 lazyReadChar :: Handle -> IO String
286 lazyReadBlock handle = do
287 htype <- readHandle handle
289 -- There cannae be an ErrorHandle here
291 writeHandle handle htype
293 SemiClosedHandle fp (buf, size) -> do
294 bytes <- _ccall_ readBlock buf fp size
295 some <- (if bytes <= 0
297 else stToIO (unpackNBytesST buf bytes))
302 #ifndef __PARALLEL_HASKELL__
303 writeForeignObj fp ``NULL''
304 writeHandle handle (SemiClosedHandle fp (``NULL'', 0))
306 writeHandle handle (SemiClosedHandle ``NULL'' (``NULL'', 0))
310 writeHandle handle htype
311 more <- unsafeInterleaveIO (lazyReadBlock handle)
312 return (some ++ more)
314 lazyReadLine handle = do
315 htype <- readHandle handle
317 -- There cannae be an ErrorHandle here
319 writeHandle handle htype
321 SemiClosedHandle fp (buf, size) -> do
322 bytes <- _ccall_ readLine buf fp size
323 some <- (if bytes <= 0
325 else stToIO (unpackNBytesST buf bytes))
330 #ifndef __PARALLEL_HASKELL__
331 writeForeignObj fp ``NULL''
332 writeHandle handle (SemiClosedHandle fp (``NULL'', 0))
334 writeHandle handle (SemiClosedHandle ``NULL'' (``NULL'', 0))
338 writeHandle handle htype
339 more <- unsafeInterleaveIO (lazyReadLine handle)
340 return (some ++ more)
342 lazyReadChar handle = do
343 htype <- readHandle handle
345 -- There cannae be an ErrorHandle here
347 writeHandle handle htype
349 SemiClosedHandle fp buf_info -> do
350 char <- _ccall_ readChar fp
354 #ifndef __PARALLEL_HASKELL__
355 writeForeignObj fp ``NULL''
356 writeHandle handle (SemiClosedHandle fp (``NULL'', 0))
358 writeHandle handle (SemiClosedHandle ``NULL'' (``NULL'', 0))
362 writeHandle handle htype
363 more <- unsafeInterleaveIO (lazyReadChar handle)
364 return (chr char : more)
369 %*********************************************************
371 \subsection{Simple output functions}
373 %*********************************************************
375 Computation $hPutChar hdl c$ writes the character {\em c} to the file
376 or channel managed by {\em hdl}. Characters may be buffered if
377 buffering is enabled for {\em hdl}.
380 --hPutChar :: Handle -> Char -> IO ()
382 hPutChar handle c = do
383 hdl <- wantWriteableHandle handle
384 rc <- _ccall_ filePutc (filePtr hdl) (ord c)
385 writeHandle handle (markHandle hdl)
388 else constructErrorAndFail "hPutChar"
391 Computation $hPutStr hdl s$ writes the string {\em s} to the file or
392 channel managed by {\em hdl}.
395 --hPutStr :: Handle -> String -> IO ()
397 hPutStr handle str = do
398 hdl <- wantWriteableHandle handle
400 The code below is not correct for line-buffered terminal streams,
401 as the output stream is not flushed when terminal input is requested
402 again, just upon seeing a newline character. A temporary fix for the
403 most common line-buffered output stream, stdout, is to assume the
404 buffering it was given when created (no buffering). This is not
405 as bad as it looks, since stdio buffering sits underneath this.
409 hdl <- getBufferMode hdl
411 (case bufferMode hdl of
412 Just LineBuffering ->
413 writeChars (filePtr hdl) str
414 --writeLines (filePtr hdl) str
415 Just (BlockBuffering (Just size)) ->
416 writeBlocks (filePtr hdl) size str
417 Just (BlockBuffering Nothing) ->
418 writeBlocks (filePtr hdl) (``BUFSIZ''-1) str
419 _ -> -- Nothing is treated pessimistically as NoBuffering
420 writeChars (filePtr hdl) str
422 writeHandle handle (markHandle hdl)
425 else constructErrorAndFail "hPutStr"
427 #ifndef __PARALLEL_HASKELL__
428 writeLines :: ForeignObj -> String -> IO Bool
430 writeLines :: Addr -> String -> IO Bool
432 writeLines = writeChunks (``BUFSIZ''-1) True
434 #ifndef __PARALLEL_HASKELL__
435 writeBlocks :: ForeignObj -> Int -> String -> IO Bool
437 writeBlocks :: Addr -> Int -> String -> IO Bool
439 writeBlocks fp size s = writeChunks size False fp s
442 The breaking up of output into lines along \n boundaries
443 works fine as long as there are newlines to split by.
444 Avoid the splitting up into lines alltogether (doesn't work
445 for overly long lines like the stuff that showsPrec instances
446 normally return). Instead, we split them up into fixed size
447 chunks before blasting them off to the Real World.
449 Hacked to avoid multiple passes over the strings - unsightly, but
450 a whole lot quicker. -- SOF 3/96
453 #ifndef __PARALLEL_HASKELL__
454 writeChunks :: Int -> Bool -> ForeignObj -> String -> IO Bool
456 writeChunks :: Int -> Bool -> Addr -> String -> IO Bool
458 writeChunks (I# bufLen) chopOnNewLine fp s =
459 stToIO (newCharArray (0,I# bufLen)) >>= \ arr@(MutableByteArray _ arr#) ->
461 write_char :: MutableByteArray# RealWorld -> Int# -> Char# -> IO ()
462 write_char arr# n x = IO $ \ s# ->
463 case (writeCharArray# arr# n x s#) of { s1# ->
466 shoveString :: Int# -> [Char] -> IO Bool
473 rc <- _ccall_ writeFile arr fp (I# n)
479 {- Flushing lines - should we bother? Yes, for line-buffered output. -}
480 if n ==# bufLen || (chopOnNewLine && (x `eqChar#` '\n'#))
482 rc <- _ccall_ writeFile arr fp (I# (n +# 1#))
484 then shoveString 0# xs
487 shoveString (n +# 1#) xs
491 #ifndef __PARALLEL_HASKELL__
492 writeChars :: ForeignObj -> String -> IO Bool
494 writeChars :: Addr -> String -> IO Bool
496 writeChars fp "" = return True
497 writeChars fp (c:cs) = do
498 rc <- _ccall_ filePutc fp (ord c)
500 then writeChars fp cs
505 The @hPutBuf hdl len elt_sz buf@ action writes the buffer @buf@ to
506 the file/channel managed by @hdl@
507 the string {\em s} to the file or
508 channel managed by {\em hdl}.
511 hPutBuf :: Handle -> Int -> Int -> ByteArray Int -> IO ()
512 hPutBuf handle len el_sz buf = do
513 hdl <- wantWriteableHandle handle
515 The code below is not correct for line-buffered terminal streams,
516 as the output stream is not flushed when terminal input is requested
517 again, just upon seeing a newline character. A temporary fix for the
518 most common line-buffered output stream, stdout, is to assume the
519 buffering it was given when created (no buffering). This is not
520 as bad as it looks, since stdio buffering sits underneath this.
524 hdl <- getBufferMode hdl
526 (case bufferMode hdl of
527 Just LineBuffering ->
528 writeChars (filePtr hdl) str
529 --writeLines (filePtr hdl) str
530 Just (BlockBuffering (Just size)) ->
531 writeBlocks (filePtr hdl) size str
532 Just (BlockBuffering Nothing) ->
533 writeBlocks (filePtr hdl) ``BUFSIZ'' str
534 _ -> -- Nothing is treated pessimistically as NoBuffering
535 writeChars (filePtr hdl) str)
536 writeHandle handle (markHandle hdl)
539 else constructErrorAndFail "hPutBuf"
543 Computation $hPrint hdl t$ writes the string representation of {\em t}
544 given by the $shows$ function to the file or channel managed by {\em
547 SOF 2/97: Seem to have disappeared in 1.4 libs.
550 --hPrint :: Show a => Handle -> a -> IO ()
551 hPrint hdl = hPutStr hdl . show
554 Derived action @hPutStrLn hdl str@ writes the string \tr{str} to
555 the handle \tr{hdl}, adding a newline at the end.
558 --hPutStrLn :: Handle -> String -> IO ()
559 hPutStrLn hndl str = do
566 %*********************************************************
568 \subsection{Try and bracket}
570 %*********************************************************
572 The construct $try comp$ exposes errors which occur within a
573 computation, and which are not fully handled. It always succeeds.
576 try :: IO a -> IO (Either IOError a)
577 try f = catch (do r <- f
581 bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
582 bracket before after m = do
590 -- variant of the above where middle computation doesn't want x
591 bracket_ :: IO a -> (a -> IO b) -> IO c -> IO c
592 bracket_ before after m = do