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" #-}
13 #ifndef BODY /* Hugs just includes this in PreludeBuiltin so no header needed */
15 Handle, -- abstract, instance of: Eq, Show.
16 HandlePosn(..), -- abstract, instance of: Eq, Show.
18 IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),
19 BufferMode(NoBuffering,LineBuffering,BlockBuffering),
20 SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),
22 stdin, stdout, stderr, -- :: Handle
24 openFile, -- :: FilePath -> IOMode -> IO Handle
25 hClose, -- :: Handle -> IO ()
26 hFileSize, -- :: Handle -> IO Integer
27 hIsEOF, -- :: Handle -> IO Bool
30 hSetBuffering, -- :: Handle -> BufferMode -> IO ()
31 hGetBuffering, -- :: Handle -> IO BufferMode
32 hFlush, -- :: Handle -> IO ()
33 hGetPosn, -- :: Handle -> IO HandlePosn
34 hSetPosn, -- :: Handle -> HandlePosn -> IO ()
35 hSeek, -- :: Handle -> SeekMode -> Integer -> IO ()
36 hWaitForInput, -- :: Handle -> Int -> IO Bool
37 hReady, -- :: Handle -> IO Bool
38 hGetChar, -- :: Handle -> IO Char
39 hGetLine, -- :: Handle -> IO [Char]
40 hLookAhead, -- :: Handle -> IO Char
41 hGetContents, -- :: Handle -> IO [Char]
42 hPutChar, -- :: Handle -> Char -> IO ()
43 hPutStr, -- :: Handle -> [Char] -> IO ()
44 hPutStrLn, -- :: Handle -> [Char] -> IO ()
45 hPrint, -- :: Show a => Handle -> a -> IO ()
46 hIsOpen, hIsClosed, -- :: Handle -> IO Bool
47 hIsReadable, hIsWritable, -- :: Handle -> IO Bool
48 hIsSeekable, -- :: Handle -> IO Bool
50 isAlreadyExistsError, isDoesNotExistError, -- :: IOError -> Bool
51 isAlreadyInUseError, isFullError,
52 isEOFError, isIllegalOperation,
53 isPermissionError, isUserError,
55 ioeGetErrorString, -- :: IOError -> String
56 ioeGetHandle, -- :: IOError -> Maybe Handle
57 ioeGetFileName, -- :: IOError -> Maybe FilePath
59 try, -- :: IO a -> IO (Either IOError a)
60 bracket, -- :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
61 bracket_, -- :: IO a -> (a -> IO b) -> IO c -> IO c
63 -- Non-standard extension (but will hopefully become standard with 1.5) is
64 -- to export the Prelude io functions via IO (in addition to exporting them
65 -- from the prelude...for now.)
67 FilePath, -- :: String
69 ioError, -- :: IOError -> IO a
70 userError, -- :: String -> IOError
71 catch, -- :: IO a -> (IOError -> IO a) -> IO a
72 interact, -- :: (String -> String) -> IO ()
74 putChar, -- :: Char -> IO ()
75 putStr, -- :: String -> IO ()
76 putStrLn, -- :: String -> IO ()
77 print, -- :: Show a => a -> IO ()
78 getChar, -- :: IO Char
79 getLine, -- :: IO String
80 getContents, -- :: IO String
81 readFile, -- :: FilePath -> IO String
82 writeFile, -- :: FilePath -> String -> IO ()
83 appendFile, -- :: FilePath -> String -> IO ()
84 readIO, -- :: Read a => String -> IO a
85 readLn, -- :: Read a => IO a
106 import PrelHandle -- much of the real stuff is in here
108 import PrelRead ( readParen, Read(..), reads, lex,
112 import PrelMaybe ( Either(..) )
113 import PrelAddr ( Addr(..), nullAddr )
114 import PrelArr ( ByteArray )
115 import PrelPack ( unpackNBytesAccST )
116 import PrelException ( ioError, catch )
118 #ifndef __PARALLEL_HASKELL__
119 import PrelForeign ( ForeignObj )
122 import Char ( ord, chr )
124 #endif /* ndef __HUGS__ */
125 #endif /* ndef BODY */
130 #define cat2(x,y) x/**/y
131 #define CCALL(fun) cat2(prim_,fun)
132 #define __CONCURRENT_HASKELL__
134 #define unpackNBytesAccST primUnpackCStringAcc
136 #define CCALL(fun) _ccall_ fun
137 #define ref_freeStdFileObject (``&freeStdFileObject''::Addr)
138 #define ref_freeFileObject (``&freeFileObject''::Addr)
139 #define const_BUFSIZ ``BUFSIZ''
144 Standard instances for @Handle@:
147 instance Eq IOError where
148 (IOError h1 e1 loc1 str1) == (IOError h2 e2 loc2 str2) =
149 e1==e2 && str1==str2 && h1==h2 && loc1 == loc2
151 instance Eq Handle where
152 (Handle h1) == (Handle h2) = h1 == h2
154 --Type declared in IOHandle, instance here because it depends on Eq.Handle
155 instance Eq HandlePosn where
156 (HandlePosn h1 p1) == (HandlePosn h2 p2) = p1==p2 && h1==h2
158 -- Type declared in IOBase, instance here because it
159 -- depends on PrelRead.(Read Maybe) instance.
160 instance Read BufferMode where
163 (\r -> let lr = lex r
165 [(NoBuffering, rest) | ("NoBuffering", rest) <- lr] ++
166 [(LineBuffering,rest) | ("LineBuffering",rest) <- lr] ++
167 [(BlockBuffering mb,rest2) | ("BlockBuffering",rest1) <- lr,
168 (mb, rest2) <- reads rest1])
172 %*********************************************************
174 \subsection{Simple input operations}
176 %*********************************************************
178 Computation @hReady hdl@ indicates whether at least
179 one item is available for input from handle {\em hdl}.
181 @hWaitForInput@ is the generalisation, wait for \tr{n} milliseconds
182 before deciding whether the Handle has run dry or not.
184 If @hWaitForInput@ finds anything in the Handle's buffer, it immediately returns.
185 If not, it tries to read from the underlying OS handle. Notice that
186 for buffered Handles connected to terminals this means waiting until a complete
190 hReady :: Handle -> IO Bool
191 hReady h = hWaitForInput h 0
193 hWaitForInput :: Handle -> Int -> IO Bool
194 hWaitForInput handle msecs =
195 wantReadableHandle "hWaitForInput" handle $ \ handle_ -> do
196 rc <- CCALL(inputReady) (haFO__ handle_) (msecs::Int) -- ConcHask: SAFE, won't block
197 writeHandle handle handle_
201 _ -> constructErrorAndFail "hWaitForInput"
204 @hGetChar hdl@ reads the next character from handle @hdl@,
205 blocking until a character is available.
208 hGetChar :: Handle -> IO Char
210 wantReadableHandle "hGetChar" handle $ \ handle_ -> do
211 let fo = haFO__ handle_
212 intc <- mayBlock fo (CCALL(fileGetc) fo) -- ConcHask: UNSAFE, may block
213 writeHandle handle handle_
214 if intc /= ((-1)::Int)
215 then return (chr intc)
216 else constructErrorAndFail "hGetChar"
219 If EOF is reached before EOL is encountered, ignore the
220 EOF and return the partial line. Next attempt at calling
221 hGetLine on the handle will yield an EOF IO exception though.
223 hGetLine :: Handle -> IO String
237 if isEOFError err then
249 @hLookahead hdl@ returns the next character from handle @hdl@
250 without removing it from the input buffer, blocking until a
251 character is available.
254 hLookAhead :: Handle -> IO Char
255 hLookAhead handle = do
256 wantReadableHandle "hLookAhead" handle $ \ handle_ -> do
257 let fo = haFO__ handle_
258 intc <- mayBlock fo (CCALL(fileLookAhead) fo) -- ConcHask: UNSAFE, may block
259 writeHandle handle handle_
261 then return (chr intc)
262 else constructErrorAndFail "hLookAhead"
267 %*********************************************************
269 \subsection{Getting the entire contents of a handle}
271 %*********************************************************
273 @hGetContents hdl@ returns the list of characters corresponding
274 to the unread portion of the channel or file managed by @hdl@,
275 which is made semi-closed.
278 hGetContents :: Handle -> IO String
279 hGetContents handle =
280 wantReadableHandle "hGetContents" handle $ \ handle_ -> do
282 To avoid introducing an extra layer of buffering here,
283 we provide three lazy read methods, based on character,
284 line, and block buffering.
286 writeHandle handle (handle_{ haType__ = SemiClosedHandle })
287 case (haBufferMode__ handle_) of
288 LineBuffering -> unsafeInterleaveIO (lazyReadLine handle (haFO__ handle_))
289 BlockBuffering _ -> unsafeInterleaveIO (lazyReadBlock handle (haFO__ handle_))
290 NoBuffering -> unsafeInterleaveIO (lazyReadChar handle (haFO__ handle_))
294 Note that someone may close the semi-closed handle (or change its buffering),
295 so each these lazy read functions are pulled on, they have to check whether
296 the handle has indeed been closed.
299 #ifndef __PARALLEL_HASKELL__
300 lazyReadBlock :: Handle -> ForeignObj -> IO String
301 lazyReadLine :: Handle -> ForeignObj -> IO String
302 lazyReadChar :: Handle -> ForeignObj -> IO String
304 lazyReadBlock :: Handle -> Addr -> IO String
305 lazyReadLine :: Handle -> Addr -> IO String
306 lazyReadChar :: Handle -> Addr -> IO String
309 lazyReadBlock handle fo = do
310 buf <- CCALL(getBufStart) fo (0::Int)
311 bytes <- mayBlock fo (CCALL(readBlock) fo) -- ConcHask: UNSAFE, may block.
313 -3 -> -- buffering has been turned off, use lazyReadChar instead
314 lazyReadChar handle fo
316 -1 -> -- an error occurred, close the handle
317 withHandle handle $ \ handle_ -> do
318 CCALL(closeFile) (haFO__ handle_) (0::Int){-don't bother flushing-} -- ConcHask: SAFE, won't block.
319 writeHandle handle (handle_ { haType__ = ClosedHandle,
320 haFO__ = nullFile__ })
323 more <- unsafeInterleaveIO (lazyReadBlock handle fo)
324 stToIO (unpackNBytesAccST buf bytes more)
326 lazyReadLine handle fo = do
327 bytes <- mayBlock fo (CCALL(readLine) fo) -- ConcHask: UNSAFE, may block.
329 -3 -> -- buffering has been turned off, use lazyReadChar instead
330 lazyReadChar handle fo
331 -2 -> return "" -- handle closed by someone else, stop reading.
332 -1 -> -- an error occurred, close the handle
333 withHandle handle $ \ handle_ -> do
334 CCALL(closeFile) (haFO__ handle_) (0::Int){- don't bother flushing-} -- ConcHask: SAFE, won't block
335 writeHandle handle (handle_ { haType__ = ClosedHandle,
336 haFO__ = nullFile__ })
339 more <- unsafeInterleaveIO (lazyReadLine handle fo)
340 buf <- CCALL(getBufStart) fo bytes -- ConcHask: won't block
341 stToIO (unpackNBytesAccST buf bytes more)
343 lazyReadChar handle fo = do
344 char <- mayBlock fo (CCALL(readChar) fo) -- ConcHask: UNSAFE, may block.
346 -4 -> -- buffering is now block-buffered, use lazyReadBlock instead
347 lazyReadBlock handle fo
349 -3 -> -- buffering is now line-buffered, use lazyReadLine instead
350 lazyReadLine handle fo
352 -1 -> -- error, silently close handle.
353 withHandle handle $ \ handle_ -> do
354 CCALL(closeFile) (haFO__ handle_) (0::Int){-don't bother flusing-} -- ConcHask: SAFE, won't block
355 writeHandle handle (handle_{ haType__ = ClosedHandle,
356 haFO__ = nullFile__ })
359 more <- unsafeInterleaveIO (lazyReadChar handle fo)
360 return (chr char : more)
365 %*********************************************************
367 \subsection{Simple output functions}
369 %*********************************************************
371 @hPutChar hdl ch@ writes the character @ch@ to the file
372 or channel managed by @hdl@. Characters may be buffered if
373 buffering is enabled for @hdl@
376 hPutChar :: Handle -> Char -> IO ()
378 wantWriteableHandle "hPutChar" handle $ \ handle_ -> do
379 let fo = haFO__ handle_
381 rc <- mayBlock fo (CCALL(filePutc) fo c) -- ConcHask: UNSAFE, may block.
382 writeHandle handle handle_
385 else constructErrorAndFail "hPutChar"
389 @hPutStr hdl s@ writes the string @s@ to the file or
390 channel managed by @hdl@, buffering the output if needs be.
393 hPutStr :: Handle -> String -> IO ()
395 wantWriteableHandle "hPutStr" handle $ \ handle_ -> do
396 let fo = haFO__ handle_
398 case haBufferMode__ handle_ of
400 buf <- CCALL(getWriteableBuf) fo
401 pos <- CCALL(getBufWPtr) fo
402 bsz <- CCALL(getBufSize) fo
403 writeLines fo buf bsz pos str
404 BlockBuffering _ -> do
405 buf <- CCALL(getWriteableBuf) fo
406 pos <- CCALL(getBufWPtr) fo
407 bsz <- CCALL(getBufSize) fo
408 writeBlocks fo buf bsz pos str
411 writeHandle handle handle_
415 Going across the border between Haskell and C is relatively costly,
416 so for block writes we pack the character strings on the Haskell-side
417 before passing the external write routine a pointer to the buffer.
422 #ifdef __CONCURRENT_HASKELL__
423 /* See comment in shoveString below for explanation */
424 #warning delayed update of buffer disnae work with killThread
427 #ifndef __PARALLEL_HASKELL__
428 writeLines :: ForeignObj -> Addr -> Int -> Int -> String -> IO ()
430 writeLines :: Addr -> Addr -> Int -> Int -> String -> IO ()
432 writeLines obj buf bufLen initPos s =
434 shoveString :: Int -> [Char] -> IO ()
439 CCALL(setBufWPtr) obj (0::Int)
442 At the end of a buffer write, update the buffer position
443 in the underlying file object, so that if the handle
444 is subsequently dropped by the program, the whole
445 buffer will be properly flushed.
447 There's one case where this delayed up-date of the buffer
448 position can go wrong: if a thread is killed, it might be
449 in the middle of filling up a buffer, with the result that
450 the partial buffer update is lost upon finalisation. Not
451 that killing of threads is supported at the moment.
454 CCALL(setBufWPtr) obj n
457 primWriteCharOffAddr buf n x
458 {- Flushing on buffer exhaustion or newlines (even if it isn't the last one) -}
459 if n == bufLen || x == '\n'
461 rc <- mayBlock obj (CCALL(writeFileObject) obj (n + 1)) -- ConcHask: UNSAFE, may block.
463 then shoveString 0 xs
464 else constructErrorAndFail "writeLines"
466 shoveString (n + 1) xs
468 shoveString initPos s
469 #else /* ndef __HUGS__ */
470 #ifndef __PARALLEL_HASKELL__
471 writeLines :: ForeignObj -> Addr -> Int -> Int -> String -> IO ()
473 writeLines :: Addr -> Addr -> Int -> Int -> String -> IO ()
475 writeLines obj buf (I# bufLen) (I# initPos#) s =
477 write_char :: Addr -> Int# -> Char# -> IO ()
478 write_char (A# buf#) n# c# =
480 case (writeCharOffAddr# buf# n# c# s#) of s2# -> (# s2#, () #)
482 shoveString :: Int# -> [Char] -> IO ()
487 CCALL(setBufWPtr) obj (0::Int)
490 At the end of a buffer write, update the buffer position
491 in the underlying file object, so that if the handle
492 is subsequently dropped by the program, the whole
493 buffer will be properly flushed.
495 There's one case where this delayed up-date of the buffer
496 position can go wrong: if a thread is killed, it might be
497 in the middle of filling up a buffer, with the result that
498 the partial buffer update is lost upon finalisation. Not
499 that killing of threads is supported at the moment.
502 CCALL(setBufWPtr) obj (I# n)
506 {- Flushing on buffer exhaustion or newlines (even if it isn't the last one) -}
507 if n ==# bufLen || x `eqChar#` '\n'#
509 rc <- mayBlock obj (CCALL(writeFileObject) obj (I# (n +# 1#))) -- ConcHask: UNSAFE, may block.
511 then shoveString 0# xs
512 else constructErrorAndFail "writeLines"
514 shoveString (n +# 1#) xs
516 shoveString initPos# s
517 #endif /* ndef __HUGS__ */
520 #ifndef __PARALLEL_HASKELL__
521 writeBlocks :: ForeignObj -> Addr -> Int -> Int -> String -> IO ()
523 writeBlocks :: Addr -> Addr -> Int -> Int -> String -> IO ()
525 writeBlocks obj buf bufLen initPos s =
527 shoveString :: Int -> [Char] -> IO ()
532 CCALL(setBufWPtr) obj (0::Int)
535 At the end of a buffer write, update the buffer position
536 in the underlying file object, so that if the handle
537 is subsequently dropped by the program, the whole
538 buffer will be properly flushed.
540 There's one case where this delayed up-date of the buffer
541 position can go wrong: if a thread is killed, it might be
542 in the middle of filling up a buffer, with the result that
543 the partial buffer update is lost upon finalisation. However,
544 by the time killThread is supported, Haskell finalisers are also
545 likely to be in, which means the 'IOFileObject' hack can go
549 CCALL(setBufWPtr) obj n
552 primWriteCharOffAddr buf n x
555 rc <- mayBlock obj (CCALL(writeFileObject) obj (n + 1)) -- ConcHask: UNSAFE, may block.
557 then shoveString 0 xs
558 else constructErrorAndFail "writeChunks"
560 shoveString (n + 1) xs
562 shoveString initPos s
563 #else /* ndef __HUGS__ */
564 #ifndef __PARALLEL_HASKELL__
565 writeBlocks :: ForeignObj -> Addr -> Int -> Int -> String -> IO ()
567 writeBlocks :: Addr -> Addr -> Int -> Int -> String -> IO ()
569 writeBlocks obj buf (I# bufLen) (I# initPos#) s =
571 write_char :: Addr -> Int# -> Char# -> IO ()
572 write_char (A# buf#) n# c# =
574 case (writeCharOffAddr# buf# n# c# s#) of s2# -> (# s2#, () #)
576 shoveString :: Int# -> [Char] -> IO ()
581 CCALL(setBufWPtr) obj (0::Int)
584 At the end of a buffer write, update the buffer position
585 in the underlying file object, so that if the handle
586 is subsequently dropped by the program, the whole
587 buffer will be properly flushed.
589 There's one case where this delayed up-date of the buffer
590 position can go wrong: if a thread is killed, it might be
591 in the middle of filling up a buffer, with the result that
592 the partial buffer update is lost upon finalisation. However,
593 by the time killThread is supported, Haskell finalisers are also
594 likely to be in, which means the 'IOFileObject' hack can go
598 CCALL(setBufWPtr) obj (I# n)
604 rc <- mayBlock obj (CCALL(writeFileObject) obj (I# (n +# 1#))) -- ConcHask: UNSAFE, may block.
606 then shoveString 0# xs
607 else constructErrorAndFail "writeChunks"
609 shoveString (n +# 1#) xs
611 shoveString initPos# s
612 #endif /* ndef __HUGS__ */
614 #ifndef __PARALLEL_HASKELL__
615 writeChars :: ForeignObj -> String -> IO ()
617 writeChars :: Addr -> String -> IO ()
619 writeChars _fo "" = return ()
620 writeChars fo (c:cs) = do
621 rc <- mayBlock fo (CCALL(filePutc) fo c) -- ConcHask: UNSAFE, may block.
623 then writeChars fo cs
624 else constructErrorAndFail "writeChars"
628 Computation @hPrint hdl t@ writes the string representation of {\em t}
629 given by the @shows@ function to the file or channel managed by {\em
632 [ Seem to have disappeared from the 1.4 interface - SOF 2/97 ]
635 hPrint :: Show a => Handle -> a -> IO ()
636 hPrint hdl = hPutStrLn hdl . show
639 Derived action @hPutStrLn hdl str@ writes the string \tr{str} to
640 the handle \tr{hdl}, adding a newline at the end.
643 hPutStrLn :: Handle -> String -> IO ()
644 hPutStrLn hndl str = do
651 %*********************************************************
653 \subsection{Try and bracket}
655 %*********************************************************
657 The construct @try comp@ exposes errors which occur within a
658 computation, and which are not fully handled. It always succeeds.
661 try :: IO a -> IO (Either IOError a)
662 try f = catch (do r <- f
666 bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
667 bracket before after m = do
675 -- variant of the above where middle computation doesn't want x
676 bracket_ :: IO a -> (a -> IO b) -> IO c -> IO c
677 bracket_ before after m = do
686 %*********************************************************
688 \subsection{Standard IO}
690 %*********************************************************
692 The Prelude has from Day 1 provided a collection of common
693 IO functions. We define these here, but let the Prelude
697 putChar :: Char -> IO ()
698 putChar c = hPutChar stdout c
700 putStr :: String -> IO ()
701 putStr s = hPutStr stdout s
703 putStrLn :: String -> IO ()
704 putStrLn s = do putStr s
707 print :: Show a => a -> IO ()
708 print x = putStrLn (show x)
711 getChar = hGetChar stdin
714 getLine = hGetLine stdin
716 getContents :: IO String
717 getContents = hGetContents stdin
719 interact :: (String -> String) -> IO ()
720 interact f = do s <- getContents
723 readFile :: FilePath -> IO String
724 readFile name = openFile name ReadMode >>= hGetContents
726 writeFile :: FilePath -> String -> IO ()
727 writeFile name str = do
728 hdl <- openFile name WriteMode
732 appendFile :: FilePath -> String -> IO ()
733 appendFile name str = do
734 hdl <- openFile name AppendMode
738 readLn :: Read a => IO a
739 readLn = do l <- getLine
743 #endif /* ndef HEAD */