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