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
62 -- Non-standard extension (but will hopefully become standard with 1.5) is
63 -- to export the Prelude io functions via IO (in addition to exporting them
64 -- from the prelude...for now.)
65 putChar, -- :: Char -> IO ()
66 putStr, -- :: String -> IO ()
67 putStrLn, -- :: String -> IO ()
68 print, -- :: Show a => a -> IO ()
69 getChar, -- :: IO Char
70 getLine, -- :: IO String
71 getContents, -- :: IO String
72 interact, -- :: (String -> String) -> IO ()
73 readFile, -- :: FilePath -> IO String
74 writeFile, -- :: FilePath -> String -> IO ()
75 appendFile, -- :: FilePath -> String -> IO ()
76 readIO, -- :: Read a => String -> IO a
77 readLn, -- :: Read a => IO a
78 FilePath, -- :: String
79 fail, -- :: IOError -> IO a
80 catch, -- :: IO a -> (IOError -> IO a) -> IO a
81 userError, -- :: String -> IOError
83 IO, -- non-standard, amazingly enough.
96 import PrelHandle -- much of the real stuff is in here
98 import PrelRead ( readParen, Read(..), reads, lex,
101 --import PrelNum ( toInteger )
102 import PrelBounded () -- Bounded Int instance.
103 import PrelEither ( Either(..) )
104 import PrelAddr ( Addr(..), nullAddr )
105 import PrelArr ( ByteArray )
106 import PrelPack ( unpackNBytesAccST )
108 #ifndef __PARALLEL_HASKELL__
109 import PrelForeign ( ForeignObj )
112 import Char ( ord, chr )
116 Standard instances for @Handle@:
119 instance Eq IOError where
120 (IOError h1 e1 loc1 str1) == (IOError h2 e2 loc2 str2) =
121 e1==e2 && str1==str2 && h1==h2 && loc1 == loc2
123 instance Eq Handle where
124 (Handle h1) == (Handle h2) = h1 == h2
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
130 -- Type declared in IOBase, instance here because it
131 -- depends on PrelRead.(Read Maybe) instance.
132 instance Read BufferMode where
135 (\r -> let lr = lex r
137 [(NoBuffering, rest) | ("NoBuffering", rest) <- lr] ++
138 [(LineBuffering,rest) | ("LineBuffering",rest) <- lr] ++
139 [(BlockBuffering mb,rest2) | ("BlockBuffering",rest1) <- lr,
140 (mb, rest2) <- reads rest1])
144 %*********************************************************
146 \subsection{Simple input operations}
148 %*********************************************************
150 Computation @hReady hdl@ indicates whether at least
151 one item is available for input from handle {\em hdl}.
153 @hWaitForInput@ is the generalisation, wait for \tr{n} milliseconds
154 before deciding whether the Handle has run dry or not.
156 If @hWaitForInput@ finds anything in the Handle's buffer, it immediately returns.
157 If not, it tries to read from the underlying OS handle. Notice that
158 for buffered Handles connected to terminals this means waiting until a complete
162 hReady :: Handle -> IO Bool
163 hReady h = hWaitForInput h 0
165 hWaitForInput :: Handle -> Int -> IO Bool
166 hWaitForInput handle msecs = do
167 handle_ <- wantReadableHandle "hWaitForInput" handle
168 rc <- _ccall_ inputReady (haFO__ handle_) (msecs::Int) -- ConcHask: SAFE, won't block
169 writeHandle handle handle_
173 _ -> constructErrorAndFail "hWaitForInput"
176 @hGetChar hdl@ reads the next character from handle @hdl@,
177 blocking until a character is available.
180 hGetChar :: Handle -> IO Char
182 handle_ <- wantReadableHandle "hGetChar" handle
183 let fo = haFO__ handle_
184 intc <- mayBlock fo (_ccall_ fileGetc fo) -- ConcHask: UNSAFE, may block
185 writeHandle handle handle_
187 then return (chr intc)
188 else constructErrorAndFail "hGetChar"
190 hGetLine :: Handle -> IO String
201 @hLookahead hdl@ returns the next character from handle @hdl@
202 without removing it from the input buffer, blocking until a
203 character is available.
206 hLookAhead :: Handle -> IO Char
207 hLookAhead handle = do
208 handle_ <- wantReadableHandle "hLookAhead" handle
209 let fo = haFO__ handle_
210 intc <- mayBlock fo (_ccall_ fileLookAhead fo) -- ConcHask: UNSAFE, may block
211 writeHandle handle handle_
213 then return (chr intc)
214 else constructErrorAndFail "hLookAhead"
219 %*********************************************************
221 \subsection{Getting the entire contents of a handle}
223 %*********************************************************
225 @hGetContents hdl@ returns the list of characters corresponding
226 to the unread portion of the channel or file managed by @hdl@,
227 which is made semi-closed.
230 hGetContents :: Handle -> IO String
231 hGetContents handle = do
232 handle_ <- wantReadableHandle "hGetContents" handle
234 To avoid introducing an extra layer of buffering here,
235 we provide three lazy read methods, based on character,
236 line, and block buffering.
238 writeHandle handle (handle_{ haType__ = SemiClosedHandle })
239 case (haBufferMode__ handle_) of
240 LineBuffering -> unsafeInterleaveIO (lazyReadLine handle (haFO__ handle_))
241 BlockBuffering _ -> unsafeInterleaveIO (lazyReadBlock handle (haFO__ handle_))
242 NoBuffering -> unsafeInterleaveIO (lazyReadChar handle (haFO__ handle_))
246 Note that someone may close the semi-closed handle (or change its buffering),
247 so each these lazy read functions are pulled on, they have to check whether
248 the handle has indeed been closed.
251 #ifndef __PARALLEL_HASKELL__
252 lazyReadBlock :: Handle -> ForeignObj -> IO String
253 lazyReadLine :: Handle -> ForeignObj -> IO String
254 lazyReadChar :: Handle -> ForeignObj -> IO String
256 lazyReadBlock :: Handle -> Addr -> IO String
257 lazyReadLine :: Handle -> Addr -> IO String
258 lazyReadChar :: Handle -> Addr -> IO String
261 lazyReadBlock handle fo = do
262 buf <- _ccall_ getBufStart fo (0::Int)
263 bytes <- mayBlock fo (_ccall_ readBlock fo) -- ConcHask: UNSAFE, may block.
265 -3 -> -- buffering has been turned off, use lazyReadChar instead
266 lazyReadChar handle fo
268 -1 -> do -- an error occurred, close the handle
269 handle_ <- readHandle handle
270 _ccall_ closeFile (haFO__ handle_) 0{-don't bother flushing-} -- ConcHask: SAFE, won't block.
271 writeHandle handle (handle_ { haType__ = ClosedHandle,
272 haFO__ = nullFile__ })
275 more <- unsafeInterleaveIO (lazyReadBlock handle fo)
276 stToIO (unpackNBytesAccST buf bytes more)
278 lazyReadLine handle fo = do
279 bytes <- mayBlock fo (_ccall_ readLine fo) -- ConcHask: UNSAFE, may block.
281 -3 -> -- buffering has been turned off, use lazyReadChar instead
282 lazyReadChar handle fo
283 -2 -> return "" -- handle closed by someone else, stop reading.
284 -1 -> do -- an error occurred, close the handle
285 handle_ <- readHandle handle
286 _ccall_ closeFile (haFO__ handle_) 0{- don't bother flushing-} -- ConcHask: SAFE, won't block
287 writeHandle handle (handle_ { haType__ = ClosedHandle,
288 haFO__ = nullFile__ })
291 more <- unsafeInterleaveIO (lazyReadLine handle fo)
292 buf <- _ccall_ getBufStart fo bytes -- ConcHask: won't block
293 stToIO (unpackNBytesAccST buf bytes more)
295 lazyReadChar handle fo = do
296 char <- mayBlock fo (_ccall_ readChar fo) -- ConcHask: UNSAFE, may block.
298 -4 -> -- buffering is now block-buffered, use lazyReadBlock instead
299 lazyReadBlock handle fo
301 -3 -> -- buffering is now line-buffered, use lazyReadLine instead
302 lazyReadLine handle fo
304 -1 -> do -- error, silently close handle.
305 handle_ <- readHandle handle
306 _ccall_ closeFile (haFO__ handle_) 0{-don't bother flusing-} -- ConcHask: SAFE, won't block
307 writeHandle handle (handle_{ haType__ = ClosedHandle,
308 haFO__ = nullFile__ })
311 more <- unsafeInterleaveIO (lazyReadChar handle fo)
312 return (chr char : more)
317 %*********************************************************
319 \subsection{Simple output functions}
321 %*********************************************************
323 @hPutChar hdl ch@ writes the character @ch@ to the file
324 or channel managed by @hdl@. Characters may be buffered if
325 buffering is enabled for @hdl@
328 hPutChar :: Handle -> Char -> IO ()
329 hPutChar handle c = do
330 handle_ <- wantWriteableHandle "hPutChar" handle
331 let fo = haFO__ handle_
332 flushConnectedHandle fo
333 rc <- mayBlock fo (_ccall_ filePutc fo c) -- ConcHask: UNSAFE, may block.
334 writeHandle handle handle_
337 else constructErrorAndFail "hPutChar"
341 @hPutStr hdl s@ writes the string @s@ to the file or
342 channel managed by @hdl@, buffering the output if needs be.
345 hPutStr :: Handle -> String -> IO ()
346 hPutStr handle str = do
347 handle_ <- wantWriteableHandle "hPutStr" handle
348 let fo = haFO__ handle_
349 flushConnectedHandle fo
350 case haBufferMode__ handle_ of
352 buf <- _ccall_ getWriteableBuf fo
353 pos <- _ccall_ getBufWPtr fo
354 bsz <- _ccall_ getBufSize fo
355 writeLines fo buf bsz pos str
356 BlockBuffering _ -> do
357 buf <- _ccall_ getWriteableBuf fo
358 pos <- _ccall_ getBufWPtr fo
359 bsz <- _ccall_ getBufSize fo
360 writeBlocks fo buf bsz pos str
363 writeHandle handle handle_
367 Going across the border between Haskell and C is relatively costly,
368 so for block writes we pack the character strings on the Haskell-side
369 before passing the external write routine a pointer to the buffer.
373 #ifndef __PARALLEL_HASKELL__
374 writeLines :: ForeignObj -> Addr -> Int -> Int -> String -> IO ()
376 writeLines :: Addr -> Addr -> Int -> Int -> String -> IO ()
378 writeLines obj buf bf@(I# bufLen) (I# initPos#) s =
380 write_char :: Addr -> Int# -> Char# -> IO ()
381 write_char (A# buf) n# c# =
383 case (writeCharOffAddr# buf n# c# s#) of s2# -> IOok s2# ()
385 shoveString :: Int# -> [Char] -> IO ()
390 _ccall_ setBufWPtr obj (0::Int)
393 At the end of a buffer write, update the buffer position
394 in the underlying file object, so that if the handle
395 is subsequently dropped by the program, the whole
396 buffer will be properly flushed.
398 There's one case where this delayed up-date of the buffer
399 position can go wrong: if a thread is killed, it might be
400 in the middle of filling up a buffer, with the result that
401 the partial buffer update is lost upon finalisation. Not
402 that killing of threads is supported at the moment.
405 _ccall_ setBufWPtr obj (I# n)
409 {- Flushing on buffer exhaustion or newlines (even if it isn't the last one) -}
410 if n ==# bufLen || x `eqChar#` '\n'#
412 rc <- mayBlock obj (_ccall_ writeFileObject obj (I# (n +# 1#))) -- ConcHask: UNSAFE, may block.
414 then shoveString 0# xs
415 else constructErrorAndFail "writeLines"
417 shoveString (n +# 1#) xs
419 shoveString initPos# s
421 #ifndef __PARALLEL_HASKELL__
422 writeBlocks :: ForeignObj -> Addr -> Int -> Int -> String -> IO ()
424 writeBlocks :: Addr -> Addr -> Int -> Int -> String -> IO ()
426 writeBlocks obj buf bf@(I# bufLen) (I# initPos#) s =
428 write_char :: Addr -> Int# -> Char# -> IO ()
429 write_char (A# buf) n# c# =
431 case (writeCharOffAddr# buf n# c# s#) of s2# -> IOok s2# ()
433 shoveString :: Int# -> [Char] -> IO ()
438 _ccall_ setBufWPtr obj (0::Int)
441 At the end of a buffer write, update the buffer position
442 in the underlying file object, so that if the handle
443 is subsequently dropped by the program, the whole
444 buffer will be properly flushed.
446 There's one case where this delayed up-date of the buffer
447 position can go wrong: if a thread is killed, it might be
448 in the middle of filling up a buffer, with the result that
449 the partial buffer update is lost upon finalisation. However,
450 by the time killThread is supported, Haskell finalisers are also
451 likely to be in, which means the 'IOFileObject' hack can go
455 _ccall_ setBufWPtr obj (I# n)
461 rc <- mayBlock obj (_ccall_ writeFileObject obj (I# (n +# 1#))) -- ConcHask: UNSAFE, may block.
463 then shoveString 0# xs
464 else constructErrorAndFail "writeChunks"
466 shoveString (n +# 1#) xs
468 shoveString initPos# s
470 #ifndef __PARALLEL_HASKELL__
471 writeChars :: ForeignObj -> String -> IO ()
473 writeChars :: Addr -> String -> IO ()
475 writeChars fo "" = return ()
476 writeChars fo (c:cs) = do
477 rc <- mayBlock fo (_ccall_ filePutc fo c) -- ConcHask: UNSAFE, may block.
479 then writeChars fo cs
480 else constructErrorAndFail "writeChars"
484 Computation @hPrint hdl t@ writes the string representation of {\em t}
485 given by the @shows@ function to the file or channel managed by {\em
488 [ Seem to have disappeared from the 1.4 interface - SOF 2/97 ]
491 hPrint :: Show a => Handle -> a -> IO ()
492 hPrint hdl = hPutStr hdl . show
495 Derived action @hPutStrLn hdl str@ writes the string \tr{str} to
496 the handle \tr{hdl}, adding a newline at the end.
499 hPutStrLn :: Handle -> String -> IO ()
500 hPutStrLn hndl str = do
507 %*********************************************************
509 \subsection{Try and bracket}
511 %*********************************************************
513 The construct @try comp@ exposes errors which occur within a
514 computation, and which are not fully handled. It always succeeds.
517 try :: IO a -> IO (Either IOError a)
518 try f = catch (do r <- f
522 bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
523 bracket before after m = do
531 -- variant of the above where middle computation doesn't want x
532 bracket_ :: IO a -> (a -> IO b) -> IO c -> IO c
533 bracket_ before after m = do
542 %*********************************************************
544 \subsection{Standard IO}
546 %*********************************************************
548 The Prelude has from Day 1 provided a collection of common
549 IO functions. We define these here, but let the Prelude
553 putChar :: Char -> IO ()
554 putChar c = hPutChar stdout c
556 putStr :: String -> IO ()
557 putStr s = hPutStr stdout s
559 putStrLn :: String -> IO ()
560 putStrLn s = do putStr s
563 print :: Show a => a -> IO ()
564 print x = putStrLn (show x)
567 getChar = hGetChar stdin
570 getLine = hGetLine stdin
572 getContents :: IO String
573 getContents = hGetContents stdin
575 interact :: (String -> String) -> IO ()
576 interact f = do s <- getContents
579 readFile :: FilePath -> IO String
580 readFile name = openFile name ReadMode >>= hGetContents
582 writeFile :: FilePath -> String -> IO ()
583 writeFile name str = do
584 hdl <- openFile name WriteMode
588 appendFile :: FilePath -> String -> IO ()
589 appendFile name str = do
590 hdl <- openFile name AppendMode
594 readLn :: Read a => IO a
595 readLn = do l <- getLine