MonadIO instance for IOEnv
[ghc-hetmet.git] / compiler / utils / IOEnv.hs
1 {-# OPTIONS -w #-}
2 -- The above warning supression flag is a temporary kludge.
3 -- While working on this module you are encouraged to remove it and fix
4 -- any warnings in the module. See
5 --     http://hackage.haskell.org/trac/ghc/wiki/Commentary/CodingStyle#Warnings
6 -- for details
7
8 --
9 -- (c) The University of Glasgow 2002-2006
10 --
11 -- The IO Monad with an environment
12 --
13
14 module IOEnv (
15         IOEnv,  -- Instance of Monad
16
17         -- Standard combinators, specialised
18         returnM, thenM, thenM_, failM, failWithM,
19         mappM, mappM_, mapSndM, sequenceM, sequenceM_, 
20         foldlM, foldrM, anyM,
21         mapAndUnzipM, mapAndUnzip3M, 
22         checkM, ifM, zipWithM, zipWithM_,
23
24         -- Getting at the environment
25         getEnv, setEnv, updEnv,
26
27         runIOEnv, unsafeInterleaveM,                    
28         tryM, tryAllM, tryMostM, fixM, 
29
30         -- I/O operations
31         ioToIOEnv,
32         IORef, newMutVar, readMutVar, writeMutVar, updMutVar
33   ) where
34 #include "HsVersions.h"
35
36 import Panic            ( try, tryUser, tryMost, Exception(..) )
37
38 import Data.IORef       ( IORef, newIORef, readIORef, writeIORef, modifyIORef )
39 import System.IO.Unsafe ( unsafeInterleaveIO )
40 import System.IO        ( fixIO )
41 import MonadUtils
42
43 ----------------------------------------------------------------------
44 --              Defining the monad type
45 ----------------------------------------------------------------------
46
47
48 newtype IOEnv env a = IOEnv (env -> IO a)
49 unIOEnv (IOEnv m) = m
50
51 instance Monad (IOEnv m) where
52     (>>=)  = thenM
53     (>>)   = thenM_
54     return = returnM
55     fail s = failM      -- Ignore the string
56
57 instance Applicative (IOEnv m) where
58     pure = returnM
59     IOEnv f <*> IOEnv x = IOEnv (\ env -> f env <*> x env )
60
61 instance Functor (IOEnv m) where
62     fmap f (IOEnv m) = IOEnv (\ env -> fmap f (m env))
63
64 returnM :: a -> IOEnv env a
65 returnM a = IOEnv (\ env -> return a)
66
67 thenM :: IOEnv env a -> (a -> IOEnv env b) -> IOEnv env b
68 thenM (IOEnv m) f = IOEnv (\ env -> do { r <- m env ;
69                                        unIOEnv (f r) env })
70
71 thenM_ :: IOEnv env a -> IOEnv env b -> IOEnv env b
72 thenM_ (IOEnv m) f = IOEnv (\ env -> do { m env ; unIOEnv f env })
73
74 failM :: IOEnv env a
75 failM = IOEnv (\ env -> ioError (userError "IOEnv failure"))
76
77 failWithM :: String -> IOEnv env a
78 failWithM s = IOEnv (\ env -> ioError (userError s))
79
80
81
82 ----------------------------------------------------------------------
83 --      Fundmantal combinators specific to the monad
84 ----------------------------------------------------------------------
85
86
87 ---------------------------
88 runIOEnv :: env -> IOEnv env a -> IO a
89 runIOEnv env (IOEnv m) = m env
90
91
92 ---------------------------
93 {-# NOINLINE fixM #-}
94   -- Aargh!  Not inlining fixTc alleviates a space leak problem.
95   -- Normally fixTc is used with a lazy tuple match: if the optimiser is
96   -- shown the definition of fixTc, it occasionally transforms the code
97   -- in such a way that the code generator doesn't spot the selector
98   -- thunks.  Sigh.
99
100 fixM :: (a -> IOEnv env a) -> IOEnv env a
101 fixM f = IOEnv (\ env -> fixIO (\ r -> unIOEnv (f r) env))
102
103
104 ---------------------------
105 tryM :: IOEnv env r -> IOEnv env (Either Exception r)
106 -- Reflect UserError exceptions (only) into IOEnv monad
107 -- Other exceptions are not caught; they are simply propagated as exns
108 --
109 -- The idea is that errors in the program being compiled will give rise
110 -- to UserErrors.  But, say, pattern-match failures in GHC itself should
111 -- not be caught here, else they'll be reported as errors in the program 
112 -- begin compiled!
113 tryM (IOEnv thing) = IOEnv (\ env -> tryUser (thing env))
114
115 tryAllM :: IOEnv env r -> IOEnv env (Either Exception r)
116 -- Catch *all* exceptions
117 -- This is used when running a Template-Haskell splice, when
118 -- even a pattern-match failure is a programmer error
119 tryAllM (IOEnv thing) = IOEnv (\ env -> try (thing env))
120
121 tryMostM :: IOEnv env r -> IOEnv env (Either Exception r)
122 tryMostM (IOEnv thing) = IOEnv (\ env -> tryMost (thing env))
123
124 ---------------------------
125 unsafeInterleaveM :: IOEnv env a -> IOEnv env a
126 unsafeInterleaveM (IOEnv m) = IOEnv (\ env -> unsafeInterleaveIO (m env))
127
128
129 ----------------------------------------------------------------------
130 --      Accessing input/output
131 ----------------------------------------------------------------------
132
133 instance MonadIO (IOEnv env) where
134     liftIO io = IOEnv (\ env -> io)
135
136 ioToIOEnv :: IO a -> IOEnv env a
137 ioToIOEnv io = IOEnv (\ env -> io)
138
139 newMutVar :: a -> IOEnv env (IORef a)
140 newMutVar val = liftIO (newIORef val)
141
142 writeMutVar :: IORef a -> a -> IOEnv env ()
143 writeMutVar var val = liftIO (writeIORef var val)
144
145 readMutVar :: IORef a -> IOEnv env a
146 readMutVar var = liftIO (readIORef var)
147
148 updMutVar :: IORef a -> (a -> a) -> IOEnv env ()
149 updMutVar var upd = liftIO (modifyIORef var upd)
150
151
152 ----------------------------------------------------------------------
153 --      Accessing the environment
154 ----------------------------------------------------------------------
155
156 getEnv :: IOEnv env env
157 {-# INLINE getEnv #-}
158 getEnv = IOEnv (\ env -> return env)
159
160 setEnv :: env' -> IOEnv env' a -> IOEnv env a
161 {-# INLINE setEnv #-}
162 setEnv new_env (IOEnv m) = IOEnv (\ env -> m new_env)
163
164 updEnv :: (env -> env') -> IOEnv env' a -> IOEnv env a
165 {-# INLINE updEnv #-}
166 updEnv upd (IOEnv m) = IOEnv (\ env -> m (upd env))
167
168
169 ----------------------------------------------------------------------
170 --      Standard combinators, but specialised for this monad
171 --                      (for efficiency)
172 ----------------------------------------------------------------------
173
174 mappM         :: (a -> IOEnv env b) -> [a] -> IOEnv env [b]
175 mappM_        :: (a -> IOEnv env b) -> [a] -> IOEnv env ()
176 mapSndM       :: (b -> IOEnv env c) -> [(a,b)] -> IOEnv env [(a,c)]
177         -- Funny names to avoid clash with Prelude
178 sequenceM     :: [IOEnv env a] -> IOEnv env [a]
179 sequenceM_    :: [IOEnv env a] -> IOEnv env ()
180 foldlM        :: (a -> b -> IOEnv env a)  -> a -> [b] -> IOEnv env a
181 foldrM        :: (b -> a -> IOEnv env a)  -> a -> [b] -> IOEnv env a
182 mapAndUnzipM  :: (a -> IOEnv env (b,c))   -> [a] -> IOEnv env ([b],[c])
183 mapAndUnzip3M :: (a -> IOEnv env (b,c,d)) -> [a] -> IOEnv env ([b],[c],[d])
184 checkM        :: Bool -> IOEnv env a -> IOEnv env ()    -- Perform arg if bool is False
185 ifM           :: Bool -> IOEnv env a -> IOEnv env ()    -- Perform arg if bool is True
186 anyM          :: (a -> IOEnv env Bool) -> [a] -> IOEnv env Bool
187
188 mappM f []     = return []
189 mappM f (x:xs) = do { r <- f x; rs <- mappM f xs; return (r:rs) }
190
191 mapSndM f []     = return []
192 mapSndM f ((a,b):xs) = do { c <- f b; rs <- mapSndM f xs; return ((a,c):rs) }
193
194 mappM_ f []     = return ()
195 mappM_ f (x:xs) = f x >> mappM_ f xs
196
197 anyM f [] = return False
198 anyM f (x:xs) = do { b <- f x; if b then return True 
199                                     else anyM f xs }
200
201 zipWithM :: (a -> b -> IOEnv env c) -> [a] -> [b] -> IOEnv env [c]
202 zipWithM f [] bs = return []
203 zipWithM f as [] = return []
204 zipWithM f (a:as) (b:bs) = do { r <- f a b; rs <- zipWithM f as bs; return (r:rs) } 
205
206 zipWithM_ :: (a -> b -> IOEnv env c) -> [a] -> [b] -> IOEnv env ()
207 zipWithM_ f [] bs = return ()
208 zipWithM_ f as [] = return ()
209 zipWithM_ f (a:as) (b:bs) = do { f a b; zipWithM_ f as bs } 
210
211 sequenceM [] = return []
212 sequenceM (x:xs) = do { r <- x; rs <- sequenceM xs; return (r:rs) }
213
214 sequenceM_ []     = return ()
215 sequenceM_ (x:xs) = do { x; sequenceM_ xs }
216
217 foldlM k z [] = return z
218 foldlM k z (x:xs) = do { r <- k z x; foldlM k r xs }
219
220 foldrM k z [] = return z
221 foldrM k z (x:xs) = do { r <- foldrM k z xs; k x r }
222
223 mapAndUnzipM f []     = return ([],[])
224 mapAndUnzipM f (x:xs) = do { (r,s) <- f x; 
225                              (rs,ss) <- mapAndUnzipM f xs; 
226                              return (r:rs, s:ss) }
227
228 mapAndUnzip3M f []     = return ([],[], [])
229 mapAndUnzip3M f (x:xs) = do { (r,s,t) <- f x; 
230                               (rs,ss,ts) <- mapAndUnzip3M f xs; 
231                               return (r:rs, s:ss, t:ts) }
232
233 checkM True  err = return ()
234 checkM False err = do { err; return () }
235
236 ifM True  do_it = do { do_it; return () }
237 ifM False do_it = return ()