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(..), Maybe(..) )
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 __CONCURRENT_HASKELL__
132 #define unpackNBytesAccST primUnpackCStringAcc
137 Standard instances for @Handle@:
140 instance Eq IOError where
141 (IOError h1 e1 loc1 str1) == (IOError h2 e2 loc2 str2) =
142 e1==e2 && str1==str2 && h1==h2 && loc1 == loc2
144 instance Eq Handle where
145 (Handle h1) == (Handle h2) = h1 == h2
147 --Type declared in IOHandle, instance here because it depends on Eq.Handle
148 instance Eq HandlePosn where
149 (HandlePosn h1 p1) == (HandlePosn h2 p2) = p1==p2 && h1==h2
151 -- Type declared in IOBase, instance here because it
152 -- depends on PrelRead.(Read Maybe) instance.
153 instance Read BufferMode where
156 (\r -> let lr = lex r
158 [(NoBuffering, rest) | ("NoBuffering", rest) <- lr] ++
159 [(LineBuffering,rest) | ("LineBuffering",rest) <- lr] ++
160 [(BlockBuffering mb,rest2) | ("BlockBuffering",rest1) <- lr,
161 (mb, rest2) <- reads rest1])
165 %*********************************************************
167 \subsection{Simple input operations}
169 %*********************************************************
171 Computation @hReady hdl@ indicates whether at least
172 one item is available for input from handle {\em hdl}.
174 @hWaitForInput@ is the generalisation, wait for \tr{n} milliseconds
175 before deciding whether the Handle has run dry or not.
177 If @hWaitForInput@ finds anything in the Handle's buffer, it immediately returns.
178 If not, it tries to read from the underlying OS handle. Notice that
179 for buffered Handles connected to terminals this means waiting until a complete
183 hReady :: Handle -> IO Bool
184 hReady h = hWaitForInput h 0
186 hWaitForInput :: Handle -> Int -> IO Bool
187 hWaitForInput handle msecs =
188 wantReadableHandle "hWaitForInput" handle $ \ handle_ -> do
189 rc <- inputReady (haFO__ handle_) (msecs::Int) -- ConcHask: SAFE, won't block
193 _ -> constructErrorAndFail "hWaitForInput"
196 @hGetChar hdl@ reads the next character from handle @hdl@,
197 blocking until a character is available.
200 hGetChar :: Handle -> IO Char
202 wantReadableHandle "hGetChar" handle $ \ handle_ -> do
203 let fo = haFO__ handle_
204 intc <- mayBlock fo (fileGetc fo) -- ConcHask: UNSAFE, may block
205 if intc /= ((-1)::Int)
206 then return (chr intc)
207 else constructErrorAndFail "hGetChar"
210 If EOF is reached before EOL is encountered, ignore the
211 EOF and return the partial line. Next attempt at calling
212 hGetLine on the handle will yield an EOF IO exception though.
214 hGetLine :: Handle -> IO String
228 if isEOFError err then
240 @hLookahead hdl@ returns the next character from handle @hdl@
241 without removing it from the input buffer, blocking until a
242 character is available.
245 hLookAhead :: Handle -> IO Char
247 wantReadableHandle "hLookAhead" handle $ \ handle_ -> do
248 let fo = haFO__ handle_
249 intc <- mayBlock fo (fileLookAhead fo) -- ConcHask: UNSAFE, may block
251 then return (chr intc)
252 else constructErrorAndFail "hLookAhead"
257 %*********************************************************
259 \subsection{Getting the entire contents of a handle}
261 %*********************************************************
263 @hGetContents hdl@ returns the list of characters corresponding
264 to the unread portion of the channel or file managed by @hdl@,
265 which is made semi-closed.
268 hGetContents :: Handle -> IO String
269 hGetContents handle =
270 -- can't use wantReadableHandle here, because we want to side effect
272 withHandle handle $ \ handle_ -> do
273 case haType__ handle_ of
274 ErrorHandle theError -> ioError theError
275 ClosedHandle -> ioe_closedHandle "hGetContents" handle
276 SemiClosedHandle -> ioe_closedHandle "hGetContents" handle
277 AppendHandle -> ioError not_readable_error
278 WriteHandle -> ioError not_readable_error
281 To avoid introducing an extra layer of buffering here,
282 we provide three lazy read methods, based on character,
283 line, and block buffering.
285 let handle_' = handle_{ haType__ = SemiClosedHandle }
286 case (haBufferMode__ handle_) of
288 str <- unsafeInterleaveIO (lazyReadLine handle (haFO__ handle_))
289 return (handle_', str)
290 BlockBuffering _ -> do
291 str <- unsafeInterleaveIO (lazyReadBlock handle (haFO__ handle_))
292 return (handle_', str)
294 str <- unsafeInterleaveIO (lazyReadChar handle (haFO__ handle_))
295 return (handle_', str)
298 IOError (Just handle) IllegalOperation "hGetContents"
299 ("handle is not open for reading")
302 Note that someone may close the semi-closed handle (or change its buffering),
303 so each these lazy read functions are pulled on, they have to check whether
304 the handle has indeed been closed.
307 #ifndef __PARALLEL_HASKELL__
308 lazyReadBlock :: Handle -> ForeignObj -> IO String
309 lazyReadLine :: Handle -> ForeignObj -> IO String
310 lazyReadChar :: Handle -> ForeignObj -> IO String
312 lazyReadBlock :: Handle -> Addr -> IO String
313 lazyReadLine :: Handle -> Addr -> IO String
314 lazyReadChar :: Handle -> Addr -> IO String
317 lazyReadBlock handle fo = do
318 buf <- getBufStart fo 0
319 bytes <- mayBlock fo (readBlock fo) -- ConcHask: UNSAFE, may block.
321 -3 -> -- buffering has been turned off, use lazyReadChar instead
322 lazyReadChar handle fo
324 -1 -> -- an error occurred, close the handle
325 withHandle handle $ \ handle_ -> do
326 closeFile (haFO__ handle_) 0{-don't bother flushing-} -- ConcHask: SAFE, won't block.
327 return (handle_ { haType__ = ClosedHandle,
328 haFO__ = nullFile__ },
331 more <- unsafeInterleaveIO (lazyReadBlock handle fo)
332 stToIO (unpackNBytesAccST buf bytes more)
334 lazyReadLine handle fo = do
335 bytes <- mayBlock fo (readLine fo) -- ConcHask: UNSAFE, may block.
337 -3 -> -- buffering has been turned off, use lazyReadChar instead
338 lazyReadChar handle fo
339 -2 -> return "" -- handle closed by someone else, stop reading.
340 -1 -> -- an error occurred, close the handle
341 withHandle handle $ \ handle_ -> do
342 closeFile (haFO__ handle_) 0{- don't bother flushing-} -- ConcHask: SAFE, won't block
343 return (handle_ { haType__ = ClosedHandle,
344 haFO__ = nullFile__ },
347 more <- unsafeInterleaveIO (lazyReadLine handle fo)
348 buf <- getBufStart fo bytes -- ConcHask: won't block
349 stToIO (unpackNBytesAccST buf bytes more)
351 lazyReadChar handle fo = do
352 char <- mayBlock fo (readChar fo) -- ConcHask: UNSAFE, may block.
354 -4 -> -- buffering is now block-buffered, use lazyReadBlock instead
355 lazyReadBlock handle fo
357 -3 -> -- buffering is now line-buffered, use lazyReadLine instead
358 lazyReadLine handle fo
360 -1 -> -- error, silently close handle.
361 withHandle handle $ \ handle_ -> do
362 closeFile (haFO__ handle_) 0{-don't bother flusing-} -- ConcHask: SAFE, won't block
363 return (handle_{ haType__ = ClosedHandle,
364 haFO__ = nullFile__ },
367 more <- unsafeInterleaveIO (lazyReadChar handle fo)
368 return (chr char : more)
373 %*********************************************************
375 \subsection{Simple output functions}
377 %*********************************************************
379 @hPutChar hdl ch@ writes the character @ch@ to the file
380 or channel managed by @hdl@. Characters may be buffered if
381 buffering is enabled for @hdl@
384 hPutChar :: Handle -> Char -> IO ()
386 wantWriteableHandle "hPutChar" handle $ \ handle_ -> do
387 let fo = haFO__ handle_
389 rc <- mayBlock fo (filePutc fo c) -- ConcHask: UNSAFE, may block.
392 else constructErrorAndFail "hPutChar"
396 @hPutStr hdl s@ writes the string @s@ to the file or
397 channel managed by @hdl@, buffering the output if needs be.
400 hPutStr :: Handle -> String -> IO ()
402 wantWriteableHandle "hPutStr" handle $ \ handle_ -> do
403 let fo = haFO__ handle_
405 case haBufferMode__ handle_ of
407 buf <- getWriteableBuf fo
410 writeLines fo buf bsz pos str
411 BlockBuffering _ -> do
412 buf <- getWriteableBuf fo
415 writeBlocks fo buf bsz pos str
420 Going across the border between Haskell and C is relatively costly,
421 so for block writes we pack the character strings on the Haskell-side
422 before passing the external write routine a pointer to the buffer.
427 #ifdef __CONCURRENT_HASKELL__
428 /* See comment in shoveString below for explanation */
429 #warning delayed update of buffer disnae work with killThread
432 #ifndef __PARALLEL_HASKELL__
433 writeLines :: ForeignObj -> Addr -> Int -> Int -> String -> IO ()
435 writeLines :: Addr -> Addr -> Int -> Int -> String -> IO ()
437 writeLines obj buf bufLen initPos s =
439 shoveString :: Int -> [Char] -> IO ()
444 setBufWPtr obj 0{-new pos-}
447 At the end of a buffer write, update the buffer position
448 in the underlying file object, so that if the handle
449 is subsequently dropped by the program, the whole
450 buffer will be properly flushed.
452 There's one case where this delayed up-date of the buffer
453 position can go wrong: if a thread is killed, it might be
454 in the middle of filling up a buffer, with the result that
455 the partial buffer update is lost upon finalisation. Not
456 that killing of threads is supported at the moment.
462 primWriteCharOffAddr buf n x
463 {- Flushing on buffer exhaustion or newlines (even if it isn't the last one) -}
464 if n == bufLen || x == '\n'
466 rc <- mayBlock obj (writeFileObject obj (n + 1)) -- ConcHask: UNSAFE, may block.
468 then shoveString 0 xs
469 else constructErrorAndFail "writeLines"
471 shoveString (n + 1) xs
473 shoveString initPos s
474 #else /* ndef __HUGS__ */
475 #ifndef __PARALLEL_HASKELL__
476 writeLines :: ForeignObj -> Addr -> Int -> Int -> String -> IO ()
478 writeLines :: Addr -> Addr -> Int -> Int -> String -> IO ()
480 writeLines obj buf (I# bufLen) (I# initPos#) s =
482 write_char :: Addr -> Int# -> Char# -> IO ()
483 write_char (A# buf#) n# c# =
485 case (writeCharOffAddr# buf# n# c# s#) of s2# -> (# s2#, () #)
487 shoveString :: Int# -> [Char] -> IO ()
495 At the end of a buffer write, update the buffer position
496 in the underlying file object, so that if the handle
497 is subsequently dropped by the program, the whole
498 buffer will be properly flushed.
500 There's one case where this delayed up-date of the buffer
501 position can go wrong: if a thread is killed, it might be
502 in the middle of filling up a buffer, with the result that
503 the partial buffer update is lost upon finalisation. Not
504 that killing of threads is supported at the moment.
507 setBufWPtr obj (I# n)
511 {- Flushing on buffer exhaustion or newlines (even if it isn't the last one) -}
512 if n ==# bufLen || x `eqChar#` '\n'#
514 rc <- mayBlock obj (writeFileObject obj (I# (n +# 1#))) -- ConcHask: UNSAFE, may block.
516 then shoveString 0# xs
517 else constructErrorAndFail "writeLines"
519 shoveString (n +# 1#) xs
521 shoveString initPos# s
522 #endif /* ndef __HUGS__ */
525 #ifndef __PARALLEL_HASKELL__
526 writeBlocks :: ForeignObj -> Addr -> Int -> Int -> String -> IO ()
528 writeBlocks :: Addr -> Addr -> Int -> Int -> String -> IO ()
530 writeBlocks obj buf bufLen initPos s =
532 shoveString :: Int -> [Char] -> IO ()
537 setBufWPtr obj (0::Int)
540 At the end of a buffer write, update the buffer position
541 in the underlying file object, so that if the handle
542 is subsequently dropped by the program, the whole
543 buffer will be properly flushed.
545 There's one case where this delayed up-date of the buffer
546 position can go wrong: if a thread is killed, it might be
547 in the middle of filling up a buffer, with the result that
548 the partial buffer update is lost upon finalisation. However,
549 by the time killThread is supported, Haskell finalisers are also
550 likely to be in, which means the 'IOFileObject' hack can go
557 primWriteCharOffAddr buf n x
560 rc <- mayBlock obj (writeFileObject obj (n + 1)) -- ConcHask: UNSAFE, may block.
562 then shoveString 0 xs
563 else constructErrorAndFail "writeChunks"
565 shoveString (n + 1) xs
567 shoveString initPos s
568 #else /* ndef __HUGS__ */
569 #ifndef __PARALLEL_HASKELL__
570 writeBlocks :: ForeignObj -> Addr -> Int -> Int -> String -> IO ()
572 writeBlocks :: Addr -> Addr -> Int -> Int -> String -> IO ()
574 writeBlocks obj buf (I# bufLen) (I# initPos#) s =
576 write_char :: Addr -> Int# -> Char# -> IO ()
577 write_char (A# buf#) n# c# =
579 case (writeCharOffAddr# buf# n# c# s#) of s2# -> (# s2#, () #)
581 shoveString :: Int# -> [Char] -> IO ()
586 setBufWPtr obj (0::Int)
589 At the end of a buffer write, update the buffer position
590 in the underlying file object, so that if the handle
591 is subsequently dropped by the program, the whole
592 buffer will be properly flushed.
594 There's one case where this delayed up-date of the buffer
595 position can go wrong: if a thread is killed, it might be
596 in the middle of filling up a buffer, with the result that
597 the partial buffer update is lost upon finalisation. However,
598 by the time killThread is supported, Haskell finalisers are also
599 likely to be in, which means the 'IOFileObject' hack can go
603 setBufWPtr obj (I# n)
609 rc <- mayBlock obj (writeFileObject obj (I# (n +# 1#))) -- ConcHask: UNSAFE, may block.
611 then shoveString 0# xs
612 else constructErrorAndFail "writeChunks"
614 shoveString (n +# 1#) xs
616 shoveString initPos# s
617 #endif /* ndef __HUGS__ */
619 #ifndef __PARALLEL_HASKELL__
620 writeChars :: ForeignObj -> String -> IO ()
622 writeChars :: Addr -> String -> IO ()
624 writeChars _fo "" = return ()
625 writeChars fo (c:cs) = do
626 rc <- mayBlock fo (filePutc fo c) -- ConcHask: UNSAFE, may block.
628 then writeChars fo cs
629 else constructErrorAndFail "writeChars"
633 Computation @hPrint hdl t@ writes the string representation of {\em t}
634 given by the @shows@ function to the file or channel managed by {\em
637 [ Seem to have disappeared from the 1.4 interface - SOF 2/97 ]
640 hPrint :: Show a => Handle -> a -> IO ()
641 hPrint hdl = hPutStrLn hdl . show
644 Derived action @hPutStrLn hdl str@ writes the string \tr{str} to
645 the handle \tr{hdl}, adding a newline at the end.
648 hPutStrLn :: Handle -> String -> IO ()
649 hPutStrLn hndl str = do
656 %*********************************************************
658 \subsection{Try and bracket}
660 %*********************************************************
662 The construct @try comp@ exposes errors which occur within a
663 computation, and which are not fully handled. It always succeeds.
666 try :: IO a -> IO (Either IOError a)
667 try f = catch (do r <- f
671 bracket :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
672 bracket before after m = do
680 -- variant of the above where middle computation doesn't want x
681 bracket_ :: IO a -> (a -> IO b) -> IO c -> IO c
682 bracket_ before after m = do
691 %*********************************************************
693 \subsection{Standard IO}
695 %*********************************************************
697 The Prelude has from Day 1 provided a collection of common
698 IO functions. We define these here, but let the Prelude
702 putChar :: Char -> IO ()
703 putChar c = hPutChar stdout c
705 putStr :: String -> IO ()
706 putStr s = hPutStr stdout s
708 putStrLn :: String -> IO ()
709 putStrLn s = do putStr s
712 print :: Show a => a -> IO ()
713 print x = putStrLn (show x)
716 getChar = hGetChar stdin
719 getLine = hGetLine stdin
721 getContents :: IO String
722 getContents = hGetContents stdin
724 interact :: (String -> String) -> IO ()
725 interact f = do s <- getContents
728 readFile :: FilePath -> IO String
729 readFile name = openFile name ReadMode >>= hGetContents
731 writeFile :: FilePath -> String -> IO ()
732 writeFile name str = do
733 hdl <- openFile name WriteMode
737 appendFile :: FilePath -> String -> IO ()
738 appendFile name str = do
739 hdl <- openFile name AppendMode
743 readLn :: Read a => IO a
744 readLn = do l <- getLine
748 #endif /* ndef HEAD */