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