[project @ 1997-06-03 22:25:28 by sof]
[ghc-hetmet.git] / ghc / lib / required / IO.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1994-1996
3 %
4
5 \section[IO]{Module @IO@}
6
7 \begin{code}
8 {-# OPTIONS -fno-implicit-prelude -#include "cbits/stgio.h" #-}
9
10 module IO (
11     Handle, HandlePosn,
12
13     IOMode(ReadMode,WriteMode,AppendMode,ReadWriteMode),
14     BufferMode(NoBuffering,LineBuffering,BlockBuffering),
15     SeekMode(AbsoluteSeek,RelativeSeek,SeekFromEnd),
16
17     stdin, stdout, stderr, 
18
19     openFile, hClose, 
20     hFileSize, hIsEOF, isEOF,
21     hSetBuffering, hGetBuffering, hFlush, 
22     hGetPosn, hSetPosn, hSeek, 
23     hWaitForInput, hReady, hGetChar, hGetLine, hLookAhead, hGetContents, 
24     hPutChar, hPutStr, hPutStrLn, hPrint,
25     hIsOpen, hIsClosed, hIsReadable, hIsWritable, hIsSeekable,
26
27     isAlreadyExistsError, isDoesNotExistError, isAlreadyInUseError, 
28     isFullError, isEOFError,
29     isIllegalOperation, isPermissionError, isUserError, 
30     ioeGetErrorString, 
31     ioeGetHandle, ioeGetFileName,
32     try, bracket, bracket_
33   ) where
34
35 import Ix
36 import STBase
37 import IOBase
38 import ArrBase          ( MutableByteArray(..), newCharArray )
39 import IOHandle         -- much of the real stuff is in here
40 import PackedString     ( nilPS, packCBytesST, unpackPS )
41 import PrelBase
42 import GHC
43 import Foreign          ( ForeignObj, Addr, makeForeignObj, writeForeignObj )
44 import Char             ( ord, chr )
45 \end{code}
46
47 %*********************************************************
48 %*                                                      *
49 \subsection{Signatures}
50 %*                                                      *
51 %*********************************************************
52
53 \begin{code}
54 --IOHandle:hClose                :: Handle -> IO () 
55 --IOHandle:hFileSize             :: Handle -> IO Integer
56 --IOHandle:hFlush                :: Handle -> IO () 
57 --IOHandle:hGetBuffering         :: Handle -> IO BufferMode
58 hGetChar              :: Handle -> IO Char
59 hGetContents          :: Handle -> IO String
60 --IOHandle:hGetPosn              :: Handle -> IO HandlePosn
61 --IOHandle:hIsClosed             :: Handle -> IO Bool
62 --IOHandle:hIsEOF                :: Handle -> IO Bool
63 --IOHandle:hIsOpen               :: Handle -> IO Bool
64 --IOHandle:hIsReadable           :: Handle -> IO Bool
65 --IOHandle:hIsSeekable           :: Handle -> IO Bool
66 --IOHandle:hIsWritable           :: Handle -> IO Bool
67 hLookAhead            :: Handle -> IO Char
68 hPrint                :: Show a => Handle -> a -> IO ()
69 hPutChar              :: Handle -> Char -> IO ()
70 hPutStr               :: Handle -> String -> IO ()
71 hPutStrLn             :: Handle -> String -> IO ()
72 hReady                :: Handle -> IO Bool 
73 hWaitForInput         :: Handle -> Int -> IO Bool
74
75 --IOHandle:hSeek                 :: Handle -> SeekMode -> Integer -> IO () 
76 --IOHandle:hSetBuffering         :: Handle -> BufferMode -> IO ()
77 --IOHandle:hSetPosn              :: HandlePosn -> IO () 
78 -- ioeGetFileName        :: IOError -> Maybe FilePath
79 -- ioeGetErrorString     :: IOError -> Maybe String
80 -- ioeGetHandle          :: IOError -> Maybe Handle
81 -- isAlreadyExistsError  :: IOError -> Bool
82 -- isAlreadyInUseError   :: IOError -> Bool
83 --IOHandle:isEOF                 :: IO Bool
84 -- isEOFError            :: IOError -> Bool
85 -- isFullError           :: IOError -> Bool
86 -- isIllegalOperation    :: IOError -> Bool
87 -- isPermissionError     :: IOError -> Bool
88 -- isUserError           :: IOError -> Maybe String
89 --IOHandle:openFile              :: FilePath -> IOMode -> IO Handle
90 --IOHandle:stdin, stdout, stderr :: Handle
91 \end{code}
92
93 Standard instances for @Handle@:
94
95 \begin{code}
96 instance Eq IOError where
97   (IOError h1 e1 str1) == (IOError h2 e2 str2) = 
98     e1==e2 && str1==str2 && h1==h2
99
100 instance Eq Handle where
101  h1 == h2 =
102   unsafePerformPrimIO (
103     ioToPrimIO (readHandle h1)      >>= \ h1_ ->
104     ioToPrimIO (writeHandle h1 h1_) >>
105     ioToPrimIO (readHandle h2)      >>= \ h2_ ->
106     ioToPrimIO (writeHandle h2 h2_) >>
107     return (
108      case (h1_,h2_) of
109       (ErrorHandle (IOError h1 _ _), ErrorHandle (IOError h2 _ _)) -> h1 == h2
110       (ClosedHandle, ClosedHandle) -> True
111       (SemiClosedHandle v1 _, SemiClosedHandle v2 _) -> v1 == v2
112       (ReadHandle v1 _ _ ,      ReadHandle v2 _ _)   -> v1 == v2
113       (WriteHandle v1 _ _ ,     WriteHandle v2 _ _)  -> v1 == v2
114       (AppendHandle v1 _ _ ,    AppendHandle v2 _ _) -> v1 == v2
115       (ReadWriteHandle v1 _ _ , ReadWriteHandle v2 _ _) -> v1 == v2
116       _ -> False))
117
118 instance Show Handle where {showsPrec p h = showString "<<Handle>>"}
119
120 \end{code}
121
122 %*********************************************************
123 %*                                                      *
124 \subsection{Simple input operations}
125 %*                                                      *
126 %*********************************************************
127
128 Computation @hReady hdl@ indicates whether at least
129 one item is available for input from handle {\em hdl}.
130
131 @hWaitForInput@ is the generalisation, wait for \tr{n} seconds
132 before deciding whether the Handle has run dry or not.
133
134 \begin{code}
135 --hReady :: Handle -> IO Bool
136 hReady h = hWaitForInput h 0
137
138 --hWaitForInput :: Handle -> Int -> IO Bool 
139 hWaitForInput handle nsecs = 
140     readHandle handle                               >>= \ htype ->
141     case htype of 
142       ErrorHandle ioError ->
143           writeHandle handle htype                  >>
144           fail ioError
145       ClosedHandle ->
146           writeHandle handle htype                  >>
147           ioe_closedHandle handle
148       SemiClosedHandle _ _ ->
149           writeHandle handle htype                  >>
150           ioe_closedHandle handle
151       AppendHandle _ _ _ ->
152           writeHandle handle htype                  >>
153           fail (IOError (Just handle) IllegalOperation "handle is not open for reading")
154       WriteHandle _ _ _ ->
155           writeHandle handle htype                  >>
156           fail (IOError (Just handle) IllegalOperation "handle is not open for reading")
157       other -> 
158           _ccall_ inputReady (filePtr other) nsecs  `thenIO_Prim` \ rc ->
159           writeHandle handle (markHandle htype)     >>
160           case rc of
161             0 -> return False
162             1 -> return True
163             _ -> constructErrorAndFail "hWaitForInput"
164 \end{code}
165
166 Computation $hGetChar hdl$ reads the next character from handle 
167 {\em hdl}, blocking until a character is available.
168
169 \begin{code}
170 --hGetChar :: Handle -> IO Char
171
172 hGetChar handle = 
173     readHandle handle                               >>= \ htype ->
174     case htype of 
175       ErrorHandle ioError ->
176           writeHandle handle htype                  >>
177           fail ioError
178       ClosedHandle ->
179           writeHandle handle htype                  >>
180           ioe_closedHandle handle
181       SemiClosedHandle _ _ ->
182           writeHandle handle htype                  >>
183           ioe_closedHandle handle
184       AppendHandle _ _ _ ->
185           writeHandle handle htype                  >>
186           fail (IOError (Just handle) IllegalOperation "handle is not open for reading")
187       WriteHandle _ _ _ ->
188           writeHandle handle htype                  >>
189           fail (IOError (Just handle) IllegalOperation "handle is not open for reading")
190       other -> 
191           _ccall_ fileGetc (filePtr other)          `thenIO_Prim` \ intc ->
192           writeHandle handle (markHandle htype)   >>
193           if intc /= ``EOF'' then
194               return (chr intc)
195           else
196               constructErrorAndFail "hGetChar"
197
198 hGetLine :: Handle -> IO String
199 hGetLine h = 
200  hGetChar h >>= \ c ->
201  if c == '\n' then 
202     return "" 
203  else 
204     hGetLine h >>= \ s -> return (c:s)
205 \end{code}
206
207 Computation $hLookahead hdl$ returns the next character from handle
208 {\em hdl} without removing it from the input buffer, blocking until a
209 character is available.
210
211 \begin{code}
212 --hLookAhead :: Handle -> IO Char
213
214 hLookAhead handle = 
215     readHandle handle                               >>= \ htype ->
216     case htype of 
217       ErrorHandle ioError ->
218           writeHandle handle htype                  >>
219           fail ioError
220       ClosedHandle ->
221           writeHandle handle htype                  >>
222           ioe_closedHandle handle
223       SemiClosedHandle _ _ ->
224           writeHandle handle htype                  >>
225           ioe_closedHandle handle
226       AppendHandle _ _ _ ->
227           writeHandle handle htype                  >>
228           fail (IOError (Just handle) IllegalOperation "handle is not open for reading")
229       WriteHandle _ _ _ ->
230           writeHandle handle htype                  >>
231           fail (IOError (Just handle) IllegalOperation "handle is not open for reading")
232       other -> 
233           _ccall_ fileLookAhead (filePtr other)    `thenIO_Prim` \ intc ->
234           writeHandle handle (markHandle htype)   >>
235           if intc /= ``EOF'' then
236               return (chr intc)
237           else
238               constructErrorAndFail "hLookAhead"
239 \end{code}
240
241
242 %*********************************************************
243 %*                                                      *
244 \subsection{Getting the entire contents of a handle}
245 %*                                                      *
246 %*********************************************************
247
248 Computation $hGetContents hdl$ returns the list of characters
249 corresponding to the unread portion of the channel or file managed by
250 {\em hdl}, which is made semi-closed.
251
252 \begin{code}
253 --hGetContents :: Handle -> IO String
254
255 hGetContents handle =
256     readHandle handle                               >>= \ htype ->
257     case htype of 
258       ErrorHandle ioError ->
259           writeHandle handle htype                  >>
260           fail ioError
261       ClosedHandle ->
262           writeHandle handle htype                  >>
263           ioe_closedHandle handle
264       SemiClosedHandle _ _ ->
265           writeHandle handle htype                  >>
266           ioe_closedHandle handle
267       AppendHandle _ _ _ ->
268           writeHandle handle htype                  >>
269           fail (IOError (Just handle) IllegalOperation "handle is not open for reading")
270       WriteHandle _ _ _ ->
271           writeHandle handle htype                  >>
272           fail (IOError (Just handle) IllegalOperation "handle is not open for reading")
273       other -> 
274           {- 
275              To avoid introducing an extra layer of buffering here,
276              we provide three lazy read methods, based on character,
277              line, and block buffering.
278           -}
279           stToIO (getBufferMode other)  >>= \ other ->
280           case (bufferMode other) of
281             Just LineBuffering ->
282                 allocBuf Nothing                    >>= \ buf_info ->
283                 writeHandle handle (SemiClosedHandle (filePtr other) buf_info)
284                                                     >>
285                 unsafeInterleavePrimIO (lazyReadLine handle)
286                                                     `thenIO_Prim` \ contents ->
287                 return contents
288
289             Just (BlockBuffering size) ->
290                 allocBuf size                       >>= \ buf_info ->
291                 writeHandle handle (SemiClosedHandle (filePtr other) buf_info)
292                                                     >>
293                 unsafeInterleavePrimIO (lazyReadBlock handle)
294                                                     `thenIO_Prim` \ contents ->
295                 return contents
296             _ -> -- Nothing is treated pessimistically as NoBuffering
297                 writeHandle handle (SemiClosedHandle (filePtr other) (``NULL'', 0))
298                                                     >>
299                 unsafeInterleavePrimIO (lazyReadChar handle)
300                                                     `thenIO_Prim` \ contents ->
301                 return contents
302   where
303     allocBuf :: Maybe Int -> IO (Addr, Int)
304     allocBuf msize =
305         _ccall_ malloc size                         `thenIO_Prim` \ buf ->
306         if buf /= ``NULL'' then
307             return (buf, size)
308         else
309             fail (IOError Nothing ResourceExhausted "not enough virtual memory")
310       where
311         size = 
312             case msize of
313               Just x -> x
314               Nothing -> ``BUFSIZ''
315 \end{code}
316
317 Note that someone may yank our handle out from under us, and then re-use
318 the same FILE * for something else.  Therefore, we have to re-examine the
319 handle every time through.
320
321 \begin{code}
322 lazyReadBlock :: Handle -> PrimIO String
323 lazyReadLine  :: Handle -> PrimIO String
324 lazyReadChar  :: Handle -> PrimIO String
325
326 lazyReadBlock handle =
327     ioToST (readHandle handle)                  >>= \ htype ->
328     case htype of 
329       -- There cannae be an ErrorHandle here
330       ClosedHandle ->
331           ioToST (writeHandle handle htype)     >>
332           returnPrimIO ""
333       SemiClosedHandle fp (buf, size) ->
334           _ccall_ readBlock buf fp size             >>= \ bytes ->
335           (if bytes <= 0
336           then return nilPS
337           else packCBytesST bytes buf)              >>= \ some ->
338           if bytes < 0 then
339               _ccall_ free buf                      >>= \ () ->
340               _ccall_ closeFile fp                  >>
341 #ifndef PAR
342               writeForeignObj fp ``NULL''           >>
343               ioToST (writeHandle handle (SemiClosedHandle fp (``NULL'', 0))) >>
344 #else
345               ioToST (writeHandle handle (SemiClosedHandle ``NULL'' (``NULL'', 0))) >>
346 #endif
347               returnPrimIO (unpackPS some)
348           else
349               ioToST (writeHandle handle htype)     >>
350               unsafeInterleavePrimIO (lazyReadBlock handle)
351                                                     >>= \ more ->
352               returnPrimIO (unpackPS some ++ more)
353
354 lazyReadLine handle =
355     ioToST (readHandle handle)                      >>= \ htype ->
356     case htype of 
357       -- There cannae be an ErrorHandle here
358       ClosedHandle ->
359           ioToST (writeHandle handle htype) >>
360           returnPrimIO ""
361       SemiClosedHandle fp (buf, size) ->
362           _ccall_ readLine buf fp size              >>= \ bytes ->
363           (if bytes <= 0
364           then return nilPS
365           else packCBytesST bytes buf)              >>= \ some ->
366           if bytes < 0 then
367               _ccall_ free buf                      >>= \ () ->
368               _ccall_ closeFile fp                  >>
369 #ifndef PAR
370               writeForeignObj fp ``NULL''           >>
371               ioToST (writeHandle handle (SemiClosedHandle fp (``NULL'', 0))) >>
372 #else
373               ioToST (writeHandle handle (SemiClosedHandle ``NULL'' (``NULL'', 0))) >>
374 #endif
375               returnPrimIO (unpackPS some)
376           else
377               ioToST (writeHandle handle htype)     >>
378               unsafeInterleavePrimIO (lazyReadLine handle)
379                                                     >>= \ more ->
380               returnPrimIO (unpackPS some ++ more)
381
382 lazyReadChar handle =
383     ioToST (readHandle handle)                      >>= \ htype ->
384     case htype of 
385       -- There cannae be an ErrorHandle here
386       ClosedHandle ->
387           ioToST (writeHandle handle htype)         >>
388           returnPrimIO ""
389       SemiClosedHandle fp buf_info ->
390           _ccall_ readChar fp                       >>= \ char ->
391           if char == ``EOF'' then
392               _ccall_ closeFile fp                  >>
393 #ifndef PAR
394               writeForeignObj fp ``NULL''           >>
395               ioToST (writeHandle handle (SemiClosedHandle fp (``NULL'', 0))) >>
396 #else
397               ioToST (writeHandle handle (SemiClosedHandle ``NULL'' (``NULL'', 0))) >>
398 #endif
399               returnPrimIO ""
400           else
401               ioToST (writeHandle handle htype)     >>
402               unsafeInterleavePrimIO (lazyReadChar handle)
403                                                     >>= \ more ->
404               returnPrimIO (chr char : more)
405
406 \end{code}
407
408
409 %*********************************************************
410 %*                                                      *
411 \subsection{Simple output functions}
412 %*                                                      *
413 %*********************************************************
414
415 Computation $hPutChar hdl c$ writes the character {\em c} to the file
416 or channel managed by {\em hdl}.  Characters may be buffered if
417 buffering is enabled for {\em hdl}.
418
419 \begin{code}
420 --hPutChar :: Handle -> Char -> IO ()
421
422 hPutChar handle c =
423     readHandle handle                               >>= \ htype ->
424     case htype of 
425       ErrorHandle ioError ->
426           writeHandle handle htype                  >>
427           fail ioError
428       ClosedHandle ->
429           writeHandle handle htype                  >>
430           ioe_closedHandle handle
431       SemiClosedHandle _ _ ->
432           writeHandle handle htype                  >>
433           ioe_closedHandle handle
434       ReadHandle _ _ _ ->
435           writeHandle handle htype                  >>
436           fail (IOError (Just handle) IllegalOperation "handle is not open for writing")
437       other -> 
438           _ccall_ filePutc (filePtr other) (ord c) `thenIO_Prim` \ rc ->
439           writeHandle handle (markHandle htype)   >>
440           if rc == 0 then
441               return ()
442           else
443               constructErrorAndFail "hPutChar"
444 \end{code}
445
446 Computation $hPutStr hdl s$ writes the string {\em s} to the file or
447 channel managed by {\em hdl}.
448
449 \begin{code}
450 --hPutStr :: Handle -> String -> IO ()
451
452 hPutStr handle str = 
453     readHandle handle                               >>= \ htype ->
454     case htype of 
455       ErrorHandle ioError ->
456           writeHandle handle htype                  >>
457           fail ioError
458       ClosedHandle ->
459           writeHandle handle htype                  >>
460           ioe_closedHandle handle
461       SemiClosedHandle _ _ ->
462           writeHandle handle htype                  >>
463           ioe_closedHandle handle
464       ReadHandle _ _ _ ->
465           writeHandle handle htype                  >>
466           fail (IOError (Just handle) IllegalOperation "handle is not open for writing")
467       other -> 
468           {-
469            The code below is not correct for line-buffered terminal streams,
470            as the output stream is not flushed when terminal input is requested
471            again, just upon seeing a newline character. A temporary fix for the
472            most common line-buffered output stream, stdout, is to assume the
473            buffering it was given when created (no buffering). This is not
474            as bad as it looks, since stdio buffering sits underneath this.
475
476            ToDo: fix me
477           -}
478           getBufferMode other                       `thenIO_Prim` \ other ->
479           (case bufferMode other of
480             Just LineBuffering ->
481                 writeChars (filePtr other) str
482                 --writeLines (filePtr other) str
483             Just (BlockBuffering (Just size)) ->
484                 writeBlocks (filePtr other) size str
485             Just (BlockBuffering Nothing) ->
486                 writeBlocks (filePtr other) ``BUFSIZ'' str
487             _ -> -- Nothing is treated pessimistically as NoBuffering
488                 writeChars (filePtr other) str
489           )                                         `thenIO_Prim` \ success ->
490           writeHandle handle (markHandle other) >>
491           if success then
492               return ()
493           else
494               constructErrorAndFail "hPutStr"
495   where
496 #ifndef PAR
497     writeLines :: ForeignObj -> String -> PrimIO Bool
498 #else
499     writeLines :: Addr -> String -> PrimIO Bool
500 #endif
501     writeLines = writeChunks ``BUFSIZ'' True 
502
503 #ifndef PAR
504     writeBlocks :: ForeignObj -> Int -> String -> PrimIO Bool
505 #else
506     writeBlocks :: Addr -> Int -> String -> PrimIO Bool
507 #endif
508     writeBlocks fp size s = writeChunks size False fp s
509  
510     {-
511       The breaking up of output into lines along \n boundaries
512       works fine as long as there are newlines to split by.
513       Avoid the splitting up into lines alltogether (doesn't work
514       for overly long lines like the stuff that showsPrec instances
515       normally return). Instead, we split them up into fixed size
516       chunks before blasting them off to the Real World.
517
518       Hacked to avoid multiple passes over the strings - unsightly, but
519       a whole lot quicker. -- SOF 3/96
520     -}
521
522 #ifndef PAR
523     writeChunks :: Int -> Bool -> ForeignObj -> String -> PrimIO Bool
524 #else
525     writeChunks :: Int -> Bool -> Addr -> String -> PrimIO Bool
526 #endif
527     writeChunks (I# bufLen) chopOnNewLine fp s =
528      newCharArray (0,I# bufLen) >>= \ arr@(MutableByteArray _ arr#) ->
529      let
530       write_char :: MutableByteArray# RealWorld -> Int# -> Char# -> PrimIO ()
531       write_char arr# n x = ST $ \ (S# s#) ->
532           case (writeCharArray# arr# n x s#) of { s1# ->
533           ( (), S# s1# ) }
534
535       shoveString :: Int# -> [Char] -> PrimIO Bool
536       shoveString n ls = 
537        case ls of
538          [] ->   
539            if n ==# 0# then
540               returnPrimIO True
541            else
542              _ccall_ writeFile arr fp (I# n) >>= \rc ->
543              returnPrimIO (rc==0)
544
545          ((C# x):xs) ->
546            write_char arr# n x  >>
547            
548            {- Flushing lines - should we bother? Yes, for line-buffered output. -}
549            if n ==# bufLen || (chopOnNewLine && (x `eqChar#` '\n'#)) then
550               _ccall_ writeFile arr fp (I# (n +# 1#)) >>= \ rc ->
551               if rc == 0 then
552                  shoveString 0# xs
553                else
554                  return False
555             else
556                shoveString (n +# 1#) xs
557      in
558      shoveString 0# s
559
560 #ifndef PAR
561     writeChars :: ForeignObj -> String -> PrimIO Bool
562 #else
563     writeChars :: Addr -> String -> PrimIO Bool
564 #endif
565     writeChars fp "" = returnPrimIO True
566     writeChars fp (c:cs) =
567         _ccall_ filePutc fp (ord c) >>= \ rc ->
568         if rc == 0 then
569             writeChars fp cs
570         else
571             returnPrimIO False
572 \end{code}
573
574 Computation $hPrint hdl t$ writes the string representation of {\em t}
575 given by the $shows$ function to the file or channel managed by {\em
576 hdl}.
577
578 SOF 2/97: Seem to have disappeared in 1.4 libs.
579
580 \begin{code}
581 --hPrint :: Show a => Handle -> a -> IO ()
582 hPrint hdl = hPutStr hdl . show
583 \end{code}
584
585 Derived action @hPutStrLn hdl str@ writes the string \tr{str} to
586 the handle \tr{hdl}, adding a newline at the end.
587
588 \begin{code}
589 --hPutStrLn :: Handle -> String -> IO ()
590 hPutStrLn hndl str = do
591  hPutStr  hndl str
592  hPutChar hndl '\n'
593
594 \end{code}
595
596
597 %*********************************************************
598 %*                                                      *
599 \subsection{Try and bracket}
600 %*                                                      *
601 %*********************************************************
602
603 The construct $try comp$ exposes errors which occur within a
604 computation, and which are not fully handled.  It always succeeds.
605
606 \begin{code}
607 try            :: IO a -> IO (Either IOError a)
608 try f          =  catch (do r <- f
609                             return (Right r))
610                         (return . Left)
611
612 bracket        :: IO a -> (a -> IO b) -> (a -> IO c) -> IO c
613 bracket before after m = do
614         x  <- before
615         rs <- try (m x)
616         after x
617         case rs of
618            Right r -> return r
619            Left  e -> fail e
620
621 -- variant of the above where middle computation doesn't want x
622 bracket_        :: IO a -> (a -> IO b) -> IO c -> IO c
623 bracket_ before after m = do
624          x  <- before
625          rs <- try m
626          after x
627          case rs of
628             Right r -> return r
629             Left  e -> fail e
630 \end{code}
631