Added Applicative 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 )
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 ioToIOEnv :: IO a -> IOEnv env a
134 ioToIOEnv io = IOEnv (\ env -> io)
135
136 newMutVar :: a -> IOEnv env (IORef a)
137 newMutVar val = IOEnv (\ env -> newIORef val)
138
139 writeMutVar :: IORef a -> a -> IOEnv env ()
140 writeMutVar var val = IOEnv (\ env -> writeIORef var val)
141
142 readMutVar :: IORef a -> IOEnv env a
143 readMutVar var = IOEnv (\ env -> readIORef var)
144
145 updMutVar :: IORef a -> (a->a) -> IOEnv env ()
146 updMutVar var upd_fn = IOEnv (\ env -> do { v <- readIORef var; writeIORef var (upd_fn v) })
147
148
149 ----------------------------------------------------------------------
150 --      Accessing the environment
151 ----------------------------------------------------------------------
152
153 getEnv :: IOEnv env env
154 {-# INLINE getEnv #-}
155 getEnv = IOEnv (\ env -> return env)
156
157 setEnv :: env' -> IOEnv env' a -> IOEnv env a
158 {-# INLINE setEnv #-}
159 setEnv new_env (IOEnv m) = IOEnv (\ env -> m new_env)
160
161 updEnv :: (env -> env') -> IOEnv env' a -> IOEnv env a
162 {-# INLINE updEnv #-}
163 updEnv upd (IOEnv m) = IOEnv (\ env -> m (upd env))
164
165
166 ----------------------------------------------------------------------
167 --      Standard combinators, but specialised for this monad
168 --                      (for efficiency)
169 ----------------------------------------------------------------------
170
171 mappM         :: (a -> IOEnv env b) -> [a] -> IOEnv env [b]
172 mappM_        :: (a -> IOEnv env b) -> [a] -> IOEnv env ()
173 mapSndM       :: (b -> IOEnv env c) -> [(a,b)] -> IOEnv env [(a,c)]
174         -- Funny names to avoid clash with Prelude
175 sequenceM     :: [IOEnv env a] -> IOEnv env [a]
176 sequenceM_    :: [IOEnv env a] -> IOEnv env ()
177 foldlM        :: (a -> b -> IOEnv env a)  -> a -> [b] -> IOEnv env a
178 foldrM        :: (b -> a -> IOEnv env a)  -> a -> [b] -> IOEnv env a
179 mapAndUnzipM  :: (a -> IOEnv env (b,c))   -> [a] -> IOEnv env ([b],[c])
180 mapAndUnzip3M :: (a -> IOEnv env (b,c,d)) -> [a] -> IOEnv env ([b],[c],[d])
181 checkM        :: Bool -> IOEnv env a -> IOEnv env ()    -- Perform arg if bool is False
182 ifM           :: Bool -> IOEnv env a -> IOEnv env ()    -- Perform arg if bool is True
183 anyM          :: (a -> IOEnv env Bool) -> [a] -> IOEnv env Bool
184
185 mappM f []     = return []
186 mappM f (x:xs) = do { r <- f x; rs <- mappM f xs; return (r:rs) }
187
188 mapSndM f []     = return []
189 mapSndM f ((a,b):xs) = do { c <- f b; rs <- mapSndM f xs; return ((a,c):rs) }
190
191 mappM_ f []     = return ()
192 mappM_ f (x:xs) = f x >> mappM_ f xs
193
194 anyM f [] = return False
195 anyM f (x:xs) = do { b <- f x; if b then return True 
196                                     else anyM f xs }
197
198 zipWithM :: (a -> b -> IOEnv env c) -> [a] -> [b] -> IOEnv env [c]
199 zipWithM f [] bs = return []
200 zipWithM f as [] = return []
201 zipWithM f (a:as) (b:bs) = do { r <- f a b; rs <- zipWithM f as bs; return (r:rs) } 
202
203 zipWithM_ :: (a -> b -> IOEnv env c) -> [a] -> [b] -> IOEnv env ()
204 zipWithM_ f [] bs = return ()
205 zipWithM_ f as [] = return ()
206 zipWithM_ f (a:as) (b:bs) = do { f a b; zipWithM_ f as bs } 
207
208 sequenceM [] = return []
209 sequenceM (x:xs) = do { r <- x; rs <- sequenceM xs; return (r:rs) }
210
211 sequenceM_ []     = return ()
212 sequenceM_ (x:xs) = do { x; sequenceM_ xs }
213
214 foldlM k z [] = return z
215 foldlM k z (x:xs) = do { r <- k z x; foldlM k r xs }
216
217 foldrM k z [] = return z
218 foldrM k z (x:xs) = do { r <- foldrM k z xs; k x r }
219
220 mapAndUnzipM f []     = return ([],[])
221 mapAndUnzipM f (x:xs) = do { (r,s) <- f x; 
222                              (rs,ss) <- mapAndUnzipM f xs; 
223                              return (r:rs, s:ss) }
224
225 mapAndUnzip3M f []     = return ([],[], [])
226 mapAndUnzip3M f (x:xs) = do { (r,s,t) <- f x; 
227                               (rs,ss,ts) <- mapAndUnzip3M f xs; 
228                               return (r:rs, s:ss, t:ts) }
229
230 checkM True  err = return ()
231 checkM False err = do { err; return () }
232
233 ifM True  do_it = do { do_it; return () }
234 ifM False do_it = return ()