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 rc <- mayBlock fo (_ccall_ filePutc fo (ord c)) -- ConcHask: UNSAFE, may block.
333 writeHandle handle handle_
336 else constructErrorAndFail "hPutChar"
340 @hPutStr hdl s@ writes the string @s@ to the file or
341 channel managed by @hdl@, buffering the output if needs be.
344 hPutStr :: Handle -> String -> IO ()
345 hPutStr handle str = do
346 handle_ <- wantWriteableHandle "hPutStr" handle
347 let fo = haFO__ handle_
348 case haBufferMode__ handle_ of
350 buf <- _ccall_ getWriteableBuf fo
351 pos <- _ccall_ getBufWPtr fo
352 bsz <- _ccall_ getBufSize fo
353 writeLines fo buf bsz pos str
354 BlockBuffering _ -> do
355 buf <- _ccall_ getWriteableBuf fo
356 pos <- _ccall_ getBufWPtr fo
357 bsz <- _ccall_ getBufSize fo
358 writeBlocks fo buf bsz pos str
361 writeHandle handle handle_
365 Going across the border between Haskell and C is relatively costly,
366 so for block writes we pack the character strings on the Haskell-side
367 before passing the external write routine a pointer to the buffer.
371 #ifndef __PARALLEL_HASKELL__
372 writeLines :: ForeignObj -> Addr -> Int -> Int -> String -> IO ()
374 writeLines :: Addr -> Addr -> Int -> Int -> String -> IO ()
376 writeLines obj buf bf@(I# bufLen) (I# initPos#) s =
378 write_char :: Addr -> Int# -> Char# -> IO ()
379 write_char (A# buf) n# c# =
381 case (writeCharOffAddr# buf n# c# s#) of s2# -> IOok s2# ()
383 shoveString :: Int# -> [Char] -> IO ()
388 _ccall_ setBufWPtr obj (0::Int)
391 At the end of a buffer write, update the buffer position
392 in the underlying file object, so that if the handle
393 is subsequently dropped by the program, the whole
394 buffer will be properly flushed.
396 There's one case where this delayed up-date of the buffer
397 position can go wrong: if a thread is killed, it might be
398 in the middle of filling up a buffer, with the result that
399 the partial buffer update is lost upon finalisation. Not
400 that killing of threads is supported at the moment.
403 _ccall_ setBufWPtr obj (I# n)
407 {- Flushing on buffer exhaustion or newlines (even if it isn't the last one) -}
408 if n ==# bufLen || x `eqChar#` '\n'#
410 rc <- mayBlock obj (_ccall_ writeFileObject obj (I# (n +# 1#))) -- ConcHask: UNSAFE, may block.
412 then shoveString 0# xs
413 else constructErrorAndFail "writeLines"
415 shoveString (n +# 1#) xs
417 shoveString initPos# s
419 #ifndef __PARALLEL_HASKELL__
420 writeBlocks :: ForeignObj -> Addr -> Int -> Int -> String -> IO ()
422 writeBlocks :: Addr -> Addr -> Int -> Int -> String -> IO ()
424 writeBlocks obj buf bf@(I# bufLen) (I# initPos#) s =
426 write_char :: Addr -> Int# -> Char# -> IO ()
427 write_char (A# buf) n# c# =
429 case (writeCharOffAddr# buf n# c# s#) of s2# -> IOok s2# ()
431 shoveString :: Int# -> [Char] -> IO ()
436 _ccall_ setBufWPtr obj (0::Int)
439 At the end of a buffer write, update the buffer position
440 in the underlying file object, so that if the handle
441 is subsequently dropped by the program, the whole
442 buffer will be properly flushed.
444 There's one case where this delayed up-date of the buffer
445 position can go wrong: if a thread is killed, it might be
446 in the middle of filling up a buffer, with the result that
447 the partial buffer update is lost upon finalisation. However,
448 by the time killThread is supported, Haskell finalisers are also
449 likely to be in, which means the 'IOFileObject' hack can go
453 _ccall_ setBufWPtr obj (I# n)
459 rc <- mayBlock obj (_ccall_ writeFileObject obj (I# (n +# 1#))) -- ConcHask: UNSAFE, may block.
461 then shoveString 0# xs
462 else constructErrorAndFail "writeChunks"
464 shoveString (n +# 1#) xs
466 shoveString initPos# s
468 #ifndef __PARALLEL_HASKELL__
469 writeChars :: ForeignObj -> String -> IO ()
471 writeChars :: Addr -> String -> IO ()
473 writeChars fo "" = return ()
474 writeChars fo (c:cs) = do
475 rc <- mayBlock fo (_ccall_ filePutc fo (ord c)) -- ConcHask: UNSAFE, may block.
477 then writeChars fo cs
478 else constructErrorAndFail "writeChars"
482 Computation @hPrint hdl t@ writes the string representation of {\em t}
483 given by the @shows@ function to the file or channel managed by {\em
486 [ Seem to have disappeared from the 1.4 interface - SOF 2/97 ]
489 hPrint :: Show a => Handle -> a -> IO ()
490 hPrint hdl = hPutStr hdl . show
493 Derived action @hPutStrLn hdl str@ writes the string \tr{str} to
494 the handle \tr{hdl}, adding a newline at the end.
497 hPutStrLn :: Handle -> String -> IO ()
498 hPutStrLn hndl str = do
505 %*********************************************************
507 \subsection{Try and bracket}
509 %*********************************************************
511 The construct @try comp@ exposes errors which occur within a
512 computation, and which are not fully handled. It always succeeds.
515 try :: IO a -> IO (Either IOError a)
516 try f = catch (do r <- f
520 bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
521 bracket before after m = do
529 -- variant of the above where middle computation doesn't want x
530 bracket_ :: IO a -> (a -> IO b) -> IO c -> IO c
531 bracket_ before after m = do
540 %*********************************************************
542 \subsection{Standard IO}
544 %*********************************************************
546 The Prelude has from Day 1 provided a collection of common
547 IO functions. We define these here, but let the Prelude
551 putChar :: Char -> IO ()
552 putChar c = hPutChar stdout c
554 putStr :: String -> IO ()
555 putStr s = hPutStr stdout s
557 putStrLn :: String -> IO ()
558 putStrLn s = do putStr s
561 print :: Show a => a -> IO ()
562 print x = putStrLn (show x)
565 getChar = hGetChar stdin
568 getLine = hGetLine stdin
570 getContents :: IO String
571 getContents = hGetContents stdin
573 interact :: (String -> String) -> IO ()
574 interact f = do s <- getContents
577 readFile :: FilePath -> IO String
578 readFile name = openFile name ReadMode >>= hGetContents
580 writeFile :: FilePath -> String -> IO ()
581 writeFile name str = do
582 hdl <- openFile name WriteMode
586 appendFile :: FilePath -> String -> IO ()
587 appendFile name str = do
588 hdl <- openFile name AppendMode
592 readLn :: Read a => IO a
593 readLn = do l <- getLine