2 % (c) The AQUA Project, Glasgow University, 1994-1996
5 \section[IOBase]{Module @IOBase@}
7 Definitions for the @IO@ monad and its friends. Everything is exported
8 concretely; the @IO@ module itself exports abstractly.
13 {-# OPTIONS -fno-implicit-prelude #-}
20 import PackedString ( unpackCString )
24 import ArrBase ( ByteArray(..), MutableVar(..) )
26 infixr 1 `thenIO_Prim`
29 %*********************************************************
31 \subsection{The @IO@ monad}
33 %*********************************************************
36 newtype IO a = IO (PrimIO (Either IOError a))
38 instance Functor IO where
39 map f x = x >>= (return . f)
41 instance Monad IO where
45 m >> k = m >>= \ _ -> k
46 return x = IO $ ST $ \ s@(S# _) -> (Right x, s)
50 let (r, new_s) = m s in
52 Left err -> (Left err, new_s)
53 Right x -> case (k x) of { IO (ST k2) ->
56 fixIO :: (a -> IO a) -> IO a
57 -- not required but worth having around
59 fixIO k = IO $ ST $ \ s ->
61 (IO (ST k_loop)) = k loop
63 (Right loop, _) = result
67 fail :: IOError -> IO a
68 fail err = IO $ ST $ \ s -> (Left err, s)
70 userError :: String -> IOError
71 userError str = IOError Nothing UserError str
73 catch :: IO a -> (IOError -> IO a) -> IO a
74 catch (IO (ST m)) k = IO $ ST $ \ s ->
75 case (m s) of { (r, new_s) ->
78 Left err -> case (k err) of { IO (ST k_err) ->
81 instance Show (IO a) where
82 showsPrec p f = showString "<<IO action>>"
83 showList = showList__ (showsPrec 0)
86 %*********************************************************
88 \subsection{Coercions to @ST@ and @PrimIO@}
90 %*********************************************************
93 stToIO :: ST RealWorld a -> IO a
94 primIOToIO :: PrimIO a -> IO a
95 ioToST :: IO a -> ST RealWorld a
96 ioToPrimIO :: IO a -> PrimIO a
98 primIOToIO = stToIO -- for backwards compatibility
101 stToIO (ST m) = IO $ ST $ \ s ->
102 case (m s) of { (r, new_s) ->
105 ioToST (IO (ST io)) = ST $ \ s ->
106 case (io s) of { (r, new_s) ->
108 Right a -> (a, new_s)
109 Left e -> error ("I/O Error (ioToST): " ++ showsPrec 0 e "\n")
113 @thenIO_Prim@ is a useful little number for doing _ccall_s in IO-land:
116 thenIO_Prim :: PrimIO a -> (a -> IO b) -> IO b
117 {-# INLINE thenIO_Prim #-}
119 thenIO_Prim (ST m) k = IO $ ST $ \ s ->
120 case (m s) of { (m_res, new_s) ->
121 case (k m_res) of { (IO (ST k_m_res)) ->
126 %*********************************************************
128 \subsection{Error/trace-ish functions}
130 %*********************************************************
133 errorIO :: PrimIO () -> a
136 = case (errorIO# io) of
139 bottom = bottom -- Never evaluated
141 -- error stops execution and displays an error message
143 error s = error__ ( \ x -> _ccall_ ErrorHdrHook x ) s
145 error__ :: (Addr{-FILE *-} -> PrimIO ()) -> String -> a
148 #ifdef __PARALLEL_HASKELL__
149 = errorIO (msg_hdr sTDERR{-msg hdr-} >>
150 _ccall_ fflush sTDERR >>
152 _ccall_ fflush sTDERR >>
153 _ccall_ stg_exit (1::Int)
156 = errorIO (msg_hdr sTDERR{-msg hdr-} >>
157 _ccall_ fflush sTDERR >>
159 _ccall_ fflush sTDERR >>
160 _ccall_ getErrorHandler >>= \ errorHandler ->
161 if errorHandler == (-1::Int) then
162 _ccall_ stg_exit (1::Int)
164 _casm_ ``%r = (StgStablePtr)(%0);'' errorHandler
166 _ccall_ decrementErrorCount >>= \ () ->
167 deRefStablePtr osptr >>= \ oact ->
170 #endif {- !parallel -}
172 sTDERR = (``stderr'' :: Addr)
176 {-# GENERATE_SPECS _trace a #-}
177 trace :: String -> a -> a
180 = unsafePerformPrimIO (
181 ((_ccall_ PreTraceHook sTDERR{-msg-}):: PrimIO ()) >>
182 fputs sTDERR string >>
183 ((_ccall_ PostTraceHook sTDERR{-msg-}):: PrimIO ()) >>
186 sTDERR = (``stderr'' :: Addr)
190 %*********************************************************
192 \subsection{Utility functions}
194 %*********************************************************
196 The construct $try comp$ exposes errors which occur within a
197 computation, and which are not fully handled. It always succeeds.
198 This one didn't make it into the 1.3 defn
201 tryIO :: IO a -> IO (Either IOError a)
202 tryIO p = catch (p >>= (return . Right)) (return . Left)
205 I'm not sure why this little function is here...
208 fputs :: Addr{-FILE*-} -> String -> PrimIO Bool
210 fputs stream [] = return True
212 fputs stream (c : cs)
213 = _ccall_ stg_putc c stream >> -- stg_putc expands to putc
214 fputs stream cs -- (just does some casting stream)
218 %*********************************************************
220 \subsection{Type @IOError@}
222 %*********************************************************
224 A value @IOError@ encode errors occurred in the @IO@ monad.
225 An @IOError@ records a more specific error type, a descriptive
226 string and maybe the handle that was used when the error was
232 (Maybe Handle) -- the handle used by the action flagging the
234 IOErrorType -- what it was.
235 String -- error type specific information.
237 instance Eq IOError where
238 (IOError h1 e1 str1) == (IOError h2 e2 str2) =
239 e1==e2 && str1==str2 && h1==h2
242 = AlreadyExists | HardwareFault
243 | IllegalOperation | InappropriateType
244 | Interrupted | InvalidArgument
245 | NoSuchThing | OtherError
246 | PermissionDenied | ProtocolError
247 | ResourceBusy | ResourceExhausted
248 | ResourceVanished | SystemError
249 | TimeExpired | UnsatisfiedConstraints
250 | UnsupportedOperation | UserError
256 Predicates on IOError; little effort made on these so far...
260 isAlreadyExistsError (IOError _ AlreadyExists _) = True
261 isAlreadyExistsError _ = False
263 isAlreadyInUseError (IOError _ ResourceBusy _) = True
264 isAlreadyInUseError _ = False
266 isFullError (IOError _ ResourceExhausted _) = True
267 isFullError _ = False
269 isEOFError (IOError _ EOF _) = True
272 isIllegalOperation (IOError _ IllegalOperation _) = True
273 isIllegalOperation _ = False
275 isPermissionError (IOError _ PermissionDenied _) = True
276 isPermissionError _ = False
278 isDoesNotExistError (IOError _ NoSuchThing _) = True
279 isDoesNotExistError _ = False
281 isUserError (IOError _ UserError s) = Just s
282 isUserError _ = Nothing
288 instance Show IOError where
289 showsPrec p (IOError _ UserError s) rs =
291 showsPrec p (IOError _ EOF _) rs =
293 showsPrec p (IOError _ iot s) rs =
298 _ -> showString ": " $
303 The @String@ part of an @IOError@ is platform-dependent. However, to
304 provide a uniform mechanism for distinguishing among errors within
305 these broad categories, each platform-specific standard shall specify
306 the exact strings to be used for particular errors. For errors not
307 explicitly mentioned in the standard, any descriptive string may be
311 SOF & 4/96 & added argument to indicate function that flagged error
313 % Hmm..does these envs work?!...SOF
316 constructErrorAndFail :: String -> IO a
317 constructErrorAndFail call_site
318 = stToIO (constructError call_site) >>= \ io_error ->
323 This doesn't seem to be documented/spelled out anywhere,
326 The implementation of the IO prelude uses various C stubs
327 to do the actual interaction with the OS. The bandwidth
328 \tr{C<->Haskell} is somewhat limited, so the general strategy
329 for flaggging any errors (apart from possibly using the
330 return code of the external call), is to set the @ghc_errtype@
331 to a value that is one of the \tr{#define}s in @includes/error.h@.
332 @ghc_errstr@ holds a character string providing error-specific
336 constructError :: String -> PrimIO IOError
337 constructError call_site =
338 _casm_ ``%r = ghc_errtype;'' >>= \ (I# errtype#) ->
339 _casm_ ``%r = ghc_errstr;'' >>= \ str ->
343 ERR_ALREADYEXISTS# -> AlreadyExists
344 ERR_HARDWAREFAULT# -> HardwareFault
345 ERR_ILLEGALOPERATION# -> IllegalOperation
346 ERR_INAPPROPRIATETYPE# -> InappropriateType
347 ERR_INTERRUPTED# -> Interrupted
348 ERR_INVALIDARGUMENT# -> InvalidArgument
349 ERR_NOSUCHTHING# -> NoSuchThing
350 ERR_OTHERERROR# -> OtherError
351 ERR_PERMISSIONDENIED# -> PermissionDenied
352 ERR_PROTOCOLERROR# -> ProtocolError
353 ERR_RESOURCEBUSY# -> ResourceBusy
354 ERR_RESOURCEEXHAUSTED# -> ResourceExhausted
355 ERR_RESOURCEVANISHED# -> ResourceVanished
356 ERR_SYSTEMERROR# -> SystemError
357 ERR_TIMEEXPIRED# -> TimeExpired
358 ERR_UNSATISFIEDCONSTRAINTS# -> UnsatisfiedConstraints
359 ERR_UNSUPPORTEDOPERATION# -> UnsupportedOperation
366 OtherError -> "bad error construct"
367 _ -> call_site ++ ':' : ' ' : unpackCString str
369 return (IOError Nothing iot msg)
372 %*********************************************************
374 \subsection{Types @Handle@, @Handle__@}
376 %*********************************************************
378 The type for @Handle@ is defined rather than in @IOHandle@
379 module, as the @IOError@ type uses it..all operations over
380 a handles reside in @IOHandle@.
385 Sigh, the MVar ops in ConcBase depend on IO, the IO
386 representation here depend on MVars for handles (when
387 compiling a concurrent way). Break the cycle by having
388 the definition of MVars go here:
391 data MVar a = MVar (SynchVar# RealWorld a)
393 #if defined(__CONCURRENT_HASKELL__)
394 type Handle = MVar Handle__
396 type Handle = MutableVar RealWorld Handle__
400 = ErrorHandle IOError
402 | SemiClosedHandle ForeignObj (Addr, Int)
403 | ReadHandle ForeignObj (Maybe BufferMode) Bool
404 | WriteHandle ForeignObj (Maybe BufferMode) Bool
405 | AppendHandle ForeignObj (Maybe BufferMode) Bool
406 | ReadWriteHandle ForeignObj (Maybe BufferMode) Bool
408 -- Standard Instances as defined by the Report..
410 instance Eq Handle {-partain:????-}
411 instance Show Handle where {showsPrec p h = showString "<<Handle>>"}
415 %*********************************************************
417 \subsection[BufferMode]{Buffering modes}
419 %*********************************************************
421 Three kinds of buffering are supported: line-buffering,
422 block-buffering or no-buffering. These modes have the following
423 effects. For output, items are written out from the internal
424 buffer according to the buffer mode:
427 \item[line-buffering] the entire output buffer is written
428 out whenever a newline is output, the output buffer overflows,
429 a flush is issued, or the handle is closed.
431 \item[block-buffering] the entire output buffer is written out whenever
432 it overflows, a flush is issued, or the handle
435 \item[no-buffering] output is written immediately, and never stored
436 in the output buffer.
439 The output buffer is emptied as soon as it has been written out.
441 Similarly, input occurs according to the buffer mode for handle {\em hdl}.
443 \item[line-buffering] when the input buffer for {\em hdl} is not empty,
444 the next item is obtained from the buffer;
445 otherwise, when the input buffer is empty,
446 characters up to and including the next newline
447 character are read into the buffer. No characters
448 are available until the newline character is
450 \item[block-buffering] when the input buffer for {\em hdl} becomes empty,
451 the next block of data is read into this buffer.
452 \item[no-buffering] the next input item is read and returned.
454 For most implementations, physical files will normally be block-buffered
455 and terminals will normally be line-buffered.
459 = NoBuffering | LineBuffering | BlockBuffering (Maybe Int)
460 deriving (Eq, Ord, Read, Show)