IOEnv.hs 7.76 KB
Newer Older
1
2
3
4
5
--
-- (c) The University of Glasgow 2002-2006
--
-- The IO Monad with an environment
--
dterei's avatar
dterei committed
6
7
8
9
-- The environment is passed around as a Reader monad but
-- as its in the IO monad, mutable references can be used
-- for updating state.
--
10
{-# LANGUAGE UndecidableInstances #-}
11

12
module IOEnv (
Ian Lynagh's avatar
Ian Lynagh committed
13
        IOEnv, -- Instance of Monad
14

Ian Lynagh's avatar
Ian Lynagh committed
15
16
        -- Monad utilities
        module MonadUtils,
17

Ian Lynagh's avatar
Ian Lynagh committed
18
19
        -- Errors
        failM, failWithM,
20
        IOEnvFailure(..),
21

Ian Lynagh's avatar
Ian Lynagh committed
22
23
        -- Getting at the environment
        getEnv, setEnv, updEnv,
24

Ian Lynagh's avatar
Ian Lynagh committed
25
26
        runIOEnv, unsafeInterleaveM,
        tryM, tryAllM, tryMostM, fixM,
27

Ian Lynagh's avatar
Ian Lynagh committed
28
        -- I/O operations
29
30
        IORef, newMutVar, readMutVar, writeMutVar, updMutVar,
        atomicUpdMutVar, atomicUpdMutVar'
31
32
  ) where

Ian Lynagh's avatar
Ian Lynagh committed
33
import DynFlags
34
35
import Exception
import Panic
Simon Marlow's avatar
Simon Marlow committed
36

37
38
import Data.IORef       ( IORef, newIORef, readIORef, writeIORef, modifyIORef,
                          atomicModifyIORef )
39
import Data.Typeable
Ian Lynagh's avatar
Ian Lynagh committed
40
41
import System.IO.Unsafe ( unsafeInterleaveIO )
import System.IO        ( fixIO )
42
import Control.Monad
twanvl's avatar
twanvl committed
43
import MonadUtils
44
45

----------------------------------------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
46
-- Defining the monad type
47
48
49
50
----------------------------------------------------------------------


newtype IOEnv env a = IOEnv (env -> IO a)
Ian Lynagh's avatar
Ian Lynagh committed
51
52

unIOEnv :: IOEnv env a -> (env -> IO a)
53
54
55
unIOEnv (IOEnv m) = m

instance Monad (IOEnv m) where
twanvl's avatar
twanvl committed
56
57
58
    (>>=)  = thenM
    (>>)   = thenM_
    return = returnM
Ian Lynagh's avatar
Ian Lynagh committed
59
    fail _ = failM -- Ignore the string
twanvl's avatar
twanvl committed
60
61
62
63

instance Applicative (IOEnv m) where
    pure = returnM
    IOEnv f <*> IOEnv x = IOEnv (\ env -> f env <*> x env )
64

65
instance Functor (IOEnv m) where
twanvl's avatar
twanvl committed
66
    fmap f (IOEnv m) = IOEnv (\ env -> fmap f (m env))
67

68
returnM :: a -> IOEnv env a
Ian Lynagh's avatar
Ian Lynagh committed
69
returnM a = IOEnv (\ _ -> return a)
70
71
72

thenM :: IOEnv env a -> (a -> IOEnv env b) -> IOEnv env b
thenM (IOEnv m) f = IOEnv (\ env -> do { r <- m env ;
Ian Lynagh's avatar
Ian Lynagh committed
73
                                         unIOEnv (f r) env })
74
75

thenM_ :: IOEnv env a -> IOEnv env b -> IOEnv env b
76
thenM_ (IOEnv m) f = IOEnv (\ env -> do { _ <- m env ; unIOEnv f env })
77
78

failM :: IOEnv env a
79
failM = IOEnv (\ _ -> throwIO IOEnvFailure)
80

81
failWithM :: String -> IOEnv env a
Ian Lynagh's avatar
Ian Lynagh committed
82
failWithM s = IOEnv (\ _ -> ioError (userError s))
83

84
85
data IOEnvFailure = IOEnvFailure
    deriving Typeable
86

87
88
89
90
instance Show IOEnvFailure where
    show IOEnvFailure = "IOEnv failure"

instance Exception IOEnvFailure
91

Ian Lynagh's avatar
Ian Lynagh committed
92
93
94
95
instance ContainsDynFlags env => HasDynFlags (IOEnv env) where
    getDynFlags = do env <- getEnv
                     return $ extractDynFlags env

96
----------------------------------------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
97
-- Fundmantal combinators specific to the monad
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
----------------------------------------------------------------------


---------------------------
runIOEnv :: env -> IOEnv env a -> IO a
runIOEnv env (IOEnv m) = m env


---------------------------
{-# NOINLINE fixM #-}
  -- Aargh!  Not inlining fixTc alleviates a space leak problem.
  -- Normally fixTc is used with a lazy tuple match: if the optimiser is
  -- shown the definition of fixTc, it occasionally transforms the code
  -- in such a way that the code generator doesn't spot the selector
  -- thunks.  Sigh.

fixM :: (a -> IOEnv env a) -> IOEnv env a
fixM f = IOEnv (\ env -> fixIO (\ r -> unIOEnv (f r) env))


---------------------------
119
tryM :: IOEnv env r -> IOEnv env (Either IOEnvFailure r)
simonpj@microsoft.com's avatar
simonpj@microsoft.com committed
120
121
122
-- Reflect UserError exceptions (only) into IOEnv monad
-- Other exceptions are not caught; they are simply propagated as exns
--
123
124
-- The idea is that errors in the program being compiled will give rise
-- to UserErrors.  But, say, pattern-match failures in GHC itself should
Ian Lynagh's avatar
Ian Lynagh committed
125
-- not be caught here, else they'll be reported as errors in the program
126
-- begin compiled!
127
128
129
130
tryM (IOEnv thing) = IOEnv (\ env -> tryIOEnvFailure (thing env))

tryIOEnvFailure :: IO a -> IO (Either IOEnvFailure a)
tryIOEnvFailure = try
131

132
133
-- XXX We shouldn't be catching everything, e.g. timeouts
tryAllM :: IOEnv env r -> IOEnv env (Either SomeException r)
134
135
136
137
-- Catch *all* exceptions
-- This is used when running a Template-Haskell splice, when
-- even a pattern-match failure is a programmer error
tryAllM (IOEnv thing) = IOEnv (\ env -> try (thing env))
138

139
tryMostM :: IOEnv env r -> IOEnv env (Either SomeException r)
140
141
tryMostM (IOEnv thing) = IOEnv (\ env -> tryMost (thing env))

142
143
144
145
146
---------------------------
unsafeInterleaveM :: IOEnv env a -> IOEnv env a
unsafeInterleaveM (IOEnv m) = IOEnv (\ env -> unsafeInterleaveIO (m env))


147
148
149
150
151
152
153
154
155
156
----------------------------------------------------------------------
-- MonadPlus
----------------------------------------------------------------------

-- For use if the user has imported Control.Monad.Error from MTL
-- Requires UndecidableInstances
instance MonadPlus IO => MonadPlus (IOEnv env) where
    mzero = IOEnv (const mzero)
    m `mplus` n = IOEnv (\env -> unIOEnv m env `mplus` unIOEnv n env)

157
----------------------------------------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
158
-- Accessing input/output
159
160
----------------------------------------------------------------------

twanvl's avatar
twanvl committed
161
instance MonadIO (IOEnv env) where
Ian Lynagh's avatar
Ian Lynagh committed
162
    liftIO io = IOEnv (\ _ -> io)
twanvl's avatar
twanvl committed
163

164
newMutVar :: a -> IOEnv env (IORef a)
twanvl's avatar
twanvl committed
165
newMutVar val = liftIO (newIORef val)
166
167

writeMutVar :: IORef a -> a -> IOEnv env ()
twanvl's avatar
twanvl committed
168
writeMutVar var val = liftIO (writeIORef var val)
169
170

readMutVar :: IORef a -> IOEnv env a
twanvl's avatar
twanvl committed
171
readMutVar var = liftIO (readIORef var)
172

twanvl's avatar
twanvl committed
173
174
updMutVar :: IORef a -> (a -> a) -> IOEnv env ()
updMutVar var upd = liftIO (modifyIORef var upd)
175

176
177
178
179
180
181
182
183
184
185
186
-- | Atomically update the reference.  Does not force the evaluation of the
-- new variable contents.  For strict update, use 'atomicUpdMutVar''.
atomicUpdMutVar :: IORef a -> (a -> (a, b)) -> IOEnv env b
atomicUpdMutVar var upd = liftIO (atomicModifyIORef var upd)

-- | Strict variant of 'atomicUpdMutVar'.
atomicUpdMutVar' :: IORef a -> (a -> (a, b)) -> IOEnv env b
atomicUpdMutVar' var upd = do
  r <- atomicUpdMutVar var upd
  _ <- liftIO . evaluate =<< readMutVar var
  return r
187
188

----------------------------------------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
189
-- Accessing the environment
190
191
192
193
194
195
----------------------------------------------------------------------

getEnv :: IOEnv env env
{-# INLINE getEnv #-}
getEnv = IOEnv (\ env -> return env)

196
-- | Perform a computation with a different environment
197
198
setEnv :: env' -> IOEnv env' a -> IOEnv env a
{-# INLINE setEnv #-}
Ian Lynagh's avatar
Ian Lynagh committed
199
setEnv new_env (IOEnv m) = IOEnv (\ _ -> m new_env)
200

201
-- | Perform a computation with an altered environment
202
203
204
205
206
207
updEnv :: (env -> env') -> IOEnv env' a -> IOEnv env a
{-# INLINE updEnv #-}
updEnv upd (IOEnv m) = IOEnv (\ env -> m (upd env))


----------------------------------------------------------------------
Ian Lynagh's avatar
Ian Lynagh committed
208
209
-- Standard combinators, but specialised for this monad
-- (for efficiency)
210
211
----------------------------------------------------------------------

212
213
214
215
216
217
218
219
220
221
222
223
224
225
-- {-# SPECIALIZE mapM          :: (a -> IOEnv env b) -> [a] -> IOEnv env [b] #-}
-- {-# SPECIALIZE mapM_         :: (a -> IOEnv env b) -> [a] -> IOEnv env () #-}
-- {-# SPECIALIZE mapSndM       :: (b -> IOEnv env c) -> [(a,b)] -> IOEnv env [(a,c)] #-}
-- {-# SPECIALIZE sequence      :: [IOEnv env a] -> IOEnv env [a] #-}
-- {-# SPECIALIZE sequence_     :: [IOEnv env a] -> IOEnv env () #-}
-- {-# SPECIALIZE foldlM        :: (a -> b -> IOEnv env a)  -> a -> [b] -> IOEnv env a #-}
-- {-# SPECIALIZE foldrM        :: (b -> a -> IOEnv env a)  -> a -> [b] -> IOEnv env a #-}
-- {-# SPECIALIZE mapAndUnzipM  :: (a -> IOEnv env (b,c))   -> [a] -> IOEnv env ([b],[c]) #-}
-- {-# SPECIALIZE mapAndUnzip3M :: (a -> IOEnv env (b,c,d)) -> [a] -> IOEnv env ([b],[c],[d]) #-}
-- {-# SPECIALIZE zipWithM      :: (a -> b -> IOEnv env c) -> [a] -> [b] -> IOEnv env [c] #-}
-- {-# SPECIALIZE zipWithM_     :: (a -> b -> IOEnv env c) -> [a] -> [b] -> IOEnv env () #-}
-- {-# SPECIALIZE anyM          :: (a -> IOEnv env Bool) -> [a] -> IOEnv env Bool #-}
-- {-# SPECIALIZE when          :: Bool -> IOEnv env a -> IOEnv env () #-}
-- {-# SPECIALIZE unless        :: Bool -> IOEnv env a -> IOEnv env () #-}