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,
111 --import PrelNum ( toInteger )
112 import PrelBounded () -- Bounded Int instance.
113 import PrelEither ( Either(..) )
114 import PrelAddr ( Addr(..), nullAddr )
115 import PrelArr ( ByteArray )
116 import PrelPack ( unpackNBytesAccST )
117 import PrelException ( ioError, catch )
119 #ifndef __PARALLEL_HASKELL__
120 import PrelForeign ( ForeignObj )
123 import Char ( ord, chr )
125 #endif /* ndef __HUGS__ */
126 #endif /* ndef BODY */
131 #define cat2(x,y) x/**/y
132 #define CCALL(fun) cat2(prim_,fun)
133 #define __CONCURRENT_HASKELL__
135 #define unpackNBytesAccST primUnpackCStringAcc
137 #define CCALL(fun) _ccall_ fun
138 #define ref_freeStdFileObject (``&freeStdFileObject''::Addr)
139 #define ref_freeFileObject (``&freeFileObject''::Addr)
140 #define const_BUFSIZ ``BUFSIZ''
145 Standard instances for @Handle@:
148 instance Eq IOError where
149 (IOError h1 e1 loc1 str1) == (IOError h2 e2 loc2 str2) =
150 e1==e2 && str1==str2 && h1==h2 && loc1 == loc2
152 instance Eq Handle where
153 (Handle h1) == (Handle h2) = h1 == h2
155 --Type declared in IOHandle, instance here because it depends on Eq.Handle
156 instance Eq HandlePosn where
157 (HandlePosn h1 p1) == (HandlePosn h2 p2) = p1==p2 && h1==h2
159 -- Type declared in IOBase, instance here because it
160 -- depends on PrelRead.(Read Maybe) instance.
161 instance Read BufferMode where
164 (\r -> let lr = lex r
166 [(NoBuffering, rest) | ("NoBuffering", rest) <- lr] ++
167 [(LineBuffering,rest) | ("LineBuffering",rest) <- lr] ++
168 [(BlockBuffering mb,rest2) | ("BlockBuffering",rest1) <- lr,
169 (mb, rest2) <- reads rest1])
173 %*********************************************************
175 \subsection{Simple input operations}
177 %*********************************************************
179 Computation @hReady hdl@ indicates whether at least
180 one item is available for input from handle {\em hdl}.
182 @hWaitForInput@ is the generalisation, wait for \tr{n} milliseconds
183 before deciding whether the Handle has run dry or not.
185 If @hWaitForInput@ finds anything in the Handle's buffer, it immediately returns.
186 If not, it tries to read from the underlying OS handle. Notice that
187 for buffered Handles connected to terminals this means waiting until a complete
191 hReady :: Handle -> IO Bool
192 hReady h = hWaitForInput h 0
194 hWaitForInput :: Handle -> Int -> IO Bool
195 hWaitForInput handle msecs =
196 wantReadableHandle "hWaitForInput" handle $ \ handle_ -> do
197 rc <- CCALL(inputReady) (haFO__ handle_) (msecs::Int) -- ConcHask: SAFE, won't block
198 writeHandle handle handle_
202 _ -> constructErrorAndFail "hWaitForInput"
205 @hGetChar hdl@ reads the next character from handle @hdl@,
206 blocking until a character is available.
209 hGetChar :: Handle -> IO Char
211 wantReadableHandle "hGetChar" handle $ \ handle_ -> do
212 let fo = haFO__ handle_
213 intc <- mayBlock fo (CCALL(fileGetc) fo) -- ConcHask: UNSAFE, may block
214 writeHandle handle handle_
215 if intc /= ((-1)::Int)
216 then return (chr intc)
217 else constructErrorAndFail "hGetChar"
219 hGetLine :: Handle -> IO String
230 @hLookahead hdl@ returns the next character from handle @hdl@
231 without removing it from the input buffer, blocking until a
232 character is available.
235 hLookAhead :: Handle -> IO Char
236 hLookAhead handle = do
237 wantReadableHandle "hLookAhead" handle $ \ handle_ -> do
238 let fo = haFO__ handle_
239 intc <- mayBlock fo (CCALL(fileLookAhead) fo) -- ConcHask: UNSAFE, may block
240 writeHandle handle handle_
242 then return (chr intc)
243 else constructErrorAndFail "hLookAhead"
248 %*********************************************************
250 \subsection{Getting the entire contents of a handle}
252 %*********************************************************
254 @hGetContents hdl@ returns the list of characters corresponding
255 to the unread portion of the channel or file managed by @hdl@,
256 which is made semi-closed.
259 hGetContents :: Handle -> IO String
260 hGetContents handle =
261 wantReadableHandle "hGetContents" handle $ \ handle_ -> do
263 To avoid introducing an extra layer of buffering here,
264 we provide three lazy read methods, based on character,
265 line, and block buffering.
267 writeHandle handle (handle_{ haType__ = SemiClosedHandle })
268 case (haBufferMode__ handle_) of
269 LineBuffering -> unsafeInterleaveIO (lazyReadLine handle (haFO__ handle_))
270 BlockBuffering _ -> unsafeInterleaveIO (lazyReadBlock handle (haFO__ handle_))
271 NoBuffering -> unsafeInterleaveIO (lazyReadChar handle (haFO__ handle_))
275 Note that someone may close the semi-closed handle (or change its buffering),
276 so each these lazy read functions are pulled on, they have to check whether
277 the handle has indeed been closed.
280 #ifndef __PARALLEL_HASKELL__
281 lazyReadBlock :: Handle -> ForeignObj -> IO String
282 lazyReadLine :: Handle -> ForeignObj -> IO String
283 lazyReadChar :: Handle -> ForeignObj -> IO String
285 lazyReadBlock :: Handle -> Addr -> IO String
286 lazyReadLine :: Handle -> Addr -> IO String
287 lazyReadChar :: Handle -> Addr -> IO String
290 lazyReadBlock handle fo = do
291 buf <- CCALL(getBufStart) fo (0::Int)
292 bytes <- mayBlock fo (CCALL(readBlock) fo) -- ConcHask: UNSAFE, may block.
294 -3 -> -- buffering has been turned off, use lazyReadChar instead
295 lazyReadChar handle fo
297 -1 -> -- an error occurred, close the handle
298 withHandle handle $ \ handle_ -> do
299 CCALL(closeFile) (haFO__ handle_) (0::Int){-don't bother flushing-} -- ConcHask: SAFE, won't block.
300 writeHandle handle (handle_ { haType__ = ClosedHandle,
301 haFO__ = nullFile__ })
304 more <- unsafeInterleaveIO (lazyReadBlock handle fo)
305 stToIO (unpackNBytesAccST buf bytes more)
307 lazyReadLine handle fo = do
308 bytes <- mayBlock fo (CCALL(readLine) fo) -- ConcHask: UNSAFE, may block.
310 -3 -> -- buffering has been turned off, use lazyReadChar instead
311 lazyReadChar handle fo
312 -2 -> return "" -- handle closed by someone else, stop reading.
313 -1 -> -- an error occurred, close the handle
314 withHandle handle $ \ handle_ -> do
315 CCALL(closeFile) (haFO__ handle_) (0::Int){- don't bother flushing-} -- ConcHask: SAFE, won't block
316 writeHandle handle (handle_ { haType__ = ClosedHandle,
317 haFO__ = nullFile__ })
320 more <- unsafeInterleaveIO (lazyReadLine handle fo)
321 buf <- CCALL(getBufStart) fo bytes -- ConcHask: won't block
322 stToIO (unpackNBytesAccST buf bytes more)
324 lazyReadChar handle fo = do
325 char <- mayBlock fo (CCALL(readChar) fo) -- ConcHask: UNSAFE, may block.
327 -4 -> -- buffering is now block-buffered, use lazyReadBlock instead
328 lazyReadBlock handle fo
330 -3 -> -- buffering is now line-buffered, use lazyReadLine instead
331 lazyReadLine handle fo
333 -1 -> -- error, silently close handle.
334 withHandle handle $ \ handle_ -> do
335 CCALL(closeFile) (haFO__ handle_) (0::Int){-don't bother flusing-} -- ConcHask: SAFE, won't block
336 writeHandle handle (handle_{ haType__ = ClosedHandle,
337 haFO__ = nullFile__ })
340 more <- unsafeInterleaveIO (lazyReadChar handle fo)
341 return (chr char : more)
346 %*********************************************************
348 \subsection{Simple output functions}
350 %*********************************************************
352 @hPutChar hdl ch@ writes the character @ch@ to the file
353 or channel managed by @hdl@. Characters may be buffered if
354 buffering is enabled for @hdl@
357 hPutChar :: Handle -> Char -> IO ()
359 wantWriteableHandle "hPutChar" handle $ \ handle_ -> do
360 let fo = haFO__ handle_
362 rc <- mayBlock fo (CCALL(filePutc) fo c) -- ConcHask: UNSAFE, may block.
363 writeHandle handle handle_
366 else constructErrorAndFail "hPutChar"
370 @hPutStr hdl s@ writes the string @s@ to the file or
371 channel managed by @hdl@, buffering the output if needs be.
374 hPutStr :: Handle -> String -> IO ()
376 wantWriteableHandle "hPutStr" handle $ \ handle_ -> do
377 let fo = haFO__ handle_
379 case haBufferMode__ handle_ of
381 buf <- CCALL(getWriteableBuf) fo
382 pos <- CCALL(getBufWPtr) fo
383 bsz <- CCALL(getBufSize) fo
384 writeLines fo buf bsz pos str
385 BlockBuffering _ -> do
386 buf <- CCALL(getWriteableBuf) fo
387 pos <- CCALL(getBufWPtr) fo
388 bsz <- CCALL(getBufSize) fo
389 writeBlocks fo buf bsz pos str
392 writeHandle handle handle_
396 Going across the border between Haskell and C is relatively costly,
397 so for block writes we pack the character strings on the Haskell-side
398 before passing the external write routine a pointer to the buffer.
403 #ifdef __CONCURRENT_HASKELL__
404 /* See comment in shoveString below for explanation */
405 #warning delayed update of buffer disnae work with killThread
408 #ifndef __PARALLEL_HASKELL__
409 writeLines :: ForeignObj -> Addr -> Int -> Int -> String -> IO ()
411 writeLines :: Addr -> Addr -> Int -> Int -> String -> IO ()
413 writeLines obj buf bufLen initPos s =
415 shoveString :: Int -> [Char] -> IO ()
420 CCALL(setBufWPtr) obj (0::Int)
423 At the end of a buffer write, update the buffer position
424 in the underlying file object, so that if the handle
425 is subsequently dropped by the program, the whole
426 buffer will be properly flushed.
428 There's one case where this delayed up-date of the buffer
429 position can go wrong: if a thread is killed, it might be
430 in the middle of filling up a buffer, with the result that
431 the partial buffer update is lost upon finalisation. Not
432 that killing of threads is supported at the moment.
435 CCALL(setBufWPtr) obj n
438 primWriteCharOffAddr buf n x
439 {- Flushing on buffer exhaustion or newlines (even if it isn't the last one) -}
440 if n == bufLen || x == '\n'
442 rc <- mayBlock obj (CCALL(writeFileObject) obj (n + 1)) -- ConcHask: UNSAFE, may block.
444 then shoveString 0 xs
445 else constructErrorAndFail "writeLines"
447 shoveString (n + 1) xs
449 shoveString initPos s
450 #else /* ndef __HUGS__ */
451 #ifndef __PARALLEL_HASKELL__
452 writeLines :: ForeignObj -> Addr -> Int -> Int -> String -> IO ()
454 writeLines :: Addr -> Addr -> Int -> Int -> String -> IO ()
456 writeLines obj buf (I# bufLen) (I# initPos#) s =
458 write_char :: Addr -> Int# -> Char# -> IO ()
459 write_char (A# buf#) n# c# =
461 case (writeCharOffAddr# buf# n# c# s#) of s2# -> (# s2#, () #)
463 shoveString :: Int# -> [Char] -> IO ()
468 CCALL(setBufWPtr) obj (0::Int)
471 At the end of a buffer write, update the buffer position
472 in the underlying file object, so that if the handle
473 is subsequently dropped by the program, the whole
474 buffer will be properly flushed.
476 There's one case where this delayed up-date of the buffer
477 position can go wrong: if a thread is killed, it might be
478 in the middle of filling up a buffer, with the result that
479 the partial buffer update is lost upon finalisation. Not
480 that killing of threads is supported at the moment.
483 CCALL(setBufWPtr) obj (I# n)
487 {- Flushing on buffer exhaustion or newlines (even if it isn't the last one) -}
488 if n ==# bufLen || x `eqChar#` '\n'#
490 rc <- mayBlock obj (CCALL(writeFileObject) obj (I# (n +# 1#))) -- ConcHask: UNSAFE, may block.
492 then shoveString 0# xs
493 else constructErrorAndFail "writeLines"
495 shoveString (n +# 1#) xs
497 shoveString initPos# s
498 #endif /* ndef __HUGS__ */
501 #ifndef __PARALLEL_HASKELL__
502 writeBlocks :: ForeignObj -> Addr -> Int -> Int -> String -> IO ()
504 writeBlocks :: Addr -> Addr -> Int -> Int -> String -> IO ()
506 writeBlocks obj buf bufLen initPos s =
508 shoveString :: Int -> [Char] -> IO ()
513 CCALL(setBufWPtr) obj (0::Int)
516 At the end of a buffer write, update the buffer position
517 in the underlying file object, so that if the handle
518 is subsequently dropped by the program, the whole
519 buffer will be properly flushed.
521 There's one case where this delayed up-date of the buffer
522 position can go wrong: if a thread is killed, it might be
523 in the middle of filling up a buffer, with the result that
524 the partial buffer update is lost upon finalisation. However,
525 by the time killThread is supported, Haskell finalisers are also
526 likely to be in, which means the 'IOFileObject' hack can go
530 CCALL(setBufWPtr) obj n
533 primWriteCharOffAddr buf n x
536 rc <- mayBlock obj (CCALL(writeFileObject) obj (n + 1)) -- ConcHask: UNSAFE, may block.
538 then shoveString 0 xs
539 else constructErrorAndFail "writeChunks"
541 shoveString (n + 1) xs
543 shoveString initPos s
544 #else /* ndef __HUGS__ */
545 #ifndef __PARALLEL_HASKELL__
546 writeBlocks :: ForeignObj -> Addr -> Int -> Int -> String -> IO ()
548 writeBlocks :: Addr -> Addr -> Int -> Int -> String -> IO ()
550 writeBlocks obj buf (I# bufLen) (I# initPos#) s =
552 write_char :: Addr -> Int# -> Char# -> IO ()
553 write_char (A# buf#) n# c# =
555 case (writeCharOffAddr# buf# n# c# s#) of s2# -> (# s2#, () #)
557 shoveString :: Int# -> [Char] -> IO ()
562 CCALL(setBufWPtr) obj (0::Int)
565 At the end of a buffer write, update the buffer position
566 in the underlying file object, so that if the handle
567 is subsequently dropped by the program, the whole
568 buffer will be properly flushed.
570 There's one case where this delayed up-date of the buffer
571 position can go wrong: if a thread is killed, it might be
572 in the middle of filling up a buffer, with the result that
573 the partial buffer update is lost upon finalisation. However,
574 by the time killThread is supported, Haskell finalisers are also
575 likely to be in, which means the 'IOFileObject' hack can go
579 CCALL(setBufWPtr) obj (I# n)
585 rc <- mayBlock obj (CCALL(writeFileObject) obj (I# (n +# 1#))) -- ConcHask: UNSAFE, may block.
587 then shoveString 0# xs
588 else constructErrorAndFail "writeChunks"
590 shoveString (n +# 1#) xs
592 shoveString initPos# s
593 #endif /* ndef __HUGS__ */
595 #ifndef __PARALLEL_HASKELL__
596 writeChars :: ForeignObj -> String -> IO ()
598 writeChars :: Addr -> String -> IO ()
600 writeChars _fo "" = return ()
601 writeChars fo (c:cs) = do
602 rc <- mayBlock fo (CCALL(filePutc) fo c) -- ConcHask: UNSAFE, may block.
604 then writeChars fo cs
605 else constructErrorAndFail "writeChars"
609 Computation @hPrint hdl t@ writes the string representation of {\em t}
610 given by the @shows@ function to the file or channel managed by {\em
613 [ Seem to have disappeared from the 1.4 interface - SOF 2/97 ]
616 hPrint :: Show a => Handle -> a -> IO ()
617 hPrint hdl = hPutStrLn hdl . show
620 Derived action @hPutStrLn hdl str@ writes the string \tr{str} to
621 the handle \tr{hdl}, adding a newline at the end.
624 hPutStrLn :: Handle -> String -> IO ()
625 hPutStrLn hndl str = do
632 %*********************************************************
634 \subsection{Try and bracket}
636 %*********************************************************
638 The construct @try comp@ exposes errors which occur within a
639 computation, and which are not fully handled. It always succeeds.
642 try :: IO a -> IO (Either IOError a)
643 try f = catch (do r <- f
647 bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
648 bracket before after m = do
656 -- variant of the above where middle computation doesn't want x
657 bracket_ :: IO a -> (a -> IO b) -> IO c -> IO c
658 bracket_ before after m = do
667 %*********************************************************
669 \subsection{Standard IO}
671 %*********************************************************
673 The Prelude has from Day 1 provided a collection of common
674 IO functions. We define these here, but let the Prelude
678 putChar :: Char -> IO ()
679 putChar c = hPutChar stdout c
681 putStr :: String -> IO ()
682 putStr s = hPutStr stdout s
684 putStrLn :: String -> IO ()
685 putStrLn s = do putStr s
688 print :: Show a => a -> IO ()
689 print x = putStrLn (show x)
692 getChar = hGetChar stdin
695 getLine = hGetLine stdin
697 getContents :: IO String
698 getContents = hGetContents stdin
700 interact :: (String -> String) -> IO ()
701 interact f = do s <- getContents
704 readFile :: FilePath -> IO String
705 readFile name = openFile name ReadMode >>= hGetContents
707 writeFile :: FilePath -> String -> IO ()
708 writeFile name str = do
709 hdl <- openFile name WriteMode
713 appendFile :: FilePath -> String -> IO ()
714 appendFile name str = do
715 hdl <- openFile name AppendMode
719 readLn :: Read a => IO a
720 readLn = do l <- getLine
724 #endif /* ndef HEAD */